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