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