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