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