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