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