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