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