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