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