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