xref: /llvm-project-15.0.7/clang/lib/AST/Expr.cpp (revision 9a728701)
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 
1362   return nullptr;
1363 }
1364 
1365 /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID. If
1366 /// not, return 0.
1367 unsigned CallExpr::getBuiltinCallee() const {
1368   // All simple function calls (e.g. func()) are implicitly cast to pointer to
1369   // function. As a result, we try and obtain the DeclRefExpr from the
1370   // ImplicitCastExpr.
1371   const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(getCallee());
1372   if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()).
1373     return 0;
1374 
1375   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr());
1376   if (!DRE)
1377     return 0;
1378 
1379   const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
1380   if (!FDecl)
1381     return 0;
1382 
1383   if (!FDecl->getIdentifier())
1384     return 0;
1385 
1386   return FDecl->getBuiltinID();
1387 }
1388 
1389 bool CallExpr::isUnevaluatedBuiltinCall(const ASTContext &Ctx) const {
1390   if (unsigned BI = getBuiltinCallee())
1391     return Ctx.BuiltinInfo.isUnevaluated(BI);
1392   return false;
1393 }
1394 
1395 QualType CallExpr::getCallReturnType(const ASTContext &Ctx) const {
1396   const Expr *Callee = getCallee();
1397   QualType CalleeType = Callee->getType();
1398   if (const auto *FnTypePtr = CalleeType->getAs<PointerType>()) {
1399     CalleeType = FnTypePtr->getPointeeType();
1400   } else if (const auto *BPT = CalleeType->getAs<BlockPointerType>()) {
1401     CalleeType = BPT->getPointeeType();
1402   } else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
1403     if (isa<CXXPseudoDestructorExpr>(Callee->IgnoreParens()))
1404       return Ctx.VoidTy;
1405 
1406     // This should never be overloaded and so should never return null.
1407     CalleeType = Expr::findBoundMemberType(Callee);
1408   }
1409 
1410   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
1411   return FnType->getReturnType();
1412 }
1413 
1414 const Attr *CallExpr::getUnusedResultAttr(const ASTContext &Ctx) const {
1415   // If the return type is a struct, union, or enum that is marked nodiscard,
1416   // then return the return type attribute.
1417   if (const TagDecl *TD = getCallReturnType(Ctx)->getAsTagDecl())
1418     if (const auto *A = TD->getAttr<WarnUnusedResultAttr>())
1419       return A;
1420 
1421   // Otherwise, see if the callee is marked nodiscard and return that attribute
1422   // instead.
1423   const Decl *D = getCalleeDecl();
1424   return D ? D->getAttr<WarnUnusedResultAttr>() : nullptr;
1425 }
1426 
1427 SourceLocation CallExpr::getBeginLoc() const {
1428   if (isa<CXXOperatorCallExpr>(this))
1429     return cast<CXXOperatorCallExpr>(this)->getBeginLoc();
1430 
1431   SourceLocation begin = getCallee()->getBeginLoc();
1432   if (begin.isInvalid() && getNumArgs() > 0 && getArg(0))
1433     begin = getArg(0)->getBeginLoc();
1434   return begin;
1435 }
1436 SourceLocation CallExpr::getEndLoc() const {
1437   if (isa<CXXOperatorCallExpr>(this))
1438     return cast<CXXOperatorCallExpr>(this)->getEndLoc();
1439 
1440   SourceLocation end = getRParenLoc();
1441   if (end.isInvalid() && getNumArgs() > 0 && getArg(getNumArgs() - 1))
1442     end = getArg(getNumArgs() - 1)->getEndLoc();
1443   return end;
1444 }
1445 
1446 OffsetOfExpr *OffsetOfExpr::Create(const ASTContext &C, QualType type,
1447                                    SourceLocation OperatorLoc,
1448                                    TypeSourceInfo *tsi,
1449                                    ArrayRef<OffsetOfNode> comps,
1450                                    ArrayRef<Expr*> exprs,
1451                                    SourceLocation RParenLoc) {
1452   void *Mem = C.Allocate(
1453       totalSizeToAlloc<OffsetOfNode, Expr *>(comps.size(), exprs.size()));
1454 
1455   return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs,
1456                                 RParenLoc);
1457 }
1458 
1459 OffsetOfExpr *OffsetOfExpr::CreateEmpty(const ASTContext &C,
1460                                         unsigned numComps, unsigned numExprs) {
1461   void *Mem =
1462       C.Allocate(totalSizeToAlloc<OffsetOfNode, Expr *>(numComps, numExprs));
1463   return new (Mem) OffsetOfExpr(numComps, numExprs);
1464 }
1465 
1466 OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type,
1467                            SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1468                            ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
1469                            SourceLocation RParenLoc)
1470   : Expr(OffsetOfExprClass, type, VK_RValue, OK_Ordinary,
1471          /*TypeDependent=*/false,
1472          /*ValueDependent=*/tsi->getType()->isDependentType(),
1473          tsi->getType()->isInstantiationDependentType(),
1474          tsi->getType()->containsUnexpandedParameterPack()),
1475     OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
1476     NumComps(comps.size()), NumExprs(exprs.size())
1477 {
1478   for (unsigned i = 0; i != comps.size(); ++i) {
1479     setComponent(i, comps[i]);
1480   }
1481 
1482   for (unsigned i = 0; i != exprs.size(); ++i) {
1483     if (exprs[i]->isTypeDependent() || exprs[i]->isValueDependent())
1484       ExprBits.ValueDependent = true;
1485     if (exprs[i]->containsUnexpandedParameterPack())
1486       ExprBits.ContainsUnexpandedParameterPack = true;
1487 
1488     setIndexExpr(i, exprs[i]);
1489   }
1490 }
1491 
1492 IdentifierInfo *OffsetOfNode::getFieldName() const {
1493   assert(getKind() == Field || getKind() == Identifier);
1494   if (getKind() == Field)
1495     return getField()->getIdentifier();
1496 
1497   return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
1498 }
1499 
1500 UnaryExprOrTypeTraitExpr::UnaryExprOrTypeTraitExpr(
1501     UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType,
1502     SourceLocation op, SourceLocation rp)
1503     : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
1504            false, // Never type-dependent (C++ [temp.dep.expr]p3).
1505            // Value-dependent if the argument is type-dependent.
1506            E->isTypeDependent(), E->isInstantiationDependent(),
1507            E->containsUnexpandedParameterPack()),
1508       OpLoc(op), RParenLoc(rp) {
1509   UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1510   UnaryExprOrTypeTraitExprBits.IsType = false;
1511   Argument.Ex = E;
1512 
1513   // Check to see if we are in the situation where alignof(decl) should be
1514   // dependent because decl's alignment is dependent.
1515   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
1516     if (!isValueDependent() || !isInstantiationDependent()) {
1517       E = E->IgnoreParens();
1518 
1519       const ValueDecl *D = nullptr;
1520       if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
1521         D = DRE->getDecl();
1522       else if (const auto *ME = dyn_cast<MemberExpr>(E))
1523         D = ME->getMemberDecl();
1524 
1525       if (D) {
1526         for (const auto *I : D->specific_attrs<AlignedAttr>()) {
1527           if (I->isAlignmentDependent()) {
1528             setValueDependent(true);
1529             setInstantiationDependent(true);
1530             break;
1531           }
1532         }
1533       }
1534     }
1535   }
1536 }
1537 
1538 MemberExpr *MemberExpr::Create(
1539     const ASTContext &C, Expr *base, bool isarrow, SourceLocation OperatorLoc,
1540     NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
1541     ValueDecl *memberdecl, DeclAccessPair founddecl,
1542     DeclarationNameInfo nameinfo, const TemplateArgumentListInfo *targs,
1543     QualType ty, ExprValueKind vk, ExprObjectKind ok) {
1544 
1545   bool hasQualOrFound = (QualifierLoc ||
1546                          founddecl.getDecl() != memberdecl ||
1547                          founddecl.getAccess() != memberdecl->getAccess());
1548 
1549   bool HasTemplateKWAndArgsInfo = targs || TemplateKWLoc.isValid();
1550   std::size_t Size =
1551       totalSizeToAlloc<MemberExprNameQualifier, ASTTemplateKWAndArgsInfo,
1552                        TemplateArgumentLoc>(hasQualOrFound ? 1 : 0,
1553                                             HasTemplateKWAndArgsInfo ? 1 : 0,
1554                                             targs ? targs->size() : 0);
1555 
1556   void *Mem = C.Allocate(Size, alignof(MemberExpr));
1557   MemberExpr *E = new (Mem)
1558       MemberExpr(base, isarrow, OperatorLoc, memberdecl, nameinfo, ty, vk, ok);
1559 
1560   if (hasQualOrFound) {
1561     // FIXME: Wrong. We should be looking at the member declaration we found.
1562     if (QualifierLoc && QualifierLoc.getNestedNameSpecifier()->isDependent()) {
1563       E->setValueDependent(true);
1564       E->setTypeDependent(true);
1565       E->setInstantiationDependent(true);
1566     }
1567     else if (QualifierLoc &&
1568              QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent())
1569       E->setInstantiationDependent(true);
1570 
1571     E->MemberExprBits.HasQualifierOrFoundDecl = true;
1572 
1573     MemberExprNameQualifier *NQ =
1574         E->getTrailingObjects<MemberExprNameQualifier>();
1575     NQ->QualifierLoc = QualifierLoc;
1576     NQ->FoundDecl = founddecl;
1577   }
1578 
1579   E->MemberExprBits.HasTemplateKWAndArgsInfo =
1580       (targs || TemplateKWLoc.isValid());
1581 
1582   if (targs) {
1583     bool Dependent = false;
1584     bool InstantiationDependent = false;
1585     bool ContainsUnexpandedParameterPack = false;
1586     E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1587         TemplateKWLoc, *targs, E->getTrailingObjects<TemplateArgumentLoc>(),
1588         Dependent, InstantiationDependent, ContainsUnexpandedParameterPack);
1589     if (InstantiationDependent)
1590       E->setInstantiationDependent(true);
1591   } else if (TemplateKWLoc.isValid()) {
1592     E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1593         TemplateKWLoc);
1594   }
1595 
1596   return E;
1597 }
1598 
1599 SourceLocation MemberExpr::getBeginLoc() const {
1600   if (isImplicitAccess()) {
1601     if (hasQualifier())
1602       return getQualifierLoc().getBeginLoc();
1603     return MemberLoc;
1604   }
1605 
1606   // FIXME: We don't want this to happen. Rather, we should be able to
1607   // detect all kinds of implicit accesses more cleanly.
1608   SourceLocation BaseStartLoc = getBase()->getBeginLoc();
1609   if (BaseStartLoc.isValid())
1610     return BaseStartLoc;
1611   return MemberLoc;
1612 }
1613 SourceLocation MemberExpr::getEndLoc() const {
1614   SourceLocation EndLoc = getMemberNameInfo().getEndLoc();
1615   if (hasExplicitTemplateArgs())
1616     EndLoc = getRAngleLoc();
1617   else if (EndLoc.isInvalid())
1618     EndLoc = getBase()->getEndLoc();
1619   return EndLoc;
1620 }
1621 
1622 bool CastExpr::CastConsistency() const {
1623   switch (getCastKind()) {
1624   case CK_DerivedToBase:
1625   case CK_UncheckedDerivedToBase:
1626   case CK_DerivedToBaseMemberPointer:
1627   case CK_BaseToDerived:
1628   case CK_BaseToDerivedMemberPointer:
1629     assert(!path_empty() && "Cast kind should have a base path!");
1630     break;
1631 
1632   case CK_CPointerToObjCPointerCast:
1633     assert(getType()->isObjCObjectPointerType());
1634     assert(getSubExpr()->getType()->isPointerType());
1635     goto CheckNoBasePath;
1636 
1637   case CK_BlockPointerToObjCPointerCast:
1638     assert(getType()->isObjCObjectPointerType());
1639     assert(getSubExpr()->getType()->isBlockPointerType());
1640     goto CheckNoBasePath;
1641 
1642   case CK_ReinterpretMemberPointer:
1643     assert(getType()->isMemberPointerType());
1644     assert(getSubExpr()->getType()->isMemberPointerType());
1645     goto CheckNoBasePath;
1646 
1647   case CK_BitCast:
1648     // Arbitrary casts to C pointer types count as bitcasts.
1649     // Otherwise, we should only have block and ObjC pointer casts
1650     // here if they stay within the type kind.
1651     if (!getType()->isPointerType()) {
1652       assert(getType()->isObjCObjectPointerType() ==
1653              getSubExpr()->getType()->isObjCObjectPointerType());
1654       assert(getType()->isBlockPointerType() ==
1655              getSubExpr()->getType()->isBlockPointerType());
1656     }
1657     goto CheckNoBasePath;
1658 
1659   case CK_AnyPointerToBlockPointerCast:
1660     assert(getType()->isBlockPointerType());
1661     assert(getSubExpr()->getType()->isAnyPointerType() &&
1662            !getSubExpr()->getType()->isBlockPointerType());
1663     goto CheckNoBasePath;
1664 
1665   case CK_CopyAndAutoreleaseBlockObject:
1666     assert(getType()->isBlockPointerType());
1667     assert(getSubExpr()->getType()->isBlockPointerType());
1668     goto CheckNoBasePath;
1669 
1670   case CK_FunctionToPointerDecay:
1671     assert(getType()->isPointerType());
1672     assert(getSubExpr()->getType()->isFunctionType());
1673     goto CheckNoBasePath;
1674 
1675   case CK_AddressSpaceConversion: {
1676     auto Ty = getType();
1677     auto SETy = getSubExpr()->getType();
1678     assert(getValueKindForType(Ty) == Expr::getValueKindForType(SETy));
1679     if (isRValue()) {
1680       Ty = Ty->getPointeeType();
1681       SETy = SETy->getPointeeType();
1682     }
1683     assert(!Ty.isNull() && !SETy.isNull() &&
1684            Ty.getAddressSpace() != SETy.getAddressSpace());
1685     goto CheckNoBasePath;
1686   }
1687   // These should not have an inheritance path.
1688   case CK_Dynamic:
1689   case CK_ToUnion:
1690   case CK_ArrayToPointerDecay:
1691   case CK_NullToMemberPointer:
1692   case CK_NullToPointer:
1693   case CK_ConstructorConversion:
1694   case CK_IntegralToPointer:
1695   case CK_PointerToIntegral:
1696   case CK_ToVoid:
1697   case CK_VectorSplat:
1698   case CK_IntegralCast:
1699   case CK_BooleanToSignedIntegral:
1700   case CK_IntegralToFloating:
1701   case CK_FloatingToIntegral:
1702   case CK_FloatingCast:
1703   case CK_ObjCObjectLValueCast:
1704   case CK_FloatingRealToComplex:
1705   case CK_FloatingComplexToReal:
1706   case CK_FloatingComplexCast:
1707   case CK_FloatingComplexToIntegralComplex:
1708   case CK_IntegralRealToComplex:
1709   case CK_IntegralComplexToReal:
1710   case CK_IntegralComplexCast:
1711   case CK_IntegralComplexToFloatingComplex:
1712   case CK_ARCProduceObject:
1713   case CK_ARCConsumeObject:
1714   case CK_ARCReclaimReturnedObject:
1715   case CK_ARCExtendBlockObject:
1716   case CK_ZeroToOCLOpaqueType:
1717   case CK_IntToOCLSampler:
1718   case CK_FixedPointCast:
1719     assert(!getType()->isBooleanType() && "unheralded conversion to bool");
1720     goto CheckNoBasePath;
1721 
1722   case CK_Dependent:
1723   case CK_LValueToRValue:
1724   case CK_NoOp:
1725   case CK_AtomicToNonAtomic:
1726   case CK_NonAtomicToAtomic:
1727   case CK_PointerToBoolean:
1728   case CK_IntegralToBoolean:
1729   case CK_FloatingToBoolean:
1730   case CK_MemberPointerToBoolean:
1731   case CK_FloatingComplexToBoolean:
1732   case CK_IntegralComplexToBoolean:
1733   case CK_LValueBitCast:            // -> bool&
1734   case CK_UserDefinedConversion:    // operator bool()
1735   case CK_BuiltinFnToFnPtr:
1736   case CK_FixedPointToBoolean:
1737   CheckNoBasePath:
1738     assert(path_empty() && "Cast kind should not have a base path!");
1739     break;
1740   }
1741   return true;
1742 }
1743 
1744 const char *CastExpr::getCastKindName(CastKind CK) {
1745   switch (CK) {
1746 #define CAST_OPERATION(Name) case CK_##Name: return #Name;
1747 #include "clang/AST/OperationKinds.def"
1748   }
1749   llvm_unreachable("Unhandled cast kind!");
1750 }
1751 
1752 namespace {
1753   const Expr *skipImplicitTemporary(const Expr *E) {
1754     // Skip through reference binding to temporary.
1755     if (auto *Materialize = dyn_cast<MaterializeTemporaryExpr>(E))
1756       E = Materialize->GetTemporaryExpr();
1757 
1758     // Skip any temporary bindings; they're implicit.
1759     if (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
1760       E = Binder->getSubExpr();
1761 
1762     return E;
1763   }
1764 }
1765 
1766 Expr *CastExpr::getSubExprAsWritten() {
1767   const Expr *SubExpr = nullptr;
1768   const CastExpr *E = this;
1769   do {
1770     SubExpr = skipImplicitTemporary(E->getSubExpr());
1771 
1772     // Conversions by constructor and conversion functions have a
1773     // subexpression describing the call; strip it off.
1774     if (E->getCastKind() == CK_ConstructorConversion)
1775       SubExpr =
1776         skipImplicitTemporary(cast<CXXConstructExpr>(SubExpr)->getArg(0));
1777     else if (E->getCastKind() == CK_UserDefinedConversion) {
1778       assert((isa<CXXMemberCallExpr>(SubExpr) ||
1779               isa<BlockExpr>(SubExpr)) &&
1780              "Unexpected SubExpr for CK_UserDefinedConversion.");
1781       if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1782         SubExpr = MCE->getImplicitObjectArgument();
1783     }
1784 
1785     // If the subexpression we're left with is an implicit cast, look
1786     // through that, too.
1787   } while ((E = dyn_cast<ImplicitCastExpr>(SubExpr)));
1788 
1789   return const_cast<Expr*>(SubExpr);
1790 }
1791 
1792 NamedDecl *CastExpr::getConversionFunction() const {
1793   const Expr *SubExpr = nullptr;
1794 
1795   for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) {
1796     SubExpr = skipImplicitTemporary(E->getSubExpr());
1797 
1798     if (E->getCastKind() == CK_ConstructorConversion)
1799       return cast<CXXConstructExpr>(SubExpr)->getConstructor();
1800 
1801     if (E->getCastKind() == CK_UserDefinedConversion) {
1802       if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1803         return MCE->getMethodDecl();
1804     }
1805   }
1806 
1807   return nullptr;
1808 }
1809 
1810 CXXBaseSpecifier **CastExpr::path_buffer() {
1811   switch (getStmtClass()) {
1812 #define ABSTRACT_STMT(x)
1813 #define CASTEXPR(Type, Base)                                                   \
1814   case Stmt::Type##Class:                                                      \
1815     return static_cast<Type *>(this)->getTrailingObjects<CXXBaseSpecifier *>();
1816 #define STMT(Type, Base)
1817 #include "clang/AST/StmtNodes.inc"
1818   default:
1819     llvm_unreachable("non-cast expressions not possible here");
1820   }
1821 }
1822 
1823 const FieldDecl *CastExpr::getTargetFieldForToUnionCast(QualType unionType,
1824                                                         QualType opType) {
1825   auto RD = unionType->castAs<RecordType>()->getDecl();
1826   return getTargetFieldForToUnionCast(RD, opType);
1827 }
1828 
1829 const FieldDecl *CastExpr::getTargetFieldForToUnionCast(const RecordDecl *RD,
1830                                                         QualType OpType) {
1831   auto &Ctx = RD->getASTContext();
1832   RecordDecl::field_iterator Field, FieldEnd;
1833   for (Field = RD->field_begin(), FieldEnd = RD->field_end();
1834        Field != FieldEnd; ++Field) {
1835     if (Ctx.hasSameUnqualifiedType(Field->getType(), OpType) &&
1836         !Field->isUnnamedBitfield()) {
1837       return *Field;
1838     }
1839   }
1840   return nullptr;
1841 }
1842 
1843 ImplicitCastExpr *ImplicitCastExpr::Create(const ASTContext &C, QualType T,
1844                                            CastKind Kind, Expr *Operand,
1845                                            const CXXCastPath *BasePath,
1846                                            ExprValueKind VK) {
1847   unsigned PathSize = (BasePath ? BasePath->size() : 0);
1848   void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
1849   ImplicitCastExpr *E =
1850     new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, VK);
1851   if (PathSize)
1852     std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
1853                               E->getTrailingObjects<CXXBaseSpecifier *>());
1854   return E;
1855 }
1856 
1857 ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(const ASTContext &C,
1858                                                 unsigned PathSize) {
1859   void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
1860   return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize);
1861 }
1862 
1863 
1864 CStyleCastExpr *CStyleCastExpr::Create(const ASTContext &C, QualType T,
1865                                        ExprValueKind VK, CastKind K, Expr *Op,
1866                                        const CXXCastPath *BasePath,
1867                                        TypeSourceInfo *WrittenTy,
1868                                        SourceLocation L, SourceLocation R) {
1869   unsigned PathSize = (BasePath ? BasePath->size() : 0);
1870   void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
1871   CStyleCastExpr *E =
1872     new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, R);
1873   if (PathSize)
1874     std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
1875                               E->getTrailingObjects<CXXBaseSpecifier *>());
1876   return E;
1877 }
1878 
1879 CStyleCastExpr *CStyleCastExpr::CreateEmpty(const ASTContext &C,
1880                                             unsigned PathSize) {
1881   void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
1882   return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize);
1883 }
1884 
1885 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1886 /// corresponds to, e.g. "<<=".
1887 StringRef BinaryOperator::getOpcodeStr(Opcode Op) {
1888   switch (Op) {
1889 #define BINARY_OPERATION(Name, Spelling) case BO_##Name: return Spelling;
1890 #include "clang/AST/OperationKinds.def"
1891   }
1892   llvm_unreachable("Invalid OpCode!");
1893 }
1894 
1895 BinaryOperatorKind
1896 BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
1897   switch (OO) {
1898   default: llvm_unreachable("Not an overloadable binary operator");
1899   case OO_Plus: return BO_Add;
1900   case OO_Minus: return BO_Sub;
1901   case OO_Star: return BO_Mul;
1902   case OO_Slash: return BO_Div;
1903   case OO_Percent: return BO_Rem;
1904   case OO_Caret: return BO_Xor;
1905   case OO_Amp: return BO_And;
1906   case OO_Pipe: return BO_Or;
1907   case OO_Equal: return BO_Assign;
1908   case OO_Spaceship: return BO_Cmp;
1909   case OO_Less: return BO_LT;
1910   case OO_Greater: return BO_GT;
1911   case OO_PlusEqual: return BO_AddAssign;
1912   case OO_MinusEqual: return BO_SubAssign;
1913   case OO_StarEqual: return BO_MulAssign;
1914   case OO_SlashEqual: return BO_DivAssign;
1915   case OO_PercentEqual: return BO_RemAssign;
1916   case OO_CaretEqual: return BO_XorAssign;
1917   case OO_AmpEqual: return BO_AndAssign;
1918   case OO_PipeEqual: return BO_OrAssign;
1919   case OO_LessLess: return BO_Shl;
1920   case OO_GreaterGreater: return BO_Shr;
1921   case OO_LessLessEqual: return BO_ShlAssign;
1922   case OO_GreaterGreaterEqual: return BO_ShrAssign;
1923   case OO_EqualEqual: return BO_EQ;
1924   case OO_ExclaimEqual: return BO_NE;
1925   case OO_LessEqual: return BO_LE;
1926   case OO_GreaterEqual: return BO_GE;
1927   case OO_AmpAmp: return BO_LAnd;
1928   case OO_PipePipe: return BO_LOr;
1929   case OO_Comma: return BO_Comma;
1930   case OO_ArrowStar: return BO_PtrMemI;
1931   }
1932 }
1933 
1934 OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
1935   static const OverloadedOperatorKind OverOps[] = {
1936     /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
1937     OO_Star, OO_Slash, OO_Percent,
1938     OO_Plus, OO_Minus,
1939     OO_LessLess, OO_GreaterGreater,
1940     OO_Spaceship,
1941     OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
1942     OO_EqualEqual, OO_ExclaimEqual,
1943     OO_Amp,
1944     OO_Caret,
1945     OO_Pipe,
1946     OO_AmpAmp,
1947     OO_PipePipe,
1948     OO_Equal, OO_StarEqual,
1949     OO_SlashEqual, OO_PercentEqual,
1950     OO_PlusEqual, OO_MinusEqual,
1951     OO_LessLessEqual, OO_GreaterGreaterEqual,
1952     OO_AmpEqual, OO_CaretEqual,
1953     OO_PipeEqual,
1954     OO_Comma
1955   };
1956   return OverOps[Opc];
1957 }
1958 
1959 bool BinaryOperator::isNullPointerArithmeticExtension(ASTContext &Ctx,
1960                                                       Opcode Opc,
1961                                                       Expr *LHS, Expr *RHS) {
1962   if (Opc != BO_Add)
1963     return false;
1964 
1965   // Check that we have one pointer and one integer operand.
1966   Expr *PExp;
1967   if (LHS->getType()->isPointerType()) {
1968     if (!RHS->getType()->isIntegerType())
1969       return false;
1970     PExp = LHS;
1971   } else if (RHS->getType()->isPointerType()) {
1972     if (!LHS->getType()->isIntegerType())
1973       return false;
1974     PExp = RHS;
1975   } else {
1976     return false;
1977   }
1978 
1979   // Check that the pointer is a nullptr.
1980   if (!PExp->IgnoreParenCasts()
1981           ->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNotNull))
1982     return false;
1983 
1984   // Check that the pointee type is char-sized.
1985   const PointerType *PTy = PExp->getType()->getAs<PointerType>();
1986   if (!PTy || !PTy->getPointeeType()->isCharType())
1987     return false;
1988 
1989   return true;
1990 }
1991 InitListExpr::InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
1992                            ArrayRef<Expr*> initExprs, SourceLocation rbraceloc)
1993   : Expr(InitListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
1994          false, false),
1995     InitExprs(C, initExprs.size()),
1996     LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), AltForm(nullptr, true)
1997 {
1998   sawArrayRangeDesignator(false);
1999   for (unsigned I = 0; I != initExprs.size(); ++I) {
2000     if (initExprs[I]->isTypeDependent())
2001       ExprBits.TypeDependent = true;
2002     if (initExprs[I]->isValueDependent())
2003       ExprBits.ValueDependent = true;
2004     if (initExprs[I]->isInstantiationDependent())
2005       ExprBits.InstantiationDependent = true;
2006     if (initExprs[I]->containsUnexpandedParameterPack())
2007       ExprBits.ContainsUnexpandedParameterPack = true;
2008   }
2009 
2010   InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end());
2011 }
2012 
2013 void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) {
2014   if (NumInits > InitExprs.size())
2015     InitExprs.reserve(C, NumInits);
2016 }
2017 
2018 void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) {
2019   InitExprs.resize(C, NumInits, nullptr);
2020 }
2021 
2022 Expr *InitListExpr::updateInit(const ASTContext &C, unsigned Init, Expr *expr) {
2023   if (Init >= InitExprs.size()) {
2024     InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr);
2025     setInit(Init, expr);
2026     return nullptr;
2027   }
2028 
2029   Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
2030   setInit(Init, expr);
2031   return Result;
2032 }
2033 
2034 void InitListExpr::setArrayFiller(Expr *filler) {
2035   assert(!hasArrayFiller() && "Filler already set!");
2036   ArrayFillerOrUnionFieldInit = filler;
2037   // Fill out any "holes" in the array due to designated initializers.
2038   Expr **inits = getInits();
2039   for (unsigned i = 0, e = getNumInits(); i != e; ++i)
2040     if (inits[i] == nullptr)
2041       inits[i] = filler;
2042 }
2043 
2044 bool InitListExpr::isStringLiteralInit() const {
2045   if (getNumInits() != 1)
2046     return false;
2047   const ArrayType *AT = getType()->getAsArrayTypeUnsafe();
2048   if (!AT || !AT->getElementType()->isIntegerType())
2049     return false;
2050   // It is possible for getInit() to return null.
2051   const Expr *Init = getInit(0);
2052   if (!Init)
2053     return false;
2054   Init = Init->IgnoreParens();
2055   return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init);
2056 }
2057 
2058 bool InitListExpr::isTransparent() const {
2059   assert(isSemanticForm() && "syntactic form never semantically transparent");
2060 
2061   // A glvalue InitListExpr is always just sugar.
2062   if (isGLValue()) {
2063     assert(getNumInits() == 1 && "multiple inits in glvalue init list");
2064     return true;
2065   }
2066 
2067   // Otherwise, we're sugar if and only if we have exactly one initializer that
2068   // is of the same type.
2069   if (getNumInits() != 1 || !getInit(0))
2070     return false;
2071 
2072   // Don't confuse aggregate initialization of a struct X { X &x; }; with a
2073   // transparent struct copy.
2074   if (!getInit(0)->isRValue() && getType()->isRecordType())
2075     return false;
2076 
2077   return getType().getCanonicalType() ==
2078          getInit(0)->getType().getCanonicalType();
2079 }
2080 
2081 bool InitListExpr::isIdiomaticZeroInitializer(const LangOptions &LangOpts) const {
2082   assert(isSyntacticForm() && "only test syntactic form as zero initializer");
2083 
2084   if (LangOpts.CPlusPlus || getNumInits() != 1) {
2085     return false;
2086   }
2087 
2088   const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(getInit(0));
2089   return Lit && Lit->getValue() == 0;
2090 }
2091 
2092 SourceLocation InitListExpr::getBeginLoc() const {
2093   if (InitListExpr *SyntacticForm = getSyntacticForm())
2094     return SyntacticForm->getBeginLoc();
2095   SourceLocation Beg = LBraceLoc;
2096   if (Beg.isInvalid()) {
2097     // Find the first non-null initializer.
2098     for (InitExprsTy::const_iterator I = InitExprs.begin(),
2099                                      E = InitExprs.end();
2100       I != E; ++I) {
2101       if (Stmt *S = *I) {
2102         Beg = S->getBeginLoc();
2103         break;
2104       }
2105     }
2106   }
2107   return Beg;
2108 }
2109 
2110 SourceLocation InitListExpr::getEndLoc() const {
2111   if (InitListExpr *SyntacticForm = getSyntacticForm())
2112     return SyntacticForm->getEndLoc();
2113   SourceLocation End = RBraceLoc;
2114   if (End.isInvalid()) {
2115     // Find the first non-null initializer from the end.
2116     for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(),
2117          E = InitExprs.rend();
2118          I != E; ++I) {
2119       if (Stmt *S = *I) {
2120         End = S->getEndLoc();
2121         break;
2122       }
2123     }
2124   }
2125   return End;
2126 }
2127 
2128 /// getFunctionType - Return the underlying function type for this block.
2129 ///
2130 const FunctionProtoType *BlockExpr::getFunctionType() const {
2131   // The block pointer is never sugared, but the function type might be.
2132   return cast<BlockPointerType>(getType())
2133            ->getPointeeType()->castAs<FunctionProtoType>();
2134 }
2135 
2136 SourceLocation BlockExpr::getCaretLocation() const {
2137   return TheBlock->getCaretLocation();
2138 }
2139 const Stmt *BlockExpr::getBody() const {
2140   return TheBlock->getBody();
2141 }
2142 Stmt *BlockExpr::getBody() {
2143   return TheBlock->getBody();
2144 }
2145 
2146 
2147 //===----------------------------------------------------------------------===//
2148 // Generic Expression Routines
2149 //===----------------------------------------------------------------------===//
2150 
2151 /// isUnusedResultAWarning - Return true if this immediate expression should
2152 /// be warned about if the result is unused.  If so, fill in Loc and Ranges
2153 /// with location to warn on and the source range[s] to report with the
2154 /// warning.
2155 bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc,
2156                                   SourceRange &R1, SourceRange &R2,
2157                                   ASTContext &Ctx) const {
2158   // Don't warn if the expr is type dependent. The type could end up
2159   // instantiating to void.
2160   if (isTypeDependent())
2161     return false;
2162 
2163   switch (getStmtClass()) {
2164   default:
2165     if (getType()->isVoidType())
2166       return false;
2167     WarnE = this;
2168     Loc = getExprLoc();
2169     R1 = getSourceRange();
2170     return true;
2171   case ParenExprClass:
2172     return cast<ParenExpr>(this)->getSubExpr()->
2173       isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2174   case GenericSelectionExprClass:
2175     return cast<GenericSelectionExpr>(this)->getResultExpr()->
2176       isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2177   case CoawaitExprClass:
2178   case CoyieldExprClass:
2179     return cast<CoroutineSuspendExpr>(this)->getResumeExpr()->
2180       isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2181   case ChooseExprClass:
2182     return cast<ChooseExpr>(this)->getChosenSubExpr()->
2183       isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2184   case UnaryOperatorClass: {
2185     const UnaryOperator *UO = cast<UnaryOperator>(this);
2186 
2187     switch (UO->getOpcode()) {
2188     case UO_Plus:
2189     case UO_Minus:
2190     case UO_AddrOf:
2191     case UO_Not:
2192     case UO_LNot:
2193     case UO_Deref:
2194       break;
2195     case UO_Coawait:
2196       // This is just the 'operator co_await' call inside the guts of a
2197       // dependent co_await call.
2198     case UO_PostInc:
2199     case UO_PostDec:
2200     case UO_PreInc:
2201     case UO_PreDec:                 // ++/--
2202       return false;  // Not a warning.
2203     case UO_Real:
2204     case UO_Imag:
2205       // accessing a piece of a volatile complex is a side-effect.
2206       if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
2207           .isVolatileQualified())
2208         return false;
2209       break;
2210     case UO_Extension:
2211       return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2212     }
2213     WarnE = this;
2214     Loc = UO->getOperatorLoc();
2215     R1 = UO->getSubExpr()->getSourceRange();
2216     return true;
2217   }
2218   case BinaryOperatorClass: {
2219     const BinaryOperator *BO = cast<BinaryOperator>(this);
2220     switch (BO->getOpcode()) {
2221       default:
2222         break;
2223       // Consider the RHS of comma for side effects. LHS was checked by
2224       // Sema::CheckCommaOperands.
2225       case BO_Comma:
2226         // ((foo = <blah>), 0) is an idiom for hiding the result (and
2227         // lvalue-ness) of an assignment written in a macro.
2228         if (IntegerLiteral *IE =
2229               dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
2230           if (IE->getValue() == 0)
2231             return false;
2232         return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2233       // Consider '||', '&&' to have side effects if the LHS or RHS does.
2234       case BO_LAnd:
2235       case BO_LOr:
2236         if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||
2237             !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
2238           return false;
2239         break;
2240     }
2241     if (BO->isAssignmentOp())
2242       return false;
2243     WarnE = this;
2244     Loc = BO->getOperatorLoc();
2245     R1 = BO->getLHS()->getSourceRange();
2246     R2 = BO->getRHS()->getSourceRange();
2247     return true;
2248   }
2249   case CompoundAssignOperatorClass:
2250   case VAArgExprClass:
2251   case AtomicExprClass:
2252     return false;
2253 
2254   case ConditionalOperatorClass: {
2255     // If only one of the LHS or RHS is a warning, the operator might
2256     // be being used for control flow. Only warn if both the LHS and
2257     // RHS are warnings.
2258     const ConditionalOperator *Exp = cast<ConditionalOperator>(this);
2259     if (!Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
2260       return false;
2261     if (!Exp->getLHS())
2262       return true;
2263     return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2264   }
2265 
2266   case MemberExprClass:
2267     WarnE = this;
2268     Loc = cast<MemberExpr>(this)->getMemberLoc();
2269     R1 = SourceRange(Loc, Loc);
2270     R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
2271     return true;
2272 
2273   case ArraySubscriptExprClass:
2274     WarnE = this;
2275     Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
2276     R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
2277     R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
2278     return true;
2279 
2280   case CXXOperatorCallExprClass: {
2281     // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator
2282     // overloads as there is no reasonable way to define these such that they
2283     // have non-trivial, desirable side-effects. See the -Wunused-comparison
2284     // warning: operators == and != are commonly typo'ed, and so warning on them
2285     // provides additional value as well. If this list is updated,
2286     // DiagnoseUnusedComparison should be as well.
2287     const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
2288     switch (Op->getOperator()) {
2289     default:
2290       break;
2291     case OO_EqualEqual:
2292     case OO_ExclaimEqual:
2293     case OO_Less:
2294     case OO_Greater:
2295     case OO_GreaterEqual:
2296     case OO_LessEqual:
2297       if (Op->getCallReturnType(Ctx)->isReferenceType() ||
2298           Op->getCallReturnType(Ctx)->isVoidType())
2299         break;
2300       WarnE = this;
2301       Loc = Op->getOperatorLoc();
2302       R1 = Op->getSourceRange();
2303       return true;
2304     }
2305 
2306     // Fallthrough for generic call handling.
2307     LLVM_FALLTHROUGH;
2308   }
2309   case CallExprClass:
2310   case CXXMemberCallExprClass:
2311   case UserDefinedLiteralClass: {
2312     // If this is a direct call, get the callee.
2313     const CallExpr *CE = cast<CallExpr>(this);
2314     if (const Decl *FD = CE->getCalleeDecl()) {
2315       // If the callee has attribute pure, const, or warn_unused_result, warn
2316       // about it. void foo() { strlen("bar"); } should warn.
2317       //
2318       // Note: If new cases are added here, DiagnoseUnusedExprResult should be
2319       // updated to match for QoI.
2320       if (CE->hasUnusedResultAttr(Ctx) ||
2321           FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>()) {
2322         WarnE = this;
2323         Loc = CE->getCallee()->getBeginLoc();
2324         R1 = CE->getCallee()->getSourceRange();
2325 
2326         if (unsigned NumArgs = CE->getNumArgs())
2327           R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
2328                            CE->getArg(NumArgs - 1)->getEndLoc());
2329         return true;
2330       }
2331     }
2332     return false;
2333   }
2334 
2335   // If we don't know precisely what we're looking at, let's not warn.
2336   case UnresolvedLookupExprClass:
2337   case CXXUnresolvedConstructExprClass:
2338     return false;
2339 
2340   case CXXTemporaryObjectExprClass:
2341   case CXXConstructExprClass: {
2342     if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) {
2343       if (Type->hasAttr<WarnUnusedAttr>()) {
2344         WarnE = this;
2345         Loc = getBeginLoc();
2346         R1 = getSourceRange();
2347         return true;
2348       }
2349     }
2350     return false;
2351   }
2352 
2353   case ObjCMessageExprClass: {
2354     const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
2355     if (Ctx.getLangOpts().ObjCAutoRefCount &&
2356         ME->isInstanceMessage() &&
2357         !ME->getType()->isVoidType() &&
2358         ME->getMethodFamily() == OMF_init) {
2359       WarnE = this;
2360       Loc = getExprLoc();
2361       R1 = ME->getSourceRange();
2362       return true;
2363     }
2364 
2365     if (const ObjCMethodDecl *MD = ME->getMethodDecl())
2366       if (MD->hasAttr<WarnUnusedResultAttr>()) {
2367         WarnE = this;
2368         Loc = getExprLoc();
2369         return true;
2370       }
2371 
2372     return false;
2373   }
2374 
2375   case ObjCPropertyRefExprClass:
2376     WarnE = this;
2377     Loc = getExprLoc();
2378     R1 = getSourceRange();
2379     return true;
2380 
2381   case PseudoObjectExprClass: {
2382     const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
2383 
2384     // Only complain about things that have the form of a getter.
2385     if (isa<UnaryOperator>(PO->getSyntacticForm()) ||
2386         isa<BinaryOperator>(PO->getSyntacticForm()))
2387       return false;
2388 
2389     WarnE = this;
2390     Loc = getExprLoc();
2391     R1 = getSourceRange();
2392     return true;
2393   }
2394 
2395   case StmtExprClass: {
2396     // Statement exprs don't logically have side effects themselves, but are
2397     // sometimes used in macros in ways that give them a type that is unused.
2398     // For example ({ blah; foo(); }) will end up with a type if foo has a type.
2399     // however, if the result of the stmt expr is dead, we don't want to emit a
2400     // warning.
2401     const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
2402     if (!CS->body_empty()) {
2403       if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
2404         return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2405       if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
2406         if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
2407           return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2408     }
2409 
2410     if (getType()->isVoidType())
2411       return false;
2412     WarnE = this;
2413     Loc = cast<StmtExpr>(this)->getLParenLoc();
2414     R1 = getSourceRange();
2415     return true;
2416   }
2417   case CXXFunctionalCastExprClass:
2418   case CStyleCastExprClass: {
2419     // Ignore an explicit cast to void unless the operand is a non-trivial
2420     // volatile lvalue.
2421     const CastExpr *CE = cast<CastExpr>(this);
2422     if (CE->getCastKind() == CK_ToVoid) {
2423       if (CE->getSubExpr()->isGLValue() &&
2424           CE->getSubExpr()->getType().isVolatileQualified()) {
2425         const DeclRefExpr *DRE =
2426             dyn_cast<DeclRefExpr>(CE->getSubExpr()->IgnoreParens());
2427         if (!(DRE && isa<VarDecl>(DRE->getDecl()) &&
2428               cast<VarDecl>(DRE->getDecl())->hasLocalStorage()) &&
2429             !isa<CallExpr>(CE->getSubExpr()->IgnoreParens())) {
2430           return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc,
2431                                                           R1, R2, Ctx);
2432         }
2433       }
2434       return false;
2435     }
2436 
2437     // If this is a cast to a constructor conversion, check the operand.
2438     // Otherwise, the result of the cast is unused.
2439     if (CE->getCastKind() == CK_ConstructorConversion)
2440       return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2441 
2442     WarnE = this;
2443     if (const CXXFunctionalCastExpr *CXXCE =
2444             dyn_cast<CXXFunctionalCastExpr>(this)) {
2445       Loc = CXXCE->getBeginLoc();
2446       R1 = CXXCE->getSubExpr()->getSourceRange();
2447     } else {
2448       const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this);
2449       Loc = CStyleCE->getLParenLoc();
2450       R1 = CStyleCE->getSubExpr()->getSourceRange();
2451     }
2452     return true;
2453   }
2454   case ImplicitCastExprClass: {
2455     const CastExpr *ICE = cast<ImplicitCastExpr>(this);
2456 
2457     // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.
2458     if (ICE->getCastKind() == CK_LValueToRValue &&
2459         ICE->getSubExpr()->getType().isVolatileQualified())
2460       return false;
2461 
2462     return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2463   }
2464   case CXXDefaultArgExprClass:
2465     return (cast<CXXDefaultArgExpr>(this)
2466             ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2467   case CXXDefaultInitExprClass:
2468     return (cast<CXXDefaultInitExpr>(this)
2469             ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2470 
2471   case CXXNewExprClass:
2472     // FIXME: In theory, there might be new expressions that don't have side
2473     // effects (e.g. a placement new with an uninitialized POD).
2474   case CXXDeleteExprClass:
2475     return false;
2476   case MaterializeTemporaryExprClass:
2477     return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
2478                ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2479   case CXXBindTemporaryExprClass:
2480     return cast<CXXBindTemporaryExpr>(this)->getSubExpr()
2481                ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2482   case ExprWithCleanupsClass:
2483     return cast<ExprWithCleanups>(this)->getSubExpr()
2484                ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2485   }
2486 }
2487 
2488 /// isOBJCGCCandidate - Check if an expression is objc gc'able.
2489 /// returns true, if it is; false otherwise.
2490 bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
2491   const Expr *E = IgnoreParens();
2492   switch (E->getStmtClass()) {
2493   default:
2494     return false;
2495   case ObjCIvarRefExprClass:
2496     return true;
2497   case Expr::UnaryOperatorClass:
2498     return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2499   case ImplicitCastExprClass:
2500     return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2501   case MaterializeTemporaryExprClass:
2502     return cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr()
2503                                                       ->isOBJCGCCandidate(Ctx);
2504   case CStyleCastExprClass:
2505     return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2506   case DeclRefExprClass: {
2507     const Decl *D = cast<DeclRefExpr>(E)->getDecl();
2508 
2509     if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2510       if (VD->hasGlobalStorage())
2511         return true;
2512       QualType T = VD->getType();
2513       // dereferencing to a  pointer is always a gc'able candidate,
2514       // unless it is __weak.
2515       return T->isPointerType() &&
2516              (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
2517     }
2518     return false;
2519   }
2520   case MemberExprClass: {
2521     const MemberExpr *M = cast<MemberExpr>(E);
2522     return M->getBase()->isOBJCGCCandidate(Ctx);
2523   }
2524   case ArraySubscriptExprClass:
2525     return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
2526   }
2527 }
2528 
2529 bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
2530   if (isTypeDependent())
2531     return false;
2532   return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
2533 }
2534 
2535 QualType Expr::findBoundMemberType(const Expr *expr) {
2536   assert(expr->hasPlaceholderType(BuiltinType::BoundMember));
2537 
2538   // Bound member expressions are always one of these possibilities:
2539   //   x->m      x.m      x->*y      x.*y
2540   // (possibly parenthesized)
2541 
2542   expr = expr->IgnoreParens();
2543   if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
2544     assert(isa<CXXMethodDecl>(mem->getMemberDecl()));
2545     return mem->getMemberDecl()->getType();
2546   }
2547 
2548   if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
2549     QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
2550                       ->getPointeeType();
2551     assert(type->isFunctionType());
2552     return type;
2553   }
2554 
2555   assert(isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr));
2556   return QualType();
2557 }
2558 
2559 static Expr *IgnoreImpCastsSingleStep(Expr *E) {
2560   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2561     return ICE->getSubExpr();
2562 
2563   if (auto *FE = dyn_cast<FullExpr>(E))
2564     return FE->getSubExpr();
2565 
2566   return E;
2567 }
2568 
2569 static Expr *IgnoreImpCastsExtraSingleStep(Expr *E) {
2570   // FIXME: Skip MaterializeTemporaryExpr and SubstNonTypeTemplateParmExpr in
2571   // addition to what IgnoreImpCasts() skips to account for the current
2572   // behaviour of IgnoreParenImpCasts().
2573   Expr *SubE = IgnoreImpCastsSingleStep(E);
2574   if (SubE != E)
2575     return SubE;
2576 
2577   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2578     return MTE->GetTemporaryExpr();
2579 
2580   if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
2581     return NTTP->getReplacement();
2582 
2583   return E;
2584 }
2585 
2586 static Expr *IgnoreCastsSingleStep(Expr *E) {
2587   if (auto *CE = dyn_cast<CastExpr>(E))
2588     return CE->getSubExpr();
2589 
2590   if (auto *FE = dyn_cast<FullExpr>(E))
2591     return FE->getSubExpr();
2592 
2593   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2594     return MTE->GetTemporaryExpr();
2595 
2596   if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
2597     return NTTP->getReplacement();
2598 
2599   return E;
2600 }
2601 
2602 static Expr *IgnoreLValueCastsSingleStep(Expr *E) {
2603   // Skip what IgnoreCastsSingleStep skips, except that only
2604   // lvalue-to-rvalue casts are skipped.
2605   if (auto *CE = dyn_cast<CastExpr>(E))
2606     if (CE->getCastKind() != CK_LValueToRValue)
2607       return E;
2608 
2609   return IgnoreCastsSingleStep(E);
2610 }
2611 
2612 static Expr *IgnoreBaseCastsSingleStep(Expr *E) {
2613   if (auto *CE = dyn_cast<CastExpr>(E))
2614     if (CE->getCastKind() == CK_DerivedToBase ||
2615         CE->getCastKind() == CK_UncheckedDerivedToBase ||
2616         CE->getCastKind() == CK_NoOp)
2617       return CE->getSubExpr();
2618 
2619   return E;
2620 }
2621 
2622 static Expr *IgnoreImplicitSingleStep(Expr *E) {
2623   Expr *SubE = IgnoreImpCastsSingleStep(E);
2624   if (SubE != E)
2625     return SubE;
2626 
2627   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2628     return MTE->GetTemporaryExpr();
2629 
2630   if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(E))
2631     return BTE->getSubExpr();
2632 
2633   return E;
2634 }
2635 
2636 static Expr *IgnoreParensSingleStep(Expr *E) {
2637   if (auto *PE = dyn_cast<ParenExpr>(E))
2638     return PE->getSubExpr();
2639 
2640   if (auto *UO = dyn_cast<UnaryOperator>(E)) {
2641     if (UO->getOpcode() == UO_Extension)
2642       return UO->getSubExpr();
2643   }
2644 
2645   else if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
2646     if (!GSE->isResultDependent())
2647       return GSE->getResultExpr();
2648   }
2649 
2650   else if (auto *CE = dyn_cast<ChooseExpr>(E)) {
2651     if (!CE->isConditionDependent())
2652       return CE->getChosenSubExpr();
2653   }
2654 
2655   else if (auto *CE = dyn_cast<ConstantExpr>(E))
2656     return CE->getSubExpr();
2657 
2658   return E;
2659 }
2660 
2661 static Expr *IgnoreNoopCastsSingleStep(const ASTContext &Ctx, Expr *E) {
2662   if (auto *CE = dyn_cast<CastExpr>(E)) {
2663     // We ignore integer <-> casts that are of the same width, ptr<->ptr and
2664     // ptr<->int casts of the same width. We also ignore all identity casts.
2665     Expr *SubExpr = CE->getSubExpr();
2666     bool IsIdentityCast =
2667         Ctx.hasSameUnqualifiedType(E->getType(), SubExpr->getType());
2668     bool IsSameWidthCast =
2669         (E->getType()->isPointerType() || E->getType()->isIntegralType(Ctx)) &&
2670         (SubExpr->getType()->isPointerType() ||
2671          SubExpr->getType()->isIntegralType(Ctx)) &&
2672         (Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SubExpr->getType()));
2673 
2674     if (IsIdentityCast || IsSameWidthCast)
2675       return SubExpr;
2676   }
2677 
2678   else if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
2679     return NTTP->getReplacement();
2680 
2681   return E;
2682 }
2683 
2684 static Expr *IgnoreExprNodesImpl(Expr *E) { return E; }
2685 template <typename FnTy, typename... FnTys>
2686 static Expr *IgnoreExprNodesImpl(Expr *E, FnTy &&Fn, FnTys &&... Fns) {
2687   return IgnoreExprNodesImpl(Fn(E), std::forward<FnTys>(Fns)...);
2688 }
2689 
2690 /// Given an expression E and functions Fn_1,...,Fn_n : Expr * -> Expr *,
2691 /// Recursively apply each of the functions to E until reaching a fixed point.
2692 /// Note that a null E is valid; in this case nothing is done.
2693 template <typename... FnTys>
2694 static Expr *IgnoreExprNodes(Expr *E, FnTys &&... Fns) {
2695   Expr *LastE = nullptr;
2696   while (E != LastE) {
2697     LastE = E;
2698     E = IgnoreExprNodesImpl(E, std::forward<FnTys>(Fns)...);
2699   }
2700   return E;
2701 }
2702 
2703 Expr *Expr::IgnoreImpCasts() {
2704   return IgnoreExprNodes(this, IgnoreImpCastsSingleStep);
2705 }
2706 
2707 Expr *Expr::IgnoreCasts() {
2708   return IgnoreExprNodes(this, IgnoreCastsSingleStep);
2709 }
2710 
2711 Expr *Expr::IgnoreImplicit() {
2712   return IgnoreExprNodes(this, IgnoreImplicitSingleStep);
2713 }
2714 
2715 Expr *Expr::IgnoreParens() {
2716   return IgnoreExprNodes(this, IgnoreParensSingleStep);
2717 }
2718 
2719 Expr *Expr::IgnoreParenImpCasts() {
2720   return IgnoreExprNodes(this, IgnoreParensSingleStep,
2721                          IgnoreImpCastsExtraSingleStep);
2722 }
2723 
2724 Expr *Expr::IgnoreParenCasts() {
2725   return IgnoreExprNodes(this, IgnoreParensSingleStep, IgnoreCastsSingleStep);
2726 }
2727 
2728 Expr *Expr::IgnoreConversionOperator() {
2729   if (auto *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
2730     if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl()))
2731       return MCE->getImplicitObjectArgument();
2732   }
2733   return this;
2734 }
2735 
2736 Expr *Expr::IgnoreParenLValueCasts() {
2737   return IgnoreExprNodes(this, IgnoreParensSingleStep,
2738                          IgnoreLValueCastsSingleStep);
2739 }
2740 
2741 Expr *Expr::ignoreParenBaseCasts() {
2742   return IgnoreExprNodes(this, IgnoreParensSingleStep,
2743                          IgnoreBaseCastsSingleStep);
2744 }
2745 
2746 Expr *Expr::IgnoreParenNoopCasts(const ASTContext &Ctx) {
2747   return IgnoreExprNodes(this, IgnoreParensSingleStep, [&Ctx](Expr *E) {
2748     return IgnoreNoopCastsSingleStep(Ctx, E);
2749   });
2750 }
2751 
2752 bool Expr::isDefaultArgument() const {
2753   const Expr *E = this;
2754   if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2755     E = M->GetTemporaryExpr();
2756 
2757   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
2758     E = ICE->getSubExprAsWritten();
2759 
2760   return isa<CXXDefaultArgExpr>(E);
2761 }
2762 
2763 /// Skip over any no-op casts and any temporary-binding
2764 /// expressions.
2765 static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {
2766   if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
2767     E = M->GetTemporaryExpr();
2768 
2769   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2770     if (ICE->getCastKind() == CK_NoOp)
2771       E = ICE->getSubExpr();
2772     else
2773       break;
2774   }
2775 
2776   while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
2777     E = BE->getSubExpr();
2778 
2779   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2780     if (ICE->getCastKind() == CK_NoOp)
2781       E = ICE->getSubExpr();
2782     else
2783       break;
2784   }
2785 
2786   return E->IgnoreParens();
2787 }
2788 
2789 /// isTemporaryObject - Determines if this expression produces a
2790 /// temporary of the given class type.
2791 bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
2792   if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
2793     return false;
2794 
2795   const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);
2796 
2797   // Temporaries are by definition pr-values of class type.
2798   if (!E->Classify(C).isPRValue()) {
2799     // In this context, property reference is a message call and is pr-value.
2800     if (!isa<ObjCPropertyRefExpr>(E))
2801       return false;
2802   }
2803 
2804   // Black-list a few cases which yield pr-values of class type that don't
2805   // refer to temporaries of that type:
2806 
2807   // - implicit derived-to-base conversions
2808   if (isa<ImplicitCastExpr>(E)) {
2809     switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
2810     case CK_DerivedToBase:
2811     case CK_UncheckedDerivedToBase:
2812       return false;
2813     default:
2814       break;
2815     }
2816   }
2817 
2818   // - member expressions (all)
2819   if (isa<MemberExpr>(E))
2820     return false;
2821 
2822   if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E))
2823     if (BO->isPtrMemOp())
2824       return false;
2825 
2826   // - opaque values (all)
2827   if (isa<OpaqueValueExpr>(E))
2828     return false;
2829 
2830   return true;
2831 }
2832 
2833 bool Expr::isImplicitCXXThis() const {
2834   const Expr *E = this;
2835 
2836   // Strip away parentheses and casts we don't care about.
2837   while (true) {
2838     if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
2839       E = Paren->getSubExpr();
2840       continue;
2841     }
2842 
2843     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2844       if (ICE->getCastKind() == CK_NoOp ||
2845           ICE->getCastKind() == CK_LValueToRValue ||
2846           ICE->getCastKind() == CK_DerivedToBase ||
2847           ICE->getCastKind() == CK_UncheckedDerivedToBase) {
2848         E = ICE->getSubExpr();
2849         continue;
2850       }
2851     }
2852 
2853     if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
2854       if (UnOp->getOpcode() == UO_Extension) {
2855         E = UnOp->getSubExpr();
2856         continue;
2857       }
2858     }
2859 
2860     if (const MaterializeTemporaryExpr *M
2861                                       = dyn_cast<MaterializeTemporaryExpr>(E)) {
2862       E = M->GetTemporaryExpr();
2863       continue;
2864     }
2865 
2866     break;
2867   }
2868 
2869   if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
2870     return This->isImplicit();
2871 
2872   return false;
2873 }
2874 
2875 /// hasAnyTypeDependentArguments - Determines if any of the expressions
2876 /// in Exprs is type-dependent.
2877 bool Expr::hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs) {
2878   for (unsigned I = 0; I < Exprs.size(); ++I)
2879     if (Exprs[I]->isTypeDependent())
2880       return true;
2881 
2882   return false;
2883 }
2884 
2885 bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,
2886                                  const Expr **Culprit) const {
2887   // This function is attempting whether an expression is an initializer
2888   // which can be evaluated at compile-time. It very closely parallels
2889   // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it
2890   // will lead to unexpected results.  Like ConstExprEmitter, it falls back
2891   // to isEvaluatable most of the time.
2892   //
2893   // If we ever capture reference-binding directly in the AST, we can
2894   // kill the second parameter.
2895 
2896   if (IsForRef) {
2897     EvalResult Result;
2898     if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects)
2899       return true;
2900     if (Culprit)
2901       *Culprit = this;
2902     return false;
2903   }
2904 
2905   switch (getStmtClass()) {
2906   default: break;
2907   case StringLiteralClass:
2908   case ObjCEncodeExprClass:
2909     return true;
2910   case CXXTemporaryObjectExprClass:
2911   case CXXConstructExprClass: {
2912     const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
2913 
2914     if (CE->getConstructor()->isTrivial() &&
2915         CE->getConstructor()->getParent()->hasTrivialDestructor()) {
2916       // Trivial default constructor
2917       if (!CE->getNumArgs()) return true;
2918 
2919       // Trivial copy constructor
2920       assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument");
2921       return CE->getArg(0)->isConstantInitializer(Ctx, false, Culprit);
2922     }
2923 
2924     break;
2925   }
2926   case ConstantExprClass: {
2927     // FIXME: We should be able to return "true" here, but it can lead to extra
2928     // error messages. E.g. in Sema/array-init.c.
2929     const Expr *Exp = cast<ConstantExpr>(this)->getSubExpr();
2930     return Exp->isConstantInitializer(Ctx, false, Culprit);
2931   }
2932   case CompoundLiteralExprClass: {
2933     // This handles gcc's extension that allows global initializers like
2934     // "struct x {int x;} x = (struct x) {};".
2935     // FIXME: This accepts other cases it shouldn't!
2936     const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
2937     return Exp->isConstantInitializer(Ctx, false, Culprit);
2938   }
2939   case DesignatedInitUpdateExprClass: {
2940     const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(this);
2941     return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) &&
2942            DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit);
2943   }
2944   case InitListExprClass: {
2945     const InitListExpr *ILE = cast<InitListExpr>(this);
2946     if (ILE->getType()->isArrayType()) {
2947       unsigned numInits = ILE->getNumInits();
2948       for (unsigned i = 0; i < numInits; i++) {
2949         if (!ILE->getInit(i)->isConstantInitializer(Ctx, false, Culprit))
2950           return false;
2951       }
2952       return true;
2953     }
2954 
2955     if (ILE->getType()->isRecordType()) {
2956       unsigned ElementNo = 0;
2957       RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl();
2958       for (const auto *Field : RD->fields()) {
2959         // If this is a union, skip all the fields that aren't being initialized.
2960         if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
2961           continue;
2962 
2963         // Don't emit anonymous bitfields, they just affect layout.
2964         if (Field->isUnnamedBitfield())
2965           continue;
2966 
2967         if (ElementNo < ILE->getNumInits()) {
2968           const Expr *Elt = ILE->getInit(ElementNo++);
2969           if (Field->isBitField()) {
2970             // Bitfields have to evaluate to an integer.
2971             EvalResult Result;
2972             if (!Elt->EvaluateAsInt(Result, Ctx)) {
2973               if (Culprit)
2974                 *Culprit = Elt;
2975               return false;
2976             }
2977           } else {
2978             bool RefType = Field->getType()->isReferenceType();
2979             if (!Elt->isConstantInitializer(Ctx, RefType, Culprit))
2980               return false;
2981           }
2982         }
2983       }
2984       return true;
2985     }
2986 
2987     break;
2988   }
2989   case ImplicitValueInitExprClass:
2990   case NoInitExprClass:
2991     return true;
2992   case ParenExprClass:
2993     return cast<ParenExpr>(this)->getSubExpr()
2994       ->isConstantInitializer(Ctx, IsForRef, Culprit);
2995   case GenericSelectionExprClass:
2996     return cast<GenericSelectionExpr>(this)->getResultExpr()
2997       ->isConstantInitializer(Ctx, IsForRef, Culprit);
2998   case ChooseExprClass:
2999     if (cast<ChooseExpr>(this)->isConditionDependent()) {
3000       if (Culprit)
3001         *Culprit = this;
3002       return false;
3003     }
3004     return cast<ChooseExpr>(this)->getChosenSubExpr()
3005       ->isConstantInitializer(Ctx, IsForRef, Culprit);
3006   case UnaryOperatorClass: {
3007     const UnaryOperator* Exp = cast<UnaryOperator>(this);
3008     if (Exp->getOpcode() == UO_Extension)
3009       return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
3010     break;
3011   }
3012   case CXXFunctionalCastExprClass:
3013   case CXXStaticCastExprClass:
3014   case ImplicitCastExprClass:
3015   case CStyleCastExprClass:
3016   case ObjCBridgedCastExprClass:
3017   case CXXDynamicCastExprClass:
3018   case CXXReinterpretCastExprClass:
3019   case CXXConstCastExprClass: {
3020     const CastExpr *CE = cast<CastExpr>(this);
3021 
3022     // Handle misc casts we want to ignore.
3023     if (CE->getCastKind() == CK_NoOp ||
3024         CE->getCastKind() == CK_LValueToRValue ||
3025         CE->getCastKind() == CK_ToUnion ||
3026         CE->getCastKind() == CK_ConstructorConversion ||
3027         CE->getCastKind() == CK_NonAtomicToAtomic ||
3028         CE->getCastKind() == CK_AtomicToNonAtomic ||
3029         CE->getCastKind() == CK_IntToOCLSampler)
3030       return CE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
3031 
3032     break;
3033   }
3034   case MaterializeTemporaryExprClass:
3035     return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
3036       ->isConstantInitializer(Ctx, false, Culprit);
3037 
3038   case SubstNonTypeTemplateParmExprClass:
3039     return cast<SubstNonTypeTemplateParmExpr>(this)->getReplacement()
3040       ->isConstantInitializer(Ctx, false, Culprit);
3041   case CXXDefaultArgExprClass:
3042     return cast<CXXDefaultArgExpr>(this)->getExpr()
3043       ->isConstantInitializer(Ctx, false, Culprit);
3044   case CXXDefaultInitExprClass:
3045     return cast<CXXDefaultInitExpr>(this)->getExpr()
3046       ->isConstantInitializer(Ctx, false, Culprit);
3047   }
3048   // Allow certain forms of UB in constant initializers: signed integer
3049   // overflow and floating-point division by zero. We'll give a warning on
3050   // these, but they're common enough that we have to accept them.
3051   if (isEvaluatable(Ctx, SE_AllowUndefinedBehavior))
3052     return true;
3053   if (Culprit)
3054     *Culprit = this;
3055   return false;
3056 }
3057 
3058 bool CallExpr::isBuiltinAssumeFalse(const ASTContext &Ctx) const {
3059   const FunctionDecl* FD = getDirectCallee();
3060   if (!FD || (FD->getBuiltinID() != Builtin::BI__assume &&
3061               FD->getBuiltinID() != Builtin::BI__builtin_assume))
3062     return false;
3063 
3064   const Expr* Arg = getArg(0);
3065   bool ArgVal;
3066   return !Arg->isValueDependent() &&
3067          Arg->EvaluateAsBooleanCondition(ArgVal, Ctx) && !ArgVal;
3068 }
3069 
3070 namespace {
3071   /// Look for any side effects within a Stmt.
3072   class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> {
3073     typedef ConstEvaluatedExprVisitor<SideEffectFinder> Inherited;
3074     const bool IncludePossibleEffects;
3075     bool HasSideEffects;
3076 
3077   public:
3078     explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible)
3079       : Inherited(Context),
3080         IncludePossibleEffects(IncludePossible), HasSideEffects(false) { }
3081 
3082     bool hasSideEffects() const { return HasSideEffects; }
3083 
3084     void VisitExpr(const Expr *E) {
3085       if (!HasSideEffects &&
3086           E->HasSideEffects(Context, IncludePossibleEffects))
3087         HasSideEffects = true;
3088     }
3089   };
3090 }
3091 
3092 bool Expr::HasSideEffects(const ASTContext &Ctx,
3093                           bool IncludePossibleEffects) const {
3094   // In circumstances where we care about definite side effects instead of
3095   // potential side effects, we want to ignore expressions that are part of a
3096   // macro expansion as a potential side effect.
3097   if (!IncludePossibleEffects && getExprLoc().isMacroID())
3098     return false;
3099 
3100   if (isInstantiationDependent())
3101     return IncludePossibleEffects;
3102 
3103   switch (getStmtClass()) {
3104   case NoStmtClass:
3105   #define ABSTRACT_STMT(Type)
3106   #define STMT(Type, Base) case Type##Class:
3107   #define EXPR(Type, Base)
3108   #include "clang/AST/StmtNodes.inc"
3109     llvm_unreachable("unexpected Expr kind");
3110 
3111   case DependentScopeDeclRefExprClass:
3112   case CXXUnresolvedConstructExprClass:
3113   case CXXDependentScopeMemberExprClass:
3114   case UnresolvedLookupExprClass:
3115   case UnresolvedMemberExprClass:
3116   case PackExpansionExprClass:
3117   case SubstNonTypeTemplateParmPackExprClass:
3118   case FunctionParmPackExprClass:
3119   case TypoExprClass:
3120   case CXXFoldExprClass:
3121     llvm_unreachable("shouldn't see dependent / unresolved nodes here");
3122 
3123   case DeclRefExprClass:
3124   case ObjCIvarRefExprClass:
3125   case PredefinedExprClass:
3126   case IntegerLiteralClass:
3127   case FixedPointLiteralClass:
3128   case FloatingLiteralClass:
3129   case ImaginaryLiteralClass:
3130   case StringLiteralClass:
3131   case CharacterLiteralClass:
3132   case OffsetOfExprClass:
3133   case ImplicitValueInitExprClass:
3134   case UnaryExprOrTypeTraitExprClass:
3135   case AddrLabelExprClass:
3136   case GNUNullExprClass:
3137   case ArrayInitIndexExprClass:
3138   case NoInitExprClass:
3139   case CXXBoolLiteralExprClass:
3140   case CXXNullPtrLiteralExprClass:
3141   case CXXThisExprClass:
3142   case CXXScalarValueInitExprClass:
3143   case TypeTraitExprClass:
3144   case ArrayTypeTraitExprClass:
3145   case ExpressionTraitExprClass:
3146   case CXXNoexceptExprClass:
3147   case SizeOfPackExprClass:
3148   case ObjCStringLiteralClass:
3149   case ObjCEncodeExprClass:
3150   case ObjCBoolLiteralExprClass:
3151   case ObjCAvailabilityCheckExprClass:
3152   case CXXUuidofExprClass:
3153   case OpaqueValueExprClass:
3154     // These never have a side-effect.
3155     return false;
3156 
3157   case ConstantExprClass:
3158     // FIXME: Move this into the "return false;" block above.
3159     return cast<ConstantExpr>(this)->getSubExpr()->HasSideEffects(
3160         Ctx, IncludePossibleEffects);
3161 
3162   case CallExprClass:
3163   case CXXOperatorCallExprClass:
3164   case CXXMemberCallExprClass:
3165   case CUDAKernelCallExprClass:
3166   case UserDefinedLiteralClass: {
3167     // We don't know a call definitely has side effects, except for calls
3168     // to pure/const functions that definitely don't.
3169     // If the call itself is considered side-effect free, check the operands.
3170     const Decl *FD = cast<CallExpr>(this)->getCalleeDecl();
3171     bool IsPure = FD && (FD->hasAttr<ConstAttr>() || FD->hasAttr<PureAttr>());
3172     if (IsPure || !IncludePossibleEffects)
3173       break;
3174     return true;
3175   }
3176 
3177   case BlockExprClass:
3178   case CXXBindTemporaryExprClass:
3179     if (!IncludePossibleEffects)
3180       break;
3181     return true;
3182 
3183   case MSPropertyRefExprClass:
3184   case MSPropertySubscriptExprClass:
3185   case CompoundAssignOperatorClass:
3186   case VAArgExprClass:
3187   case AtomicExprClass:
3188   case CXXThrowExprClass:
3189   case CXXNewExprClass:
3190   case CXXDeleteExprClass:
3191   case CoawaitExprClass:
3192   case DependentCoawaitExprClass:
3193   case CoyieldExprClass:
3194     // These always have a side-effect.
3195     return true;
3196 
3197   case StmtExprClass: {
3198     // StmtExprs have a side-effect if any substatement does.
3199     SideEffectFinder Finder(Ctx, IncludePossibleEffects);
3200     Finder.Visit(cast<StmtExpr>(this)->getSubStmt());
3201     return Finder.hasSideEffects();
3202   }
3203 
3204   case ExprWithCleanupsClass:
3205     if (IncludePossibleEffects)
3206       if (cast<ExprWithCleanups>(this)->cleanupsHaveSideEffects())
3207         return true;
3208     break;
3209 
3210   case ParenExprClass:
3211   case ArraySubscriptExprClass:
3212   case OMPArraySectionExprClass:
3213   case MemberExprClass:
3214   case ConditionalOperatorClass:
3215   case BinaryConditionalOperatorClass:
3216   case CompoundLiteralExprClass:
3217   case ExtVectorElementExprClass:
3218   case DesignatedInitExprClass:
3219   case DesignatedInitUpdateExprClass:
3220   case ArrayInitLoopExprClass:
3221   case ParenListExprClass:
3222   case CXXPseudoDestructorExprClass:
3223   case CXXStdInitializerListExprClass:
3224   case SubstNonTypeTemplateParmExprClass:
3225   case MaterializeTemporaryExprClass:
3226   case ShuffleVectorExprClass:
3227   case ConvertVectorExprClass:
3228   case AsTypeExprClass:
3229     // These have a side-effect if any subexpression does.
3230     break;
3231 
3232   case UnaryOperatorClass:
3233     if (cast<UnaryOperator>(this)->isIncrementDecrementOp())
3234       return true;
3235     break;
3236 
3237   case BinaryOperatorClass:
3238     if (cast<BinaryOperator>(this)->isAssignmentOp())
3239       return true;
3240     break;
3241 
3242   case InitListExprClass:
3243     // FIXME: The children for an InitListExpr doesn't include the array filler.
3244     if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())
3245       if (E->HasSideEffects(Ctx, IncludePossibleEffects))
3246         return true;
3247     break;
3248 
3249   case GenericSelectionExprClass:
3250     return cast<GenericSelectionExpr>(this)->getResultExpr()->
3251         HasSideEffects(Ctx, IncludePossibleEffects);
3252 
3253   case ChooseExprClass:
3254     return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(
3255         Ctx, IncludePossibleEffects);
3256 
3257   case CXXDefaultArgExprClass:
3258     return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(
3259         Ctx, IncludePossibleEffects);
3260 
3261   case CXXDefaultInitExprClass: {
3262     const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField();
3263     if (const Expr *E = FD->getInClassInitializer())
3264       return E->HasSideEffects(Ctx, IncludePossibleEffects);
3265     // If we've not yet parsed the initializer, assume it has side-effects.
3266     return true;
3267   }
3268 
3269   case CXXDynamicCastExprClass: {
3270     // A dynamic_cast expression has side-effects if it can throw.
3271     const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this);
3272     if (DCE->getTypeAsWritten()->isReferenceType() &&
3273         DCE->getCastKind() == CK_Dynamic)
3274       return true;
3275     }
3276     LLVM_FALLTHROUGH;
3277   case ImplicitCastExprClass:
3278   case CStyleCastExprClass:
3279   case CXXStaticCastExprClass:
3280   case CXXReinterpretCastExprClass:
3281   case CXXConstCastExprClass:
3282   case CXXFunctionalCastExprClass: {
3283     // While volatile reads are side-effecting in both C and C++, we treat them
3284     // as having possible (not definite) side-effects. This allows idiomatic
3285     // code to behave without warning, such as sizeof(*v) for a volatile-
3286     // qualified pointer.
3287     if (!IncludePossibleEffects)
3288       break;
3289 
3290     const CastExpr *CE = cast<CastExpr>(this);
3291     if (CE->getCastKind() == CK_LValueToRValue &&
3292         CE->getSubExpr()->getType().isVolatileQualified())
3293       return true;
3294     break;
3295   }
3296 
3297   case CXXTypeidExprClass:
3298     // typeid might throw if its subexpression is potentially-evaluated, so has
3299     // side-effects in that case whether or not its subexpression does.
3300     return cast<CXXTypeidExpr>(this)->isPotentiallyEvaluated();
3301 
3302   case CXXConstructExprClass:
3303   case CXXTemporaryObjectExprClass: {
3304     const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
3305     if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects)
3306       return true;
3307     // A trivial constructor does not add any side-effects of its own. Just look
3308     // at its arguments.
3309     break;
3310   }
3311 
3312   case CXXInheritedCtorInitExprClass: {
3313     const auto *ICIE = cast<CXXInheritedCtorInitExpr>(this);
3314     if (!ICIE->getConstructor()->isTrivial() && IncludePossibleEffects)
3315       return true;
3316     break;
3317   }
3318 
3319   case LambdaExprClass: {
3320     const LambdaExpr *LE = cast<LambdaExpr>(this);
3321     for (Expr *E : LE->capture_inits())
3322       if (E->HasSideEffects(Ctx, IncludePossibleEffects))
3323         return true;
3324     return false;
3325   }
3326 
3327   case PseudoObjectExprClass: {
3328     // Only look for side-effects in the semantic form, and look past
3329     // OpaqueValueExpr bindings in that form.
3330     const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
3331     for (PseudoObjectExpr::const_semantics_iterator I = PO->semantics_begin(),
3332                                                     E = PO->semantics_end();
3333          I != E; ++I) {
3334       const Expr *Subexpr = *I;
3335       if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))
3336         Subexpr = OVE->getSourceExpr();
3337       if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects))
3338         return true;
3339     }
3340     return false;
3341   }
3342 
3343   case ObjCBoxedExprClass:
3344   case ObjCArrayLiteralClass:
3345   case ObjCDictionaryLiteralClass:
3346   case ObjCSelectorExprClass:
3347   case ObjCProtocolExprClass:
3348   case ObjCIsaExprClass:
3349   case ObjCIndirectCopyRestoreExprClass:
3350   case ObjCSubscriptRefExprClass:
3351   case ObjCBridgedCastExprClass:
3352   case ObjCMessageExprClass:
3353   case ObjCPropertyRefExprClass:
3354   // FIXME: Classify these cases better.
3355     if (IncludePossibleEffects)
3356       return true;
3357     break;
3358   }
3359 
3360   // Recurse to children.
3361   for (const Stmt *SubStmt : children())
3362     if (SubStmt &&
3363         cast<Expr>(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects))
3364       return true;
3365 
3366   return false;
3367 }
3368 
3369 namespace {
3370   /// Look for a call to a non-trivial function within an expression.
3371   class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder>
3372   {
3373     typedef ConstEvaluatedExprVisitor<NonTrivialCallFinder> Inherited;
3374 
3375     bool NonTrivial;
3376 
3377   public:
3378     explicit NonTrivialCallFinder(const ASTContext &Context)
3379       : Inherited(Context), NonTrivial(false) { }
3380 
3381     bool hasNonTrivialCall() const { return NonTrivial; }
3382 
3383     void VisitCallExpr(const CallExpr *E) {
3384       if (const CXXMethodDecl *Method
3385           = dyn_cast_or_null<const CXXMethodDecl>(E->getCalleeDecl())) {
3386         if (Method->isTrivial()) {
3387           // Recurse to children of the call.
3388           Inherited::VisitStmt(E);
3389           return;
3390         }
3391       }
3392 
3393       NonTrivial = true;
3394     }
3395 
3396     void VisitCXXConstructExpr(const CXXConstructExpr *E) {
3397       if (E->getConstructor()->isTrivial()) {
3398         // Recurse to children of the call.
3399         Inherited::VisitStmt(E);
3400         return;
3401       }
3402 
3403       NonTrivial = true;
3404     }
3405 
3406     void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
3407       if (E->getTemporary()->getDestructor()->isTrivial()) {
3408         Inherited::VisitStmt(E);
3409         return;
3410       }
3411 
3412       NonTrivial = true;
3413     }
3414   };
3415 }
3416 
3417 bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const {
3418   NonTrivialCallFinder Finder(Ctx);
3419   Finder.Visit(this);
3420   return Finder.hasNonTrivialCall();
3421 }
3422 
3423 /// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
3424 /// pointer constant or not, as well as the specific kind of constant detected.
3425 /// Null pointer constants can be integer constant expressions with the
3426 /// value zero, casts of zero to void*, nullptr (C++0X), or __null
3427 /// (a GNU extension).
3428 Expr::NullPointerConstantKind
3429 Expr::isNullPointerConstant(ASTContext &Ctx,
3430                             NullPointerConstantValueDependence NPC) const {
3431   if (isValueDependent() &&
3432       (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) {
3433     switch (NPC) {
3434     case NPC_NeverValueDependent:
3435       llvm_unreachable("Unexpected value dependent expression!");
3436     case NPC_ValueDependentIsNull:
3437       if (isTypeDependent() || getType()->isIntegralType(Ctx))
3438         return NPCK_ZeroExpression;
3439       else
3440         return NPCK_NotNull;
3441 
3442     case NPC_ValueDependentIsNotNull:
3443       return NPCK_NotNull;
3444     }
3445   }
3446 
3447   // Strip off a cast to void*, if it exists. Except in C++.
3448   if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
3449     if (!Ctx.getLangOpts().CPlusPlus) {
3450       // Check that it is a cast to void*.
3451       if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
3452         QualType Pointee = PT->getPointeeType();
3453         Qualifiers Qs = Pointee.getQualifiers();
3454         // Only (void*)0 or equivalent are treated as nullptr. If pointee type
3455         // has non-default address space it is not treated as nullptr.
3456         // (__generic void*)0 in OpenCL 2.0 should not be treated as nullptr
3457         // since it cannot be assigned to a pointer to constant address space.
3458         if ((Ctx.getLangOpts().OpenCLVersion >= 200 &&
3459              Pointee.getAddressSpace() == LangAS::opencl_generic) ||
3460             (Ctx.getLangOpts().OpenCL &&
3461              Ctx.getLangOpts().OpenCLVersion < 200 &&
3462              Pointee.getAddressSpace() == LangAS::opencl_private))
3463           Qs.removeAddressSpace();
3464 
3465         if (Pointee->isVoidType() && Qs.empty() && // to void*
3466             CE->getSubExpr()->getType()->isIntegerType()) // from int
3467           return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3468       }
3469     }
3470   } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
3471     // Ignore the ImplicitCastExpr type entirely.
3472     return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3473   } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
3474     // Accept ((void*)0) as a null pointer constant, as many other
3475     // implementations do.
3476     return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3477   } else if (const GenericSelectionExpr *GE =
3478                dyn_cast<GenericSelectionExpr>(this)) {
3479     if (GE->isResultDependent())
3480       return NPCK_NotNull;
3481     return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
3482   } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(this)) {
3483     if (CE->isConditionDependent())
3484       return NPCK_NotNull;
3485     return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC);
3486   } else if (const CXXDefaultArgExpr *DefaultArg
3487                = dyn_cast<CXXDefaultArgExpr>(this)) {
3488     // See through default argument expressions.
3489     return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
3490   } else if (const CXXDefaultInitExpr *DefaultInit
3491                = dyn_cast<CXXDefaultInitExpr>(this)) {
3492     // See through default initializer expressions.
3493     return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC);
3494   } else if (isa<GNUNullExpr>(this)) {
3495     // The GNU __null extension is always a null pointer constant.
3496     return NPCK_GNUNull;
3497   } else if (const MaterializeTemporaryExpr *M
3498                                    = dyn_cast<MaterializeTemporaryExpr>(this)) {
3499     return M->GetTemporaryExpr()->isNullPointerConstant(Ctx, NPC);
3500   } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
3501     if (const Expr *Source = OVE->getSourceExpr())
3502       return Source->isNullPointerConstant(Ctx, NPC);
3503   }
3504 
3505   // C++11 nullptr_t is always a null pointer constant.
3506   if (getType()->isNullPtrType())
3507     return NPCK_CXX11_nullptr;
3508 
3509   if (const RecordType *UT = getType()->getAsUnionType())
3510     if (!Ctx.getLangOpts().CPlusPlus11 &&
3511         UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
3512       if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
3513         const Expr *InitExpr = CLE->getInitializer();
3514         if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
3515           return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
3516       }
3517   // This expression must be an integer type.
3518   if (!getType()->isIntegerType() ||
3519       (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
3520     return NPCK_NotNull;
3521 
3522   if (Ctx.getLangOpts().CPlusPlus11) {
3523     // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with
3524     // value zero or a prvalue of type std::nullptr_t.
3525     // Microsoft mode permits C++98 rules reflecting MSVC behavior.
3526     const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(this);
3527     if (Lit && !Lit->getValue())
3528       return NPCK_ZeroLiteral;
3529     else if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx))
3530       return NPCK_NotNull;
3531   } else {
3532     // If we have an integer constant expression, we need to *evaluate* it and
3533     // test for the value 0.
3534     if (!isIntegerConstantExpr(Ctx))
3535       return NPCK_NotNull;
3536   }
3537 
3538   if (EvaluateKnownConstInt(Ctx) != 0)
3539     return NPCK_NotNull;
3540 
3541   if (isa<IntegerLiteral>(this))
3542     return NPCK_ZeroLiteral;
3543   return NPCK_ZeroExpression;
3544 }
3545 
3546 /// If this expression is an l-value for an Objective C
3547 /// property, find the underlying property reference expression.
3548 const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
3549   const Expr *E = this;
3550   while (true) {
3551     assert((E->getValueKind() == VK_LValue &&
3552             E->getObjectKind() == OK_ObjCProperty) &&
3553            "expression is not a property reference");
3554     E = E->IgnoreParenCasts();
3555     if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3556       if (BO->getOpcode() == BO_Comma) {
3557         E = BO->getRHS();
3558         continue;
3559       }
3560     }
3561 
3562     break;
3563   }
3564 
3565   return cast<ObjCPropertyRefExpr>(E);
3566 }
3567 
3568 bool Expr::isObjCSelfExpr() const {
3569   const Expr *E = IgnoreParenImpCasts();
3570 
3571   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
3572   if (!DRE)
3573     return false;
3574 
3575   const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl());
3576   if (!Param)
3577     return false;
3578 
3579   const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext());
3580   if (!M)
3581     return false;
3582 
3583   return M->getSelfDecl() == Param;
3584 }
3585 
3586 FieldDecl *Expr::getSourceBitField() {
3587   Expr *E = this->IgnoreParens();
3588 
3589   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3590     if (ICE->getCastKind() == CK_LValueToRValue ||
3591         (ICE->getValueKind() != VK_RValue && ICE->getCastKind() == CK_NoOp))
3592       E = ICE->getSubExpr()->IgnoreParens();
3593     else
3594       break;
3595   }
3596 
3597   if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
3598     if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
3599       if (Field->isBitField())
3600         return Field;
3601 
3602   if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
3603     FieldDecl *Ivar = IvarRef->getDecl();
3604     if (Ivar->isBitField())
3605       return Ivar;
3606   }
3607 
3608   if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E)) {
3609     if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
3610       if (Field->isBitField())
3611         return Field;
3612 
3613     if (BindingDecl *BD = dyn_cast<BindingDecl>(DeclRef->getDecl()))
3614       if (Expr *E = BD->getBinding())
3615         return E->getSourceBitField();
3616   }
3617 
3618   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
3619     if (BinOp->isAssignmentOp() && BinOp->getLHS())
3620       return BinOp->getLHS()->getSourceBitField();
3621 
3622     if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
3623       return BinOp->getRHS()->getSourceBitField();
3624   }
3625 
3626   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E))
3627     if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp())
3628       return UnOp->getSubExpr()->getSourceBitField();
3629 
3630   return nullptr;
3631 }
3632 
3633 bool Expr::refersToVectorElement() const {
3634   // FIXME: Why do we not just look at the ObjectKind here?
3635   const Expr *E = this->IgnoreParens();
3636 
3637   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3638     if (ICE->getValueKind() != VK_RValue &&
3639         ICE->getCastKind() == CK_NoOp)
3640       E = ICE->getSubExpr()->IgnoreParens();
3641     else
3642       break;
3643   }
3644 
3645   if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
3646     return ASE->getBase()->getType()->isVectorType();
3647 
3648   if (isa<ExtVectorElementExpr>(E))
3649     return true;
3650 
3651   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3652     if (auto *BD = dyn_cast<BindingDecl>(DRE->getDecl()))
3653       if (auto *E = BD->getBinding())
3654         return E->refersToVectorElement();
3655 
3656   return false;
3657 }
3658 
3659 bool Expr::refersToGlobalRegisterVar() const {
3660   const Expr *E = this->IgnoreParenImpCasts();
3661 
3662   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3663     if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
3664       if (VD->getStorageClass() == SC_Register &&
3665           VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
3666         return true;
3667 
3668   return false;
3669 }
3670 
3671 /// isArrow - Return true if the base expression is a pointer to vector,
3672 /// return false if the base expression is a vector.
3673 bool ExtVectorElementExpr::isArrow() const {
3674   return getBase()->getType()->isPointerType();
3675 }
3676 
3677 unsigned ExtVectorElementExpr::getNumElements() const {
3678   if (const VectorType *VT = getType()->getAs<VectorType>())
3679     return VT->getNumElements();
3680   return 1;
3681 }
3682 
3683 /// containsDuplicateElements - Return true if any element access is repeated.
3684 bool ExtVectorElementExpr::containsDuplicateElements() const {
3685   // FIXME: Refactor this code to an accessor on the AST node which returns the
3686   // "type" of component access, and share with code below and in Sema.
3687   StringRef Comp = Accessor->getName();
3688 
3689   // Halving swizzles do not contain duplicate elements.
3690   if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
3691     return false;
3692 
3693   // Advance past s-char prefix on hex swizzles.
3694   if (Comp[0] == 's' || Comp[0] == 'S')
3695     Comp = Comp.substr(1);
3696 
3697   for (unsigned i = 0, e = Comp.size(); i != e; ++i)
3698     if (Comp.substr(i + 1).find(Comp[i]) != StringRef::npos)
3699         return true;
3700 
3701   return false;
3702 }
3703 
3704 /// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
3705 void ExtVectorElementExpr::getEncodedElementAccess(
3706     SmallVectorImpl<uint32_t> &Elts) const {
3707   StringRef Comp = Accessor->getName();
3708   bool isNumericAccessor = false;
3709   if (Comp[0] == 's' || Comp[0] == 'S') {
3710     Comp = Comp.substr(1);
3711     isNumericAccessor = true;
3712   }
3713 
3714   bool isHi =   Comp == "hi";
3715   bool isLo =   Comp == "lo";
3716   bool isEven = Comp == "even";
3717   bool isOdd  = Comp == "odd";
3718 
3719   for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
3720     uint64_t Index;
3721 
3722     if (isHi)
3723       Index = e + i;
3724     else if (isLo)
3725       Index = i;
3726     else if (isEven)
3727       Index = 2 * i;
3728     else if (isOdd)
3729       Index = 2 * i + 1;
3730     else
3731       Index = ExtVectorType::getAccessorIdx(Comp[i], isNumericAccessor);
3732 
3733     Elts.push_back(Index);
3734   }
3735 }
3736 
3737 ShuffleVectorExpr::ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args,
3738                                      QualType Type, SourceLocation BLoc,
3739                                      SourceLocation RP)
3740    : Expr(ShuffleVectorExprClass, Type, VK_RValue, OK_Ordinary,
3741           Type->isDependentType(), Type->isDependentType(),
3742           Type->isInstantiationDependentType(),
3743           Type->containsUnexpandedParameterPack()),
3744      BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size())
3745 {
3746   SubExprs = new (C) Stmt*[args.size()];
3747   for (unsigned i = 0; i != args.size(); i++) {
3748     if (args[i]->isTypeDependent())
3749       ExprBits.TypeDependent = true;
3750     if (args[i]->isValueDependent())
3751       ExprBits.ValueDependent = true;
3752     if (args[i]->isInstantiationDependent())
3753       ExprBits.InstantiationDependent = true;
3754     if (args[i]->containsUnexpandedParameterPack())
3755       ExprBits.ContainsUnexpandedParameterPack = true;
3756 
3757     SubExprs[i] = args[i];
3758   }
3759 }
3760 
3761 void ShuffleVectorExpr::setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs) {
3762   if (SubExprs) C.Deallocate(SubExprs);
3763 
3764   this->NumExprs = Exprs.size();
3765   SubExprs = new (C) Stmt*[NumExprs];
3766   memcpy(SubExprs, Exprs.data(), sizeof(Expr *) * Exprs.size());
3767 }
3768 
3769 GenericSelectionExpr::GenericSelectionExpr(
3770     const ASTContext &, SourceLocation GenericLoc, Expr *ControllingExpr,
3771     ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
3772     SourceLocation DefaultLoc, SourceLocation RParenLoc,
3773     bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
3774     : Expr(GenericSelectionExprClass, AssocExprs[ResultIndex]->getType(),
3775            AssocExprs[ResultIndex]->getValueKind(),
3776            AssocExprs[ResultIndex]->getObjectKind(),
3777            AssocExprs[ResultIndex]->isTypeDependent(),
3778            AssocExprs[ResultIndex]->isValueDependent(),
3779            AssocExprs[ResultIndex]->isInstantiationDependent(),
3780            ContainsUnexpandedParameterPack),
3781       NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
3782       DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
3783   assert(AssocTypes.size() == AssocExprs.size() &&
3784          "Must have the same number of association expressions"
3785          " and TypeSourceInfo!");
3786   assert(ResultIndex < NumAssocs && "ResultIndex is out-of-bounds!");
3787 
3788   GenericSelectionExprBits.GenericLoc = GenericLoc;
3789   getTrailingObjects<Stmt *>()[ControllingIndex] = ControllingExpr;
3790   std::copy(AssocExprs.begin(), AssocExprs.end(),
3791             getTrailingObjects<Stmt *>() + AssocExprStartIndex);
3792   std::copy(AssocTypes.begin(), AssocTypes.end(),
3793             getTrailingObjects<TypeSourceInfo *>());
3794 }
3795 
3796 GenericSelectionExpr::GenericSelectionExpr(
3797     const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
3798     ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
3799     SourceLocation DefaultLoc, SourceLocation RParenLoc,
3800     bool ContainsUnexpandedParameterPack)
3801     : Expr(GenericSelectionExprClass, Context.DependentTy, VK_RValue,
3802            OK_Ordinary,
3803            /*isTypeDependent=*/true,
3804            /*isValueDependent=*/true,
3805            /*isInstantiationDependent=*/true, ContainsUnexpandedParameterPack),
3806       NumAssocs(AssocExprs.size()), ResultIndex(ResultDependentIndex),
3807       DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
3808   assert(AssocTypes.size() == AssocExprs.size() &&
3809          "Must have the same number of association expressions"
3810          " and TypeSourceInfo!");
3811 
3812   GenericSelectionExprBits.GenericLoc = GenericLoc;
3813   getTrailingObjects<Stmt *>()[ControllingIndex] = ControllingExpr;
3814   std::copy(AssocExprs.begin(), AssocExprs.end(),
3815             getTrailingObjects<Stmt *>() + AssocExprStartIndex);
3816   std::copy(AssocTypes.begin(), AssocTypes.end(),
3817             getTrailingObjects<TypeSourceInfo *>());
3818 }
3819 
3820 GenericSelectionExpr::GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs)
3821     : Expr(GenericSelectionExprClass, Empty), NumAssocs(NumAssocs) {}
3822 
3823 GenericSelectionExpr *GenericSelectionExpr::Create(
3824     const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
3825     ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
3826     SourceLocation DefaultLoc, SourceLocation RParenLoc,
3827     bool ContainsUnexpandedParameterPack, unsigned ResultIndex) {
3828   unsigned NumAssocs = AssocExprs.size();
3829   void *Mem = Context.Allocate(
3830       totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
3831       alignof(GenericSelectionExpr));
3832   return new (Mem) GenericSelectionExpr(
3833       Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
3834       RParenLoc, ContainsUnexpandedParameterPack, ResultIndex);
3835 }
3836 
3837 GenericSelectionExpr *GenericSelectionExpr::Create(
3838     const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
3839     ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
3840     SourceLocation DefaultLoc, SourceLocation RParenLoc,
3841     bool ContainsUnexpandedParameterPack) {
3842   unsigned NumAssocs = AssocExprs.size();
3843   void *Mem = Context.Allocate(
3844       totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
3845       alignof(GenericSelectionExpr));
3846   return new (Mem) GenericSelectionExpr(
3847       Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
3848       RParenLoc, ContainsUnexpandedParameterPack);
3849 }
3850 
3851 GenericSelectionExpr *
3852 GenericSelectionExpr::CreateEmpty(const ASTContext &Context,
3853                                   unsigned NumAssocs) {
3854   void *Mem = Context.Allocate(
3855       totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
3856       alignof(GenericSelectionExpr));
3857   return new (Mem) GenericSelectionExpr(EmptyShell(), NumAssocs);
3858 }
3859 
3860 //===----------------------------------------------------------------------===//
3861 //  DesignatedInitExpr
3862 //===----------------------------------------------------------------------===//
3863 
3864 IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const {
3865   assert(Kind == FieldDesignator && "Only valid on a field designator");
3866   if (Field.NameOrField & 0x01)
3867     return reinterpret_cast<IdentifierInfo *>(Field.NameOrField&~0x01);
3868   else
3869     return getField()->getIdentifier();
3870 }
3871 
3872 DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty,
3873                                        llvm::ArrayRef<Designator> Designators,
3874                                        SourceLocation EqualOrColonLoc,
3875                                        bool GNUSyntax,
3876                                        ArrayRef<Expr*> IndexExprs,
3877                                        Expr *Init)
3878   : Expr(DesignatedInitExprClass, Ty,
3879          Init->getValueKind(), Init->getObjectKind(),
3880          Init->isTypeDependent(), Init->isValueDependent(),
3881          Init->isInstantiationDependent(),
3882          Init->containsUnexpandedParameterPack()),
3883     EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
3884     NumDesignators(Designators.size()), NumSubExprs(IndexExprs.size() + 1) {
3885   this->Designators = new (C) Designator[NumDesignators];
3886 
3887   // Record the initializer itself.
3888   child_iterator Child = child_begin();
3889   *Child++ = Init;
3890 
3891   // Copy the designators and their subexpressions, computing
3892   // value-dependence along the way.
3893   unsigned IndexIdx = 0;
3894   for (unsigned I = 0; I != NumDesignators; ++I) {
3895     this->Designators[I] = Designators[I];
3896 
3897     if (this->Designators[I].isArrayDesignator()) {
3898       // Compute type- and value-dependence.
3899       Expr *Index = IndexExprs[IndexIdx];
3900       if (Index->isTypeDependent() || Index->isValueDependent())
3901         ExprBits.TypeDependent = ExprBits.ValueDependent = true;
3902       if (Index->isInstantiationDependent())
3903         ExprBits.InstantiationDependent = true;
3904       // Propagate unexpanded parameter packs.
3905       if (Index->containsUnexpandedParameterPack())
3906         ExprBits.ContainsUnexpandedParameterPack = true;
3907 
3908       // Copy the index expressions into permanent storage.
3909       *Child++ = IndexExprs[IndexIdx++];
3910     } else if (this->Designators[I].isArrayRangeDesignator()) {
3911       // Compute type- and value-dependence.
3912       Expr *Start = IndexExprs[IndexIdx];
3913       Expr *End = IndexExprs[IndexIdx + 1];
3914       if (Start->isTypeDependent() || Start->isValueDependent() ||
3915           End->isTypeDependent() || End->isValueDependent()) {
3916         ExprBits.TypeDependent = ExprBits.ValueDependent = true;
3917         ExprBits.InstantiationDependent = true;
3918       } else if (Start->isInstantiationDependent() ||
3919                  End->isInstantiationDependent()) {
3920         ExprBits.InstantiationDependent = true;
3921       }
3922 
3923       // Propagate unexpanded parameter packs.
3924       if (Start->containsUnexpandedParameterPack() ||
3925           End->containsUnexpandedParameterPack())
3926         ExprBits.ContainsUnexpandedParameterPack = true;
3927 
3928       // Copy the start/end expressions into permanent storage.
3929       *Child++ = IndexExprs[IndexIdx++];
3930       *Child++ = IndexExprs[IndexIdx++];
3931     }
3932   }
3933 
3934   assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions");
3935 }
3936 
3937 DesignatedInitExpr *
3938 DesignatedInitExpr::Create(const ASTContext &C,
3939                            llvm::ArrayRef<Designator> Designators,
3940                            ArrayRef<Expr*> IndexExprs,
3941                            SourceLocation ColonOrEqualLoc,
3942                            bool UsesColonSyntax, Expr *Init) {
3943   void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(IndexExprs.size() + 1),
3944                          alignof(DesignatedInitExpr));
3945   return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators,
3946                                       ColonOrEqualLoc, UsesColonSyntax,
3947                                       IndexExprs, Init);
3948 }
3949 
3950 DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(const ASTContext &C,
3951                                                     unsigned NumIndexExprs) {
3952   void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(NumIndexExprs + 1),
3953                          alignof(DesignatedInitExpr));
3954   return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
3955 }
3956 
3957 void DesignatedInitExpr::setDesignators(const ASTContext &C,
3958                                         const Designator *Desigs,
3959                                         unsigned NumDesigs) {
3960   Designators = new (C) Designator[NumDesigs];
3961   NumDesignators = NumDesigs;
3962   for (unsigned I = 0; I != NumDesigs; ++I)
3963     Designators[I] = Desigs[I];
3964 }
3965 
3966 SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const {
3967   DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
3968   if (size() == 1)
3969     return DIE->getDesignator(0)->getSourceRange();
3970   return SourceRange(DIE->getDesignator(0)->getBeginLoc(),
3971                      DIE->getDesignator(size() - 1)->getEndLoc());
3972 }
3973 
3974 SourceLocation DesignatedInitExpr::getBeginLoc() const {
3975   SourceLocation StartLoc;
3976   auto *DIE = const_cast<DesignatedInitExpr *>(this);
3977   Designator &First = *DIE->getDesignator(0);
3978   if (First.isFieldDesignator()) {
3979     if (GNUSyntax)
3980       StartLoc = SourceLocation::getFromRawEncoding(First.Field.FieldLoc);
3981     else
3982       StartLoc = SourceLocation::getFromRawEncoding(First.Field.DotLoc);
3983   } else
3984     StartLoc =
3985       SourceLocation::getFromRawEncoding(First.ArrayOrRange.LBracketLoc);
3986   return StartLoc;
3987 }
3988 
3989 SourceLocation DesignatedInitExpr::getEndLoc() const {
3990   return getInit()->getEndLoc();
3991 }
3992 
3993 Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) const {
3994   assert(D.Kind == Designator::ArrayDesignator && "Requires array designator");
3995   return getSubExpr(D.ArrayOrRange.Index + 1);
3996 }
3997 
3998 Expr *DesignatedInitExpr::getArrayRangeStart(const Designator &D) const {
3999   assert(D.Kind == Designator::ArrayRangeDesignator &&
4000          "Requires array range designator");
4001   return getSubExpr(D.ArrayOrRange.Index + 1);
4002 }
4003 
4004 Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator &D) const {
4005   assert(D.Kind == Designator::ArrayRangeDesignator &&
4006          "Requires array range designator");
4007   return getSubExpr(D.ArrayOrRange.Index + 2);
4008 }
4009 
4010 /// Replaces the designator at index @p Idx with the series
4011 /// of designators in [First, Last).
4012 void DesignatedInitExpr::ExpandDesignator(const ASTContext &C, unsigned Idx,
4013                                           const Designator *First,
4014                                           const Designator *Last) {
4015   unsigned NumNewDesignators = Last - First;
4016   if (NumNewDesignators == 0) {
4017     std::copy_backward(Designators + Idx + 1,
4018                        Designators + NumDesignators,
4019                        Designators + Idx);
4020     --NumNewDesignators;
4021     return;
4022   } else if (NumNewDesignators == 1) {
4023     Designators[Idx] = *First;
4024     return;
4025   }
4026 
4027   Designator *NewDesignators
4028     = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
4029   std::copy(Designators, Designators + Idx, NewDesignators);
4030   std::copy(First, Last, NewDesignators + Idx);
4031   std::copy(Designators + Idx + 1, Designators + NumDesignators,
4032             NewDesignators + Idx + NumNewDesignators);
4033   Designators = NewDesignators;
4034   NumDesignators = NumDesignators - 1 + NumNewDesignators;
4035 }
4036 
4037 DesignatedInitUpdateExpr::DesignatedInitUpdateExpr(const ASTContext &C,
4038     SourceLocation lBraceLoc, Expr *baseExpr, SourceLocation rBraceLoc)
4039   : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_RValue,
4040          OK_Ordinary, false, false, false, false) {
4041   BaseAndUpdaterExprs[0] = baseExpr;
4042 
4043   InitListExpr *ILE = new (C) InitListExpr(C, lBraceLoc, None, rBraceLoc);
4044   ILE->setType(baseExpr->getType());
4045   BaseAndUpdaterExprs[1] = ILE;
4046 }
4047 
4048 SourceLocation DesignatedInitUpdateExpr::getBeginLoc() const {
4049   return getBase()->getBeginLoc();
4050 }
4051 
4052 SourceLocation DesignatedInitUpdateExpr::getEndLoc() const {
4053   return getBase()->getEndLoc();
4054 }
4055 
4056 ParenListExpr::ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs,
4057                              SourceLocation RParenLoc)
4058     : Expr(ParenListExprClass, QualType(), VK_RValue, OK_Ordinary, false, false,
4059            false, false),
4060       LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
4061   ParenListExprBits.NumExprs = Exprs.size();
4062 
4063   for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
4064     if (Exprs[I]->isTypeDependent())
4065       ExprBits.TypeDependent = true;
4066     if (Exprs[I]->isValueDependent())
4067       ExprBits.ValueDependent = true;
4068     if (Exprs[I]->isInstantiationDependent())
4069       ExprBits.InstantiationDependent = true;
4070     if (Exprs[I]->containsUnexpandedParameterPack())
4071       ExprBits.ContainsUnexpandedParameterPack = true;
4072 
4073     getTrailingObjects<Stmt *>()[I] = Exprs[I];
4074   }
4075 }
4076 
4077 ParenListExpr::ParenListExpr(EmptyShell Empty, unsigned NumExprs)
4078     : Expr(ParenListExprClass, Empty) {
4079   ParenListExprBits.NumExprs = NumExprs;
4080 }
4081 
4082 ParenListExpr *ParenListExpr::Create(const ASTContext &Ctx,
4083                                      SourceLocation LParenLoc,
4084                                      ArrayRef<Expr *> Exprs,
4085                                      SourceLocation RParenLoc) {
4086   void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(Exprs.size()),
4087                            alignof(ParenListExpr));
4088   return new (Mem) ParenListExpr(LParenLoc, Exprs, RParenLoc);
4089 }
4090 
4091 ParenListExpr *ParenListExpr::CreateEmpty(const ASTContext &Ctx,
4092                                           unsigned NumExprs) {
4093   void *Mem =
4094       Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumExprs), alignof(ParenListExpr));
4095   return new (Mem) ParenListExpr(EmptyShell(), NumExprs);
4096 }
4097 
4098 const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {
4099   if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
4100     e = ewc->getSubExpr();
4101   if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
4102     e = m->GetTemporaryExpr();
4103   e = cast<CXXConstructExpr>(e)->getArg(0);
4104   while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
4105     e = ice->getSubExpr();
4106   return cast<OpaqueValueExpr>(e);
4107 }
4108 
4109 PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &Context,
4110                                            EmptyShell sh,
4111                                            unsigned numSemanticExprs) {
4112   void *buffer =
4113       Context.Allocate(totalSizeToAlloc<Expr *>(1 + numSemanticExprs),
4114                        alignof(PseudoObjectExpr));
4115   return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
4116 }
4117 
4118 PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
4119   : Expr(PseudoObjectExprClass, shell) {
4120   PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
4121 }
4122 
4123 PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &C, Expr *syntax,
4124                                            ArrayRef<Expr*> semantics,
4125                                            unsigned resultIndex) {
4126   assert(syntax && "no syntactic expression!");
4127   assert(semantics.size() && "no semantic expressions!");
4128 
4129   QualType type;
4130   ExprValueKind VK;
4131   if (resultIndex == NoResult) {
4132     type = C.VoidTy;
4133     VK = VK_RValue;
4134   } else {
4135     assert(resultIndex < semantics.size());
4136     type = semantics[resultIndex]->getType();
4137     VK = semantics[resultIndex]->getValueKind();
4138     assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary);
4139   }
4140 
4141   void *buffer = C.Allocate(totalSizeToAlloc<Expr *>(semantics.size() + 1),
4142                             alignof(PseudoObjectExpr));
4143   return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
4144                                       resultIndex);
4145 }
4146 
4147 PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
4148                                    Expr *syntax, ArrayRef<Expr*> semantics,
4149                                    unsigned resultIndex)
4150   : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary,
4151          /*filled in at end of ctor*/ false, false, false, false) {
4152   PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
4153   PseudoObjectExprBits.ResultIndex = resultIndex + 1;
4154 
4155   for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) {
4156     Expr *E = (i == 0 ? syntax : semantics[i-1]);
4157     getSubExprsBuffer()[i] = E;
4158 
4159     if (E->isTypeDependent())
4160       ExprBits.TypeDependent = true;
4161     if (E->isValueDependent())
4162       ExprBits.ValueDependent = true;
4163     if (E->isInstantiationDependent())
4164       ExprBits.InstantiationDependent = true;
4165     if (E->containsUnexpandedParameterPack())
4166       ExprBits.ContainsUnexpandedParameterPack = true;
4167 
4168     if (isa<OpaqueValueExpr>(E))
4169       assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr &&
4170              "opaque-value semantic expressions for pseudo-object "
4171              "operations must have sources");
4172   }
4173 }
4174 
4175 //===----------------------------------------------------------------------===//
4176 //  Child Iterators for iterating over subexpressions/substatements
4177 //===----------------------------------------------------------------------===//
4178 
4179 // UnaryExprOrTypeTraitExpr
4180 Stmt::child_range UnaryExprOrTypeTraitExpr::children() {
4181   const_child_range CCR =
4182       const_cast<const UnaryExprOrTypeTraitExpr *>(this)->children();
4183   return child_range(cast_away_const(CCR.begin()), cast_away_const(CCR.end()));
4184 }
4185 
4186 Stmt::const_child_range UnaryExprOrTypeTraitExpr::children() const {
4187   // If this is of a type and the type is a VLA type (and not a typedef), the
4188   // size expression of the VLA needs to be treated as an executable expression.
4189   // Why isn't this weirdness documented better in StmtIterator?
4190   if (isArgumentType()) {
4191     if (const VariableArrayType *T =
4192             dyn_cast<VariableArrayType>(getArgumentType().getTypePtr()))
4193       return const_child_range(const_child_iterator(T), const_child_iterator());
4194     return const_child_range(const_child_iterator(), const_child_iterator());
4195   }
4196   return const_child_range(&Argument.Ex, &Argument.Ex + 1);
4197 }
4198 
4199 AtomicExpr::AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args,
4200                        QualType t, AtomicOp op, SourceLocation RP)
4201   : Expr(AtomicExprClass, t, VK_RValue, OK_Ordinary,
4202          false, false, false, false),
4203     NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op)
4204 {
4205   assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions");
4206   for (unsigned i = 0; i != args.size(); i++) {
4207     if (args[i]->isTypeDependent())
4208       ExprBits.TypeDependent = true;
4209     if (args[i]->isValueDependent())
4210       ExprBits.ValueDependent = true;
4211     if (args[i]->isInstantiationDependent())
4212       ExprBits.InstantiationDependent = true;
4213     if (args[i]->containsUnexpandedParameterPack())
4214       ExprBits.ContainsUnexpandedParameterPack = true;
4215 
4216     SubExprs[i] = args[i];
4217   }
4218 }
4219 
4220 unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) {
4221   switch (Op) {
4222   case AO__c11_atomic_init:
4223   case AO__opencl_atomic_init:
4224   case AO__c11_atomic_load:
4225   case AO__atomic_load_n:
4226     return 2;
4227 
4228   case AO__opencl_atomic_load:
4229   case AO__c11_atomic_store:
4230   case AO__c11_atomic_exchange:
4231   case AO__atomic_load:
4232   case AO__atomic_store:
4233   case AO__atomic_store_n:
4234   case AO__atomic_exchange_n:
4235   case AO__c11_atomic_fetch_add:
4236   case AO__c11_atomic_fetch_sub:
4237   case AO__c11_atomic_fetch_and:
4238   case AO__c11_atomic_fetch_or:
4239   case AO__c11_atomic_fetch_xor:
4240   case AO__atomic_fetch_add:
4241   case AO__atomic_fetch_sub:
4242   case AO__atomic_fetch_and:
4243   case AO__atomic_fetch_or:
4244   case AO__atomic_fetch_xor:
4245   case AO__atomic_fetch_nand:
4246   case AO__atomic_add_fetch:
4247   case AO__atomic_sub_fetch:
4248   case AO__atomic_and_fetch:
4249   case AO__atomic_or_fetch:
4250   case AO__atomic_xor_fetch:
4251   case AO__atomic_nand_fetch:
4252   case AO__atomic_fetch_min:
4253   case AO__atomic_fetch_max:
4254     return 3;
4255 
4256   case AO__opencl_atomic_store:
4257   case AO__opencl_atomic_exchange:
4258   case AO__opencl_atomic_fetch_add:
4259   case AO__opencl_atomic_fetch_sub:
4260   case AO__opencl_atomic_fetch_and:
4261   case AO__opencl_atomic_fetch_or:
4262   case AO__opencl_atomic_fetch_xor:
4263   case AO__opencl_atomic_fetch_min:
4264   case AO__opencl_atomic_fetch_max:
4265   case AO__atomic_exchange:
4266     return 4;
4267 
4268   case AO__c11_atomic_compare_exchange_strong:
4269   case AO__c11_atomic_compare_exchange_weak:
4270     return 5;
4271 
4272   case AO__opencl_atomic_compare_exchange_strong:
4273   case AO__opencl_atomic_compare_exchange_weak:
4274   case AO__atomic_compare_exchange:
4275   case AO__atomic_compare_exchange_n:
4276     return 6;
4277   }
4278   llvm_unreachable("unknown atomic op");
4279 }
4280 
4281 QualType AtomicExpr::getValueType() const {
4282   auto T = getPtr()->getType()->castAs<PointerType>()->getPointeeType();
4283   if (auto AT = T->getAs<AtomicType>())
4284     return AT->getValueType();
4285   return T;
4286 }
4287 
4288 QualType OMPArraySectionExpr::getBaseOriginalType(const Expr *Base) {
4289   unsigned ArraySectionCount = 0;
4290   while (auto *OASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParens())) {
4291     Base = OASE->getBase();
4292     ++ArraySectionCount;
4293   }
4294   while (auto *ASE =
4295              dyn_cast<ArraySubscriptExpr>(Base->IgnoreParenImpCasts())) {
4296     Base = ASE->getBase();
4297     ++ArraySectionCount;
4298   }
4299   Base = Base->IgnoreParenImpCasts();
4300   auto OriginalTy = Base->getType();
4301   if (auto *DRE = dyn_cast<DeclRefExpr>(Base))
4302     if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
4303       OriginalTy = PVD->getOriginalType().getNonReferenceType();
4304 
4305   for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) {
4306     if (OriginalTy->isAnyPointerType())
4307       OriginalTy = OriginalTy->getPointeeType();
4308     else {
4309       assert (OriginalTy->isArrayType());
4310       OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType();
4311     }
4312   }
4313   return OriginalTy;
4314 }
4315