1 //===--- Expr.cpp - Expression AST Node Implementation --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Expr class and subclasses.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/APValue.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/AST/EvaluatedExprVisitor.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/Mangle.h"
24 #include "clang/AST/RecordLayout.h"
25 #include "clang/AST/StmtVisitor.h"
26 #include "clang/Basic/Builtins.h"
27 #include "clang/Basic/CharInfo.h"
28 #include "clang/Basic/SourceManager.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/Lexer.h"
31 #include "clang/Lex/LiteralSupport.h"
32 #include "clang/Sema/SemaDiagnostic.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include <algorithm>
36 #include <cstring>
37 using namespace clang;
38 
getBestDynamicClassType() const39 const CXXRecordDecl *Expr::getBestDynamicClassType() const {
40   const Expr *E = ignoreParenBaseCasts();
41 
42   QualType DerivedType = E->getType();
43   if (const PointerType *PTy = DerivedType->getAs<PointerType>())
44     DerivedType = PTy->getPointeeType();
45 
46   if (DerivedType->isDependentType())
47     return nullptr;
48 
49   const RecordType *Ty = DerivedType->castAs<RecordType>();
50   Decl *D = Ty->getDecl();
51   return cast<CXXRecordDecl>(D);
52 }
53 
skipRValueSubobjectAdjustments(SmallVectorImpl<const Expr * > & CommaLHSs,SmallVectorImpl<SubobjectAdjustment> & Adjustments) const54 const Expr *Expr::skipRValueSubobjectAdjustments(
55     SmallVectorImpl<const Expr *> &CommaLHSs,
56     SmallVectorImpl<SubobjectAdjustment> &Adjustments) const {
57   const Expr *E = this;
58   while (true) {
59     E = E->IgnoreParens();
60 
61     if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
62       if ((CE->getCastKind() == CK_DerivedToBase ||
63            CE->getCastKind() == CK_UncheckedDerivedToBase) &&
64           E->getType()->isRecordType()) {
65         E = CE->getSubExpr();
66         CXXRecordDecl *Derived
67           = cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
68         Adjustments.push_back(SubobjectAdjustment(CE, Derived));
69         continue;
70       }
71 
72       if (CE->getCastKind() == CK_NoOp) {
73         E = CE->getSubExpr();
74         continue;
75       }
76     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
77       if (!ME->isArrow()) {
78         assert(ME->getBase()->getType()->isRecordType());
79         if (FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
80           if (!Field->isBitField() && !Field->getType()->isReferenceType()) {
81             E = ME->getBase();
82             Adjustments.push_back(SubobjectAdjustment(Field));
83             continue;
84           }
85         }
86       }
87     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
88       if (BO->isPtrMemOp()) {
89         assert(BO->getRHS()->isRValue());
90         E = BO->getLHS();
91         const MemberPointerType *MPT =
92           BO->getRHS()->getType()->getAs<MemberPointerType>();
93         Adjustments.push_back(SubobjectAdjustment(MPT, BO->getRHS()));
94         continue;
95       } else if (BO->getOpcode() == BO_Comma) {
96         CommaLHSs.push_back(BO->getLHS());
97         E = BO->getRHS();
98         continue;
99       }
100     }
101 
102     // Nothing changed.
103     break;
104   }
105   return E;
106 }
107 
108 /// isKnownToHaveBooleanValue - Return true if this is an integer expression
109 /// that is known to return 0 or 1.  This happens for _Bool/bool expressions
110 /// but also int expressions which are produced by things like comparisons in
111 /// C.
isKnownToHaveBooleanValue() const112 bool Expr::isKnownToHaveBooleanValue() const {
113   const Expr *E = IgnoreParens();
114 
115   // If this value has _Bool type, it is obvious 0/1.
116   if (E->getType()->isBooleanType()) return true;
117   // If this is a non-scalar-integer type, we don't care enough to try.
118   if (!E->getType()->isIntegralOrEnumerationType()) return false;
119 
120   if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
121     switch (UO->getOpcode()) {
122     case UO_Plus:
123       return UO->getSubExpr()->isKnownToHaveBooleanValue();
124     case UO_LNot:
125       return true;
126     default:
127       return false;
128     }
129   }
130 
131   // Only look through implicit casts.  If the user writes
132   // '(int) (a && b)' treat it as an arbitrary int.
133   if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
134     return CE->getSubExpr()->isKnownToHaveBooleanValue();
135 
136   if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
137     switch (BO->getOpcode()) {
138     default: return false;
139     case BO_LT:   // Relational operators.
140     case BO_GT:
141     case BO_LE:
142     case BO_GE:
143     case BO_EQ:   // Equality operators.
144     case BO_NE:
145     case BO_LAnd: // AND operator.
146     case BO_LOr:  // Logical OR operator.
147       return true;
148 
149     case BO_And:  // Bitwise AND operator.
150     case BO_Xor:  // Bitwise XOR operator.
151     case BO_Or:   // Bitwise OR operator.
152       // Handle things like (x==2)|(y==12).
153       return BO->getLHS()->isKnownToHaveBooleanValue() &&
154              BO->getRHS()->isKnownToHaveBooleanValue();
155 
156     case BO_Comma:
157     case BO_Assign:
158       return BO->getRHS()->isKnownToHaveBooleanValue();
159     }
160   }
161 
162   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
163     return CO->getTrueExpr()->isKnownToHaveBooleanValue() &&
164            CO->getFalseExpr()->isKnownToHaveBooleanValue();
165 
166   return false;
167 }
168 
169 // Amusing macro metaprogramming hack: check whether a class provides
170 // a more specific implementation of getExprLoc().
171 //
172 // See also Stmt.cpp:{getLocStart(),getLocEnd()}.
173 namespace {
174   /// This implementation is used when a class provides a custom
175   /// implementation of getExprLoc.
176   template <class E, class T>
getExprLocImpl(const Expr * expr,SourceLocation (T::* v)()const)177   SourceLocation getExprLocImpl(const Expr *expr,
178                                 SourceLocation (T::*v)() const) {
179     return static_cast<const E*>(expr)->getExprLoc();
180   }
181 
182   /// This implementation is used when a class doesn't provide
183   /// a custom implementation of getExprLoc.  Overload resolution
184   /// should pick it over the implementation above because it's
185   /// more specialized according to function template partial ordering.
186   template <class E>
getExprLocImpl(const Expr * expr,SourceLocation (Expr::* v)()const)187   SourceLocation getExprLocImpl(const Expr *expr,
188                                 SourceLocation (Expr::*v)() const) {
189     return static_cast<const E*>(expr)->getLocStart();
190   }
191 }
192 
getExprLoc() const193 SourceLocation Expr::getExprLoc() const {
194   switch (getStmtClass()) {
195   case Stmt::NoStmtClass: llvm_unreachable("statement without class");
196 #define ABSTRACT_STMT(type)
197 #define STMT(type, base) \
198   case Stmt::type##Class: break;
199 #define EXPR(type, base) \
200   case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);
201 #include "clang/AST/StmtNodes.inc"
202   }
203   llvm_unreachable("unknown expression kind");
204 }
205 
206 //===----------------------------------------------------------------------===//
207 // Primary Expressions.
208 //===----------------------------------------------------------------------===//
209 
210 /// \brief Compute the type-, value-, and instantiation-dependence of a
211 /// declaration reference
212 /// based on the declaration being referenced.
computeDeclRefDependence(const ASTContext & Ctx,NamedDecl * D,QualType T,bool & TypeDependent,bool & ValueDependent,bool & InstantiationDependent)213 static void computeDeclRefDependence(const ASTContext &Ctx, NamedDecl *D,
214                                      QualType T, bool &TypeDependent,
215                                      bool &ValueDependent,
216                                      bool &InstantiationDependent) {
217   TypeDependent = false;
218   ValueDependent = false;
219   InstantiationDependent = false;
220 
221   // (TD) C++ [temp.dep.expr]p3:
222   //   An id-expression is type-dependent if it contains:
223   //
224   // and
225   //
226   // (VD) C++ [temp.dep.constexpr]p2:
227   //  An identifier is value-dependent if it is:
228 
229   //  (TD)  - an identifier that was declared with dependent type
230   //  (VD)  - a name declared with a dependent type,
231   if (T->isDependentType()) {
232     TypeDependent = true;
233     ValueDependent = true;
234     InstantiationDependent = true;
235     return;
236   } else if (T->isInstantiationDependentType()) {
237     InstantiationDependent = true;
238   }
239 
240   //  (TD)  - a conversion-function-id that specifies a dependent type
241   if (D->getDeclName().getNameKind()
242                                 == DeclarationName::CXXConversionFunctionName) {
243     QualType T = D->getDeclName().getCXXNameType();
244     if (T->isDependentType()) {
245       TypeDependent = true;
246       ValueDependent = true;
247       InstantiationDependent = true;
248       return;
249     }
250 
251     if (T->isInstantiationDependentType())
252       InstantiationDependent = true;
253   }
254 
255   //  (VD)  - the name of a non-type template parameter,
256   if (isa<NonTypeTemplateParmDecl>(D)) {
257     ValueDependent = true;
258     InstantiationDependent = true;
259     return;
260   }
261 
262   //  (VD) - a constant with integral or enumeration type and is
263   //         initialized with an expression that is value-dependent.
264   //  (VD) - a constant with literal type and is initialized with an
265   //         expression that is value-dependent [C++11].
266   //  (VD) - FIXME: Missing from the standard:
267   //       -  an entity with reference type and is initialized with an
268   //          expression that is value-dependent [C++11]
269   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
270     if ((Ctx.getLangOpts().CPlusPlus11 ?
271            Var->getType()->isLiteralType(Ctx) :
272            Var->getType()->isIntegralOrEnumerationType()) &&
273         (Var->getType().isConstQualified() ||
274          Var->getType()->isReferenceType())) {
275       if (const Expr *Init = Var->getAnyInitializer())
276         if (Init->isValueDependent()) {
277           ValueDependent = true;
278           InstantiationDependent = true;
279         }
280     }
281 
282     // (VD) - FIXME: Missing from the standard:
283     //      -  a member function or a static data member of the current
284     //         instantiation
285     if (Var->isStaticDataMember() &&
286         Var->getDeclContext()->isDependentContext()) {
287       ValueDependent = true;
288       InstantiationDependent = true;
289       TypeSourceInfo *TInfo = Var->getFirstDecl()->getTypeSourceInfo();
290       if (TInfo->getType()->isIncompleteArrayType())
291         TypeDependent = true;
292     }
293 
294     return;
295   }
296 
297   // (VD) - FIXME: Missing from the standard:
298   //      -  a member function or a static data member of the current
299   //         instantiation
300   if (isa<CXXMethodDecl>(D) && D->getDeclContext()->isDependentContext()) {
301     ValueDependent = true;
302     InstantiationDependent = true;
303   }
304 }
305 
computeDependence(const ASTContext & Ctx)306 void DeclRefExpr::computeDependence(const ASTContext &Ctx) {
307   bool TypeDependent = false;
308   bool ValueDependent = false;
309   bool InstantiationDependent = false;
310   computeDeclRefDependence(Ctx, getDecl(), getType(), TypeDependent,
311                            ValueDependent, InstantiationDependent);
312 
313   ExprBits.TypeDependent |= TypeDependent;
314   ExprBits.ValueDependent |= ValueDependent;
315   ExprBits.InstantiationDependent |= InstantiationDependent;
316 
317   // Is the declaration a parameter pack?
318   if (getDecl()->isParameterPack())
319     ExprBits.ContainsUnexpandedParameterPack = true;
320 }
321 
DeclRefExpr(const ASTContext & Ctx,NestedNameSpecifierLoc QualifierLoc,SourceLocation TemplateKWLoc,ValueDecl * D,bool RefersToEnclosingVariableOrCapture,const DeclarationNameInfo & NameInfo,NamedDecl * FoundD,const TemplateArgumentListInfo * TemplateArgs,QualType T,ExprValueKind VK)322 DeclRefExpr::DeclRefExpr(const ASTContext &Ctx,
323                          NestedNameSpecifierLoc QualifierLoc,
324                          SourceLocation TemplateKWLoc,
325                          ValueDecl *D, bool RefersToEnclosingVariableOrCapture,
326                          const DeclarationNameInfo &NameInfo,
327                          NamedDecl *FoundD,
328                          const TemplateArgumentListInfo *TemplateArgs,
329                          QualType T, ExprValueKind VK)
330   : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
331     D(D), Loc(NameInfo.getLoc()), DNLoc(NameInfo.getInfo()) {
332   DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0;
333   if (QualifierLoc) {
334     getInternalQualifierLoc() = QualifierLoc;
335     auto *NNS = QualifierLoc.getNestedNameSpecifier();
336     if (NNS->isInstantiationDependent())
337       ExprBits.InstantiationDependent = true;
338     if (NNS->containsUnexpandedParameterPack())
339       ExprBits.ContainsUnexpandedParameterPack = true;
340   }
341   DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0;
342   if (FoundD)
343     getInternalFoundDecl() = FoundD;
344   DeclRefExprBits.HasTemplateKWAndArgsInfo
345     = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0;
346   DeclRefExprBits.RefersToEnclosingVariableOrCapture =
347       RefersToEnclosingVariableOrCapture;
348   if (TemplateArgs) {
349     bool Dependent = false;
350     bool InstantiationDependent = false;
351     bool ContainsUnexpandedParameterPack = false;
352     getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc, *TemplateArgs,
353                                                Dependent,
354                                                InstantiationDependent,
355                                                ContainsUnexpandedParameterPack);
356     assert(!Dependent && "built a DeclRefExpr with dependent template args");
357     ExprBits.InstantiationDependent |= InstantiationDependent;
358     ExprBits.ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack;
359   } else if (TemplateKWLoc.isValid()) {
360     getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc);
361   }
362   DeclRefExprBits.HadMultipleCandidates = 0;
363 
364   computeDependence(Ctx);
365 }
366 
Create(const ASTContext & Context,NestedNameSpecifierLoc QualifierLoc,SourceLocation TemplateKWLoc,ValueDecl * D,bool RefersToEnclosingVariableOrCapture,SourceLocation NameLoc,QualType T,ExprValueKind VK,NamedDecl * FoundD,const TemplateArgumentListInfo * TemplateArgs)367 DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
368                                  NestedNameSpecifierLoc QualifierLoc,
369                                  SourceLocation TemplateKWLoc,
370                                  ValueDecl *D,
371                                  bool RefersToEnclosingVariableOrCapture,
372                                  SourceLocation NameLoc,
373                                  QualType T,
374                                  ExprValueKind VK,
375                                  NamedDecl *FoundD,
376                                  const TemplateArgumentListInfo *TemplateArgs) {
377   return Create(Context, QualifierLoc, TemplateKWLoc, D,
378                 RefersToEnclosingVariableOrCapture,
379                 DeclarationNameInfo(D->getDeclName(), NameLoc),
380                 T, VK, FoundD, TemplateArgs);
381 }
382 
Create(const ASTContext & Context,NestedNameSpecifierLoc QualifierLoc,SourceLocation TemplateKWLoc,ValueDecl * D,bool RefersToEnclosingVariableOrCapture,const DeclarationNameInfo & NameInfo,QualType T,ExprValueKind VK,NamedDecl * FoundD,const TemplateArgumentListInfo * TemplateArgs)383 DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
384                                  NestedNameSpecifierLoc QualifierLoc,
385                                  SourceLocation TemplateKWLoc,
386                                  ValueDecl *D,
387                                  bool RefersToEnclosingVariableOrCapture,
388                                  const DeclarationNameInfo &NameInfo,
389                                  QualType T,
390                                  ExprValueKind VK,
391                                  NamedDecl *FoundD,
392                                  const TemplateArgumentListInfo *TemplateArgs) {
393   // Filter out cases where the found Decl is the same as the value refenenced.
394   if (D == FoundD)
395     FoundD = nullptr;
396 
397   std::size_t Size = sizeof(DeclRefExpr);
398   if (QualifierLoc)
399     Size += sizeof(NestedNameSpecifierLoc);
400   if (FoundD)
401     Size += sizeof(NamedDecl *);
402   if (TemplateArgs) {
403     Size = llvm::RoundUpToAlignment(Size,
404                                     llvm::alignOf<ASTTemplateKWAndArgsInfo>());
405     Size += ASTTemplateKWAndArgsInfo::sizeFor(TemplateArgs->size());
406   } else if (TemplateKWLoc.isValid()) {
407     Size = llvm::RoundUpToAlignment(Size,
408                                     llvm::alignOf<ASTTemplateKWAndArgsInfo>());
409     Size += ASTTemplateKWAndArgsInfo::sizeFor(0);
410   }
411 
412   void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>());
413   return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D,
414                                RefersToEnclosingVariableOrCapture,
415                                NameInfo, FoundD, TemplateArgs, T, VK);
416 }
417 
CreateEmpty(const ASTContext & Context,bool HasQualifier,bool HasFoundDecl,bool HasTemplateKWAndArgsInfo,unsigned NumTemplateArgs)418 DeclRefExpr *DeclRefExpr::CreateEmpty(const ASTContext &Context,
419                                       bool HasQualifier,
420                                       bool HasFoundDecl,
421                                       bool HasTemplateKWAndArgsInfo,
422                                       unsigned NumTemplateArgs) {
423   std::size_t Size = sizeof(DeclRefExpr);
424   if (HasQualifier)
425     Size += sizeof(NestedNameSpecifierLoc);
426   if (HasFoundDecl)
427     Size += sizeof(NamedDecl *);
428   if (HasTemplateKWAndArgsInfo) {
429     Size = llvm::RoundUpToAlignment(Size,
430                                     llvm::alignOf<ASTTemplateKWAndArgsInfo>());
431     Size += ASTTemplateKWAndArgsInfo::sizeFor(NumTemplateArgs);
432   }
433 
434   void *Mem = Context.Allocate(Size, llvm::alignOf<DeclRefExpr>());
435   return new (Mem) DeclRefExpr(EmptyShell());
436 }
437 
getLocStart() const438 SourceLocation DeclRefExpr::getLocStart() const {
439   if (hasQualifier())
440     return getQualifierLoc().getBeginLoc();
441   return getNameInfo().getLocStart();
442 }
getLocEnd() const443 SourceLocation DeclRefExpr::getLocEnd() const {
444   if (hasExplicitTemplateArgs())
445     return getRAngleLoc();
446   return getNameInfo().getLocEnd();
447 }
448 
PredefinedExpr(SourceLocation L,QualType FNTy,IdentType IT,StringLiteral * SL)449 PredefinedExpr::PredefinedExpr(SourceLocation L, QualType FNTy, IdentType IT,
450                                StringLiteral *SL)
451     : Expr(PredefinedExprClass, FNTy, VK_LValue, OK_Ordinary,
452            FNTy->isDependentType(), FNTy->isDependentType(),
453            FNTy->isInstantiationDependentType(),
454            /*ContainsUnexpandedParameterPack=*/false),
455       Loc(L), Type(IT), FnName(SL) {}
456 
getFunctionName()457 StringLiteral *PredefinedExpr::getFunctionName() {
458   return cast_or_null<StringLiteral>(FnName);
459 }
460 
getIdentTypeName(PredefinedExpr::IdentType IT)461 StringRef PredefinedExpr::getIdentTypeName(PredefinedExpr::IdentType IT) {
462   switch (IT) {
463   case Func:
464     return "__func__";
465   case Function:
466     return "__FUNCTION__";
467   case FuncDName:
468     return "__FUNCDNAME__";
469   case LFunction:
470     return "L__FUNCTION__";
471   case PrettyFunction:
472     return "__PRETTY_FUNCTION__";
473   case FuncSig:
474     return "__FUNCSIG__";
475   case PrettyFunctionNoVirtual:
476     break;
477   }
478   llvm_unreachable("Unknown ident type for PredefinedExpr");
479 }
480 
481 // FIXME: Maybe this should use DeclPrinter with a special "print predefined
482 // expr" policy instead.
ComputeName(IdentType IT,const Decl * CurrentDecl)483 std::string PredefinedExpr::ComputeName(IdentType IT, const Decl *CurrentDecl) {
484   ASTContext &Context = CurrentDecl->getASTContext();
485 
486   if (IT == PredefinedExpr::FuncDName) {
487     if (const NamedDecl *ND = dyn_cast<NamedDecl>(CurrentDecl)) {
488       std::unique_ptr<MangleContext> MC;
489       MC.reset(Context.createMangleContext());
490 
491       if (MC->shouldMangleDeclName(ND)) {
492         SmallString<256> Buffer;
493         llvm::raw_svector_ostream Out(Buffer);
494         if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(ND))
495           MC->mangleCXXCtor(CD, Ctor_Base, Out);
496         else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(ND))
497           MC->mangleCXXDtor(DD, Dtor_Base, Out);
498         else
499           MC->mangleName(ND, Out);
500 
501         if (!Buffer.empty() && Buffer.front() == '\01')
502           return Buffer.substr(1);
503         return Buffer.str();
504       } else
505         return ND->getIdentifier()->getName();
506     }
507     return "";
508   }
509   if (auto *BD = dyn_cast<BlockDecl>(CurrentDecl)) {
510     std::unique_ptr<MangleContext> MC;
511     MC.reset(Context.createMangleContext());
512     SmallString<256> Buffer;
513     llvm::raw_svector_ostream Out(Buffer);
514     auto DC = CurrentDecl->getDeclContext();
515     if (DC->isFileContext())
516       MC->mangleGlobalBlock(BD, /*ID*/ nullptr, Out);
517     else if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
518       MC->mangleCtorBlock(CD, /*CT*/ Ctor_Complete, BD, Out);
519     else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
520       MC->mangleDtorBlock(DD, /*DT*/ Dtor_Complete, BD, Out);
521     else
522       MC->mangleBlock(DC, BD, Out);
523     return Out.str();
524   }
525   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
526     if (IT != PrettyFunction && IT != PrettyFunctionNoVirtual && IT != FuncSig)
527       return FD->getNameAsString();
528 
529     SmallString<256> Name;
530     llvm::raw_svector_ostream Out(Name);
531 
532     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
533       if (MD->isVirtual() && IT != PrettyFunctionNoVirtual)
534         Out << "virtual ";
535       if (MD->isStatic())
536         Out << "static ";
537     }
538 
539     PrintingPolicy Policy(Context.getLangOpts());
540     std::string Proto;
541     llvm::raw_string_ostream POut(Proto);
542 
543     const FunctionDecl *Decl = FD;
544     if (const FunctionDecl* Pattern = FD->getTemplateInstantiationPattern())
545       Decl = Pattern;
546     const FunctionType *AFT = Decl->getType()->getAs<FunctionType>();
547     const FunctionProtoType *FT = nullptr;
548     if (FD->hasWrittenPrototype())
549       FT = dyn_cast<FunctionProtoType>(AFT);
550 
551     if (IT == FuncSig) {
552       switch (FT->getCallConv()) {
553       case CC_C: POut << "__cdecl "; break;
554       case CC_X86StdCall: POut << "__stdcall "; break;
555       case CC_X86FastCall: POut << "__fastcall "; break;
556       case CC_X86ThisCall: POut << "__thiscall "; break;
557       case CC_X86VectorCall: POut << "__vectorcall "; break;
558       // Only bother printing the conventions that MSVC knows about.
559       default: break;
560       }
561     }
562 
563     FD->printQualifiedName(POut, Policy);
564 
565     POut << "(";
566     if (FT) {
567       for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) {
568         if (i) POut << ", ";
569         POut << Decl->getParamDecl(i)->getType().stream(Policy);
570       }
571 
572       if (FT->isVariadic()) {
573         if (FD->getNumParams()) POut << ", ";
574         POut << "...";
575       }
576     }
577     POut << ")";
578 
579     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
580       const FunctionType *FT = MD->getType()->castAs<FunctionType>();
581       if (FT->isConst())
582         POut << " const";
583       if (FT->isVolatile())
584         POut << " volatile";
585       RefQualifierKind Ref = MD->getRefQualifier();
586       if (Ref == RQ_LValue)
587         POut << " &";
588       else if (Ref == RQ_RValue)
589         POut << " &&";
590     }
591 
592     typedef SmallVector<const ClassTemplateSpecializationDecl *, 8> SpecsTy;
593     SpecsTy Specs;
594     const DeclContext *Ctx = FD->getDeclContext();
595     while (Ctx && isa<NamedDecl>(Ctx)) {
596       const ClassTemplateSpecializationDecl *Spec
597                                = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
598       if (Spec && !Spec->isExplicitSpecialization())
599         Specs.push_back(Spec);
600       Ctx = Ctx->getParent();
601     }
602 
603     std::string TemplateParams;
604     llvm::raw_string_ostream TOut(TemplateParams);
605     for (SpecsTy::reverse_iterator I = Specs.rbegin(), E = Specs.rend();
606          I != E; ++I) {
607       const TemplateParameterList *Params
608                   = (*I)->getSpecializedTemplate()->getTemplateParameters();
609       const TemplateArgumentList &Args = (*I)->getTemplateArgs();
610       assert(Params->size() == Args.size());
611       for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) {
612         StringRef Param = Params->getParam(i)->getName();
613         if (Param.empty()) continue;
614         TOut << Param << " = ";
615         Args.get(i).print(Policy, TOut);
616         TOut << ", ";
617       }
618     }
619 
620     FunctionTemplateSpecializationInfo *FSI
621                                           = FD->getTemplateSpecializationInfo();
622     if (FSI && !FSI->isExplicitSpecialization()) {
623       const TemplateParameterList* Params
624                                   = FSI->getTemplate()->getTemplateParameters();
625       const TemplateArgumentList* Args = FSI->TemplateArguments;
626       assert(Params->size() == Args->size());
627       for (unsigned i = 0, e = Params->size(); i != e; ++i) {
628         StringRef Param = Params->getParam(i)->getName();
629         if (Param.empty()) continue;
630         TOut << Param << " = ";
631         Args->get(i).print(Policy, TOut);
632         TOut << ", ";
633       }
634     }
635 
636     TOut.flush();
637     if (!TemplateParams.empty()) {
638       // remove the trailing comma and space
639       TemplateParams.resize(TemplateParams.size() - 2);
640       POut << " [" << TemplateParams << "]";
641     }
642 
643     POut.flush();
644 
645     // Print "auto" for all deduced return types. This includes C++1y return
646     // type deduction and lambdas. For trailing return types resolve the
647     // decltype expression. Otherwise print the real type when this is
648     // not a constructor or destructor.
649     if (isa<CXXMethodDecl>(FD) &&
650          cast<CXXMethodDecl>(FD)->getParent()->isLambda())
651       Proto = "auto " + Proto;
652     else if (FT && FT->getReturnType()->getAs<DecltypeType>())
653       FT->getReturnType()
654           ->getAs<DecltypeType>()
655           ->getUnderlyingType()
656           .getAsStringInternal(Proto, Policy);
657     else if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
658       AFT->getReturnType().getAsStringInternal(Proto, Policy);
659 
660     Out << Proto;
661 
662     return Name.str().str();
663   }
664   if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(CurrentDecl)) {
665     for (const DeclContext *DC = CD->getParent(); DC; DC = DC->getParent())
666       // Skip to its enclosing function or method, but not its enclosing
667       // CapturedDecl.
668       if (DC->isFunctionOrMethod() && (DC->getDeclKind() != Decl::Captured)) {
669         const Decl *D = Decl::castFromDeclContext(DC);
670         return ComputeName(IT, D);
671       }
672     llvm_unreachable("CapturedDecl not inside a function or method");
673   }
674   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
675     SmallString<256> Name;
676     llvm::raw_svector_ostream Out(Name);
677     Out << (MD->isInstanceMethod() ? '-' : '+');
678     Out << '[';
679 
680     // For incorrect code, there might not be an ObjCInterfaceDecl.  Do
681     // a null check to avoid a crash.
682     if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
683       Out << *ID;
684 
685     if (const ObjCCategoryImplDecl *CID =
686         dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
687       Out << '(' << *CID << ')';
688 
689     Out <<  ' ';
690     MD->getSelector().print(Out);
691     Out <<  ']';
692 
693     return Name.str().str();
694   }
695   if (isa<TranslationUnitDecl>(CurrentDecl) && IT == PrettyFunction) {
696     // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
697     return "top level";
698   }
699   return "";
700 }
701 
setIntValue(const ASTContext & C,const llvm::APInt & Val)702 void APNumericStorage::setIntValue(const ASTContext &C,
703                                    const llvm::APInt &Val) {
704   if (hasAllocation())
705     C.Deallocate(pVal);
706 
707   BitWidth = Val.getBitWidth();
708   unsigned NumWords = Val.getNumWords();
709   const uint64_t* Words = Val.getRawData();
710   if (NumWords > 1) {
711     pVal = new (C) uint64_t[NumWords];
712     std::copy(Words, Words + NumWords, pVal);
713   } else if (NumWords == 1)
714     VAL = Words[0];
715   else
716     VAL = 0;
717 }
718 
IntegerLiteral(const ASTContext & C,const llvm::APInt & V,QualType type,SourceLocation l)719 IntegerLiteral::IntegerLiteral(const ASTContext &C, const llvm::APInt &V,
720                                QualType type, SourceLocation l)
721   : Expr(IntegerLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
722          false, false),
723     Loc(l) {
724   assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
725   assert(V.getBitWidth() == C.getIntWidth(type) &&
726          "Integer type is not the correct size for constant.");
727   setValue(C, V);
728 }
729 
730 IntegerLiteral *
Create(const ASTContext & C,const llvm::APInt & V,QualType type,SourceLocation l)731 IntegerLiteral::Create(const ASTContext &C, const llvm::APInt &V,
732                        QualType type, SourceLocation l) {
733   return new (C) IntegerLiteral(C, V, type, l);
734 }
735 
736 IntegerLiteral *
Create(const ASTContext & C,EmptyShell Empty)737 IntegerLiteral::Create(const ASTContext &C, EmptyShell Empty) {
738   return new (C) IntegerLiteral(Empty);
739 }
740 
FloatingLiteral(const ASTContext & C,const llvm::APFloat & V,bool isexact,QualType Type,SourceLocation L)741 FloatingLiteral::FloatingLiteral(const ASTContext &C, const llvm::APFloat &V,
742                                  bool isexact, QualType Type, SourceLocation L)
743   : Expr(FloatingLiteralClass, Type, VK_RValue, OK_Ordinary, false, false,
744          false, false), Loc(L) {
745   setSemantics(V.getSemantics());
746   FloatingLiteralBits.IsExact = isexact;
747   setValue(C, V);
748 }
749 
FloatingLiteral(const ASTContext & C,EmptyShell Empty)750 FloatingLiteral::FloatingLiteral(const ASTContext &C, EmptyShell Empty)
751   : Expr(FloatingLiteralClass, Empty) {
752   setRawSemantics(IEEEhalf);
753   FloatingLiteralBits.IsExact = false;
754 }
755 
756 FloatingLiteral *
Create(const ASTContext & C,const llvm::APFloat & V,bool isexact,QualType Type,SourceLocation L)757 FloatingLiteral::Create(const ASTContext &C, const llvm::APFloat &V,
758                         bool isexact, QualType Type, SourceLocation L) {
759   return new (C) FloatingLiteral(C, V, isexact, Type, L);
760 }
761 
762 FloatingLiteral *
Create(const ASTContext & C,EmptyShell Empty)763 FloatingLiteral::Create(const ASTContext &C, EmptyShell Empty) {
764   return new (C) FloatingLiteral(C, Empty);
765 }
766 
getSemantics() const767 const llvm::fltSemantics &FloatingLiteral::getSemantics() const {
768   switch(FloatingLiteralBits.Semantics) {
769   case IEEEhalf:
770     return llvm::APFloat::IEEEhalf;
771   case IEEEsingle:
772     return llvm::APFloat::IEEEsingle;
773   case IEEEdouble:
774     return llvm::APFloat::IEEEdouble;
775   case x87DoubleExtended:
776     return llvm::APFloat::x87DoubleExtended;
777   case IEEEquad:
778     return llvm::APFloat::IEEEquad;
779   case PPCDoubleDouble:
780     return llvm::APFloat::PPCDoubleDouble;
781   }
782   llvm_unreachable("Unrecognised floating semantics");
783 }
784 
setSemantics(const llvm::fltSemantics & Sem)785 void FloatingLiteral::setSemantics(const llvm::fltSemantics &Sem) {
786   if (&Sem == &llvm::APFloat::IEEEhalf)
787     FloatingLiteralBits.Semantics = IEEEhalf;
788   else if (&Sem == &llvm::APFloat::IEEEsingle)
789     FloatingLiteralBits.Semantics = IEEEsingle;
790   else if (&Sem == &llvm::APFloat::IEEEdouble)
791     FloatingLiteralBits.Semantics = IEEEdouble;
792   else if (&Sem == &llvm::APFloat::x87DoubleExtended)
793     FloatingLiteralBits.Semantics = x87DoubleExtended;
794   else if (&Sem == &llvm::APFloat::IEEEquad)
795     FloatingLiteralBits.Semantics = IEEEquad;
796   else if (&Sem == &llvm::APFloat::PPCDoubleDouble)
797     FloatingLiteralBits.Semantics = PPCDoubleDouble;
798   else
799     llvm_unreachable("Unknown floating semantics");
800 }
801 
802 /// getValueAsApproximateDouble - This returns the value as an inaccurate
803 /// double.  Note that this may cause loss of precision, but is useful for
804 /// debugging dumps, etc.
getValueAsApproximateDouble() const805 double FloatingLiteral::getValueAsApproximateDouble() const {
806   llvm::APFloat V = getValue();
807   bool ignored;
808   V.convert(llvm::APFloat::IEEEdouble, llvm::APFloat::rmNearestTiesToEven,
809             &ignored);
810   return V.convertToDouble();
811 }
812 
mapCharByteWidth(TargetInfo const & target,StringKind k)813 int StringLiteral::mapCharByteWidth(TargetInfo const &target,StringKind k) {
814   int CharByteWidth = 0;
815   switch(k) {
816     case Ascii:
817     case UTF8:
818       CharByteWidth = target.getCharWidth();
819       break;
820     case Wide:
821       CharByteWidth = target.getWCharWidth();
822       break;
823     case UTF16:
824       CharByteWidth = target.getChar16Width();
825       break;
826     case UTF32:
827       CharByteWidth = target.getChar32Width();
828       break;
829   }
830   assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
831   CharByteWidth /= 8;
832   assert((CharByteWidth==1 || CharByteWidth==2 || CharByteWidth==4)
833          && "character byte widths supported are 1, 2, and 4 only");
834   return CharByteWidth;
835 }
836 
Create(const ASTContext & C,StringRef Str,StringKind Kind,bool Pascal,QualType Ty,const SourceLocation * Loc,unsigned NumStrs)837 StringLiteral *StringLiteral::Create(const ASTContext &C, StringRef Str,
838                                      StringKind Kind, bool Pascal, QualType Ty,
839                                      const SourceLocation *Loc,
840                                      unsigned NumStrs) {
841   assert(C.getAsConstantArrayType(Ty) &&
842          "StringLiteral must be of constant array type!");
843 
844   // Allocate enough space for the StringLiteral plus an array of locations for
845   // any concatenated string tokens.
846   void *Mem = C.Allocate(sizeof(StringLiteral)+
847                          sizeof(SourceLocation)*(NumStrs-1),
848                          llvm::alignOf<StringLiteral>());
849   StringLiteral *SL = new (Mem) StringLiteral(Ty);
850 
851   // OPTIMIZE: could allocate this appended to the StringLiteral.
852   SL->setString(C,Str,Kind,Pascal);
853 
854   SL->TokLocs[0] = Loc[0];
855   SL->NumConcatenated = NumStrs;
856 
857   if (NumStrs != 1)
858     memcpy(&SL->TokLocs[1], Loc+1, sizeof(SourceLocation)*(NumStrs-1));
859   return SL;
860 }
861 
CreateEmpty(const ASTContext & C,unsigned NumStrs)862 StringLiteral *StringLiteral::CreateEmpty(const ASTContext &C,
863                                           unsigned NumStrs) {
864   void *Mem = C.Allocate(sizeof(StringLiteral)+
865                          sizeof(SourceLocation)*(NumStrs-1),
866                          llvm::alignOf<StringLiteral>());
867   StringLiteral *SL = new (Mem) StringLiteral(QualType());
868   SL->CharByteWidth = 0;
869   SL->Length = 0;
870   SL->NumConcatenated = NumStrs;
871   return SL;
872 }
873 
outputString(raw_ostream & OS) const874 void StringLiteral::outputString(raw_ostream &OS) const {
875   switch (getKind()) {
876   case Ascii: break; // no prefix.
877   case Wide:  OS << 'L'; break;
878   case UTF8:  OS << "u8"; break;
879   case UTF16: OS << 'u'; break;
880   case UTF32: OS << 'U'; break;
881   }
882   OS << '"';
883   static const char Hex[] = "0123456789ABCDEF";
884 
885   unsigned LastSlashX = getLength();
886   for (unsigned I = 0, N = getLength(); I != N; ++I) {
887     switch (uint32_t Char = getCodeUnit(I)) {
888     default:
889       // FIXME: Convert UTF-8 back to codepoints before rendering.
890 
891       // Convert UTF-16 surrogate pairs back to codepoints before rendering.
892       // Leave invalid surrogates alone; we'll use \x for those.
893       if (getKind() == UTF16 && I != N - 1 && Char >= 0xd800 &&
894           Char <= 0xdbff) {
895         uint32_t Trail = getCodeUnit(I + 1);
896         if (Trail >= 0xdc00 && Trail <= 0xdfff) {
897           Char = 0x10000 + ((Char - 0xd800) << 10) + (Trail - 0xdc00);
898           ++I;
899         }
900       }
901 
902       if (Char > 0xff) {
903         // If this is a wide string, output characters over 0xff using \x
904         // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is a
905         // codepoint: use \x escapes for invalid codepoints.
906         if (getKind() == Wide ||
907             (Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) {
908           // FIXME: Is this the best way to print wchar_t?
909           OS << "\\x";
910           int Shift = 28;
911           while ((Char >> Shift) == 0)
912             Shift -= 4;
913           for (/**/; Shift >= 0; Shift -= 4)
914             OS << Hex[(Char >> Shift) & 15];
915           LastSlashX = I;
916           break;
917         }
918 
919         if (Char > 0xffff)
920           OS << "\\U00"
921              << Hex[(Char >> 20) & 15]
922              << Hex[(Char >> 16) & 15];
923         else
924           OS << "\\u";
925         OS << Hex[(Char >> 12) & 15]
926            << Hex[(Char >>  8) & 15]
927            << Hex[(Char >>  4) & 15]
928            << Hex[(Char >>  0) & 15];
929         break;
930       }
931 
932       // If we used \x... for the previous character, and this character is a
933       // hexadecimal digit, prevent it being slurped as part of the \x.
934       if (LastSlashX + 1 == I) {
935         switch (Char) {
936           case '0': case '1': case '2': case '3': case '4':
937           case '5': case '6': case '7': case '8': case '9':
938           case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
939           case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
940             OS << "\"\"";
941         }
942       }
943 
944       assert(Char <= 0xff &&
945              "Characters above 0xff should already have been handled.");
946 
947       if (isPrintable(Char))
948         OS << (char)Char;
949       else  // Output anything hard as an octal escape.
950         OS << '\\'
951            << (char)('0' + ((Char >> 6) & 7))
952            << (char)('0' + ((Char >> 3) & 7))
953            << (char)('0' + ((Char >> 0) & 7));
954       break;
955     // Handle some common non-printable cases to make dumps prettier.
956     case '\\': OS << "\\\\"; break;
957     case '"': OS << "\\\""; break;
958     case '\n': OS << "\\n"; break;
959     case '\t': OS << "\\t"; break;
960     case '\a': OS << "\\a"; break;
961     case '\b': OS << "\\b"; break;
962     }
963   }
964   OS << '"';
965 }
966 
setString(const ASTContext & C,StringRef Str,StringKind Kind,bool IsPascal)967 void StringLiteral::setString(const ASTContext &C, StringRef Str,
968                               StringKind Kind, bool IsPascal) {
969   //FIXME: we assume that the string data comes from a target that uses the same
970   // code unit size and endianess for the type of string.
971   this->Kind = Kind;
972   this->IsPascal = IsPascal;
973 
974   CharByteWidth = mapCharByteWidth(C.getTargetInfo(),Kind);
975   assert((Str.size()%CharByteWidth == 0)
976          && "size of data must be multiple of CharByteWidth");
977   Length = Str.size()/CharByteWidth;
978 
979   switch(CharByteWidth) {
980     case 1: {
981       char *AStrData = new (C) char[Length];
982       std::memcpy(AStrData,Str.data(),Length*sizeof(*AStrData));
983       StrData.asChar = AStrData;
984       break;
985     }
986     case 2: {
987       uint16_t *AStrData = new (C) uint16_t[Length];
988       std::memcpy(AStrData,Str.data(),Length*sizeof(*AStrData));
989       StrData.asUInt16 = AStrData;
990       break;
991     }
992     case 4: {
993       uint32_t *AStrData = new (C) uint32_t[Length];
994       std::memcpy(AStrData,Str.data(),Length*sizeof(*AStrData));
995       StrData.asUInt32 = AStrData;
996       break;
997     }
998     default:
999       assert(false && "unsupported CharByteWidth");
1000   }
1001 }
1002 
1003 /// getLocationOfByte - Return a source location that points to the specified
1004 /// byte of this string literal.
1005 ///
1006 /// Strings are amazingly complex.  They can be formed from multiple tokens and
1007 /// can have escape sequences in them in addition to the usual trigraph and
1008 /// escaped newline business.  This routine handles this complexity.
1009 ///
1010 /// The *StartToken sets the first token to be searched in this function and
1011 /// the *StartTokenByteOffset is the byte offset of the first token. Before
1012 /// returning, it updates the *StartToken to the TokNo of the token being found
1013 /// and sets *StartTokenByteOffset to the byte offset of the token in the
1014 /// string.
1015 /// Using these two parameters can reduce the time complexity from O(n^2) to
1016 /// O(n) if one wants to get the location of byte for all the tokens in a
1017 /// string.
1018 ///
1019 SourceLocation
getLocationOfByte(unsigned ByteNo,const SourceManager & SM,const LangOptions & Features,const TargetInfo & Target,unsigned * StartToken,unsigned * StartTokenByteOffset) const1020 StringLiteral::getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1021                                  const LangOptions &Features,
1022                                  const TargetInfo &Target, unsigned *StartToken,
1023                                  unsigned *StartTokenByteOffset) const {
1024   assert((Kind == StringLiteral::Ascii || Kind == StringLiteral::UTF8) &&
1025          "Only narrow string literals are currently supported");
1026 
1027   // Loop over all of the tokens in this string until we find the one that
1028   // contains the byte we're looking for.
1029   unsigned TokNo = 0;
1030   unsigned StringOffset = 0;
1031   if (StartToken)
1032     TokNo = *StartToken;
1033   if (StartTokenByteOffset) {
1034     StringOffset = *StartTokenByteOffset;
1035     ByteNo -= StringOffset;
1036   }
1037   while (1) {
1038     assert(TokNo < getNumConcatenated() && "Invalid byte number!");
1039     SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
1040 
1041     // Get the spelling of the string so that we can get the data that makes up
1042     // the string literal, not the identifier for the macro it is potentially
1043     // expanded through.
1044     SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
1045 
1046     // Re-lex the token to get its length and original spelling.
1047     std::pair<FileID, unsigned> LocInfo =
1048         SM.getDecomposedLoc(StrTokSpellingLoc);
1049     bool Invalid = false;
1050     StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
1051     if (Invalid) {
1052       if (StartTokenByteOffset != nullptr)
1053         *StartTokenByteOffset = StringOffset;
1054       if (StartToken != nullptr)
1055         *StartToken = TokNo;
1056       return StrTokSpellingLoc;
1057     }
1058 
1059     const char *StrData = Buffer.data()+LocInfo.second;
1060 
1061     // Create a lexer starting at the beginning of this token.
1062     Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features,
1063                    Buffer.begin(), StrData, Buffer.end());
1064     Token TheTok;
1065     TheLexer.LexFromRawLexer(TheTok);
1066 
1067     // Use the StringLiteralParser to compute the length of the string in bytes.
1068     StringLiteralParser SLP(TheTok, SM, Features, Target);
1069     unsigned TokNumBytes = SLP.GetStringLength();
1070 
1071     // If the byte is in this token, return the location of the byte.
1072     if (ByteNo < TokNumBytes ||
1073         (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {
1074       unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
1075 
1076       // Now that we know the offset of the token in the spelling, use the
1077       // preprocessor to get the offset in the original source.
1078       if (StartTokenByteOffset != nullptr)
1079         *StartTokenByteOffset = StringOffset;
1080       if (StartToken != nullptr)
1081         *StartToken = TokNo;
1082       return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
1083     }
1084 
1085     // Move to the next string token.
1086     StringOffset += TokNumBytes;
1087     ++TokNo;
1088     ByteNo -= TokNumBytes;
1089   }
1090 }
1091 
1092 
1093 
1094 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1095 /// corresponds to, e.g. "sizeof" or "[pre]++".
getOpcodeStr(Opcode Op)1096 StringRef UnaryOperator::getOpcodeStr(Opcode Op) {
1097   switch (Op) {
1098   case UO_PostInc: return "++";
1099   case UO_PostDec: return "--";
1100   case UO_PreInc:  return "++";
1101   case UO_PreDec:  return "--";
1102   case UO_AddrOf:  return "&";
1103   case UO_Deref:   return "*";
1104   case UO_Plus:    return "+";
1105   case UO_Minus:   return "-";
1106   case UO_Not:     return "~";
1107   case UO_LNot:    return "!";
1108   case UO_Real:    return "__real";
1109   case UO_Imag:    return "__imag";
1110   case UO_Extension: return "__extension__";
1111   case UO_Coawait: return "co_await";
1112   }
1113   llvm_unreachable("Unknown unary operator");
1114 }
1115 
1116 UnaryOperatorKind
getOverloadedOpcode(OverloadedOperatorKind OO,bool Postfix)1117 UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {
1118   switch (OO) {
1119   default: llvm_unreachable("No unary operator for overloaded function");
1120   case OO_PlusPlus:   return Postfix ? UO_PostInc : UO_PreInc;
1121   case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
1122   case OO_Amp:        return UO_AddrOf;
1123   case OO_Star:       return UO_Deref;
1124   case OO_Plus:       return UO_Plus;
1125   case OO_Minus:      return UO_Minus;
1126   case OO_Tilde:      return UO_Not;
1127   case OO_Exclaim:    return UO_LNot;
1128   case OO_Coawait:    return UO_Coawait;
1129   }
1130 }
1131 
getOverloadedOperator(Opcode Opc)1132 OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {
1133   switch (Opc) {
1134   case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
1135   case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
1136   case UO_AddrOf: return OO_Amp;
1137   case UO_Deref: return OO_Star;
1138   case UO_Plus: return OO_Plus;
1139   case UO_Minus: return OO_Minus;
1140   case UO_Not: return OO_Tilde;
1141   case UO_LNot: return OO_Exclaim;
1142   case UO_Coawait: return OO_Coawait;
1143   default: return OO_None;
1144   }
1145 }
1146 
1147 
1148 //===----------------------------------------------------------------------===//
1149 // Postfix Operators.
1150 //===----------------------------------------------------------------------===//
1151 
CallExpr(const ASTContext & C,StmtClass SC,Expr * fn,unsigned NumPreArgs,ArrayRef<Expr * > args,QualType t,ExprValueKind VK,SourceLocation rparenloc)1152 CallExpr::CallExpr(const ASTContext& C, StmtClass SC, Expr *fn,
1153                    unsigned NumPreArgs, ArrayRef<Expr*> args, QualType t,
1154                    ExprValueKind VK, SourceLocation rparenloc)
1155   : Expr(SC, t, VK, OK_Ordinary,
1156          fn->isTypeDependent(),
1157          fn->isValueDependent(),
1158          fn->isInstantiationDependent(),
1159          fn->containsUnexpandedParameterPack()),
1160     NumArgs(args.size()) {
1161 
1162   SubExprs = new (C) Stmt*[args.size()+PREARGS_START+NumPreArgs];
1163   SubExprs[FN] = fn;
1164   for (unsigned i = 0; i != args.size(); ++i) {
1165     if (args[i]->isTypeDependent())
1166       ExprBits.TypeDependent = true;
1167     if (args[i]->isValueDependent())
1168       ExprBits.ValueDependent = true;
1169     if (args[i]->isInstantiationDependent())
1170       ExprBits.InstantiationDependent = true;
1171     if (args[i]->containsUnexpandedParameterPack())
1172       ExprBits.ContainsUnexpandedParameterPack = true;
1173 
1174     SubExprs[i+PREARGS_START+NumPreArgs] = args[i];
1175   }
1176 
1177   CallExprBits.NumPreArgs = NumPreArgs;
1178   RParenLoc = rparenloc;
1179 }
1180 
CallExpr(const ASTContext & C,Expr * fn,ArrayRef<Expr * > args,QualType t,ExprValueKind VK,SourceLocation rparenloc)1181 CallExpr::CallExpr(const ASTContext &C, Expr *fn, ArrayRef<Expr *> args,
1182                    QualType t, ExprValueKind VK, SourceLocation rparenloc)
1183     : CallExpr(C, CallExprClass, fn, /*NumPreArgs=*/0, args, t, VK, rparenloc) {
1184 }
1185 
CallExpr(const ASTContext & C,StmtClass SC,EmptyShell Empty)1186 CallExpr::CallExpr(const ASTContext &C, StmtClass SC, EmptyShell Empty)
1187     : CallExpr(C, SC, /*NumPreArgs=*/0, Empty) {}
1188 
CallExpr(const ASTContext & C,StmtClass SC,unsigned NumPreArgs,EmptyShell Empty)1189 CallExpr::CallExpr(const ASTContext &C, StmtClass SC, unsigned NumPreArgs,
1190                    EmptyShell Empty)
1191   : Expr(SC, Empty), SubExprs(nullptr), NumArgs(0) {
1192   // FIXME: Why do we allocate this?
1193   SubExprs = new (C) Stmt*[PREARGS_START+NumPreArgs];
1194   CallExprBits.NumPreArgs = NumPreArgs;
1195 }
1196 
getCalleeDecl()1197 Decl *CallExpr::getCalleeDecl() {
1198   Expr *CEE = getCallee()->IgnoreParenImpCasts();
1199 
1200   while (SubstNonTypeTemplateParmExpr *NTTP
1201                                 = dyn_cast<SubstNonTypeTemplateParmExpr>(CEE)) {
1202     CEE = NTTP->getReplacement()->IgnoreParenCasts();
1203   }
1204 
1205   // If we're calling a dereference, look at the pointer instead.
1206   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CEE)) {
1207     if (BO->isPtrMemOp())
1208       CEE = BO->getRHS()->IgnoreParenCasts();
1209   } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(CEE)) {
1210     if (UO->getOpcode() == UO_Deref)
1211       CEE = UO->getSubExpr()->IgnoreParenCasts();
1212   }
1213   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE))
1214     return DRE->getDecl();
1215   if (MemberExpr *ME = dyn_cast<MemberExpr>(CEE))
1216     return ME->getMemberDecl();
1217 
1218   return nullptr;
1219 }
1220 
getDirectCallee()1221 FunctionDecl *CallExpr::getDirectCallee() {
1222   return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
1223 }
1224 
1225 /// setNumArgs - This changes the number of arguments present in this call.
1226 /// Any orphaned expressions are deleted by this, and any new operands are set
1227 /// to null.
setNumArgs(const ASTContext & C,unsigned NumArgs)1228 void CallExpr::setNumArgs(const ASTContext& C, unsigned NumArgs) {
1229   // No change, just return.
1230   if (NumArgs == getNumArgs()) return;
1231 
1232   // If shrinking # arguments, just delete the extras and forgot them.
1233   if (NumArgs < getNumArgs()) {
1234     this->NumArgs = NumArgs;
1235     return;
1236   }
1237 
1238   // Otherwise, we are growing the # arguments.  New an bigger argument array.
1239   unsigned NumPreArgs = getNumPreArgs();
1240   Stmt **NewSubExprs = new (C) Stmt*[NumArgs+PREARGS_START+NumPreArgs];
1241   // Copy over args.
1242   for (unsigned i = 0; i != getNumArgs()+PREARGS_START+NumPreArgs; ++i)
1243     NewSubExprs[i] = SubExprs[i];
1244   // Null out new args.
1245   for (unsigned i = getNumArgs()+PREARGS_START+NumPreArgs;
1246        i != NumArgs+PREARGS_START+NumPreArgs; ++i)
1247     NewSubExprs[i] = nullptr;
1248 
1249   if (SubExprs) C.Deallocate(SubExprs);
1250   SubExprs = NewSubExprs;
1251   this->NumArgs = NumArgs;
1252 }
1253 
1254 /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID. If
1255 /// not, return 0.
getBuiltinCallee() const1256 unsigned CallExpr::getBuiltinCallee() const {
1257   // All simple function calls (e.g. func()) are implicitly cast to pointer to
1258   // function. As a result, we try and obtain the DeclRefExpr from the
1259   // ImplicitCastExpr.
1260   const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(getCallee());
1261   if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()).
1262     return 0;
1263 
1264   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
1265   if (!DRE)
1266     return 0;
1267 
1268   const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
1269   if (!FDecl)
1270     return 0;
1271 
1272   if (!FDecl->getIdentifier())
1273     return 0;
1274 
1275   return FDecl->getBuiltinID();
1276 }
1277 
isUnevaluatedBuiltinCall(const ASTContext & Ctx) const1278 bool CallExpr::isUnevaluatedBuiltinCall(const ASTContext &Ctx) const {
1279   if (unsigned BI = getBuiltinCallee())
1280     return Ctx.BuiltinInfo.isUnevaluated(BI);
1281   return false;
1282 }
1283 
getCallReturnType(const ASTContext & Ctx) const1284 QualType CallExpr::getCallReturnType(const ASTContext &Ctx) const {
1285   const Expr *Callee = getCallee();
1286   QualType CalleeType = Callee->getType();
1287   if (const auto *FnTypePtr = CalleeType->getAs<PointerType>()) {
1288     CalleeType = FnTypePtr->getPointeeType();
1289   } else if (const auto *BPT = CalleeType->getAs<BlockPointerType>()) {
1290     CalleeType = BPT->getPointeeType();
1291   } else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
1292     if (isa<CXXPseudoDestructorExpr>(Callee->IgnoreParens()))
1293       return Ctx.VoidTy;
1294 
1295     // This should never be overloaded and so should never return null.
1296     CalleeType = Expr::findBoundMemberType(Callee);
1297   }
1298 
1299   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
1300   return FnType->getReturnType();
1301 }
1302 
getLocStart() const1303 SourceLocation CallExpr::getLocStart() const {
1304   if (isa<CXXOperatorCallExpr>(this))
1305     return cast<CXXOperatorCallExpr>(this)->getLocStart();
1306 
1307   SourceLocation begin = getCallee()->getLocStart();
1308   if (begin.isInvalid() && getNumArgs() > 0 && getArg(0))
1309     begin = getArg(0)->getLocStart();
1310   return begin;
1311 }
getLocEnd() const1312 SourceLocation CallExpr::getLocEnd() const {
1313   if (isa<CXXOperatorCallExpr>(this))
1314     return cast<CXXOperatorCallExpr>(this)->getLocEnd();
1315 
1316   SourceLocation end = getRParenLoc();
1317   if (end.isInvalid() && getNumArgs() > 0 && getArg(getNumArgs() - 1))
1318     end = getArg(getNumArgs() - 1)->getLocEnd();
1319   return end;
1320 }
1321 
Create(const ASTContext & C,QualType type,SourceLocation OperatorLoc,TypeSourceInfo * tsi,ArrayRef<OffsetOfNode> comps,ArrayRef<Expr * > exprs,SourceLocation RParenLoc)1322 OffsetOfExpr *OffsetOfExpr::Create(const ASTContext &C, QualType type,
1323                                    SourceLocation OperatorLoc,
1324                                    TypeSourceInfo *tsi,
1325                                    ArrayRef<OffsetOfNode> comps,
1326                                    ArrayRef<Expr*> exprs,
1327                                    SourceLocation RParenLoc) {
1328   void *Mem = C.Allocate(sizeof(OffsetOfExpr) +
1329                          sizeof(OffsetOfNode) * comps.size() +
1330                          sizeof(Expr*) * exprs.size());
1331 
1332   return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs,
1333                                 RParenLoc);
1334 }
1335 
CreateEmpty(const ASTContext & C,unsigned numComps,unsigned numExprs)1336 OffsetOfExpr *OffsetOfExpr::CreateEmpty(const ASTContext &C,
1337                                         unsigned numComps, unsigned numExprs) {
1338   void *Mem = C.Allocate(sizeof(OffsetOfExpr) +
1339                          sizeof(OffsetOfNode) * numComps +
1340                          sizeof(Expr*) * numExprs);
1341   return new (Mem) OffsetOfExpr(numComps, numExprs);
1342 }
1343 
OffsetOfExpr(const ASTContext & C,QualType type,SourceLocation OperatorLoc,TypeSourceInfo * tsi,ArrayRef<OffsetOfNode> comps,ArrayRef<Expr * > exprs,SourceLocation RParenLoc)1344 OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type,
1345                            SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1346                            ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
1347                            SourceLocation RParenLoc)
1348   : Expr(OffsetOfExprClass, type, VK_RValue, OK_Ordinary,
1349          /*TypeDependent=*/false,
1350          /*ValueDependent=*/tsi->getType()->isDependentType(),
1351          tsi->getType()->isInstantiationDependentType(),
1352          tsi->getType()->containsUnexpandedParameterPack()),
1353     OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
1354     NumComps(comps.size()), NumExprs(exprs.size())
1355 {
1356   for (unsigned i = 0; i != comps.size(); ++i) {
1357     setComponent(i, comps[i]);
1358   }
1359 
1360   for (unsigned i = 0; i != exprs.size(); ++i) {
1361     if (exprs[i]->isTypeDependent() || exprs[i]->isValueDependent())
1362       ExprBits.ValueDependent = true;
1363     if (exprs[i]->containsUnexpandedParameterPack())
1364       ExprBits.ContainsUnexpandedParameterPack = true;
1365 
1366     setIndexExpr(i, exprs[i]);
1367   }
1368 }
1369 
getFieldName() const1370 IdentifierInfo *OffsetOfExpr::OffsetOfNode::getFieldName() const {
1371   assert(getKind() == Field || getKind() == Identifier);
1372   if (getKind() == Field)
1373     return getField()->getIdentifier();
1374 
1375   return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
1376 }
1377 
UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind,Expr * E,QualType resultType,SourceLocation op,SourceLocation rp)1378 UnaryExprOrTypeTraitExpr::UnaryExprOrTypeTraitExpr(
1379     UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType,
1380     SourceLocation op, SourceLocation rp)
1381     : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1382            false, // Never type-dependent (C++ [temp.dep.expr]p3).
1383            // Value-dependent if the argument is type-dependent.
1384            E->isTypeDependent(), E->isInstantiationDependent(),
1385            E->containsUnexpandedParameterPack()),
1386       OpLoc(op), RParenLoc(rp) {
1387   UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1388   UnaryExprOrTypeTraitExprBits.IsType = false;
1389   Argument.Ex = E;
1390 
1391   // Check to see if we are in the situation where alignof(decl) should be
1392   // dependent because decl's alignment is dependent.
1393   if (ExprKind == UETT_AlignOf) {
1394     if (!isValueDependent() || !isInstantiationDependent()) {
1395       E = E->IgnoreParens();
1396 
1397       const ValueDecl *D = nullptr;
1398       if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
1399         D = DRE->getDecl();
1400       else if (const auto *ME = dyn_cast<MemberExpr>(E))
1401         D = ME->getMemberDecl();
1402 
1403       if (D) {
1404         for (const auto *I : D->specific_attrs<AlignedAttr>()) {
1405           if (I->isAlignmentDependent()) {
1406             setValueDependent(true);
1407             setInstantiationDependent(true);
1408             break;
1409           }
1410         }
1411       }
1412     }
1413   }
1414 }
1415 
Create(const ASTContext & C,Expr * base,bool isarrow,SourceLocation OperatorLoc,NestedNameSpecifierLoc QualifierLoc,SourceLocation TemplateKWLoc,ValueDecl * memberdecl,DeclAccessPair founddecl,DeclarationNameInfo nameinfo,const TemplateArgumentListInfo * targs,QualType ty,ExprValueKind vk,ExprObjectKind ok)1416 MemberExpr *MemberExpr::Create(
1417     const ASTContext &C, Expr *base, bool isarrow, SourceLocation OperatorLoc,
1418     NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
1419     ValueDecl *memberdecl, DeclAccessPair founddecl,
1420     DeclarationNameInfo nameinfo, const TemplateArgumentListInfo *targs,
1421     QualType ty, ExprValueKind vk, ExprObjectKind ok) {
1422   std::size_t Size = sizeof(MemberExpr);
1423 
1424   bool hasQualOrFound = (QualifierLoc ||
1425                          founddecl.getDecl() != memberdecl ||
1426                          founddecl.getAccess() != memberdecl->getAccess());
1427   if (hasQualOrFound)
1428     Size += sizeof(MemberNameQualifier);
1429 
1430   if (targs)
1431     Size += ASTTemplateKWAndArgsInfo::sizeFor(targs->size());
1432   else if (TemplateKWLoc.isValid())
1433     Size += ASTTemplateKWAndArgsInfo::sizeFor(0);
1434 
1435   void *Mem = C.Allocate(Size, llvm::alignOf<MemberExpr>());
1436   MemberExpr *E = new (Mem)
1437       MemberExpr(base, isarrow, OperatorLoc, memberdecl, nameinfo, ty, vk, ok);
1438 
1439   if (hasQualOrFound) {
1440     // FIXME: Wrong. We should be looking at the member declaration we found.
1441     if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent()) {
1442       E->setValueDependent(true);
1443       E->setTypeDependent(true);
1444       E->setInstantiationDependent(true);
1445     }
1446     else if (QualifierLoc &&
1447              QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent())
1448       E->setInstantiationDependent(true);
1449 
1450     E->HasQualifierOrFoundDecl = true;
1451 
1452     MemberNameQualifier *NQ = E->getMemberQualifier();
1453     NQ->QualifierLoc = QualifierLoc;
1454     NQ->FoundDecl = founddecl;
1455   }
1456 
1457   E->HasTemplateKWAndArgsInfo = (targs || TemplateKWLoc.isValid());
1458 
1459   if (targs) {
1460     bool Dependent = false;
1461     bool InstantiationDependent = false;
1462     bool ContainsUnexpandedParameterPack = false;
1463     E->getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc, *targs,
1464                                                   Dependent,
1465                                                   InstantiationDependent,
1466                                              ContainsUnexpandedParameterPack);
1467     if (InstantiationDependent)
1468       E->setInstantiationDependent(true);
1469   } else if (TemplateKWLoc.isValid()) {
1470     E->getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc);
1471   }
1472 
1473   return E;
1474 }
1475 
getLocStart() const1476 SourceLocation MemberExpr::getLocStart() const {
1477   if (isImplicitAccess()) {
1478     if (hasQualifier())
1479       return getQualifierLoc().getBeginLoc();
1480     return MemberLoc;
1481   }
1482 
1483   // FIXME: We don't want this to happen. Rather, we should be able to
1484   // detect all kinds of implicit accesses more cleanly.
1485   SourceLocation BaseStartLoc = getBase()->getLocStart();
1486   if (BaseStartLoc.isValid())
1487     return BaseStartLoc;
1488   return MemberLoc;
1489 }
getLocEnd() const1490 SourceLocation MemberExpr::getLocEnd() const {
1491   SourceLocation EndLoc = getMemberNameInfo().getEndLoc();
1492   if (hasExplicitTemplateArgs())
1493     EndLoc = getRAngleLoc();
1494   else if (EndLoc.isInvalid())
1495     EndLoc = getBase()->getLocEnd();
1496   return EndLoc;
1497 }
1498 
CastConsistency() const1499 bool CastExpr::CastConsistency() const {
1500   switch (getCastKind()) {
1501   case CK_DerivedToBase:
1502   case CK_UncheckedDerivedToBase:
1503   case CK_DerivedToBaseMemberPointer:
1504   case CK_BaseToDerived:
1505   case CK_BaseToDerivedMemberPointer:
1506     assert(!path_empty() && "Cast kind should have a base path!");
1507     break;
1508 
1509   case CK_CPointerToObjCPointerCast:
1510     assert(getType()->isObjCObjectPointerType());
1511     assert(getSubExpr()->getType()->isPointerType());
1512     goto CheckNoBasePath;
1513 
1514   case CK_BlockPointerToObjCPointerCast:
1515     assert(getType()->isObjCObjectPointerType());
1516     assert(getSubExpr()->getType()->isBlockPointerType());
1517     goto CheckNoBasePath;
1518 
1519   case CK_ReinterpretMemberPointer:
1520     assert(getType()->isMemberPointerType());
1521     assert(getSubExpr()->getType()->isMemberPointerType());
1522     goto CheckNoBasePath;
1523 
1524   case CK_BitCast:
1525     // Arbitrary casts to C pointer types count as bitcasts.
1526     // Otherwise, we should only have block and ObjC pointer casts
1527     // here if they stay within the type kind.
1528     if (!getType()->isPointerType()) {
1529       assert(getType()->isObjCObjectPointerType() ==
1530              getSubExpr()->getType()->isObjCObjectPointerType());
1531       assert(getType()->isBlockPointerType() ==
1532              getSubExpr()->getType()->isBlockPointerType());
1533     }
1534     goto CheckNoBasePath;
1535 
1536   case CK_AnyPointerToBlockPointerCast:
1537     assert(getType()->isBlockPointerType());
1538     assert(getSubExpr()->getType()->isAnyPointerType() &&
1539            !getSubExpr()->getType()->isBlockPointerType());
1540     goto CheckNoBasePath;
1541 
1542   case CK_CopyAndAutoreleaseBlockObject:
1543     assert(getType()->isBlockPointerType());
1544     assert(getSubExpr()->getType()->isBlockPointerType());
1545     goto CheckNoBasePath;
1546 
1547   case CK_FunctionToPointerDecay:
1548     assert(getType()->isPointerType());
1549     assert(getSubExpr()->getType()->isFunctionType());
1550     goto CheckNoBasePath;
1551 
1552   case CK_AddressSpaceConversion:
1553     assert(getType()->isPointerType());
1554     assert(getSubExpr()->getType()->isPointerType());
1555     assert(getType()->getPointeeType().getAddressSpace() !=
1556            getSubExpr()->getType()->getPointeeType().getAddressSpace());
1557   // These should not have an inheritance path.
1558   case CK_Dynamic:
1559   case CK_ToUnion:
1560   case CK_ArrayToPointerDecay:
1561   case CK_NullToMemberPointer:
1562   case CK_NullToPointer:
1563   case CK_ConstructorConversion:
1564   case CK_IntegralToPointer:
1565   case CK_PointerToIntegral:
1566   case CK_ToVoid:
1567   case CK_VectorSplat:
1568   case CK_IntegralCast:
1569   case CK_IntegralToFloating:
1570   case CK_FloatingToIntegral:
1571   case CK_FloatingCast:
1572   case CK_ObjCObjectLValueCast:
1573   case CK_FloatingRealToComplex:
1574   case CK_FloatingComplexToReal:
1575   case CK_FloatingComplexCast:
1576   case CK_FloatingComplexToIntegralComplex:
1577   case CK_IntegralRealToComplex:
1578   case CK_IntegralComplexToReal:
1579   case CK_IntegralComplexCast:
1580   case CK_IntegralComplexToFloatingComplex:
1581   case CK_ARCProduceObject:
1582   case CK_ARCConsumeObject:
1583   case CK_ARCReclaimReturnedObject:
1584   case CK_ARCExtendBlockObject:
1585   case CK_ZeroToOCLEvent:
1586     assert(!getType()->isBooleanType() && "unheralded conversion to bool");
1587     goto CheckNoBasePath;
1588 
1589   case CK_Dependent:
1590   case CK_LValueToRValue:
1591   case CK_NoOp:
1592   case CK_AtomicToNonAtomic:
1593   case CK_NonAtomicToAtomic:
1594   case CK_PointerToBoolean:
1595   case CK_IntegralToBoolean:
1596   case CK_FloatingToBoolean:
1597   case CK_MemberPointerToBoolean:
1598   case CK_FloatingComplexToBoolean:
1599   case CK_IntegralComplexToBoolean:
1600   case CK_LValueBitCast:            // -> bool&
1601   case CK_UserDefinedConversion:    // operator bool()
1602   case CK_BuiltinFnToFnPtr:
1603   CheckNoBasePath:
1604     assert(path_empty() && "Cast kind should not have a base path!");
1605     break;
1606   }
1607   return true;
1608 }
1609 
getCastKindName() const1610 const char *CastExpr::getCastKindName() const {
1611   switch (getCastKind()) {
1612   case CK_Dependent:
1613     return "Dependent";
1614   case CK_BitCast:
1615     return "BitCast";
1616   case CK_LValueBitCast:
1617     return "LValueBitCast";
1618   case CK_LValueToRValue:
1619     return "LValueToRValue";
1620   case CK_NoOp:
1621     return "NoOp";
1622   case CK_BaseToDerived:
1623     return "BaseToDerived";
1624   case CK_DerivedToBase:
1625     return "DerivedToBase";
1626   case CK_UncheckedDerivedToBase:
1627     return "UncheckedDerivedToBase";
1628   case CK_Dynamic:
1629     return "Dynamic";
1630   case CK_ToUnion:
1631     return "ToUnion";
1632   case CK_ArrayToPointerDecay:
1633     return "ArrayToPointerDecay";
1634   case CK_FunctionToPointerDecay:
1635     return "FunctionToPointerDecay";
1636   case CK_NullToMemberPointer:
1637     return "NullToMemberPointer";
1638   case CK_NullToPointer:
1639     return "NullToPointer";
1640   case CK_BaseToDerivedMemberPointer:
1641     return "BaseToDerivedMemberPointer";
1642   case CK_DerivedToBaseMemberPointer:
1643     return "DerivedToBaseMemberPointer";
1644   case CK_ReinterpretMemberPointer:
1645     return "ReinterpretMemberPointer";
1646   case CK_UserDefinedConversion:
1647     return "UserDefinedConversion";
1648   case CK_ConstructorConversion:
1649     return "ConstructorConversion";
1650   case CK_IntegralToPointer:
1651     return "IntegralToPointer";
1652   case CK_PointerToIntegral:
1653     return "PointerToIntegral";
1654   case CK_PointerToBoolean:
1655     return "PointerToBoolean";
1656   case CK_ToVoid:
1657     return "ToVoid";
1658   case CK_VectorSplat:
1659     return "VectorSplat";
1660   case CK_IntegralCast:
1661     return "IntegralCast";
1662   case CK_IntegralToBoolean:
1663     return "IntegralToBoolean";
1664   case CK_IntegralToFloating:
1665     return "IntegralToFloating";
1666   case CK_FloatingToIntegral:
1667     return "FloatingToIntegral";
1668   case CK_FloatingCast:
1669     return "FloatingCast";
1670   case CK_FloatingToBoolean:
1671     return "FloatingToBoolean";
1672   case CK_MemberPointerToBoolean:
1673     return "MemberPointerToBoolean";
1674   case CK_CPointerToObjCPointerCast:
1675     return "CPointerToObjCPointerCast";
1676   case CK_BlockPointerToObjCPointerCast:
1677     return "BlockPointerToObjCPointerCast";
1678   case CK_AnyPointerToBlockPointerCast:
1679     return "AnyPointerToBlockPointerCast";
1680   case CK_ObjCObjectLValueCast:
1681     return "ObjCObjectLValueCast";
1682   case CK_FloatingRealToComplex:
1683     return "FloatingRealToComplex";
1684   case CK_FloatingComplexToReal:
1685     return "FloatingComplexToReal";
1686   case CK_FloatingComplexToBoolean:
1687     return "FloatingComplexToBoolean";
1688   case CK_FloatingComplexCast:
1689     return "FloatingComplexCast";
1690   case CK_FloatingComplexToIntegralComplex:
1691     return "FloatingComplexToIntegralComplex";
1692   case CK_IntegralRealToComplex:
1693     return "IntegralRealToComplex";
1694   case CK_IntegralComplexToReal:
1695     return "IntegralComplexToReal";
1696   case CK_IntegralComplexToBoolean:
1697     return "IntegralComplexToBoolean";
1698   case CK_IntegralComplexCast:
1699     return "IntegralComplexCast";
1700   case CK_IntegralComplexToFloatingComplex:
1701     return "IntegralComplexToFloatingComplex";
1702   case CK_ARCConsumeObject:
1703     return "ARCConsumeObject";
1704   case CK_ARCProduceObject:
1705     return "ARCProduceObject";
1706   case CK_ARCReclaimReturnedObject:
1707     return "ARCReclaimReturnedObject";
1708   case CK_ARCExtendBlockObject:
1709     return "ARCExtendBlockObject";
1710   case CK_AtomicToNonAtomic:
1711     return "AtomicToNonAtomic";
1712   case CK_NonAtomicToAtomic:
1713     return "NonAtomicToAtomic";
1714   case CK_CopyAndAutoreleaseBlockObject:
1715     return "CopyAndAutoreleaseBlockObject";
1716   case CK_BuiltinFnToFnPtr:
1717     return "BuiltinFnToFnPtr";
1718   case CK_ZeroToOCLEvent:
1719     return "ZeroToOCLEvent";
1720   case CK_AddressSpaceConversion:
1721     return "AddressSpaceConversion";
1722   }
1723 
1724   llvm_unreachable("Unhandled cast kind!");
1725 }
1726 
getSubExprAsWritten()1727 Expr *CastExpr::getSubExprAsWritten() {
1728   Expr *SubExpr = nullptr;
1729   CastExpr *E = this;
1730   do {
1731     SubExpr = E->getSubExpr();
1732 
1733     // Skip through reference binding to temporary.
1734     if (MaterializeTemporaryExpr *Materialize
1735                                   = dyn_cast<MaterializeTemporaryExpr>(SubExpr))
1736       SubExpr = Materialize->GetTemporaryExpr();
1737 
1738     // Skip any temporary bindings; they're implicit.
1739     if (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(SubExpr))
1740       SubExpr = Binder->getSubExpr();
1741 
1742     // Conversions by constructor and conversion functions have a
1743     // subexpression describing the call; strip it off.
1744     if (E->getCastKind() == CK_ConstructorConversion)
1745       SubExpr = cast<CXXConstructExpr>(SubExpr)->getArg(0);
1746     else if (E->getCastKind() == CK_UserDefinedConversion)
1747       SubExpr = cast<CXXMemberCallExpr>(SubExpr)->getImplicitObjectArgument();
1748 
1749     // If the subexpression we're left with is an implicit cast, look
1750     // through that, too.
1751   } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr)));
1752 
1753   return SubExpr;
1754 }
1755 
path_buffer()1756 CXXBaseSpecifier **CastExpr::path_buffer() {
1757   switch (getStmtClass()) {
1758 #define ABSTRACT_STMT(x)
1759 #define CASTEXPR(Type, Base) \
1760   case Stmt::Type##Class: \
1761     return reinterpret_cast<CXXBaseSpecifier**>(static_cast<Type*>(this)+1);
1762 #define STMT(Type, Base)
1763 #include "clang/AST/StmtNodes.inc"
1764   default:
1765     llvm_unreachable("non-cast expressions not possible here");
1766   }
1767 }
1768 
setCastPath(const CXXCastPath & Path)1769 void CastExpr::setCastPath(const CXXCastPath &Path) {
1770   assert(Path.size() == path_size());
1771   memcpy(path_buffer(), Path.data(), Path.size() * sizeof(CXXBaseSpecifier*));
1772 }
1773 
Create(const ASTContext & C,QualType T,CastKind Kind,Expr * Operand,const CXXCastPath * BasePath,ExprValueKind VK)1774 ImplicitCastExpr *ImplicitCastExpr::Create(const ASTContext &C, QualType T,
1775                                            CastKind Kind, Expr *Operand,
1776                                            const CXXCastPath *BasePath,
1777                                            ExprValueKind VK) {
1778   unsigned PathSize = (BasePath ? BasePath->size() : 0);
1779   void *Buffer =
1780     C.Allocate(sizeof(ImplicitCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1781   ImplicitCastExpr *E =
1782     new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK);
1783   if (PathSize) E->setCastPath(*BasePath);
1784   return E;
1785 }
1786 
CreateEmpty(const ASTContext & C,unsigned PathSize)1787 ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(const ASTContext &C,
1788                                                 unsigned PathSize) {
1789   void *Buffer =
1790     C.Allocate(sizeof(ImplicitCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1791   return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize);
1792 }
1793 
1794 
Create(const ASTContext & C,QualType T,ExprValueKind VK,CastKind K,Expr * Op,const CXXCastPath * BasePath,TypeSourceInfo * WrittenTy,SourceLocation L,SourceLocation R)1795 CStyleCastExpr *CStyleCastExpr::Create(const ASTContext &C, QualType T,
1796                                        ExprValueKind VK, CastKind K, Expr *Op,
1797                                        const CXXCastPath *BasePath,
1798                                        TypeSourceInfo *WrittenTy,
1799                                        SourceLocation L, SourceLocation R) {
1800   unsigned PathSize = (BasePath ? BasePath->size() : 0);
1801   void *Buffer =
1802     C.Allocate(sizeof(CStyleCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1803   CStyleCastExpr *E =
1804     new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, R);
1805   if (PathSize) E->setCastPath(*BasePath);
1806   return E;
1807 }
1808 
CreateEmpty(const ASTContext & C,unsigned PathSize)1809 CStyleCastExpr *CStyleCastExpr::CreateEmpty(const ASTContext &C,
1810                                             unsigned PathSize) {
1811   void *Buffer =
1812     C.Allocate(sizeof(CStyleCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
1813   return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize);
1814 }
1815 
1816 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1817 /// corresponds to, e.g. "<<=".
getOpcodeStr(Opcode Op)1818 StringRef BinaryOperator::getOpcodeStr(Opcode Op) {
1819   switch (Op) {
1820   case BO_PtrMemD:   return ".*";
1821   case BO_PtrMemI:   return "->*";
1822   case BO_Mul:       return "*";
1823   case BO_Div:       return "/";
1824   case BO_Rem:       return "%";
1825   case BO_Add:       return "+";
1826   case BO_Sub:       return "-";
1827   case BO_Shl:       return "<<";
1828   case BO_Shr:       return ">>";
1829   case BO_LT:        return "<";
1830   case BO_GT:        return ">";
1831   case BO_LE:        return "<=";
1832   case BO_GE:        return ">=";
1833   case BO_EQ:        return "==";
1834   case BO_NE:        return "!=";
1835   case BO_And:       return "&";
1836   case BO_Xor:       return "^";
1837   case BO_Or:        return "|";
1838   case BO_LAnd:      return "&&";
1839   case BO_LOr:       return "||";
1840   case BO_Assign:    return "=";
1841   case BO_MulAssign: return "*=";
1842   case BO_DivAssign: return "/=";
1843   case BO_RemAssign: return "%=";
1844   case BO_AddAssign: return "+=";
1845   case BO_SubAssign: return "-=";
1846   case BO_ShlAssign: return "<<=";
1847   case BO_ShrAssign: return ">>=";
1848   case BO_AndAssign: return "&=";
1849   case BO_XorAssign: return "^=";
1850   case BO_OrAssign:  return "|=";
1851   case BO_Comma:     return ",";
1852   }
1853 
1854   llvm_unreachable("Invalid OpCode!");
1855 }
1856 
1857 BinaryOperatorKind
getOverloadedOpcode(OverloadedOperatorKind OO)1858 BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
1859   switch (OO) {
1860   default: llvm_unreachable("Not an overloadable binary operator");
1861   case OO_Plus: return BO_Add;
1862   case OO_Minus: return BO_Sub;
1863   case OO_Star: return BO_Mul;
1864   case OO_Slash: return BO_Div;
1865   case OO_Percent: return BO_Rem;
1866   case OO_Caret: return BO_Xor;
1867   case OO_Amp: return BO_And;
1868   case OO_Pipe: return BO_Or;
1869   case OO_Equal: return BO_Assign;
1870   case OO_Less: return BO_LT;
1871   case OO_Greater: return BO_GT;
1872   case OO_PlusEqual: return BO_AddAssign;
1873   case OO_MinusEqual: return BO_SubAssign;
1874   case OO_StarEqual: return BO_MulAssign;
1875   case OO_SlashEqual: return BO_DivAssign;
1876   case OO_PercentEqual: return BO_RemAssign;
1877   case OO_CaretEqual: return BO_XorAssign;
1878   case OO_AmpEqual: return BO_AndAssign;
1879   case OO_PipeEqual: return BO_OrAssign;
1880   case OO_LessLess: return BO_Shl;
1881   case OO_GreaterGreater: return BO_Shr;
1882   case OO_LessLessEqual: return BO_ShlAssign;
1883   case OO_GreaterGreaterEqual: return BO_ShrAssign;
1884   case OO_EqualEqual: return BO_EQ;
1885   case OO_ExclaimEqual: return BO_NE;
1886   case OO_LessEqual: return BO_LE;
1887   case OO_GreaterEqual: return BO_GE;
1888   case OO_AmpAmp: return BO_LAnd;
1889   case OO_PipePipe: return BO_LOr;
1890   case OO_Comma: return BO_Comma;
1891   case OO_ArrowStar: return BO_PtrMemI;
1892   }
1893 }
1894 
getOverloadedOperator(Opcode Opc)1895 OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
1896   static const OverloadedOperatorKind OverOps[] = {
1897     /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
1898     OO_Star, OO_Slash, OO_Percent,
1899     OO_Plus, OO_Minus,
1900     OO_LessLess, OO_GreaterGreater,
1901     OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
1902     OO_EqualEqual, OO_ExclaimEqual,
1903     OO_Amp,
1904     OO_Caret,
1905     OO_Pipe,
1906     OO_AmpAmp,
1907     OO_PipePipe,
1908     OO_Equal, OO_StarEqual,
1909     OO_SlashEqual, OO_PercentEqual,
1910     OO_PlusEqual, OO_MinusEqual,
1911     OO_LessLessEqual, OO_GreaterGreaterEqual,
1912     OO_AmpEqual, OO_CaretEqual,
1913     OO_PipeEqual,
1914     OO_Comma
1915   };
1916   return OverOps[Opc];
1917 }
1918 
InitListExpr(const ASTContext & C,SourceLocation lbraceloc,ArrayRef<Expr * > initExprs,SourceLocation rbraceloc)1919 InitListExpr::InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
1920                            ArrayRef<Expr*> initExprs, SourceLocation rbraceloc)
1921   : Expr(InitListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
1922          false, false),
1923     InitExprs(C, initExprs.size()),
1924     LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), AltForm(nullptr, true)
1925 {
1926   sawArrayRangeDesignator(false);
1927   for (unsigned I = 0; I != initExprs.size(); ++I) {
1928     if (initExprs[I]->isTypeDependent())
1929       ExprBits.TypeDependent = true;
1930     if (initExprs[I]->isValueDependent())
1931       ExprBits.ValueDependent = true;
1932     if (initExprs[I]->isInstantiationDependent())
1933       ExprBits.InstantiationDependent = true;
1934     if (initExprs[I]->containsUnexpandedParameterPack())
1935       ExprBits.ContainsUnexpandedParameterPack = true;
1936   }
1937 
1938   InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end());
1939 }
1940 
reserveInits(const ASTContext & C,unsigned NumInits)1941 void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) {
1942   if (NumInits > InitExprs.size())
1943     InitExprs.reserve(C, NumInits);
1944 }
1945 
resizeInits(const ASTContext & C,unsigned NumInits)1946 void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) {
1947   InitExprs.resize(C, NumInits, nullptr);
1948 }
1949 
updateInit(const ASTContext & C,unsigned Init,Expr * expr)1950 Expr *InitListExpr::updateInit(const ASTContext &C, unsigned Init, Expr *expr) {
1951   if (Init >= InitExprs.size()) {
1952     InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr);
1953     setInit(Init, expr);
1954     return nullptr;
1955   }
1956 
1957   Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
1958   setInit(Init, expr);
1959   return Result;
1960 }
1961 
setArrayFiller(Expr * filler)1962 void InitListExpr::setArrayFiller(Expr *filler) {
1963   assert(!hasArrayFiller() && "Filler already set!");
1964   ArrayFillerOrUnionFieldInit = filler;
1965   // Fill out any "holes" in the array due to designated initializers.
1966   Expr **inits = getInits();
1967   for (unsigned i = 0, e = getNumInits(); i != e; ++i)
1968     if (inits[i] == nullptr)
1969       inits[i] = filler;
1970 }
1971 
isStringLiteralInit() const1972 bool InitListExpr::isStringLiteralInit() const {
1973   if (getNumInits() != 1)
1974     return false;
1975   const ArrayType *AT = getType()->getAsArrayTypeUnsafe();
1976   if (!AT || !AT->getElementType()->isIntegerType())
1977     return false;
1978   // It is possible for getInit() to return null.
1979   const Expr *Init = getInit(0);
1980   if (!Init)
1981     return false;
1982   Init = Init->IgnoreParens();
1983   return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init);
1984 }
1985 
getLocStart() const1986 SourceLocation InitListExpr::getLocStart() const {
1987   if (InitListExpr *SyntacticForm = getSyntacticForm())
1988     return SyntacticForm->getLocStart();
1989   SourceLocation Beg = LBraceLoc;
1990   if (Beg.isInvalid()) {
1991     // Find the first non-null initializer.
1992     for (InitExprsTy::const_iterator I = InitExprs.begin(),
1993                                      E = InitExprs.end();
1994       I != E; ++I) {
1995       if (Stmt *S = *I) {
1996         Beg = S->getLocStart();
1997         break;
1998       }
1999     }
2000   }
2001   return Beg;
2002 }
2003 
getLocEnd() const2004 SourceLocation InitListExpr::getLocEnd() const {
2005   if (InitListExpr *SyntacticForm = getSyntacticForm())
2006     return SyntacticForm->getLocEnd();
2007   SourceLocation End = RBraceLoc;
2008   if (End.isInvalid()) {
2009     // Find the first non-null initializer from the end.
2010     for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(),
2011          E = InitExprs.rend();
2012          I != E; ++I) {
2013       if (Stmt *S = *I) {
2014         End = S->getLocEnd();
2015         break;
2016       }
2017     }
2018   }
2019   return End;
2020 }
2021 
2022 /// getFunctionType - Return the underlying function type for this block.
2023 ///
getFunctionType() const2024 const FunctionProtoType *BlockExpr::getFunctionType() const {
2025   // The block pointer is never sugared, but the function type might be.
2026   return cast<BlockPointerType>(getType())
2027            ->getPointeeType()->castAs<FunctionProtoType>();
2028 }
2029 
getCaretLocation() const2030 SourceLocation BlockExpr::getCaretLocation() const {
2031   return TheBlock->getCaretLocation();
2032 }
getBody() const2033 const Stmt *BlockExpr::getBody() const {
2034   return TheBlock->getBody();
2035 }
getBody()2036 Stmt *BlockExpr::getBody() {
2037   return TheBlock->getBody();
2038 }
2039 
2040 
2041 //===----------------------------------------------------------------------===//
2042 // Generic Expression Routines
2043 //===----------------------------------------------------------------------===//
2044 
2045 /// isUnusedResultAWarning - Return true if this immediate expression should
2046 /// be warned about if the result is unused.  If so, fill in Loc and Ranges
2047 /// with location to warn on and the source range[s] to report with the
2048 /// warning.
isUnusedResultAWarning(const Expr * & WarnE,SourceLocation & Loc,SourceRange & R1,SourceRange & R2,ASTContext & Ctx) const2049 bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc,
2050                                   SourceRange &R1, SourceRange &R2,
2051                                   ASTContext &Ctx) const {
2052   // Don't warn if the expr is type dependent. The type could end up
2053   // instantiating to void.
2054   if (isTypeDependent())
2055     return false;
2056 
2057   switch (getStmtClass()) {
2058   default:
2059     if (getType()->isVoidType())
2060       return false;
2061     WarnE = this;
2062     Loc = getExprLoc();
2063     R1 = getSourceRange();
2064     return true;
2065   case ParenExprClass:
2066     return cast<ParenExpr>(this)->getSubExpr()->
2067       isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2068   case GenericSelectionExprClass:
2069     return cast<GenericSelectionExpr>(this)->getResultExpr()->
2070       isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2071   case ChooseExprClass:
2072     return cast<ChooseExpr>(this)->getChosenSubExpr()->
2073       isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2074   case UnaryOperatorClass: {
2075     const UnaryOperator *UO = cast<UnaryOperator>(this);
2076 
2077     switch (UO->getOpcode()) {
2078     case UO_Plus:
2079     case UO_Minus:
2080     case UO_AddrOf:
2081     case UO_Not:
2082     case UO_LNot:
2083     case UO_Deref:
2084       break;
2085     case UO_Coawait:
2086       // This is just the 'operator co_await' call inside the guts of a
2087       // dependent co_await call.
2088     case UO_PostInc:
2089     case UO_PostDec:
2090     case UO_PreInc:
2091     case UO_PreDec:                 // ++/--
2092       return false;  // Not a warning.
2093     case UO_Real:
2094     case UO_Imag:
2095       // accessing a piece of a volatile complex is a side-effect.
2096       if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
2097           .isVolatileQualified())
2098         return false;
2099       break;
2100     case UO_Extension:
2101       return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2102     }
2103     WarnE = this;
2104     Loc = UO->getOperatorLoc();
2105     R1 = UO->getSubExpr()->getSourceRange();
2106     return true;
2107   }
2108   case BinaryOperatorClass: {
2109     const BinaryOperator *BO = cast<BinaryOperator>(this);
2110     switch (BO->getOpcode()) {
2111       default:
2112         break;
2113       // Consider the RHS of comma for side effects. LHS was checked by
2114       // Sema::CheckCommaOperands.
2115       case BO_Comma:
2116         // ((foo = <blah>), 0) is an idiom for hiding the result (and
2117         // lvalue-ness) of an assignment written in a macro.
2118         if (IntegerLiteral *IE =
2119               dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
2120           if (IE->getValue() == 0)
2121             return false;
2122         return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2123       // Consider '||', '&&' to have side effects if the LHS or RHS does.
2124       case BO_LAnd:
2125       case BO_LOr:
2126         if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||
2127             !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
2128           return false;
2129         break;
2130     }
2131     if (BO->isAssignmentOp())
2132       return false;
2133     WarnE = this;
2134     Loc = BO->getOperatorLoc();
2135     R1 = BO->getLHS()->getSourceRange();
2136     R2 = BO->getRHS()->getSourceRange();
2137     return true;
2138   }
2139   case CompoundAssignOperatorClass:
2140   case VAArgExprClass:
2141   case AtomicExprClass:
2142     return false;
2143 
2144   case ConditionalOperatorClass: {
2145     // If only one of the LHS or RHS is a warning, the operator might
2146     // be being used for control flow. Only warn if both the LHS and
2147     // RHS are warnings.
2148     const ConditionalOperator *Exp = cast<ConditionalOperator>(this);
2149     if (!Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
2150       return false;
2151     if (!Exp->getLHS())
2152       return true;
2153     return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2154   }
2155 
2156   case MemberExprClass:
2157     WarnE = this;
2158     Loc = cast<MemberExpr>(this)->getMemberLoc();
2159     R1 = SourceRange(Loc, Loc);
2160     R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
2161     return true;
2162 
2163   case ArraySubscriptExprClass:
2164     WarnE = this;
2165     Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
2166     R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
2167     R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
2168     return true;
2169 
2170   case CXXOperatorCallExprClass: {
2171     // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator
2172     // overloads as there is no reasonable way to define these such that they
2173     // have non-trivial, desirable side-effects. See the -Wunused-comparison
2174     // warning: operators == and != are commonly typo'ed, and so warning on them
2175     // provides additional value as well. If this list is updated,
2176     // DiagnoseUnusedComparison should be as well.
2177     const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
2178     switch (Op->getOperator()) {
2179     default:
2180       break;
2181     case OO_EqualEqual:
2182     case OO_ExclaimEqual:
2183     case OO_Less:
2184     case OO_Greater:
2185     case OO_GreaterEqual:
2186     case OO_LessEqual:
2187       if (Op->getCallReturnType(Ctx)->isReferenceType() ||
2188           Op->getCallReturnType(Ctx)->isVoidType())
2189         break;
2190       WarnE = this;
2191       Loc = Op->getOperatorLoc();
2192       R1 = Op->getSourceRange();
2193       return true;
2194     }
2195 
2196     // Fallthrough for generic call handling.
2197   }
2198   case CallExprClass:
2199   case CXXMemberCallExprClass:
2200   case UserDefinedLiteralClass: {
2201     // If this is a direct call, get the callee.
2202     const CallExpr *CE = cast<CallExpr>(this);
2203     if (const Decl *FD = CE->getCalleeDecl()) {
2204       const FunctionDecl *Func = dyn_cast<FunctionDecl>(FD);
2205       bool HasWarnUnusedResultAttr = Func ? Func->hasUnusedResultAttr()
2206                                           : FD->hasAttr<WarnUnusedResultAttr>();
2207 
2208       // If the callee has attribute pure, const, or warn_unused_result, warn
2209       // about it. void foo() { strlen("bar"); } should warn.
2210       //
2211       // Note: If new cases are added here, DiagnoseUnusedExprResult should be
2212       // updated to match for QoI.
2213       if (HasWarnUnusedResultAttr ||
2214           FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>()) {
2215         WarnE = this;
2216         Loc = CE->getCallee()->getLocStart();
2217         R1 = CE->getCallee()->getSourceRange();
2218 
2219         if (unsigned NumArgs = CE->getNumArgs())
2220           R2 = SourceRange(CE->getArg(0)->getLocStart(),
2221                            CE->getArg(NumArgs-1)->getLocEnd());
2222         return true;
2223       }
2224     }
2225     return false;
2226   }
2227 
2228   // If we don't know precisely what we're looking at, let's not warn.
2229   case UnresolvedLookupExprClass:
2230   case CXXUnresolvedConstructExprClass:
2231     return false;
2232 
2233   case CXXTemporaryObjectExprClass:
2234   case CXXConstructExprClass: {
2235     if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) {
2236       if (Type->hasAttr<WarnUnusedAttr>()) {
2237         WarnE = this;
2238         Loc = getLocStart();
2239         R1 = getSourceRange();
2240         return true;
2241       }
2242     }
2243     return false;
2244   }
2245 
2246   case ObjCMessageExprClass: {
2247     const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
2248     if (Ctx.getLangOpts().ObjCAutoRefCount &&
2249         ME->isInstanceMessage() &&
2250         !ME->getType()->isVoidType() &&
2251         ME->getMethodFamily() == OMF_init) {
2252       WarnE = this;
2253       Loc = getExprLoc();
2254       R1 = ME->getSourceRange();
2255       return true;
2256     }
2257 
2258     if (const ObjCMethodDecl *MD = ME->getMethodDecl())
2259       if (MD->hasAttr<WarnUnusedResultAttr>()) {
2260         WarnE = this;
2261         Loc = getExprLoc();
2262         return true;
2263       }
2264 
2265     return false;
2266   }
2267 
2268   case ObjCPropertyRefExprClass:
2269     WarnE = this;
2270     Loc = getExprLoc();
2271     R1 = getSourceRange();
2272     return true;
2273 
2274   case PseudoObjectExprClass: {
2275     const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
2276 
2277     // Only complain about things that have the form of a getter.
2278     if (isa<UnaryOperator>(PO->getSyntacticForm()) ||
2279         isa<BinaryOperator>(PO->getSyntacticForm()))
2280       return false;
2281 
2282     WarnE = this;
2283     Loc = getExprLoc();
2284     R1 = getSourceRange();
2285     return true;
2286   }
2287 
2288   case StmtExprClass: {
2289     // Statement exprs don't logically have side effects themselves, but are
2290     // sometimes used in macros in ways that give them a type that is unused.
2291     // For example ({ blah; foo(); }) will end up with a type if foo has a type.
2292     // however, if the result of the stmt expr is dead, we don't want to emit a
2293     // warning.
2294     const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
2295     if (!CS->body_empty()) {
2296       if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
2297         return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2298       if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
2299         if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
2300           return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2301     }
2302 
2303     if (getType()->isVoidType())
2304       return false;
2305     WarnE = this;
2306     Loc = cast<StmtExpr>(this)->getLParenLoc();
2307     R1 = getSourceRange();
2308     return true;
2309   }
2310   case CXXFunctionalCastExprClass:
2311   case CStyleCastExprClass: {
2312     // Ignore an explicit cast to void unless the operand is a non-trivial
2313     // volatile lvalue.
2314     const CastExpr *CE = cast<CastExpr>(this);
2315     if (CE->getCastKind() == CK_ToVoid) {
2316       if (CE->getSubExpr()->isGLValue() &&
2317           CE->getSubExpr()->getType().isVolatileQualified()) {
2318         const DeclRefExpr *DRE =
2319             dyn_cast<DeclRefExpr>(CE->getSubExpr()->IgnoreParens());
2320         if (!(DRE && isa<VarDecl>(DRE->getDecl()) &&
2321               cast<VarDecl>(DRE->getDecl())->hasLocalStorage())) {
2322           return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc,
2323                                                           R1, R2, Ctx);
2324         }
2325       }
2326       return false;
2327     }
2328 
2329     // If this is a cast to a constructor conversion, check the operand.
2330     // Otherwise, the result of the cast is unused.
2331     if (CE->getCastKind() == CK_ConstructorConversion)
2332       return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2333 
2334     WarnE = this;
2335     if (const CXXFunctionalCastExpr *CXXCE =
2336             dyn_cast<CXXFunctionalCastExpr>(this)) {
2337       Loc = CXXCE->getLocStart();
2338       R1 = CXXCE->getSubExpr()->getSourceRange();
2339     } else {
2340       const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this);
2341       Loc = CStyleCE->getLParenLoc();
2342       R1 = CStyleCE->getSubExpr()->getSourceRange();
2343     }
2344     return true;
2345   }
2346   case ImplicitCastExprClass: {
2347     const CastExpr *ICE = cast<ImplicitCastExpr>(this);
2348 
2349     // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.
2350     if (ICE->getCastKind() == CK_LValueToRValue &&
2351         ICE->getSubExpr()->getType().isVolatileQualified())
2352       return false;
2353 
2354     return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2355   }
2356   case CXXDefaultArgExprClass:
2357     return (cast<CXXDefaultArgExpr>(this)
2358             ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2359   case CXXDefaultInitExprClass:
2360     return (cast<CXXDefaultInitExpr>(this)
2361             ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2362 
2363   case CXXNewExprClass:
2364     // FIXME: In theory, there might be new expressions that don't have side
2365     // effects (e.g. a placement new with an uninitialized POD).
2366   case CXXDeleteExprClass:
2367     return false;
2368   case CXXBindTemporaryExprClass:
2369     return (cast<CXXBindTemporaryExpr>(this)
2370             ->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2371   case ExprWithCleanupsClass:
2372     return (cast<ExprWithCleanups>(this)
2373             ->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2374   }
2375 }
2376 
2377 /// isOBJCGCCandidate - Check if an expression is objc gc'able.
2378 /// returns true, if it is; false otherwise.
isOBJCGCCandidate(ASTContext & Ctx) const2379 bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
2380   const Expr *E = IgnoreParens();
2381   switch (E->getStmtClass()) {
2382   default:
2383     return false;
2384   case ObjCIvarRefExprClass:
2385     return true;
2386   case Expr::UnaryOperatorClass:
2387     return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2388   case ImplicitCastExprClass:
2389     return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2390   case MaterializeTemporaryExprClass:
2391     return cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr()
2392                                                       ->isOBJCGCCandidate(Ctx);
2393   case CStyleCastExprClass:
2394     return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2395   case DeclRefExprClass: {
2396     const Decl *D = cast<DeclRefExpr>(E)->getDecl();
2397 
2398     if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2399       if (VD->hasGlobalStorage())
2400         return true;
2401       QualType T = VD->getType();
2402       // dereferencing to a  pointer is always a gc'able candidate,
2403       // unless it is __weak.
2404       return T->isPointerType() &&
2405              (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
2406     }
2407     return false;
2408   }
2409   case MemberExprClass: {
2410     const MemberExpr *M = cast<MemberExpr>(E);
2411     return M->getBase()->isOBJCGCCandidate(Ctx);
2412   }
2413   case ArraySubscriptExprClass:
2414     return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
2415   }
2416 }
2417 
isBoundMemberFunction(ASTContext & Ctx) const2418 bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
2419   if (isTypeDependent())
2420     return false;
2421   return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
2422 }
2423 
findBoundMemberType(const Expr * expr)2424 QualType Expr::findBoundMemberType(const Expr *expr) {
2425   assert(expr->hasPlaceholderType(BuiltinType::BoundMember));
2426 
2427   // Bound member expressions are always one of these possibilities:
2428   //   x->m      x.m      x->*y      x.*y
2429   // (possibly parenthesized)
2430 
2431   expr = expr->IgnoreParens();
2432   if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
2433     assert(isa<CXXMethodDecl>(mem->getMemberDecl()));
2434     return mem->getMemberDecl()->getType();
2435   }
2436 
2437   if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
2438     QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
2439                       ->getPointeeType();
2440     assert(type->isFunctionType());
2441     return type;
2442   }
2443 
2444   assert(isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr));
2445   return QualType();
2446 }
2447 
IgnoreParens()2448 Expr* Expr::IgnoreParens() {
2449   Expr* E = this;
2450   while (true) {
2451     if (ParenExpr* P = dyn_cast<ParenExpr>(E)) {
2452       E = P->getSubExpr();
2453       continue;
2454     }
2455     if (UnaryOperator* P = dyn_cast<UnaryOperator>(E)) {
2456       if (P->getOpcode() == UO_Extension) {
2457         E = P->getSubExpr();
2458         continue;
2459       }
2460     }
2461     if (GenericSelectionExpr* P = dyn_cast<GenericSelectionExpr>(E)) {
2462       if (!P->isResultDependent()) {
2463         E = P->getResultExpr();
2464         continue;
2465       }
2466     }
2467     if (ChooseExpr* P = dyn_cast<ChooseExpr>(E)) {
2468       if (!P->isConditionDependent()) {
2469         E = P->getChosenSubExpr();
2470         continue;
2471       }
2472     }
2473     return E;
2474   }
2475 }
2476 
2477 /// IgnoreParenCasts - Ignore parentheses and casts.  Strip off any ParenExpr
2478 /// or CastExprs or ImplicitCastExprs, returning their operand.
IgnoreParenCasts()2479 Expr *Expr::IgnoreParenCasts() {
2480   Expr *E = this;
2481   while (true) {
2482     E = E->IgnoreParens();
2483     if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2484       E = P->getSubExpr();
2485       continue;
2486     }
2487     if (MaterializeTemporaryExpr *Materialize
2488                                       = dyn_cast<MaterializeTemporaryExpr>(E)) {
2489       E = Materialize->GetTemporaryExpr();
2490       continue;
2491     }
2492     if (SubstNonTypeTemplateParmExpr *NTTP
2493                                   = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2494       E = NTTP->getReplacement();
2495       continue;
2496     }
2497     return E;
2498   }
2499 }
2500 
IgnoreCasts()2501 Expr *Expr::IgnoreCasts() {
2502   Expr *E = this;
2503   while (true) {
2504     if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2505       E = P->getSubExpr();
2506       continue;
2507     }
2508     if (MaterializeTemporaryExpr *Materialize
2509         = dyn_cast<MaterializeTemporaryExpr>(E)) {
2510       E = Materialize->GetTemporaryExpr();
2511       continue;
2512     }
2513     if (SubstNonTypeTemplateParmExpr *NTTP
2514         = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2515       E = NTTP->getReplacement();
2516       continue;
2517     }
2518     return E;
2519   }
2520 }
2521 
2522 /// IgnoreParenLValueCasts - Ignore parentheses and lvalue-to-rvalue
2523 /// casts.  This is intended purely as a temporary workaround for code
2524 /// that hasn't yet been rewritten to do the right thing about those
2525 /// casts, and may disappear along with the last internal use.
IgnoreParenLValueCasts()2526 Expr *Expr::IgnoreParenLValueCasts() {
2527   Expr *E = this;
2528   while (true) {
2529     E = E->IgnoreParens();
2530     if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2531       if (P->getCastKind() == CK_LValueToRValue) {
2532         E = P->getSubExpr();
2533         continue;
2534       }
2535     } else if (MaterializeTemporaryExpr *Materialize
2536                                       = dyn_cast<MaterializeTemporaryExpr>(E)) {
2537       E = Materialize->GetTemporaryExpr();
2538       continue;
2539     } else if (SubstNonTypeTemplateParmExpr *NTTP
2540                                   = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2541       E = NTTP->getReplacement();
2542       continue;
2543     }
2544     break;
2545   }
2546   return E;
2547 }
2548 
ignoreParenBaseCasts()2549 Expr *Expr::ignoreParenBaseCasts() {
2550   Expr *E = this;
2551   while (true) {
2552     E = E->IgnoreParens();
2553     if (CastExpr *CE = dyn_cast<CastExpr>(E)) {
2554       if (CE->getCastKind() == CK_DerivedToBase ||
2555           CE->getCastKind() == CK_UncheckedDerivedToBase ||
2556           CE->getCastKind() == CK_NoOp) {
2557         E = CE->getSubExpr();
2558         continue;
2559       }
2560     }
2561 
2562     return E;
2563   }
2564 }
2565 
IgnoreParenImpCasts()2566 Expr *Expr::IgnoreParenImpCasts() {
2567   Expr *E = this;
2568   while (true) {
2569     E = E->IgnoreParens();
2570     if (ImplicitCastExpr *P = dyn_cast<ImplicitCastExpr>(E)) {
2571       E = P->getSubExpr();
2572       continue;
2573     }
2574     if (MaterializeTemporaryExpr *Materialize
2575                                       = dyn_cast<MaterializeTemporaryExpr>(E)) {
2576       E = Materialize->GetTemporaryExpr();
2577       continue;
2578     }
2579     if (SubstNonTypeTemplateParmExpr *NTTP
2580                                   = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2581       E = NTTP->getReplacement();
2582       continue;
2583     }
2584     return E;
2585   }
2586 }
2587 
IgnoreConversionOperator()2588 Expr *Expr::IgnoreConversionOperator() {
2589   if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
2590     if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl()))
2591       return MCE->getImplicitObjectArgument();
2592   }
2593   return this;
2594 }
2595 
2596 /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
2597 /// value (including ptr->int casts of the same size).  Strip off any
2598 /// ParenExpr or CastExprs, returning their operand.
IgnoreParenNoopCasts(ASTContext & Ctx)2599 Expr *Expr::IgnoreParenNoopCasts(ASTContext &Ctx) {
2600   Expr *E = this;
2601   while (true) {
2602     E = E->IgnoreParens();
2603 
2604     if (CastExpr *P = dyn_cast<CastExpr>(E)) {
2605       // We ignore integer <-> casts that are of the same width, ptr<->ptr and
2606       // ptr<->int casts of the same width.  We also ignore all identity casts.
2607       Expr *SE = P->getSubExpr();
2608 
2609       if (Ctx.hasSameUnqualifiedType(E->getType(), SE->getType())) {
2610         E = SE;
2611         continue;
2612       }
2613 
2614       if ((E->getType()->isPointerType() ||
2615            E->getType()->isIntegralType(Ctx)) &&
2616           (SE->getType()->isPointerType() ||
2617            SE->getType()->isIntegralType(Ctx)) &&
2618           Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SE->getType())) {
2619         E = SE;
2620         continue;
2621       }
2622     }
2623 
2624     if (SubstNonTypeTemplateParmExpr *NTTP
2625                                   = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
2626       E = NTTP->getReplacement();
2627       continue;
2628     }
2629 
2630     return E;
2631   }
2632 }
2633 
isDefaultArgument() const2634 bool Expr::isDefaultArgument() const {
2635   const Expr *E = this;
2636   if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2637     E = M->GetTemporaryExpr();
2638 
2639   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
2640     E = ICE->getSubExprAsWritten();
2641 
2642   return isa<CXXDefaultArgExpr>(E);
2643 }
2644 
2645 /// \brief Skip over any no-op casts and any temporary-binding
2646 /// expressions.
skipTemporaryBindingsNoOpCastsAndParens(const Expr * E)2647 static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {
2648   if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2649     E = M->GetTemporaryExpr();
2650 
2651   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2652     if (ICE->getCastKind() == CK_NoOp)
2653       E = ICE->getSubExpr();
2654     else
2655       break;
2656   }
2657 
2658   while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
2659     E = BE->getSubExpr();
2660 
2661   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2662     if (ICE->getCastKind() == CK_NoOp)
2663       E = ICE->getSubExpr();
2664     else
2665       break;
2666   }
2667 
2668   return E->IgnoreParens();
2669 }
2670 
2671 /// isTemporaryObject - Determines if this expression produces a
2672 /// temporary of the given class type.
isTemporaryObject(ASTContext & C,const CXXRecordDecl * TempTy) const2673 bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
2674   if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
2675     return false;
2676 
2677   const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);
2678 
2679   // Temporaries are by definition pr-values of class type.
2680   if (!E->Classify(C).isPRValue()) {
2681     // In this context, property reference is a message call and is pr-value.
2682     if (!isa<ObjCPropertyRefExpr>(E))
2683       return false;
2684   }
2685 
2686   // Black-list a few cases which yield pr-values of class type that don't
2687   // refer to temporaries of that type:
2688 
2689   // - implicit derived-to-base conversions
2690   if (isa<ImplicitCastExpr>(E)) {
2691     switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
2692     case CK_DerivedToBase:
2693     case CK_UncheckedDerivedToBase:
2694       return false;
2695     default:
2696       break;
2697     }
2698   }
2699 
2700   // - member expressions (all)
2701   if (isa<MemberExpr>(E))
2702     return false;
2703 
2704   if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E))
2705     if (BO->isPtrMemOp())
2706       return false;
2707 
2708   // - opaque values (all)
2709   if (isa<OpaqueValueExpr>(E))
2710     return false;
2711 
2712   return true;
2713 }
2714 
isImplicitCXXThis() const2715 bool Expr::isImplicitCXXThis() const {
2716   const Expr *E = this;
2717 
2718   // Strip away parentheses and casts we don't care about.
2719   while (true) {
2720     if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
2721       E = Paren->getSubExpr();
2722       continue;
2723     }
2724 
2725     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2726       if (ICE->getCastKind() == CK_NoOp ||
2727           ICE->getCastKind() == CK_LValueToRValue ||
2728           ICE->getCastKind() == CK_DerivedToBase ||
2729           ICE->getCastKind() == CK_UncheckedDerivedToBase) {
2730         E = ICE->getSubExpr();
2731         continue;
2732       }
2733     }
2734 
2735     if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
2736       if (UnOp->getOpcode() == UO_Extension) {
2737         E = UnOp->getSubExpr();
2738         continue;
2739       }
2740     }
2741 
2742     if (const MaterializeTemporaryExpr *M
2743                                       = dyn_cast<MaterializeTemporaryExpr>(E)) {
2744       E = M->GetTemporaryExpr();
2745       continue;
2746     }
2747 
2748     break;
2749   }
2750 
2751   if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
2752     return This->isImplicit();
2753 
2754   return false;
2755 }
2756 
2757 /// hasAnyTypeDependentArguments - Determines if any of the expressions
2758 /// in Exprs is type-dependent.
hasAnyTypeDependentArguments(ArrayRef<Expr * > Exprs)2759 bool Expr::hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs) {
2760   for (unsigned I = 0; I < Exprs.size(); ++I)
2761     if (Exprs[I]->isTypeDependent())
2762       return true;
2763 
2764   return false;
2765 }
2766 
isConstantInitializer(ASTContext & Ctx,bool IsForRef,const Expr ** Culprit) const2767 bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,
2768                                  const Expr **Culprit) const {
2769   // This function is attempting whether an expression is an initializer
2770   // which can be evaluated at compile-time. It very closely parallels
2771   // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it
2772   // will lead to unexpected results.  Like ConstExprEmitter, it falls back
2773   // to isEvaluatable most of the time.
2774   //
2775   // If we ever capture reference-binding directly in the AST, we can
2776   // kill the second parameter.
2777 
2778   if (IsForRef) {
2779     EvalResult Result;
2780     if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects)
2781       return true;
2782     if (Culprit)
2783       *Culprit = this;
2784     return false;
2785   }
2786 
2787   switch (getStmtClass()) {
2788   default: break;
2789   case StringLiteralClass:
2790   case ObjCEncodeExprClass:
2791     return true;
2792   case CXXTemporaryObjectExprClass:
2793   case CXXConstructExprClass: {
2794     const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
2795 
2796     if (CE->getConstructor()->isTrivial() &&
2797         CE->getConstructor()->getParent()->hasTrivialDestructor()) {
2798       // Trivial default constructor
2799       if (!CE->getNumArgs()) return true;
2800 
2801       // Trivial copy constructor
2802       assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument");
2803       return CE->getArg(0)->isConstantInitializer(Ctx, false, Culprit);
2804     }
2805 
2806     break;
2807   }
2808   case CompoundLiteralExprClass: {
2809     // This handles gcc's extension that allows global initializers like
2810     // "struct x {int x;} x = (struct x) {};".
2811     // FIXME: This accepts other cases it shouldn't!
2812     const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
2813     return Exp->isConstantInitializer(Ctx, false, Culprit);
2814   }
2815   case DesignatedInitUpdateExprClass: {
2816     const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(this);
2817     return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) &&
2818            DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit);
2819   }
2820   case InitListExprClass: {
2821     const InitListExpr *ILE = cast<InitListExpr>(this);
2822     if (ILE->getType()->isArrayType()) {
2823       unsigned numInits = ILE->getNumInits();
2824       for (unsigned i = 0; i < numInits; i++) {
2825         if (!ILE->getInit(i)->isConstantInitializer(Ctx, false, Culprit))
2826           return false;
2827       }
2828       return true;
2829     }
2830 
2831     if (ILE->getType()->isRecordType()) {
2832       unsigned ElementNo = 0;
2833       RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl();
2834       for (const auto *Field : RD->fields()) {
2835         // If this is a union, skip all the fields that aren't being initialized.
2836         if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
2837           continue;
2838 
2839         // Don't emit anonymous bitfields, they just affect layout.
2840         if (Field->isUnnamedBitfield())
2841           continue;
2842 
2843         if (ElementNo < ILE->getNumInits()) {
2844           const Expr *Elt = ILE->getInit(ElementNo++);
2845           if (Field->isBitField()) {
2846             // Bitfields have to evaluate to an integer.
2847             llvm::APSInt ResultTmp;
2848             if (!Elt->EvaluateAsInt(ResultTmp, Ctx)) {
2849               if (Culprit)
2850                 *Culprit = Elt;
2851               return false;
2852             }
2853           } else {
2854             bool RefType = Field->getType()->isReferenceType();
2855             if (!Elt->isConstantInitializer(Ctx, RefType, Culprit))
2856               return false;
2857           }
2858         }
2859       }
2860       return true;
2861     }
2862 
2863     break;
2864   }
2865   case ImplicitValueInitExprClass:
2866   case NoInitExprClass:
2867     return true;
2868   case ParenExprClass:
2869     return cast<ParenExpr>(this)->getSubExpr()
2870       ->isConstantInitializer(Ctx, IsForRef, Culprit);
2871   case GenericSelectionExprClass:
2872     return cast<GenericSelectionExpr>(this)->getResultExpr()
2873       ->isConstantInitializer(Ctx, IsForRef, Culprit);
2874   case ChooseExprClass:
2875     if (cast<ChooseExpr>(this)->isConditionDependent()) {
2876       if (Culprit)
2877         *Culprit = this;
2878       return false;
2879     }
2880     return cast<ChooseExpr>(this)->getChosenSubExpr()
2881       ->isConstantInitializer(Ctx, IsForRef, Culprit);
2882   case UnaryOperatorClass: {
2883     const UnaryOperator* Exp = cast<UnaryOperator>(this);
2884     if (Exp->getOpcode() == UO_Extension)
2885       return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
2886     break;
2887   }
2888   case CXXFunctionalCastExprClass:
2889   case CXXStaticCastExprClass:
2890   case ImplicitCastExprClass:
2891   case CStyleCastExprClass:
2892   case ObjCBridgedCastExprClass:
2893   case CXXDynamicCastExprClass:
2894   case CXXReinterpretCastExprClass:
2895   case CXXConstCastExprClass: {
2896     const CastExpr *CE = cast<CastExpr>(this);
2897 
2898     // Handle misc casts we want to ignore.
2899     if (CE->getCastKind() == CK_NoOp ||
2900         CE->getCastKind() == CK_LValueToRValue ||
2901         CE->getCastKind() == CK_ToUnion ||
2902         CE->getCastKind() == CK_ConstructorConversion ||
2903         CE->getCastKind() == CK_NonAtomicToAtomic ||
2904         CE->getCastKind() == CK_AtomicToNonAtomic)
2905       return CE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
2906 
2907     break;
2908   }
2909   case MaterializeTemporaryExprClass:
2910     return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
2911       ->isConstantInitializer(Ctx, false, Culprit);
2912 
2913   case SubstNonTypeTemplateParmExprClass:
2914     return cast<SubstNonTypeTemplateParmExpr>(this)->getReplacement()
2915       ->isConstantInitializer(Ctx, false, Culprit);
2916   case CXXDefaultArgExprClass:
2917     return cast<CXXDefaultArgExpr>(this)->getExpr()
2918       ->isConstantInitializer(Ctx, false, Culprit);
2919   case CXXDefaultInitExprClass:
2920     return cast<CXXDefaultInitExpr>(this)->getExpr()
2921       ->isConstantInitializer(Ctx, false, Culprit);
2922   }
2923   // Allow certain forms of UB in constant initializers: signed integer
2924   // overflow and floating-point division by zero. We'll give a warning on
2925   // these, but they're common enough that we have to accept them.
2926   if (isEvaluatable(Ctx, SE_AllowUndefinedBehavior))
2927     return true;
2928   if (Culprit)
2929     *Culprit = this;
2930   return false;
2931 }
2932 
2933 namespace {
2934   /// \brief Look for any side effects within a Stmt.
2935   class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> {
2936     typedef ConstEvaluatedExprVisitor<SideEffectFinder> Inherited;
2937     const bool IncludePossibleEffects;
2938     bool HasSideEffects;
2939 
2940   public:
SideEffectFinder(const ASTContext & Context,bool IncludePossible)2941     explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible)
2942       : Inherited(Context),
2943         IncludePossibleEffects(IncludePossible), HasSideEffects(false) { }
2944 
hasSideEffects() const2945     bool hasSideEffects() const { return HasSideEffects; }
2946 
VisitExpr(const Expr * E)2947     void VisitExpr(const Expr *E) {
2948       if (!HasSideEffects &&
2949           E->HasSideEffects(Context, IncludePossibleEffects))
2950         HasSideEffects = true;
2951     }
2952   };
2953 }
2954 
HasSideEffects(const ASTContext & Ctx,bool IncludePossibleEffects) const2955 bool Expr::HasSideEffects(const ASTContext &Ctx,
2956                           bool IncludePossibleEffects) const {
2957   // In circumstances where we care about definite side effects instead of
2958   // potential side effects, we want to ignore expressions that are part of a
2959   // macro expansion as a potential side effect.
2960   if (!IncludePossibleEffects && getExprLoc().isMacroID())
2961     return false;
2962 
2963   if (isInstantiationDependent())
2964     return IncludePossibleEffects;
2965 
2966   switch (getStmtClass()) {
2967   case NoStmtClass:
2968   #define ABSTRACT_STMT(Type)
2969   #define STMT(Type, Base) case Type##Class:
2970   #define EXPR(Type, Base)
2971   #include "clang/AST/StmtNodes.inc"
2972     llvm_unreachable("unexpected Expr kind");
2973 
2974   case DependentScopeDeclRefExprClass:
2975   case CXXUnresolvedConstructExprClass:
2976   case CXXDependentScopeMemberExprClass:
2977   case UnresolvedLookupExprClass:
2978   case UnresolvedMemberExprClass:
2979   case PackExpansionExprClass:
2980   case SubstNonTypeTemplateParmPackExprClass:
2981   case FunctionParmPackExprClass:
2982   case TypoExprClass:
2983   case CXXFoldExprClass:
2984     llvm_unreachable("shouldn't see dependent / unresolved nodes here");
2985 
2986   case DeclRefExprClass:
2987   case ObjCIvarRefExprClass:
2988   case PredefinedExprClass:
2989   case IntegerLiteralClass:
2990   case FloatingLiteralClass:
2991   case ImaginaryLiteralClass:
2992   case StringLiteralClass:
2993   case CharacterLiteralClass:
2994   case OffsetOfExprClass:
2995   case ImplicitValueInitExprClass:
2996   case UnaryExprOrTypeTraitExprClass:
2997   case AddrLabelExprClass:
2998   case GNUNullExprClass:
2999   case NoInitExprClass:
3000   case CXXBoolLiteralExprClass:
3001   case CXXNullPtrLiteralExprClass:
3002   case CXXThisExprClass:
3003   case CXXScalarValueInitExprClass:
3004   case TypeTraitExprClass:
3005   case ArrayTypeTraitExprClass:
3006   case ExpressionTraitExprClass:
3007   case CXXNoexceptExprClass:
3008   case SizeOfPackExprClass:
3009   case ObjCStringLiteralClass:
3010   case ObjCEncodeExprClass:
3011   case ObjCBoolLiteralExprClass:
3012   case CXXUuidofExprClass:
3013   case OpaqueValueExprClass:
3014     // These never have a side-effect.
3015     return false;
3016 
3017   case CallExprClass:
3018   case CXXOperatorCallExprClass:
3019   case CXXMemberCallExprClass:
3020   case CUDAKernelCallExprClass:
3021   case UserDefinedLiteralClass: {
3022     // We don't know a call definitely has side effects, except for calls
3023     // to pure/const functions that definitely don't.
3024     // If the call itself is considered side-effect free, check the operands.
3025     const Decl *FD = cast<CallExpr>(this)->getCalleeDecl();
3026     bool IsPure = FD && (FD->hasAttr<ConstAttr>() || FD->hasAttr<PureAttr>());
3027     if (IsPure || !IncludePossibleEffects)
3028       break;
3029     return true;
3030   }
3031 
3032   case BlockExprClass:
3033   case CXXBindTemporaryExprClass:
3034     if (!IncludePossibleEffects)
3035       break;
3036     return true;
3037 
3038   case MSPropertyRefExprClass:
3039   case MSPropertySubscriptExprClass:
3040   case CompoundAssignOperatorClass:
3041   case VAArgExprClass:
3042   case AtomicExprClass:
3043   case CXXThrowExprClass:
3044   case CXXNewExprClass:
3045   case CXXDeleteExprClass:
3046   case ExprWithCleanupsClass:
3047   case CoawaitExprClass:
3048   case CoyieldExprClass:
3049     // These always have a side-effect.
3050     return true;
3051 
3052   case StmtExprClass: {
3053     // StmtExprs have a side-effect if any substatement does.
3054     SideEffectFinder Finder(Ctx, IncludePossibleEffects);
3055     Finder.Visit(cast<StmtExpr>(this)->getSubStmt());
3056     return Finder.hasSideEffects();
3057   }
3058 
3059   case ParenExprClass:
3060   case ArraySubscriptExprClass:
3061   case OMPArraySectionExprClass:
3062   case MemberExprClass:
3063   case ConditionalOperatorClass:
3064   case BinaryConditionalOperatorClass:
3065   case CompoundLiteralExprClass:
3066   case ExtVectorElementExprClass:
3067   case DesignatedInitExprClass:
3068   case DesignatedInitUpdateExprClass:
3069   case ParenListExprClass:
3070   case CXXPseudoDestructorExprClass:
3071   case CXXStdInitializerListExprClass:
3072   case SubstNonTypeTemplateParmExprClass:
3073   case MaterializeTemporaryExprClass:
3074   case ShuffleVectorExprClass:
3075   case ConvertVectorExprClass:
3076   case AsTypeExprClass:
3077     // These have a side-effect if any subexpression does.
3078     break;
3079 
3080   case UnaryOperatorClass:
3081     if (cast<UnaryOperator>(this)->isIncrementDecrementOp())
3082       return true;
3083     break;
3084 
3085   case BinaryOperatorClass:
3086     if (cast<BinaryOperator>(this)->isAssignmentOp())
3087       return true;
3088     break;
3089 
3090   case InitListExprClass:
3091     // FIXME: The children for an InitListExpr doesn't include the array filler.
3092     if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())
3093       if (E->HasSideEffects(Ctx, IncludePossibleEffects))
3094         return true;
3095     break;
3096 
3097   case GenericSelectionExprClass:
3098     return cast<GenericSelectionExpr>(this)->getResultExpr()->
3099         HasSideEffects(Ctx, IncludePossibleEffects);
3100 
3101   case ChooseExprClass:
3102     return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(
3103         Ctx, IncludePossibleEffects);
3104 
3105   case CXXDefaultArgExprClass:
3106     return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(
3107         Ctx, IncludePossibleEffects);
3108 
3109   case CXXDefaultInitExprClass: {
3110     const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField();
3111     if (const Expr *E = FD->getInClassInitializer())
3112       return E->HasSideEffects(Ctx, IncludePossibleEffects);
3113     // If we've not yet parsed the initializer, assume it has side-effects.
3114     return true;
3115   }
3116 
3117   case CXXDynamicCastExprClass: {
3118     // A dynamic_cast expression has side-effects if it can throw.
3119     const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this);
3120     if (DCE->getTypeAsWritten()->isReferenceType() &&
3121         DCE->getCastKind() == CK_Dynamic)
3122       return true;
3123   } // Fall through.
3124   case ImplicitCastExprClass:
3125   case CStyleCastExprClass:
3126   case CXXStaticCastExprClass:
3127   case CXXReinterpretCastExprClass:
3128   case CXXConstCastExprClass:
3129   case CXXFunctionalCastExprClass: {
3130     // While volatile reads are side-effecting in both C and C++, we treat them
3131     // as having possible (not definite) side-effects. This allows idiomatic
3132     // code to behave without warning, such as sizeof(*v) for a volatile-
3133     // qualified pointer.
3134     if (!IncludePossibleEffects)
3135       break;
3136 
3137     const CastExpr *CE = cast<CastExpr>(this);
3138     if (CE->getCastKind() == CK_LValueToRValue &&
3139         CE->getSubExpr()->getType().isVolatileQualified())
3140       return true;
3141     break;
3142   }
3143 
3144   case CXXTypeidExprClass:
3145     // typeid might throw if its subexpression is potentially-evaluated, so has
3146     // side-effects in that case whether or not its subexpression does.
3147     return cast<CXXTypeidExpr>(this)->isPotentiallyEvaluated();
3148 
3149   case CXXConstructExprClass:
3150   case CXXTemporaryObjectExprClass: {
3151     const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
3152     if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects)
3153       return true;
3154     // A trivial constructor does not add any side-effects of its own. Just look
3155     // at its arguments.
3156     break;
3157   }
3158 
3159   case LambdaExprClass: {
3160     const LambdaExpr *LE = cast<LambdaExpr>(this);
3161     for (LambdaExpr::capture_iterator I = LE->capture_begin(),
3162                                       E = LE->capture_end(); I != E; ++I)
3163       if (I->getCaptureKind() == LCK_ByCopy)
3164         // FIXME: Only has a side-effect if the variable is volatile or if
3165         // the copy would invoke a non-trivial copy constructor.
3166         return true;
3167     return false;
3168   }
3169 
3170   case PseudoObjectExprClass: {
3171     // Only look for side-effects in the semantic form, and look past
3172     // OpaqueValueExpr bindings in that form.
3173     const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
3174     for (PseudoObjectExpr::const_semantics_iterator I = PO->semantics_begin(),
3175                                                     E = PO->semantics_end();
3176          I != E; ++I) {
3177       const Expr *Subexpr = *I;
3178       if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))
3179         Subexpr = OVE->getSourceExpr();
3180       if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects))
3181         return true;
3182     }
3183     return false;
3184   }
3185 
3186   case ObjCBoxedExprClass:
3187   case ObjCArrayLiteralClass:
3188   case ObjCDictionaryLiteralClass:
3189   case ObjCSelectorExprClass:
3190   case ObjCProtocolExprClass:
3191   case ObjCIsaExprClass:
3192   case ObjCIndirectCopyRestoreExprClass:
3193   case ObjCSubscriptRefExprClass:
3194   case ObjCBridgedCastExprClass:
3195   case ObjCMessageExprClass:
3196   case ObjCPropertyRefExprClass:
3197   // FIXME: Classify these cases better.
3198     if (IncludePossibleEffects)
3199       return true;
3200     break;
3201   }
3202 
3203   // Recurse to children.
3204   for (const Stmt *SubStmt : children())
3205     if (SubStmt &&
3206         cast<Expr>(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects))
3207       return true;
3208 
3209   return false;
3210 }
3211 
3212 namespace {
3213   /// \brief Look for a call to a non-trivial function within an expression.
3214   class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder>
3215   {
3216     typedef ConstEvaluatedExprVisitor<NonTrivialCallFinder> Inherited;
3217 
3218     bool NonTrivial;
3219 
3220   public:
NonTrivialCallFinder(const ASTContext & Context)3221     explicit NonTrivialCallFinder(const ASTContext &Context)
3222       : Inherited(Context), NonTrivial(false) { }
3223 
hasNonTrivialCall() const3224     bool hasNonTrivialCall() const { return NonTrivial; }
3225 
VisitCallExpr(const CallExpr * E)3226     void VisitCallExpr(const CallExpr *E) {
3227       if (const CXXMethodDecl *Method
3228           = dyn_cast_or_null<const CXXMethodDecl>(E->getCalleeDecl())) {
3229         if (Method->isTrivial()) {
3230           // Recurse to children of the call.
3231           Inherited::VisitStmt(E);
3232           return;
3233         }
3234       }
3235 
3236       NonTrivial = true;
3237     }
3238 
VisitCXXConstructExpr(const CXXConstructExpr * E)3239     void VisitCXXConstructExpr(const CXXConstructExpr *E) {
3240       if (E->getConstructor()->isTrivial()) {
3241         // Recurse to children of the call.
3242         Inherited::VisitStmt(E);
3243         return;
3244       }
3245 
3246       NonTrivial = true;
3247     }
3248 
VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr * E)3249     void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
3250       if (E->getTemporary()->getDestructor()->isTrivial()) {
3251         Inherited::VisitStmt(E);
3252         return;
3253       }
3254 
3255       NonTrivial = true;
3256     }
3257   };
3258 }
3259 
hasNonTrivialCall(const ASTContext & Ctx) const3260 bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const {
3261   NonTrivialCallFinder Finder(Ctx);
3262   Finder.Visit(this);
3263   return Finder.hasNonTrivialCall();
3264 }
3265 
3266 /// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
3267 /// pointer constant or not, as well as the specific kind of constant detected.
3268 /// Null pointer constants can be integer constant expressions with the
3269 /// value zero, casts of zero to void*, nullptr (C++0X), or __null
3270 /// (a GNU extension).
3271 Expr::NullPointerConstantKind
isNullPointerConstant(ASTContext & Ctx,NullPointerConstantValueDependence NPC) const3272 Expr::isNullPointerConstant(ASTContext &Ctx,
3273                             NullPointerConstantValueDependence NPC) const {
3274   if (isValueDependent() &&
3275       (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) {
3276     switch (NPC) {
3277     case NPC_NeverValueDependent:
3278       llvm_unreachable("Unexpected value dependent expression!");
3279     case NPC_ValueDependentIsNull:
3280       if (isTypeDependent() || getType()->isIntegralType(Ctx))
3281         return NPCK_ZeroExpression;
3282       else
3283         return NPCK_NotNull;
3284 
3285     case NPC_ValueDependentIsNotNull:
3286       return NPCK_NotNull;
3287     }
3288   }
3289 
3290   // Strip off a cast to void*, if it exists. Except in C++.
3291   if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
3292     if (!Ctx.getLangOpts().CPlusPlus) {
3293       // Check that it is a cast to void*.
3294       if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
3295         QualType Pointee = PT->getPointeeType();
3296         Qualifiers Q = Pointee.getQualifiers();
3297         // In OpenCL v2.0 generic address space acts as a placeholder
3298         // and should be ignored.
3299         bool IsASValid = true;
3300         if (Ctx.getLangOpts().OpenCLVersion >= 200) {
3301           if (Pointee.getAddressSpace() == LangAS::opencl_generic)
3302             Q.removeAddressSpace();
3303           else
3304             IsASValid = false;
3305         }
3306 
3307         if (IsASValid && !Q.hasQualifiers() &&
3308             Pointee->isVoidType() &&                      // to void*
3309             CE->getSubExpr()->getType()->isIntegerType()) // from int.
3310           return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3311       }
3312     }
3313   } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
3314     // Ignore the ImplicitCastExpr type entirely.
3315     return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3316   } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
3317     // Accept ((void*)0) as a null pointer constant, as many other
3318     // implementations do.
3319     return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3320   } else if (const GenericSelectionExpr *GE =
3321                dyn_cast<GenericSelectionExpr>(this)) {
3322     if (GE->isResultDependent())
3323       return NPCK_NotNull;
3324     return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
3325   } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(this)) {
3326     if (CE->isConditionDependent())
3327       return NPCK_NotNull;
3328     return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC);
3329   } else if (const CXXDefaultArgExpr *DefaultArg
3330                = dyn_cast<CXXDefaultArgExpr>(this)) {
3331     // See through default argument expressions.
3332     return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
3333   } else if (const CXXDefaultInitExpr *DefaultInit
3334                = dyn_cast<CXXDefaultInitExpr>(this)) {
3335     // See through default initializer expressions.
3336     return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC);
3337   } else if (isa<GNUNullExpr>(this)) {
3338     // The GNU __null extension is always a null pointer constant.
3339     return NPCK_GNUNull;
3340   } else if (const MaterializeTemporaryExpr *M
3341                                    = dyn_cast<MaterializeTemporaryExpr>(this)) {
3342     return M->GetTemporaryExpr()->isNullPointerConstant(Ctx, NPC);
3343   } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
3344     if (const Expr *Source = OVE->getSourceExpr())
3345       return Source->isNullPointerConstant(Ctx, NPC);
3346   }
3347 
3348   // C++11 nullptr_t is always a null pointer constant.
3349   if (getType()->isNullPtrType())
3350     return NPCK_CXX11_nullptr;
3351 
3352   if (const RecordType *UT = getType()->getAsUnionType())
3353     if (!Ctx.getLangOpts().CPlusPlus11 &&
3354         UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
3355       if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
3356         const Expr *InitExpr = CLE->getInitializer();
3357         if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
3358           return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
3359       }
3360   // This expression must be an integer type.
3361   if (!getType()->isIntegerType() ||
3362       (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
3363     return NPCK_NotNull;
3364 
3365   if (Ctx.getLangOpts().CPlusPlus11) {
3366     // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with
3367     // value zero or a prvalue of type std::nullptr_t.
3368     // Microsoft mode permits C++98 rules reflecting MSVC behavior.
3369     const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(this);
3370     if (Lit && !Lit->getValue())
3371       return NPCK_ZeroLiteral;
3372     else if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx))
3373       return NPCK_NotNull;
3374   } else {
3375     // If we have an integer constant expression, we need to *evaluate* it and
3376     // test for the value 0.
3377     if (!isIntegerConstantExpr(Ctx))
3378       return NPCK_NotNull;
3379   }
3380 
3381   if (EvaluateKnownConstInt(Ctx) != 0)
3382     return NPCK_NotNull;
3383 
3384   if (isa<IntegerLiteral>(this))
3385     return NPCK_ZeroLiteral;
3386   return NPCK_ZeroExpression;
3387 }
3388 
3389 /// \brief If this expression is an l-value for an Objective C
3390 /// property, find the underlying property reference expression.
getObjCProperty() const3391 const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
3392   const Expr *E = this;
3393   while (true) {
3394     assert((E->getValueKind() == VK_LValue &&
3395             E->getObjectKind() == OK_ObjCProperty) &&
3396            "expression is not a property reference");
3397     E = E->IgnoreParenCasts();
3398     if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3399       if (BO->getOpcode() == BO_Comma) {
3400         E = BO->getRHS();
3401         continue;
3402       }
3403     }
3404 
3405     break;
3406   }
3407 
3408   return cast<ObjCPropertyRefExpr>(E);
3409 }
3410 
isObjCSelfExpr() const3411 bool Expr::isObjCSelfExpr() const {
3412   const Expr *E = IgnoreParenImpCasts();
3413 
3414   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
3415   if (!DRE)
3416     return false;
3417 
3418   const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl());
3419   if (!Param)
3420     return false;
3421 
3422   const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext());
3423   if (!M)
3424     return false;
3425 
3426   return M->getSelfDecl() == Param;
3427 }
3428 
getSourceBitField()3429 FieldDecl *Expr::getSourceBitField() {
3430   Expr *E = this->IgnoreParens();
3431 
3432   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3433     if (ICE->getCastKind() == CK_LValueToRValue ||
3434         (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp))
3435       E = ICE->getSubExpr()->IgnoreParens();
3436     else
3437       break;
3438   }
3439 
3440   if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
3441     if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
3442       if (Field->isBitField())
3443         return Field;
3444 
3445   if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E))
3446     if (FieldDecl *Ivar = dyn_cast<FieldDecl>(IvarRef->getDecl()))
3447       if (Ivar->isBitField())
3448         return Ivar;
3449 
3450   if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E))
3451     if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
3452       if (Field->isBitField())
3453         return Field;
3454 
3455   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
3456     if (BinOp->isAssignmentOp() && BinOp->getLHS())
3457       return BinOp->getLHS()->getSourceBitField();
3458 
3459     if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
3460       return BinOp->getRHS()->getSourceBitField();
3461   }
3462 
3463   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E))
3464     if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp())
3465       return UnOp->getSubExpr()->getSourceBitField();
3466 
3467   return nullptr;
3468 }
3469 
refersToVectorElement() const3470 bool Expr::refersToVectorElement() const {
3471   const Expr *E = this->IgnoreParens();
3472 
3473   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3474     if (ICE->getValueKind() != VK_RValue &&
3475         ICE->getCastKind() == CK_NoOp)
3476       E = ICE->getSubExpr()->IgnoreParens();
3477     else
3478       break;
3479   }
3480 
3481   if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
3482     return ASE->getBase()->getType()->isVectorType();
3483 
3484   if (isa<ExtVectorElementExpr>(E))
3485     return true;
3486 
3487   return false;
3488 }
3489 
refersToGlobalRegisterVar() const3490 bool Expr::refersToGlobalRegisterVar() const {
3491   const Expr *E = this->IgnoreParenImpCasts();
3492 
3493   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3494     if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
3495       if (VD->getStorageClass() == SC_Register &&
3496           VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
3497         return true;
3498 
3499   return false;
3500 }
3501 
3502 /// isArrow - Return true if the base expression is a pointer to vector,
3503 /// return false if the base expression is a vector.
isArrow() const3504 bool ExtVectorElementExpr::isArrow() const {
3505   return getBase()->getType()->isPointerType();
3506 }
3507 
getNumElements() const3508 unsigned ExtVectorElementExpr::getNumElements() const {
3509   if (const VectorType *VT = getType()->getAs<VectorType>())
3510     return VT->getNumElements();
3511   return 1;
3512 }
3513 
3514 /// containsDuplicateElements - Return true if any element access is repeated.
containsDuplicateElements() const3515 bool ExtVectorElementExpr::containsDuplicateElements() const {
3516   // FIXME: Refactor this code to an accessor on the AST node which returns the
3517   // "type" of component access, and share with code below and in Sema.
3518   StringRef Comp = Accessor->getName();
3519 
3520   // Halving swizzles do not contain duplicate elements.
3521   if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
3522     return false;
3523 
3524   // Advance past s-char prefix on hex swizzles.
3525   if (Comp[0] == 's' || Comp[0] == 'S')
3526     Comp = Comp.substr(1);
3527 
3528   for (unsigned i = 0, e = Comp.size(); i != e; ++i)
3529     if (Comp.substr(i + 1).find(Comp[i]) != StringRef::npos)
3530         return true;
3531 
3532   return false;
3533 }
3534 
3535 /// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
getEncodedElementAccess(SmallVectorImpl<uint32_t> & Elts) const3536 void ExtVectorElementExpr::getEncodedElementAccess(
3537     SmallVectorImpl<uint32_t> &Elts) const {
3538   StringRef Comp = Accessor->getName();
3539   if (Comp[0] == 's' || Comp[0] == 'S')
3540     Comp = Comp.substr(1);
3541 
3542   bool isHi =   Comp == "hi";
3543   bool isLo =   Comp == "lo";
3544   bool isEven = Comp == "even";
3545   bool isOdd  = Comp == "odd";
3546 
3547   for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
3548     uint64_t Index;
3549 
3550     if (isHi)
3551       Index = e + i;
3552     else if (isLo)
3553       Index = i;
3554     else if (isEven)
3555       Index = 2 * i;
3556     else if (isOdd)
3557       Index = 2 * i + 1;
3558     else
3559       Index = ExtVectorType::getAccessorIdx(Comp[i]);
3560 
3561     Elts.push_back(Index);
3562   }
3563 }
3564 
ShuffleVectorExpr(const ASTContext & C,ArrayRef<Expr * > args,QualType Type,SourceLocation BLoc,SourceLocation RP)3565 ShuffleVectorExpr::ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args,
3566                                      QualType Type, SourceLocation BLoc,
3567                                      SourceLocation RP)
3568    : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary,
3569           Type->isDependentType(), Type->isDependentType(),
3570           Type->isInstantiationDependentType(),
3571           Type->containsUnexpandedParameterPack()),
3572      BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size())
3573 {
3574   SubExprs = new (C) Stmt*[args.size()];
3575   for (unsigned i = 0; i != args.size(); i++) {
3576     if (args[i]->isTypeDependent())
3577       ExprBits.TypeDependent = true;
3578     if (args[i]->isValueDependent())
3579       ExprBits.ValueDependent = true;
3580     if (args[i]->isInstantiationDependent())
3581       ExprBits.InstantiationDependent = true;
3582     if (args[i]->containsUnexpandedParameterPack())
3583       ExprBits.ContainsUnexpandedParameterPack = true;
3584 
3585     SubExprs[i] = args[i];
3586   }
3587 }
3588 
setExprs(const ASTContext & C,ArrayRef<Expr * > Exprs)3589 void ShuffleVectorExpr::setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs) {
3590   if (SubExprs) C.Deallocate(SubExprs);
3591 
3592   this->NumExprs = Exprs.size();
3593   SubExprs = new (C) Stmt*[NumExprs];
3594   memcpy(SubExprs, Exprs.data(), sizeof(Expr *) * Exprs.size());
3595 }
3596 
GenericSelectionExpr(const ASTContext & Context,SourceLocation GenericLoc,Expr * ControllingExpr,ArrayRef<TypeSourceInfo * > AssocTypes,ArrayRef<Expr * > AssocExprs,SourceLocation DefaultLoc,SourceLocation RParenLoc,bool ContainsUnexpandedParameterPack,unsigned ResultIndex)3597 GenericSelectionExpr::GenericSelectionExpr(const ASTContext &Context,
3598                                SourceLocation GenericLoc, Expr *ControllingExpr,
3599                                ArrayRef<TypeSourceInfo*> AssocTypes,
3600                                ArrayRef<Expr*> AssocExprs,
3601                                SourceLocation DefaultLoc,
3602                                SourceLocation RParenLoc,
3603                                bool ContainsUnexpandedParameterPack,
3604                                unsigned ResultIndex)
3605   : Expr(GenericSelectionExprClass,
3606          AssocExprs[ResultIndex]->getType(),
3607          AssocExprs[ResultIndex]->getValueKind(),
3608          AssocExprs[ResultIndex]->getObjectKind(),
3609          AssocExprs[ResultIndex]->isTypeDependent(),
3610          AssocExprs[ResultIndex]->isValueDependent(),
3611          AssocExprs[ResultIndex]->isInstantiationDependent(),
3612          ContainsUnexpandedParameterPack),
3613     AssocTypes(new (Context) TypeSourceInfo*[AssocTypes.size()]),
3614     SubExprs(new (Context) Stmt*[END_EXPR+AssocExprs.size()]),
3615     NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
3616     GenericLoc(GenericLoc), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
3617   SubExprs[CONTROLLING] = ControllingExpr;
3618   assert(AssocTypes.size() == AssocExprs.size());
3619   std::copy(AssocTypes.begin(), AssocTypes.end(), this->AssocTypes);
3620   std::copy(AssocExprs.begin(), AssocExprs.end(), SubExprs+END_EXPR);
3621 }
3622 
GenericSelectionExpr(const ASTContext & Context,SourceLocation GenericLoc,Expr * ControllingExpr,ArrayRef<TypeSourceInfo * > AssocTypes,ArrayRef<Expr * > AssocExprs,SourceLocation DefaultLoc,SourceLocation RParenLoc,bool ContainsUnexpandedParameterPack)3623 GenericSelectionExpr::GenericSelectionExpr(const ASTContext &Context,
3624                                SourceLocation GenericLoc, Expr *ControllingExpr,
3625                                ArrayRef<TypeSourceInfo*> AssocTypes,
3626                                ArrayRef<Expr*> AssocExprs,
3627                                SourceLocation DefaultLoc,
3628                                SourceLocation RParenLoc,
3629                                bool ContainsUnexpandedParameterPack)
3630   : Expr(GenericSelectionExprClass,
3631          Context.DependentTy,
3632          VK_RValue,
3633          OK_Ordinary,
3634          /*isTypeDependent=*/true,
3635          /*isValueDependent=*/true,
3636          /*isInstantiationDependent=*/true,
3637          ContainsUnexpandedParameterPack),
3638     AssocTypes(new (Context) TypeSourceInfo*[AssocTypes.size()]),
3639     SubExprs(new (Context) Stmt*[END_EXPR+AssocExprs.size()]),
3640     NumAssocs(AssocExprs.size()), ResultIndex(-1U), GenericLoc(GenericLoc),
3641     DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
3642   SubExprs[CONTROLLING] = ControllingExpr;
3643   assert(AssocTypes.size() == AssocExprs.size());
3644   std::copy(AssocTypes.begin(), AssocTypes.end(), this->AssocTypes);
3645   std::copy(AssocExprs.begin(), AssocExprs.end(), SubExprs+END_EXPR);
3646 }
3647 
3648 //===----------------------------------------------------------------------===//
3649 //  DesignatedInitExpr
3650 //===----------------------------------------------------------------------===//
3651 
getFieldName() const3652 IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const {
3653   assert(Kind == FieldDesignator && "Only valid on a field designator");
3654   if (Field.NameOrField & 0x01)
3655     return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01);
3656   else
3657     return getField()->getIdentifier();
3658 }
3659 
DesignatedInitExpr(const ASTContext & C,QualType Ty,unsigned NumDesignators,const Designator * Designators,SourceLocation EqualOrColonLoc,bool GNUSyntax,ArrayRef<Expr * > IndexExprs,Expr * Init)3660 DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty,
3661                                        unsigned NumDesignators,
3662                                        const Designator *Designators,
3663                                        SourceLocation EqualOrColonLoc,
3664                                        bool GNUSyntax,
3665                                        ArrayRef<Expr*> IndexExprs,
3666                                        Expr *Init)
3667   : Expr(DesignatedInitExprClass, Ty,
3668          Init->getValueKind(), Init->getObjectKind(),
3669          Init->isTypeDependent(), Init->isValueDependent(),
3670          Init->isInstantiationDependent(),
3671          Init->containsUnexpandedParameterPack()),
3672     EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
3673     NumDesignators(NumDesignators), NumSubExprs(IndexExprs.size() + 1) {
3674   this->Designators = new (C) Designator[NumDesignators];
3675 
3676   // Record the initializer itself.
3677   child_iterator Child = child_begin();
3678   *Child++ = Init;
3679 
3680   // Copy the designators and their subexpressions, computing
3681   // value-dependence along the way.
3682   unsigned IndexIdx = 0;
3683   for (unsigned I = 0; I != NumDesignators; ++I) {
3684     this->Designators[I] = Designators[I];
3685 
3686     if (this->Designators[I].isArrayDesignator()) {
3687       // Compute type- and value-dependence.
3688       Expr *Index = IndexExprs[IndexIdx];
3689       if (Index->isTypeDependent() || Index->isValueDependent())
3690         ExprBits.TypeDependent = ExprBits.ValueDependent = true;
3691       if (Index->isInstantiationDependent())
3692         ExprBits.InstantiationDependent = true;
3693       // Propagate unexpanded parameter packs.
3694       if (Index->containsUnexpandedParameterPack())
3695         ExprBits.ContainsUnexpandedParameterPack = true;
3696 
3697       // Copy the index expressions into permanent storage.
3698       *Child++ = IndexExprs[IndexIdx++];
3699     } else if (this->Designators[I].isArrayRangeDesignator()) {
3700       // Compute type- and value-dependence.
3701       Expr *Start = IndexExprs[IndexIdx];
3702       Expr *End = IndexExprs[IndexIdx + 1];
3703       if (Start->isTypeDependent() || Start->isValueDependent() ||
3704           End->isTypeDependent() || End->isValueDependent()) {
3705         ExprBits.TypeDependent = ExprBits.ValueDependent = true;
3706         ExprBits.InstantiationDependent = true;
3707       } else if (Start->isInstantiationDependent() ||
3708                  End->isInstantiationDependent()) {
3709         ExprBits.InstantiationDependent = true;
3710       }
3711 
3712       // Propagate unexpanded parameter packs.
3713       if (Start->containsUnexpandedParameterPack() ||
3714           End->containsUnexpandedParameterPack())
3715         ExprBits.ContainsUnexpandedParameterPack = true;
3716 
3717       // Copy the start/end expressions into permanent storage.
3718       *Child++ = IndexExprs[IndexIdx++];
3719       *Child++ = IndexExprs[IndexIdx++];
3720     }
3721   }
3722 
3723   assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions");
3724 }
3725 
3726 DesignatedInitExpr *
Create(const ASTContext & C,Designator * Designators,unsigned NumDesignators,ArrayRef<Expr * > IndexExprs,SourceLocation ColonOrEqualLoc,bool UsesColonSyntax,Expr * Init)3727 DesignatedInitExpr::Create(const ASTContext &C, Designator *Designators,
3728                            unsigned NumDesignators,
3729                            ArrayRef<Expr*> IndexExprs,
3730                            SourceLocation ColonOrEqualLoc,
3731                            bool UsesColonSyntax, Expr *Init) {
3732   void *Mem = C.Allocate(sizeof(DesignatedInitExpr) +
3733                              sizeof(Stmt *) * (IndexExprs.size() + 1),
3734                          llvm::alignOf<DesignatedInitExpr>());
3735   return new (Mem) DesignatedInitExpr(C, C.VoidTy, NumDesignators, Designators,
3736                                       ColonOrEqualLoc, UsesColonSyntax,
3737                                       IndexExprs, Init);
3738 }
3739 
CreateEmpty(const ASTContext & C,unsigned NumIndexExprs)3740 DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(const ASTContext &C,
3741                                                     unsigned NumIndexExprs) {
3742   void *Mem = C.Allocate(sizeof(DesignatedInitExpr) +
3743                          sizeof(Stmt *) * (NumIndexExprs + 1), 8);
3744   return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
3745 }
3746 
setDesignators(const ASTContext & C,const Designator * Desigs,unsigned NumDesigs)3747 void DesignatedInitExpr::setDesignators(const ASTContext &C,
3748                                         const Designator *Desigs,
3749                                         unsigned NumDesigs) {
3750   Designators = new (C) Designator[NumDesigs];
3751   NumDesignators = NumDesigs;
3752   for (unsigned I = 0; I != NumDesigs; ++I)
3753     Designators[I] = Desigs[I];
3754 }
3755 
getDesignatorsSourceRange() const3756 SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const {
3757   DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
3758   if (size() == 1)
3759     return DIE->getDesignator(0)->getSourceRange();
3760   return SourceRange(DIE->getDesignator(0)->getLocStart(),
3761                      DIE->getDesignator(size()-1)->getLocEnd());
3762 }
3763 
getLocStart() const3764 SourceLocation DesignatedInitExpr::getLocStart() const {
3765   SourceLocation StartLoc;
3766   Designator &First =
3767     *const_cast<DesignatedInitExpr*>(this)->designators_begin();
3768   if (First.isFieldDesignator()) {
3769     if (GNUSyntax)
3770       StartLoc = SourceLocation::getFromRawEncoding(First.Field.FieldLoc);
3771     else
3772       StartLoc = SourceLocation::getFromRawEncoding(First.Field.DotLoc);
3773   } else
3774     StartLoc =
3775       SourceLocation::getFromRawEncoding(First.ArrayOrRange.LBracketLoc);
3776   return StartLoc;
3777 }
3778 
getLocEnd() const3779 SourceLocation DesignatedInitExpr::getLocEnd() const {
3780   return getInit()->getLocEnd();
3781 }
3782 
getArrayIndex(const Designator & D) const3783 Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) const {
3784   assert(D.Kind == Designator::ArrayDesignator && "Requires array designator");
3785   Stmt *const *SubExprs = reinterpret_cast<Stmt *const *>(this + 1);
3786   return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 1));
3787 }
3788 
getArrayRangeStart(const Designator & D) const3789 Expr *DesignatedInitExpr::getArrayRangeStart(const Designator &D) const {
3790   assert(D.Kind == Designator::ArrayRangeDesignator &&
3791          "Requires array range designator");
3792   Stmt *const *SubExprs = reinterpret_cast<Stmt *const *>(this + 1);
3793   return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 1));
3794 }
3795 
getArrayRangeEnd(const Designator & D) const3796 Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator &D) const {
3797   assert(D.Kind == Designator::ArrayRangeDesignator &&
3798          "Requires array range designator");
3799   Stmt *const *SubExprs = reinterpret_cast<Stmt *const *>(this + 1);
3800   return cast<Expr>(*(SubExprs + D.ArrayOrRange.Index + 2));
3801 }
3802 
3803 /// \brief Replaces the designator at index @p Idx with the series
3804 /// of designators in [First, Last).
ExpandDesignator(const ASTContext & C,unsigned Idx,const Designator * First,const Designator * Last)3805 void DesignatedInitExpr::ExpandDesignator(const ASTContext &C, unsigned Idx,
3806                                           const Designator *First,
3807                                           const Designator *Last) {
3808   unsigned NumNewDesignators = Last - First;
3809   if (NumNewDesignators == 0) {
3810     std::copy_backward(Designators + Idx + 1,
3811                        Designators + NumDesignators,
3812                        Designators + Idx);
3813     --NumNewDesignators;
3814     return;
3815   } else if (NumNewDesignators == 1) {
3816     Designators[Idx] = *First;
3817     return;
3818   }
3819 
3820   Designator *NewDesignators
3821     = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
3822   std::copy(Designators, Designators + Idx, NewDesignators);
3823   std::copy(First, Last, NewDesignators + Idx);
3824   std::copy(Designators + Idx + 1, Designators + NumDesignators,
3825             NewDesignators + Idx + NumNewDesignators);
3826   Designators = NewDesignators;
3827   NumDesignators = NumDesignators - 1 + NumNewDesignators;
3828 }
3829 
DesignatedInitUpdateExpr(const ASTContext & C,SourceLocation lBraceLoc,Expr * baseExpr,SourceLocation rBraceLoc)3830 DesignatedInitUpdateExpr::DesignatedInitUpdateExpr(const ASTContext &C,
3831     SourceLocation lBraceLoc, Expr *baseExpr, SourceLocation rBraceLoc)
3832   : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_RValue,
3833          OK_Ordinary, false, false, false, false) {
3834   BaseAndUpdaterExprs[0] = baseExpr;
3835 
3836   InitListExpr *ILE = new (C) InitListExpr(C, lBraceLoc, None, rBraceLoc);
3837   ILE->setType(baseExpr->getType());
3838   BaseAndUpdaterExprs[1] = ILE;
3839 }
3840 
getLocStart() const3841 SourceLocation DesignatedInitUpdateExpr::getLocStart() const {
3842   return getBase()->getLocStart();
3843 }
3844 
getLocEnd() const3845 SourceLocation DesignatedInitUpdateExpr::getLocEnd() const {
3846   return getBase()->getLocEnd();
3847 }
3848 
ParenListExpr(const ASTContext & C,SourceLocation lparenloc,ArrayRef<Expr * > exprs,SourceLocation rparenloc)3849 ParenListExpr::ParenListExpr(const ASTContext& C, SourceLocation lparenloc,
3850                              ArrayRef<Expr*> exprs,
3851                              SourceLocation rparenloc)
3852   : Expr(ParenListExprClass, QualType(), VK_RValue, OK_Ordinary,
3853          false, false, false, false),
3854     NumExprs(exprs.size()), LParenLoc(lparenloc), RParenLoc(rparenloc) {
3855   Exprs = new (C) Stmt*[exprs.size()];
3856   for (unsigned i = 0; i != exprs.size(); ++i) {
3857     if (exprs[i]->isTypeDependent())
3858       ExprBits.TypeDependent = true;
3859     if (exprs[i]->isValueDependent())
3860       ExprBits.ValueDependent = true;
3861     if (exprs[i]->isInstantiationDependent())
3862       ExprBits.InstantiationDependent = true;
3863     if (exprs[i]->containsUnexpandedParameterPack())
3864       ExprBits.ContainsUnexpandedParameterPack = true;
3865 
3866     Exprs[i] = exprs[i];
3867   }
3868 }
3869 
findInCopyConstruct(const Expr * e)3870 const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {
3871   if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
3872     e = ewc->getSubExpr();
3873   if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
3874     e = m->GetTemporaryExpr();
3875   e = cast<CXXConstructExpr>(e)->getArg(0);
3876   while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
3877     e = ice->getSubExpr();
3878   return cast<OpaqueValueExpr>(e);
3879 }
3880 
Create(const ASTContext & Context,EmptyShell sh,unsigned numSemanticExprs)3881 PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &Context,
3882                                            EmptyShell sh,
3883                                            unsigned numSemanticExprs) {
3884   void *buffer = Context.Allocate(sizeof(PseudoObjectExpr) +
3885                                     (1 + numSemanticExprs) * sizeof(Expr*),
3886                                   llvm::alignOf<PseudoObjectExpr>());
3887   return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
3888 }
3889 
PseudoObjectExpr(EmptyShell shell,unsigned numSemanticExprs)3890 PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
3891   : Expr(PseudoObjectExprClass, shell) {
3892   PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
3893 }
3894 
Create(const ASTContext & C,Expr * syntax,ArrayRef<Expr * > semantics,unsigned resultIndex)3895 PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &C, Expr *syntax,
3896                                            ArrayRef<Expr*> semantics,
3897                                            unsigned resultIndex) {
3898   assert(syntax && "no syntactic expression!");
3899   assert(semantics.size() && "no semantic expressions!");
3900 
3901   QualType type;
3902   ExprValueKind VK;
3903   if (resultIndex == NoResult) {
3904     type = C.VoidTy;
3905     VK = VK_RValue;
3906   } else {
3907     assert(resultIndex < semantics.size());
3908     type = semantics[resultIndex]->getType();
3909     VK = semantics[resultIndex]->getValueKind();
3910     assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary);
3911   }
3912 
3913   void *buffer = C.Allocate(sizeof(PseudoObjectExpr) +
3914                               (1 + semantics.size()) * sizeof(Expr*),
3915                             llvm::alignOf<PseudoObjectExpr>());
3916   return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
3917                                       resultIndex);
3918 }
3919 
PseudoObjectExpr(QualType type,ExprValueKind VK,Expr * syntax,ArrayRef<Expr * > semantics,unsigned resultIndex)3920 PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
3921                                    Expr *syntax, ArrayRef<Expr*> semantics,
3922                                    unsigned resultIndex)
3923   : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary,
3924          /*filled in at end of ctor*/ false, false, false, false) {
3925   PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
3926   PseudoObjectExprBits.ResultIndex = resultIndex + 1;
3927 
3928   for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) {
3929     Expr *E = (i == 0 ? syntax : semantics[i-1]);
3930     getSubExprsBuffer()[i] = E;
3931 
3932     if (E->isTypeDependent())
3933       ExprBits.TypeDependent = true;
3934     if (E->isValueDependent())
3935       ExprBits.ValueDependent = true;
3936     if (E->isInstantiationDependent())
3937       ExprBits.InstantiationDependent = true;
3938     if (E->containsUnexpandedParameterPack())
3939       ExprBits.ContainsUnexpandedParameterPack = true;
3940 
3941     if (isa<OpaqueValueExpr>(E))
3942       assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr &&
3943              "opaque-value semantic expressions for pseudo-object "
3944              "operations must have sources");
3945   }
3946 }
3947 
3948 //===----------------------------------------------------------------------===//
3949 //  Child Iterators for iterating over subexpressions/substatements
3950 //===----------------------------------------------------------------------===//
3951 
3952 // UnaryExprOrTypeTraitExpr
children()3953 Stmt::child_range UnaryExprOrTypeTraitExpr::children() {
3954   // If this is of a type and the type is a VLA type (and not a typedef), the
3955   // size expression of the VLA needs to be treated as an executable expression.
3956   // Why isn't this weirdness documented better in StmtIterator?
3957   if (isArgumentType()) {
3958     if (const VariableArrayType* T = dyn_cast<VariableArrayType>(
3959                                    getArgumentType().getTypePtr()))
3960       return child_range(child_iterator(T), child_iterator());
3961     return child_range(child_iterator(), child_iterator());
3962   }
3963   return child_range(&Argument.Ex, &Argument.Ex + 1);
3964 }
3965 
AtomicExpr(SourceLocation BLoc,ArrayRef<Expr * > args,QualType t,AtomicOp op,SourceLocation RP)3966 AtomicExpr::AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args,
3967                        QualType t, AtomicOp op, SourceLocation RP)
3968   : Expr(AtomicExprClass, t, VK_RValue, OK_Ordinary,
3969          false, false, false, false),
3970     NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op)
3971 {
3972   assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions");
3973   for (unsigned i = 0; i != args.size(); i++) {
3974     if (args[i]->isTypeDependent())
3975       ExprBits.TypeDependent = true;
3976     if (args[i]->isValueDependent())
3977       ExprBits.ValueDependent = true;
3978     if (args[i]->isInstantiationDependent())
3979       ExprBits.InstantiationDependent = true;
3980     if (args[i]->containsUnexpandedParameterPack())
3981       ExprBits.ContainsUnexpandedParameterPack = true;
3982 
3983     SubExprs[i] = args[i];
3984   }
3985 }
3986 
getNumSubExprs(AtomicOp Op)3987 unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) {
3988   switch (Op) {
3989   case AO__c11_atomic_init:
3990   case AO__c11_atomic_load:
3991   case AO__atomic_load_n:
3992     return 2;
3993 
3994   case AO__c11_atomic_store:
3995   case AO__c11_atomic_exchange:
3996   case AO__atomic_load:
3997   case AO__atomic_store:
3998   case AO__atomic_store_n:
3999   case AO__atomic_exchange_n:
4000   case AO__c11_atomic_fetch_add:
4001   case AO__c11_atomic_fetch_sub:
4002   case AO__c11_atomic_fetch_and:
4003   case AO__c11_atomic_fetch_or:
4004   case AO__c11_atomic_fetch_xor:
4005   case AO__atomic_fetch_add:
4006   case AO__atomic_fetch_sub:
4007   case AO__atomic_fetch_and:
4008   case AO__atomic_fetch_or:
4009   case AO__atomic_fetch_xor:
4010   case AO__atomic_fetch_nand:
4011   case AO__atomic_add_fetch:
4012   case AO__atomic_sub_fetch:
4013   case AO__atomic_and_fetch:
4014   case AO__atomic_or_fetch:
4015   case AO__atomic_xor_fetch:
4016   case AO__atomic_nand_fetch:
4017     return 3;
4018 
4019   case AO__atomic_exchange:
4020     return 4;
4021 
4022   case AO__c11_atomic_compare_exchange_strong:
4023   case AO__c11_atomic_compare_exchange_weak:
4024     return 5;
4025 
4026   case AO__atomic_compare_exchange:
4027   case AO__atomic_compare_exchange_n:
4028     return 6;
4029   }
4030   llvm_unreachable("unknown atomic op");
4031 }
4032 
getBaseOriginalType(Expr * Base)4033 QualType OMPArraySectionExpr::getBaseOriginalType(Expr *Base) {
4034   unsigned ArraySectionCount = 0;
4035   while (auto *OASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParens())) {
4036     Base = OASE->getBase();
4037     ++ArraySectionCount;
4038   }
4039   while (auto *ASE = dyn_cast<ArraySubscriptExpr>(Base->IgnoreParens())) {
4040     Base = ASE->getBase();
4041     ++ArraySectionCount;
4042   }
4043   auto OriginalTy = Base->getType();
4044   if (auto *DRE = dyn_cast<DeclRefExpr>(Base))
4045     if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
4046       OriginalTy = PVD->getOriginalType().getNonReferenceType();
4047 
4048   for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) {
4049     if (OriginalTy->isAnyPointerType())
4050       OriginalTy = OriginalTy->getPointeeType();
4051     else {
4052       assert (OriginalTy->isArrayType());
4053       OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType();
4054     }
4055   }
4056   return OriginalTy;
4057 }
4058 
4059