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