1 //===- ExprCXX.cpp - (C++) 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 subclesses of Expr class declared in ExprCXX.h
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/ExprCXX.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/Attr.h"
16 #include "clang/AST/ComputeDependence.h"
17 #include "clang/AST/Decl.h"
18 #include "clang/AST/DeclAccessPair.h"
19 #include "clang/AST/DeclBase.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/DeclarationName.h"
23 #include "clang/AST/DependenceFlags.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/LambdaCapture.h"
26 #include "clang/AST/NestedNameSpecifier.h"
27 #include "clang/AST/TemplateBase.h"
28 #include "clang/AST/Type.h"
29 #include "clang/AST/TypeLoc.h"
30 #include "clang/Basic/LLVM.h"
31 #include "clang/Basic/OperatorKinds.h"
32 #include "clang/Basic/SourceLocation.h"
33 #include "clang/Basic/Specifiers.h"
34 #include "llvm/ADT/ArrayRef.h"
35 #include "llvm/Support/Casting.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include <cassert>
38 #include <cstddef>
39 #include <cstring>
40 #include <memory>
41 
42 using namespace clang;
43 
44 //===----------------------------------------------------------------------===//
45 //  Child Iterators for iterating over subexpressions/substatements
46 //===----------------------------------------------------------------------===//
47 
48 bool CXXOperatorCallExpr::isInfixBinaryOp() const {
49   // An infix binary operator is any operator with two arguments other than
50   // operator() and operator[]. Note that none of these operators can have
51   // default arguments, so it suffices to check the number of argument
52   // expressions.
53   if (getNumArgs() != 2)
54     return false;
55 
56   switch (getOperator()) {
57   case OO_Call: case OO_Subscript:
58     return false;
59   default:
60     return true;
61   }
62 }
63 
64 CXXRewrittenBinaryOperator::DecomposedForm
65 CXXRewrittenBinaryOperator::getDecomposedForm() const {
66   DecomposedForm Result = {};
67   const Expr *E = getSemanticForm()->IgnoreImplicit();
68 
69   // Remove an outer '!' if it exists (only happens for a '!=' rewrite).
70   bool SkippedNot = false;
71   if (auto *NotEq = dyn_cast<UnaryOperator>(E)) {
72     assert(NotEq->getOpcode() == UO_LNot);
73     E = NotEq->getSubExpr()->IgnoreImplicit();
74     SkippedNot = true;
75   }
76 
77   // Decompose the outer binary operator.
78   if (auto *BO = dyn_cast<BinaryOperator>(E)) {
79     assert(!SkippedNot || BO->getOpcode() == BO_EQ);
80     Result.Opcode = SkippedNot ? BO_NE : BO->getOpcode();
81     Result.LHS = BO->getLHS();
82     Result.RHS = BO->getRHS();
83     Result.InnerBinOp = BO;
84   } else if (auto *BO = dyn_cast<CXXOperatorCallExpr>(E)) {
85     assert(!SkippedNot || BO->getOperator() == OO_EqualEqual);
86     assert(BO->isInfixBinaryOp());
87     switch (BO->getOperator()) {
88     case OO_Less: Result.Opcode = BO_LT; break;
89     case OO_LessEqual: Result.Opcode = BO_LE; break;
90     case OO_Greater: Result.Opcode = BO_GT; break;
91     case OO_GreaterEqual: Result.Opcode = BO_GE; break;
92     case OO_Spaceship: Result.Opcode = BO_Cmp; break;
93     case OO_EqualEqual: Result.Opcode = SkippedNot ? BO_NE : BO_EQ; break;
94     default: llvm_unreachable("unexpected binop in rewritten operator expr");
95     }
96     Result.LHS = BO->getArg(0);
97     Result.RHS = BO->getArg(1);
98     Result.InnerBinOp = BO;
99   } else {
100     llvm_unreachable("unexpected rewritten operator form");
101   }
102 
103   // Put the operands in the right order for == and !=, and canonicalize the
104   // <=> subexpression onto the LHS for all other forms.
105   if (isReversed())
106     std::swap(Result.LHS, Result.RHS);
107 
108   // If this isn't a spaceship rewrite, we're done.
109   if (Result.Opcode == BO_EQ || Result.Opcode == BO_NE)
110     return Result;
111 
112   // Otherwise, we expect a <=> to now be on the LHS.
113   E = Result.LHS->IgnoreImplicitAsWritten();
114   if (auto *BO = dyn_cast<BinaryOperator>(E)) {
115     assert(BO->getOpcode() == BO_Cmp);
116     Result.LHS = BO->getLHS();
117     Result.RHS = BO->getRHS();
118     Result.InnerBinOp = BO;
119   } else if (auto *BO = dyn_cast<CXXOperatorCallExpr>(E)) {
120     assert(BO->getOperator() == OO_Spaceship);
121     Result.LHS = BO->getArg(0);
122     Result.RHS = BO->getArg(1);
123     Result.InnerBinOp = BO;
124   } else {
125     llvm_unreachable("unexpected rewritten operator form");
126   }
127 
128   // Put the comparison operands in the right order.
129   if (isReversed())
130     std::swap(Result.LHS, Result.RHS);
131   return Result;
132 }
133 
134 bool CXXTypeidExpr::isPotentiallyEvaluated() const {
135   if (isTypeOperand())
136     return false;
137 
138   // C++11 [expr.typeid]p3:
139   //   When typeid is applied to an expression other than a glvalue of
140   //   polymorphic class type, [...] the expression is an unevaluated operand.
141   const Expr *E = getExprOperand();
142   if (const CXXRecordDecl *RD = E->getType()->getAsCXXRecordDecl())
143     if (RD->isPolymorphic() && E->isGLValue())
144       return true;
145 
146   return false;
147 }
148 
149 bool CXXTypeidExpr::isMostDerived(ASTContext &Context) const {
150   assert(!isTypeOperand() && "Cannot call isMostDerived for typeid(type)");
151   const Expr *E = getExprOperand()->IgnoreParenNoopCasts(Context);
152   if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
153     QualType Ty = DRE->getDecl()->getType();
154     if (!Ty->isPointerType() && !Ty->isReferenceType())
155       return true;
156   }
157 
158   return false;
159 }
160 
161 QualType CXXTypeidExpr::getTypeOperand(ASTContext &Context) const {
162   assert(isTypeOperand() && "Cannot call getTypeOperand for typeid(expr)");
163   Qualifiers Quals;
164   return Context.getUnqualifiedArrayType(
165       Operand.get<TypeSourceInfo *>()->getType().getNonReferenceType(), Quals);
166 }
167 
168 QualType CXXUuidofExpr::getTypeOperand(ASTContext &Context) const {
169   assert(isTypeOperand() && "Cannot call getTypeOperand for __uuidof(expr)");
170   Qualifiers Quals;
171   return Context.getUnqualifiedArrayType(
172       Operand.get<TypeSourceInfo *>()->getType().getNonReferenceType(), Quals);
173 }
174 
175 // CXXScalarValueInitExpr
176 SourceLocation CXXScalarValueInitExpr::getBeginLoc() const {
177   return TypeInfo ? TypeInfo->getTypeLoc().getBeginLoc() : getRParenLoc();
178 }
179 
180 // CXXNewExpr
181 CXXNewExpr::CXXNewExpr(bool IsGlobalNew, FunctionDecl *OperatorNew,
182                        FunctionDecl *OperatorDelete, bool ShouldPassAlignment,
183                        bool UsualArrayDeleteWantsSize,
184                        ArrayRef<Expr *> PlacementArgs, SourceRange TypeIdParens,
185                        Optional<Expr *> ArraySize,
186                        InitializationStyle InitializationStyle,
187                        Expr *Initializer, QualType Ty,
188                        TypeSourceInfo *AllocatedTypeInfo, SourceRange Range,
189                        SourceRange DirectInitRange)
190     : Expr(CXXNewExprClass, Ty, VK_RValue, OK_Ordinary),
191       OperatorNew(OperatorNew), OperatorDelete(OperatorDelete),
192       AllocatedTypeInfo(AllocatedTypeInfo), Range(Range),
193       DirectInitRange(DirectInitRange) {
194 
195   assert((Initializer != nullptr || InitializationStyle == NoInit) &&
196          "Only NoInit can have no initializer!");
197 
198   CXXNewExprBits.IsGlobalNew = IsGlobalNew;
199   CXXNewExprBits.IsArray = ArraySize.hasValue();
200   CXXNewExprBits.ShouldPassAlignment = ShouldPassAlignment;
201   CXXNewExprBits.UsualArrayDeleteWantsSize = UsualArrayDeleteWantsSize;
202   CXXNewExprBits.StoredInitializationStyle =
203       Initializer ? InitializationStyle + 1 : 0;
204   bool IsParenTypeId = TypeIdParens.isValid();
205   CXXNewExprBits.IsParenTypeId = IsParenTypeId;
206   CXXNewExprBits.NumPlacementArgs = PlacementArgs.size();
207 
208   if (ArraySize)
209     getTrailingObjects<Stmt *>()[arraySizeOffset()] = *ArraySize;
210   if (Initializer)
211     getTrailingObjects<Stmt *>()[initExprOffset()] = Initializer;
212   for (unsigned I = 0; I != PlacementArgs.size(); ++I)
213     getTrailingObjects<Stmt *>()[placementNewArgsOffset() + I] =
214         PlacementArgs[I];
215   if (IsParenTypeId)
216     getTrailingObjects<SourceRange>()[0] = TypeIdParens;
217 
218   switch (getInitializationStyle()) {
219   case CallInit:
220     this->Range.setEnd(DirectInitRange.getEnd());
221     break;
222   case ListInit:
223     this->Range.setEnd(getInitializer()->getSourceRange().getEnd());
224     break;
225   default:
226     if (IsParenTypeId)
227       this->Range.setEnd(TypeIdParens.getEnd());
228     break;
229   }
230 
231   setDependence(computeDependence(this));
232 }
233 
234 CXXNewExpr::CXXNewExpr(EmptyShell Empty, bool IsArray,
235                        unsigned NumPlacementArgs, bool IsParenTypeId)
236     : Expr(CXXNewExprClass, Empty) {
237   CXXNewExprBits.IsArray = IsArray;
238   CXXNewExprBits.NumPlacementArgs = NumPlacementArgs;
239   CXXNewExprBits.IsParenTypeId = IsParenTypeId;
240 }
241 
242 CXXNewExpr *
243 CXXNewExpr::Create(const ASTContext &Ctx, bool IsGlobalNew,
244                    FunctionDecl *OperatorNew, FunctionDecl *OperatorDelete,
245                    bool ShouldPassAlignment, bool UsualArrayDeleteWantsSize,
246                    ArrayRef<Expr *> PlacementArgs, SourceRange TypeIdParens,
247                    Optional<Expr *> ArraySize,
248                    InitializationStyle InitializationStyle, Expr *Initializer,
249                    QualType Ty, TypeSourceInfo *AllocatedTypeInfo,
250                    SourceRange Range, SourceRange DirectInitRange) {
251   bool IsArray = ArraySize.hasValue();
252   bool HasInit = Initializer != nullptr;
253   unsigned NumPlacementArgs = PlacementArgs.size();
254   bool IsParenTypeId = TypeIdParens.isValid();
255   void *Mem =
256       Ctx.Allocate(totalSizeToAlloc<Stmt *, SourceRange>(
257                        IsArray + HasInit + NumPlacementArgs, IsParenTypeId),
258                    alignof(CXXNewExpr));
259   return new (Mem)
260       CXXNewExpr(IsGlobalNew, OperatorNew, OperatorDelete, ShouldPassAlignment,
261                  UsualArrayDeleteWantsSize, PlacementArgs, TypeIdParens,
262                  ArraySize, InitializationStyle, Initializer, Ty,
263                  AllocatedTypeInfo, Range, DirectInitRange);
264 }
265 
266 CXXNewExpr *CXXNewExpr::CreateEmpty(const ASTContext &Ctx, bool IsArray,
267                                     bool HasInit, unsigned NumPlacementArgs,
268                                     bool IsParenTypeId) {
269   void *Mem =
270       Ctx.Allocate(totalSizeToAlloc<Stmt *, SourceRange>(
271                        IsArray + HasInit + NumPlacementArgs, IsParenTypeId),
272                    alignof(CXXNewExpr));
273   return new (Mem)
274       CXXNewExpr(EmptyShell(), IsArray, NumPlacementArgs, IsParenTypeId);
275 }
276 
277 bool CXXNewExpr::shouldNullCheckAllocation() const {
278   return getOperatorNew()
279              ->getType()
280              ->castAs<FunctionProtoType>()
281              ->isNothrow() &&
282          !getOperatorNew()->isReservedGlobalPlacementOperator();
283 }
284 
285 // CXXDeleteExpr
286 QualType CXXDeleteExpr::getDestroyedType() const {
287   const Expr *Arg = getArgument();
288 
289   // For a destroying operator delete, we may have implicitly converted the
290   // pointer type to the type of the parameter of the 'operator delete'
291   // function.
292   while (const auto *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
293     if (ICE->getCastKind() == CK_DerivedToBase ||
294         ICE->getCastKind() == CK_UncheckedDerivedToBase ||
295         ICE->getCastKind() == CK_NoOp) {
296       assert((ICE->getCastKind() == CK_NoOp ||
297               getOperatorDelete()->isDestroyingOperatorDelete()) &&
298              "only a destroying operator delete can have a converted arg");
299       Arg = ICE->getSubExpr();
300     } else
301       break;
302   }
303 
304   // The type-to-delete may not be a pointer if it's a dependent type.
305   const QualType ArgType = Arg->getType();
306 
307   if (ArgType->isDependentType() && !ArgType->isPointerType())
308     return QualType();
309 
310   return ArgType->castAs<PointerType>()->getPointeeType();
311 }
312 
313 // CXXPseudoDestructorExpr
314 PseudoDestructorTypeStorage::PseudoDestructorTypeStorage(TypeSourceInfo *Info)
315     : Type(Info) {
316   Location = Info->getTypeLoc().getLocalSourceRange().getBegin();
317 }
318 
319 CXXPseudoDestructorExpr::CXXPseudoDestructorExpr(
320     const ASTContext &Context, Expr *Base, bool isArrow,
321     SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc,
322     TypeSourceInfo *ScopeType, SourceLocation ColonColonLoc,
323     SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType)
324     : Expr(CXXPseudoDestructorExprClass, Context.BoundMemberTy, VK_RValue,
325            OK_Ordinary),
326       Base(static_cast<Stmt *>(Base)), IsArrow(isArrow),
327       OperatorLoc(OperatorLoc), QualifierLoc(QualifierLoc),
328       ScopeType(ScopeType), ColonColonLoc(ColonColonLoc), TildeLoc(TildeLoc),
329       DestroyedType(DestroyedType) {
330   setDependence(computeDependence(this));
331 }
332 
333 QualType CXXPseudoDestructorExpr::getDestroyedType() const {
334   if (TypeSourceInfo *TInfo = DestroyedType.getTypeSourceInfo())
335     return TInfo->getType();
336 
337   return QualType();
338 }
339 
340 SourceLocation CXXPseudoDestructorExpr::getEndLoc() const {
341   SourceLocation End = DestroyedType.getLocation();
342   if (TypeSourceInfo *TInfo = DestroyedType.getTypeSourceInfo())
343     End = TInfo->getTypeLoc().getLocalSourceRange().getEnd();
344   return End;
345 }
346 
347 // UnresolvedLookupExpr
348 UnresolvedLookupExpr::UnresolvedLookupExpr(
349     const ASTContext &Context, CXXRecordDecl *NamingClass,
350     NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
351     const DeclarationNameInfo &NameInfo, bool RequiresADL, bool Overloaded,
352     const TemplateArgumentListInfo *TemplateArgs, UnresolvedSetIterator Begin,
353     UnresolvedSetIterator End)
354     : OverloadExpr(UnresolvedLookupExprClass, Context, QualifierLoc,
355                    TemplateKWLoc, NameInfo, TemplateArgs, Begin, End, false,
356                    false, false),
357       NamingClass(NamingClass) {
358   UnresolvedLookupExprBits.RequiresADL = RequiresADL;
359   UnresolvedLookupExprBits.Overloaded = Overloaded;
360 }
361 
362 UnresolvedLookupExpr::UnresolvedLookupExpr(EmptyShell Empty,
363                                            unsigned NumResults,
364                                            bool HasTemplateKWAndArgsInfo)
365     : OverloadExpr(UnresolvedLookupExprClass, Empty, NumResults,
366                    HasTemplateKWAndArgsInfo) {}
367 
368 UnresolvedLookupExpr *UnresolvedLookupExpr::Create(
369     const ASTContext &Context, CXXRecordDecl *NamingClass,
370     NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo,
371     bool RequiresADL, bool Overloaded, UnresolvedSetIterator Begin,
372     UnresolvedSetIterator End) {
373   unsigned NumResults = End - Begin;
374   unsigned Size = totalSizeToAlloc<DeclAccessPair, ASTTemplateKWAndArgsInfo,
375                                    TemplateArgumentLoc>(NumResults, 0, 0);
376   void *Mem = Context.Allocate(Size, alignof(UnresolvedLookupExpr));
377   return new (Mem) UnresolvedLookupExpr(Context, NamingClass, QualifierLoc,
378                                         SourceLocation(), NameInfo, RequiresADL,
379                                         Overloaded, nullptr, Begin, End);
380 }
381 
382 UnresolvedLookupExpr *UnresolvedLookupExpr::Create(
383     const ASTContext &Context, CXXRecordDecl *NamingClass,
384     NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
385     const DeclarationNameInfo &NameInfo, bool RequiresADL,
386     const TemplateArgumentListInfo *Args, UnresolvedSetIterator Begin,
387     UnresolvedSetIterator End) {
388   assert(Args || TemplateKWLoc.isValid());
389   unsigned NumResults = End - Begin;
390   unsigned NumTemplateArgs = Args ? Args->size() : 0;
391   unsigned Size =
392       totalSizeToAlloc<DeclAccessPair, ASTTemplateKWAndArgsInfo,
393                        TemplateArgumentLoc>(NumResults, 1, NumTemplateArgs);
394   void *Mem = Context.Allocate(Size, alignof(UnresolvedLookupExpr));
395   return new (Mem) UnresolvedLookupExpr(Context, NamingClass, QualifierLoc,
396                                         TemplateKWLoc, NameInfo, RequiresADL,
397                                         /*Overloaded*/ true, Args, Begin, End);
398 }
399 
400 UnresolvedLookupExpr *UnresolvedLookupExpr::CreateEmpty(
401     const ASTContext &Context, unsigned NumResults,
402     bool HasTemplateKWAndArgsInfo, unsigned NumTemplateArgs) {
403   assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);
404   unsigned Size = totalSizeToAlloc<DeclAccessPair, ASTTemplateKWAndArgsInfo,
405                                    TemplateArgumentLoc>(
406       NumResults, HasTemplateKWAndArgsInfo, NumTemplateArgs);
407   void *Mem = Context.Allocate(Size, alignof(UnresolvedLookupExpr));
408   return new (Mem)
409       UnresolvedLookupExpr(EmptyShell(), NumResults, HasTemplateKWAndArgsInfo);
410 }
411 
412 OverloadExpr::OverloadExpr(StmtClass SC, const ASTContext &Context,
413                            NestedNameSpecifierLoc QualifierLoc,
414                            SourceLocation TemplateKWLoc,
415                            const DeclarationNameInfo &NameInfo,
416                            const TemplateArgumentListInfo *TemplateArgs,
417                            UnresolvedSetIterator Begin,
418                            UnresolvedSetIterator End, bool KnownDependent,
419                            bool KnownInstantiationDependent,
420                            bool KnownContainsUnexpandedParameterPack)
421     : Expr(SC, Context.OverloadTy, VK_LValue, OK_Ordinary), NameInfo(NameInfo),
422       QualifierLoc(QualifierLoc) {
423   unsigned NumResults = End - Begin;
424   OverloadExprBits.NumResults = NumResults;
425   OverloadExprBits.HasTemplateKWAndArgsInfo =
426       (TemplateArgs != nullptr ) || TemplateKWLoc.isValid();
427 
428   if (NumResults) {
429     // Copy the results to the trailing array past UnresolvedLookupExpr
430     // or UnresolvedMemberExpr.
431     DeclAccessPair *Results = getTrailingResults();
432     memcpy(Results, Begin.I, NumResults * sizeof(DeclAccessPair));
433   }
434 
435   if (TemplateArgs) {
436     auto Deps = TemplateArgumentDependence::None;
437     getTrailingASTTemplateKWAndArgsInfo()->initializeFrom(
438         TemplateKWLoc, *TemplateArgs, getTrailingTemplateArgumentLoc(), Deps);
439   } else if (TemplateKWLoc.isValid()) {
440     getTrailingASTTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc);
441   }
442 
443   setDependence(computeDependence(this, KnownDependent,
444                                   KnownInstantiationDependent,
445                                   KnownContainsUnexpandedParameterPack));
446   if (isTypeDependent())
447     setType(Context.DependentTy);
448 }
449 
450 OverloadExpr::OverloadExpr(StmtClass SC, EmptyShell Empty, unsigned NumResults,
451                            bool HasTemplateKWAndArgsInfo)
452     : Expr(SC, Empty) {
453   OverloadExprBits.NumResults = NumResults;
454   OverloadExprBits.HasTemplateKWAndArgsInfo = HasTemplateKWAndArgsInfo;
455 }
456 
457 // DependentScopeDeclRefExpr
458 DependentScopeDeclRefExpr::DependentScopeDeclRefExpr(
459     QualType Ty, NestedNameSpecifierLoc QualifierLoc,
460     SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo,
461     const TemplateArgumentListInfo *Args)
462     : Expr(DependentScopeDeclRefExprClass, Ty, VK_LValue, OK_Ordinary),
463       QualifierLoc(QualifierLoc), NameInfo(NameInfo) {
464   DependentScopeDeclRefExprBits.HasTemplateKWAndArgsInfo =
465       (Args != nullptr) || TemplateKWLoc.isValid();
466   if (Args) {
467     auto Deps = TemplateArgumentDependence::None;
468     getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
469         TemplateKWLoc, *Args, getTrailingObjects<TemplateArgumentLoc>(), Deps);
470   } else if (TemplateKWLoc.isValid()) {
471     getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
472         TemplateKWLoc);
473   }
474   setDependence(computeDependence(this));
475 }
476 
477 DependentScopeDeclRefExpr *DependentScopeDeclRefExpr::Create(
478     const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
479     SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo,
480     const TemplateArgumentListInfo *Args) {
481   assert(QualifierLoc && "should be created for dependent qualifiers");
482   bool HasTemplateKWAndArgsInfo = Args || TemplateKWLoc.isValid();
483   std::size_t Size =
484       totalSizeToAlloc<ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
485           HasTemplateKWAndArgsInfo, Args ? Args->size() : 0);
486   void *Mem = Context.Allocate(Size);
487   return new (Mem) DependentScopeDeclRefExpr(Context.DependentTy, QualifierLoc,
488                                              TemplateKWLoc, NameInfo, Args);
489 }
490 
491 DependentScopeDeclRefExpr *
492 DependentScopeDeclRefExpr::CreateEmpty(const ASTContext &Context,
493                                        bool HasTemplateKWAndArgsInfo,
494                                        unsigned NumTemplateArgs) {
495   assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);
496   std::size_t Size =
497       totalSizeToAlloc<ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
498           HasTemplateKWAndArgsInfo, NumTemplateArgs);
499   void *Mem = Context.Allocate(Size);
500   auto *E = new (Mem) DependentScopeDeclRefExpr(
501       QualType(), NestedNameSpecifierLoc(), SourceLocation(),
502       DeclarationNameInfo(), nullptr);
503   E->DependentScopeDeclRefExprBits.HasTemplateKWAndArgsInfo =
504       HasTemplateKWAndArgsInfo;
505   return E;
506 }
507 
508 SourceLocation CXXConstructExpr::getBeginLoc() const {
509   if (isa<CXXTemporaryObjectExpr>(this))
510     return cast<CXXTemporaryObjectExpr>(this)->getBeginLoc();
511   return getLocation();
512 }
513 
514 SourceLocation CXXConstructExpr::getEndLoc() const {
515   if (isa<CXXTemporaryObjectExpr>(this))
516     return cast<CXXTemporaryObjectExpr>(this)->getEndLoc();
517 
518   if (ParenOrBraceRange.isValid())
519     return ParenOrBraceRange.getEnd();
520 
521   SourceLocation End = getLocation();
522   for (unsigned I = getNumArgs(); I > 0; --I) {
523     const Expr *Arg = getArg(I-1);
524     if (!Arg->isDefaultArgument()) {
525       SourceLocation NewEnd = Arg->getEndLoc();
526       if (NewEnd.isValid()) {
527         End = NewEnd;
528         break;
529       }
530     }
531   }
532 
533   return End;
534 }
535 
536 CXXOperatorCallExpr::CXXOperatorCallExpr(OverloadedOperatorKind OpKind,
537                                          Expr *Fn, ArrayRef<Expr *> Args,
538                                          QualType Ty, ExprValueKind VK,
539                                          SourceLocation OperatorLoc,
540                                          FPOptionsOverride FPFeatures,
541                                          ADLCallKind UsesADL)
542     : CallExpr(CXXOperatorCallExprClass, Fn, /*PreArgs=*/{}, Args, Ty, VK,
543                OperatorLoc, FPFeatures, /*MinNumArgs=*/0, UsesADL) {
544   CXXOperatorCallExprBits.OperatorKind = OpKind;
545   assert(
546       (CXXOperatorCallExprBits.OperatorKind == static_cast<unsigned>(OpKind)) &&
547       "OperatorKind overflow!");
548   Range = getSourceRangeImpl();
549 }
550 
551 CXXOperatorCallExpr::CXXOperatorCallExpr(unsigned NumArgs, bool HasFPFeatures,
552                                          EmptyShell Empty)
553     : CallExpr(CXXOperatorCallExprClass, /*NumPreArgs=*/0, NumArgs,
554                HasFPFeatures, Empty) {}
555 
556 CXXOperatorCallExpr *
557 CXXOperatorCallExpr::Create(const ASTContext &Ctx,
558                             OverloadedOperatorKind OpKind, Expr *Fn,
559                             ArrayRef<Expr *> Args, QualType Ty,
560                             ExprValueKind VK, SourceLocation OperatorLoc,
561                             FPOptionsOverride FPFeatures, ADLCallKind UsesADL) {
562   // Allocate storage for the trailing objects of CallExpr.
563   unsigned NumArgs = Args.size();
564   unsigned SizeOfTrailingObjects = CallExpr::sizeOfTrailingObjects(
565       /*NumPreArgs=*/0, NumArgs, FPFeatures.requiresTrailingStorage());
566   void *Mem = Ctx.Allocate(sizeof(CXXOperatorCallExpr) + SizeOfTrailingObjects,
567                            alignof(CXXOperatorCallExpr));
568   return new (Mem) CXXOperatorCallExpr(OpKind, Fn, Args, Ty, VK, OperatorLoc,
569                                        FPFeatures, UsesADL);
570 }
571 
572 CXXOperatorCallExpr *CXXOperatorCallExpr::CreateEmpty(const ASTContext &Ctx,
573                                                       unsigned NumArgs,
574                                                       bool HasFPFeatures,
575                                                       EmptyShell Empty) {
576   // Allocate storage for the trailing objects of CallExpr.
577   unsigned SizeOfTrailingObjects =
578       CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs, HasFPFeatures);
579   void *Mem = Ctx.Allocate(sizeof(CXXOperatorCallExpr) + SizeOfTrailingObjects,
580                            alignof(CXXOperatorCallExpr));
581   return new (Mem) CXXOperatorCallExpr(NumArgs, HasFPFeatures, Empty);
582 }
583 
584 SourceRange CXXOperatorCallExpr::getSourceRangeImpl() const {
585   OverloadedOperatorKind Kind = getOperator();
586   if (Kind == OO_PlusPlus || Kind == OO_MinusMinus) {
587     if (getNumArgs() == 1)
588       // Prefix operator
589       return SourceRange(getOperatorLoc(), getArg(0)->getEndLoc());
590     else
591       // Postfix operator
592       return SourceRange(getArg(0)->getBeginLoc(), getOperatorLoc());
593   } else if (Kind == OO_Arrow) {
594     return SourceRange(getArg(0)->getBeginLoc(), getOperatorLoc());
595   } else if (Kind == OO_Call) {
596     return SourceRange(getArg(0)->getBeginLoc(), getRParenLoc());
597   } else if (Kind == OO_Subscript) {
598     return SourceRange(getArg(0)->getBeginLoc(), getRParenLoc());
599   } else if (getNumArgs() == 1) {
600     return SourceRange(getOperatorLoc(), getArg(0)->getEndLoc());
601   } else if (getNumArgs() == 2) {
602     return SourceRange(getArg(0)->getBeginLoc(), getArg(1)->getEndLoc());
603   } else {
604     return getOperatorLoc();
605   }
606 }
607 
608 CXXMemberCallExpr::CXXMemberCallExpr(Expr *Fn, ArrayRef<Expr *> Args,
609                                      QualType Ty, ExprValueKind VK,
610                                      SourceLocation RP,
611                                      FPOptionsOverride FPOptions,
612                                      unsigned MinNumArgs)
613     : CallExpr(CXXMemberCallExprClass, Fn, /*PreArgs=*/{}, Args, Ty, VK, RP,
614                FPOptions, MinNumArgs, NotADL) {}
615 
616 CXXMemberCallExpr::CXXMemberCallExpr(unsigned NumArgs, bool HasFPFeatures,
617                                      EmptyShell Empty)
618     : CallExpr(CXXMemberCallExprClass, /*NumPreArgs=*/0, NumArgs, HasFPFeatures,
619                Empty) {}
620 
621 CXXMemberCallExpr *CXXMemberCallExpr::Create(const ASTContext &Ctx, Expr *Fn,
622                                              ArrayRef<Expr *> Args, QualType Ty,
623                                              ExprValueKind VK,
624                                              SourceLocation RP,
625                                              FPOptionsOverride FPFeatures,
626                                              unsigned MinNumArgs) {
627   // Allocate storage for the trailing objects of CallExpr.
628   unsigned NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
629   unsigned SizeOfTrailingObjects = CallExpr::sizeOfTrailingObjects(
630       /*NumPreArgs=*/0, NumArgs, FPFeatures.requiresTrailingStorage());
631   void *Mem = Ctx.Allocate(sizeof(CXXMemberCallExpr) + SizeOfTrailingObjects,
632                            alignof(CXXMemberCallExpr));
633   return new (Mem)
634       CXXMemberCallExpr(Fn, Args, Ty, VK, RP, FPFeatures, MinNumArgs);
635 }
636 
637 CXXMemberCallExpr *CXXMemberCallExpr::CreateEmpty(const ASTContext &Ctx,
638                                                   unsigned NumArgs,
639                                                   bool HasFPFeatures,
640                                                   EmptyShell Empty) {
641   // Allocate storage for the trailing objects of CallExpr.
642   unsigned SizeOfTrailingObjects =
643       CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs, HasFPFeatures);
644   void *Mem = Ctx.Allocate(sizeof(CXXMemberCallExpr) + SizeOfTrailingObjects,
645                            alignof(CXXMemberCallExpr));
646   return new (Mem) CXXMemberCallExpr(NumArgs, HasFPFeatures, Empty);
647 }
648 
649 Expr *CXXMemberCallExpr::getImplicitObjectArgument() const {
650   const Expr *Callee = getCallee()->IgnoreParens();
651   if (const auto *MemExpr = dyn_cast<MemberExpr>(Callee))
652     return MemExpr->getBase();
653   if (const auto *BO = dyn_cast<BinaryOperator>(Callee))
654     if (BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI)
655       return BO->getLHS();
656 
657   // FIXME: Will eventually need to cope with member pointers.
658   return nullptr;
659 }
660 
661 QualType CXXMemberCallExpr::getObjectType() const {
662   QualType Ty = getImplicitObjectArgument()->getType();
663   if (Ty->isPointerType())
664     Ty = Ty->getPointeeType();
665   return Ty;
666 }
667 
668 CXXMethodDecl *CXXMemberCallExpr::getMethodDecl() const {
669   if (const auto *MemExpr = dyn_cast<MemberExpr>(getCallee()->IgnoreParens()))
670     return cast<CXXMethodDecl>(MemExpr->getMemberDecl());
671 
672   // FIXME: Will eventually need to cope with member pointers.
673   return nullptr;
674 }
675 
676 CXXRecordDecl *CXXMemberCallExpr::getRecordDecl() const {
677   Expr* ThisArg = getImplicitObjectArgument();
678   if (!ThisArg)
679     return nullptr;
680 
681   if (ThisArg->getType()->isAnyPointerType())
682     return ThisArg->getType()->getPointeeType()->getAsCXXRecordDecl();
683 
684   return ThisArg->getType()->getAsCXXRecordDecl();
685 }
686 
687 //===----------------------------------------------------------------------===//
688 //  Named casts
689 //===----------------------------------------------------------------------===//
690 
691 /// getCastName - Get the name of the C++ cast being used, e.g.,
692 /// "static_cast", "dynamic_cast", "reinterpret_cast", or
693 /// "const_cast". The returned pointer must not be freed.
694 const char *CXXNamedCastExpr::getCastName() const {
695   switch (getStmtClass()) {
696   case CXXStaticCastExprClass:      return "static_cast";
697   case CXXDynamicCastExprClass:     return "dynamic_cast";
698   case CXXReinterpretCastExprClass: return "reinterpret_cast";
699   case CXXConstCastExprClass:       return "const_cast";
700   case CXXAddrspaceCastExprClass:   return "addrspace_cast";
701   default:                          return "<invalid cast>";
702   }
703 }
704 
705 CXXStaticCastExpr *
706 CXXStaticCastExpr::Create(const ASTContext &C, QualType T, ExprValueKind VK,
707                           CastKind K, Expr *Op, const CXXCastPath *BasePath,
708                           TypeSourceInfo *WrittenTy, FPOptionsOverride FPO,
709                           SourceLocation L, SourceLocation RParenLoc,
710                           SourceRange AngleBrackets) {
711   unsigned PathSize = (BasePath ? BasePath->size() : 0);
712   void *Buffer =
713       C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
714           PathSize, FPO.requiresTrailingStorage()));
715   auto *E = new (Buffer) CXXStaticCastExpr(T, VK, K, Op, PathSize, WrittenTy,
716                                            FPO, L, RParenLoc, AngleBrackets);
717   if (PathSize)
718     std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
719                               E->getTrailingObjects<CXXBaseSpecifier *>());
720   return E;
721 }
722 
723 CXXStaticCastExpr *CXXStaticCastExpr::CreateEmpty(const ASTContext &C,
724                                                   unsigned PathSize,
725                                                   bool HasFPFeatures) {
726   void *Buffer =
727       C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
728           PathSize, HasFPFeatures));
729   return new (Buffer) CXXStaticCastExpr(EmptyShell(), PathSize, HasFPFeatures);
730 }
731 
732 CXXDynamicCastExpr *CXXDynamicCastExpr::Create(const ASTContext &C, QualType T,
733                                                ExprValueKind VK,
734                                                CastKind K, Expr *Op,
735                                                const CXXCastPath *BasePath,
736                                                TypeSourceInfo *WrittenTy,
737                                                SourceLocation L,
738                                                SourceLocation RParenLoc,
739                                                SourceRange AngleBrackets) {
740   unsigned PathSize = (BasePath ? BasePath->size() : 0);
741   void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
742   auto *E =
743       new (Buffer) CXXDynamicCastExpr(T, VK, K, Op, PathSize, WrittenTy, L,
744                                       RParenLoc, AngleBrackets);
745   if (PathSize)
746     std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
747                               E->getTrailingObjects<CXXBaseSpecifier *>());
748   return E;
749 }
750 
751 CXXDynamicCastExpr *CXXDynamicCastExpr::CreateEmpty(const ASTContext &C,
752                                                     unsigned PathSize) {
753   void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
754   return new (Buffer) CXXDynamicCastExpr(EmptyShell(), PathSize);
755 }
756 
757 /// isAlwaysNull - Return whether the result of the dynamic_cast is proven
758 /// to always be null. For example:
759 ///
760 /// struct A { };
761 /// struct B final : A { };
762 /// struct C { };
763 ///
764 /// C *f(B* b) { return dynamic_cast<C*>(b); }
765 bool CXXDynamicCastExpr::isAlwaysNull() const
766 {
767   QualType SrcType = getSubExpr()->getType();
768   QualType DestType = getType();
769 
770   if (const auto *SrcPTy = SrcType->getAs<PointerType>()) {
771     SrcType = SrcPTy->getPointeeType();
772     DestType = DestType->castAs<PointerType>()->getPointeeType();
773   }
774 
775   if (DestType->isVoidType())
776     return false;
777 
778   const auto *SrcRD =
779       cast<CXXRecordDecl>(SrcType->castAs<RecordType>()->getDecl());
780 
781   if (!SrcRD->hasAttr<FinalAttr>())
782     return false;
783 
784   const auto *DestRD =
785       cast<CXXRecordDecl>(DestType->castAs<RecordType>()->getDecl());
786 
787   return !DestRD->isDerivedFrom(SrcRD);
788 }
789 
790 CXXReinterpretCastExpr *
791 CXXReinterpretCastExpr::Create(const ASTContext &C, QualType T,
792                                ExprValueKind VK, CastKind K, Expr *Op,
793                                const CXXCastPath *BasePath,
794                                TypeSourceInfo *WrittenTy, SourceLocation L,
795                                SourceLocation RParenLoc,
796                                SourceRange AngleBrackets) {
797   unsigned PathSize = (BasePath ? BasePath->size() : 0);
798   void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
799   auto *E =
800       new (Buffer) CXXReinterpretCastExpr(T, VK, K, Op, PathSize, WrittenTy, L,
801                                           RParenLoc, AngleBrackets);
802   if (PathSize)
803     std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
804                               E->getTrailingObjects<CXXBaseSpecifier *>());
805   return E;
806 }
807 
808 CXXReinterpretCastExpr *
809 CXXReinterpretCastExpr::CreateEmpty(const ASTContext &C, unsigned PathSize) {
810   void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
811   return new (Buffer) CXXReinterpretCastExpr(EmptyShell(), PathSize);
812 }
813 
814 CXXConstCastExpr *CXXConstCastExpr::Create(const ASTContext &C, QualType T,
815                                            ExprValueKind VK, Expr *Op,
816                                            TypeSourceInfo *WrittenTy,
817                                            SourceLocation L,
818                                            SourceLocation RParenLoc,
819                                            SourceRange AngleBrackets) {
820   return new (C) CXXConstCastExpr(T, VK, Op, WrittenTy, L, RParenLoc, AngleBrackets);
821 }
822 
823 CXXConstCastExpr *CXXConstCastExpr::CreateEmpty(const ASTContext &C) {
824   return new (C) CXXConstCastExpr(EmptyShell());
825 }
826 
827 CXXAddrspaceCastExpr *
828 CXXAddrspaceCastExpr::Create(const ASTContext &C, QualType T, ExprValueKind VK,
829                              CastKind K, Expr *Op, TypeSourceInfo *WrittenTy,
830                              SourceLocation L, SourceLocation RParenLoc,
831                              SourceRange AngleBrackets) {
832   return new (C) CXXAddrspaceCastExpr(T, VK, K, Op, WrittenTy, L, RParenLoc,
833                                       AngleBrackets);
834 }
835 
836 CXXAddrspaceCastExpr *CXXAddrspaceCastExpr::CreateEmpty(const ASTContext &C) {
837   return new (C) CXXAddrspaceCastExpr(EmptyShell());
838 }
839 
840 CXXFunctionalCastExpr *CXXFunctionalCastExpr::Create(
841     const ASTContext &C, QualType T, ExprValueKind VK, TypeSourceInfo *Written,
842     CastKind K, Expr *Op, const CXXCastPath *BasePath, FPOptionsOverride FPO,
843     SourceLocation L, SourceLocation R) {
844   unsigned PathSize = (BasePath ? BasePath->size() : 0);
845   void *Buffer =
846       C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
847           PathSize, FPO.requiresTrailingStorage()));
848   auto *E = new (Buffer)
849       CXXFunctionalCastExpr(T, VK, Written, K, Op, PathSize, FPO, L, R);
850   if (PathSize)
851     std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
852                               E->getTrailingObjects<CXXBaseSpecifier *>());
853   return E;
854 }
855 
856 CXXFunctionalCastExpr *CXXFunctionalCastExpr::CreateEmpty(const ASTContext &C,
857                                                           unsigned PathSize,
858                                                           bool HasFPFeatures) {
859   void *Buffer =
860       C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
861           PathSize, HasFPFeatures));
862   return new (Buffer)
863       CXXFunctionalCastExpr(EmptyShell(), PathSize, HasFPFeatures);
864 }
865 
866 SourceLocation CXXFunctionalCastExpr::getBeginLoc() const {
867   return getTypeInfoAsWritten()->getTypeLoc().getBeginLoc();
868 }
869 
870 SourceLocation CXXFunctionalCastExpr::getEndLoc() const {
871   return RParenLoc.isValid() ? RParenLoc : getSubExpr()->getEndLoc();
872 }
873 
874 UserDefinedLiteral::UserDefinedLiteral(Expr *Fn, ArrayRef<Expr *> Args,
875                                        QualType Ty, ExprValueKind VK,
876                                        SourceLocation LitEndLoc,
877                                        SourceLocation SuffixLoc,
878                                        FPOptionsOverride FPFeatures)
879     : CallExpr(UserDefinedLiteralClass, Fn, /*PreArgs=*/{}, Args, Ty, VK,
880                LitEndLoc, FPFeatures, /*MinNumArgs=*/0, NotADL),
881       UDSuffixLoc(SuffixLoc) {}
882 
883 UserDefinedLiteral::UserDefinedLiteral(unsigned NumArgs, bool HasFPFeatures,
884                                        EmptyShell Empty)
885     : CallExpr(UserDefinedLiteralClass, /*NumPreArgs=*/0, NumArgs,
886                HasFPFeatures, Empty) {}
887 
888 UserDefinedLiteral *UserDefinedLiteral::Create(const ASTContext &Ctx, Expr *Fn,
889                                                ArrayRef<Expr *> Args,
890                                                QualType Ty, ExprValueKind VK,
891                                                SourceLocation LitEndLoc,
892                                                SourceLocation SuffixLoc,
893                                                FPOptionsOverride FPFeatures) {
894   // Allocate storage for the trailing objects of CallExpr.
895   unsigned NumArgs = Args.size();
896   unsigned SizeOfTrailingObjects = CallExpr::sizeOfTrailingObjects(
897       /*NumPreArgs=*/0, NumArgs, FPFeatures.requiresTrailingStorage());
898   void *Mem = Ctx.Allocate(sizeof(UserDefinedLiteral) + SizeOfTrailingObjects,
899                            alignof(UserDefinedLiteral));
900   return new (Mem)
901       UserDefinedLiteral(Fn, Args, Ty, VK, LitEndLoc, SuffixLoc, FPFeatures);
902 }
903 
904 UserDefinedLiteral *UserDefinedLiteral::CreateEmpty(const ASTContext &Ctx,
905                                                     unsigned NumArgs,
906                                                     bool HasFPOptions,
907                                                     EmptyShell Empty) {
908   // Allocate storage for the trailing objects of CallExpr.
909   unsigned SizeOfTrailingObjects =
910       CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs, HasFPOptions);
911   void *Mem = Ctx.Allocate(sizeof(UserDefinedLiteral) + SizeOfTrailingObjects,
912                            alignof(UserDefinedLiteral));
913   return new (Mem) UserDefinedLiteral(NumArgs, HasFPOptions, Empty);
914 }
915 
916 UserDefinedLiteral::LiteralOperatorKind
917 UserDefinedLiteral::getLiteralOperatorKind() const {
918   if (getNumArgs() == 0)
919     return LOK_Template;
920   if (getNumArgs() == 2)
921     return LOK_String;
922 
923   assert(getNumArgs() == 1 && "unexpected #args in literal operator call");
924   QualType ParamTy =
925     cast<FunctionDecl>(getCalleeDecl())->getParamDecl(0)->getType();
926   if (ParamTy->isPointerType())
927     return LOK_Raw;
928   if (ParamTy->isAnyCharacterType())
929     return LOK_Character;
930   if (ParamTy->isIntegerType())
931     return LOK_Integer;
932   if (ParamTy->isFloatingType())
933     return LOK_Floating;
934 
935   llvm_unreachable("unknown kind of literal operator");
936 }
937 
938 Expr *UserDefinedLiteral::getCookedLiteral() {
939 #ifndef NDEBUG
940   LiteralOperatorKind LOK = getLiteralOperatorKind();
941   assert(LOK != LOK_Template && LOK != LOK_Raw && "not a cooked literal");
942 #endif
943   return getArg(0);
944 }
945 
946 const IdentifierInfo *UserDefinedLiteral::getUDSuffix() const {
947   return cast<FunctionDecl>(getCalleeDecl())->getLiteralIdentifier();
948 }
949 
950 CXXDefaultInitExpr::CXXDefaultInitExpr(const ASTContext &Ctx,
951                                        SourceLocation Loc, FieldDecl *Field,
952                                        QualType Ty, DeclContext *UsedContext)
953     : Expr(CXXDefaultInitExprClass, Ty.getNonLValueExprType(Ctx),
954            Ty->isLValueReferenceType()
955                ? VK_LValue
956                : Ty->isRValueReferenceType() ? VK_XValue : VK_RValue,
957            /*FIXME*/ OK_Ordinary),
958       Field(Field), UsedContext(UsedContext) {
959   CXXDefaultInitExprBits.Loc = Loc;
960   assert(Field->hasInClassInitializer());
961 
962   setDependence(computeDependence(this));
963 }
964 
965 CXXTemporary *CXXTemporary::Create(const ASTContext &C,
966                                    const CXXDestructorDecl *Destructor) {
967   return new (C) CXXTemporary(Destructor);
968 }
969 
970 CXXBindTemporaryExpr *CXXBindTemporaryExpr::Create(const ASTContext &C,
971                                                    CXXTemporary *Temp,
972                                                    Expr* SubExpr) {
973   assert((SubExpr->getType()->isRecordType() ||
974           SubExpr->getType()->isArrayType()) &&
975          "Expression bound to a temporary must have record or array type!");
976 
977   return new (C) CXXBindTemporaryExpr(Temp, SubExpr);
978 }
979 
980 CXXTemporaryObjectExpr::CXXTemporaryObjectExpr(
981     CXXConstructorDecl *Cons, QualType Ty, TypeSourceInfo *TSI,
982     ArrayRef<Expr *> Args, SourceRange ParenOrBraceRange,
983     bool HadMultipleCandidates, bool ListInitialization,
984     bool StdInitListInitialization, bool ZeroInitialization)
985     : CXXConstructExpr(
986           CXXTemporaryObjectExprClass, Ty, TSI->getTypeLoc().getBeginLoc(),
987           Cons, /* Elidable=*/false, Args, HadMultipleCandidates,
988           ListInitialization, StdInitListInitialization, ZeroInitialization,
989           CXXConstructExpr::CK_Complete, ParenOrBraceRange),
990       TSI(TSI) {}
991 
992 CXXTemporaryObjectExpr::CXXTemporaryObjectExpr(EmptyShell Empty,
993                                                unsigned NumArgs)
994     : CXXConstructExpr(CXXTemporaryObjectExprClass, Empty, NumArgs) {}
995 
996 CXXTemporaryObjectExpr *CXXTemporaryObjectExpr::Create(
997     const ASTContext &Ctx, CXXConstructorDecl *Cons, QualType Ty,
998     TypeSourceInfo *TSI, ArrayRef<Expr *> Args, SourceRange ParenOrBraceRange,
999     bool HadMultipleCandidates, bool ListInitialization,
1000     bool StdInitListInitialization, bool ZeroInitialization) {
1001   unsigned SizeOfTrailingObjects = sizeOfTrailingObjects(Args.size());
1002   void *Mem =
1003       Ctx.Allocate(sizeof(CXXTemporaryObjectExpr) + SizeOfTrailingObjects,
1004                    alignof(CXXTemporaryObjectExpr));
1005   return new (Mem) CXXTemporaryObjectExpr(
1006       Cons, Ty, TSI, Args, ParenOrBraceRange, HadMultipleCandidates,
1007       ListInitialization, StdInitListInitialization, ZeroInitialization);
1008 }
1009 
1010 CXXTemporaryObjectExpr *
1011 CXXTemporaryObjectExpr::CreateEmpty(const ASTContext &Ctx, unsigned NumArgs) {
1012   unsigned SizeOfTrailingObjects = sizeOfTrailingObjects(NumArgs);
1013   void *Mem =
1014       Ctx.Allocate(sizeof(CXXTemporaryObjectExpr) + SizeOfTrailingObjects,
1015                    alignof(CXXTemporaryObjectExpr));
1016   return new (Mem) CXXTemporaryObjectExpr(EmptyShell(), NumArgs);
1017 }
1018 
1019 SourceLocation CXXTemporaryObjectExpr::getBeginLoc() const {
1020   return getTypeSourceInfo()->getTypeLoc().getBeginLoc();
1021 }
1022 
1023 SourceLocation CXXTemporaryObjectExpr::getEndLoc() const {
1024   SourceLocation Loc = getParenOrBraceRange().getEnd();
1025   if (Loc.isInvalid() && getNumArgs())
1026     Loc = getArg(getNumArgs() - 1)->getEndLoc();
1027   return Loc;
1028 }
1029 
1030 CXXConstructExpr *CXXConstructExpr::Create(
1031     const ASTContext &Ctx, QualType Ty, SourceLocation Loc,
1032     CXXConstructorDecl *Ctor, bool Elidable, ArrayRef<Expr *> Args,
1033     bool HadMultipleCandidates, bool ListInitialization,
1034     bool StdInitListInitialization, bool ZeroInitialization,
1035     ConstructionKind ConstructKind, SourceRange ParenOrBraceRange) {
1036   unsigned SizeOfTrailingObjects = sizeOfTrailingObjects(Args.size());
1037   void *Mem = Ctx.Allocate(sizeof(CXXConstructExpr) + SizeOfTrailingObjects,
1038                            alignof(CXXConstructExpr));
1039   return new (Mem) CXXConstructExpr(
1040       CXXConstructExprClass, Ty, Loc, Ctor, Elidable, Args,
1041       HadMultipleCandidates, ListInitialization, StdInitListInitialization,
1042       ZeroInitialization, ConstructKind, ParenOrBraceRange);
1043 }
1044 
1045 CXXConstructExpr *CXXConstructExpr::CreateEmpty(const ASTContext &Ctx,
1046                                                 unsigned NumArgs) {
1047   unsigned SizeOfTrailingObjects = sizeOfTrailingObjects(NumArgs);
1048   void *Mem = Ctx.Allocate(sizeof(CXXConstructExpr) + SizeOfTrailingObjects,
1049                            alignof(CXXConstructExpr));
1050   return new (Mem)
1051       CXXConstructExpr(CXXConstructExprClass, EmptyShell(), NumArgs);
1052 }
1053 
1054 CXXConstructExpr::CXXConstructExpr(
1055     StmtClass SC, QualType Ty, SourceLocation Loc, CXXConstructorDecl *Ctor,
1056     bool Elidable, ArrayRef<Expr *> Args, bool HadMultipleCandidates,
1057     bool ListInitialization, bool StdInitListInitialization,
1058     bool ZeroInitialization, ConstructionKind ConstructKind,
1059     SourceRange ParenOrBraceRange)
1060     : Expr(SC, Ty, VK_RValue, OK_Ordinary), Constructor(Ctor),
1061       ParenOrBraceRange(ParenOrBraceRange), NumArgs(Args.size()) {
1062   CXXConstructExprBits.Elidable = Elidable;
1063   CXXConstructExprBits.HadMultipleCandidates = HadMultipleCandidates;
1064   CXXConstructExprBits.ListInitialization = ListInitialization;
1065   CXXConstructExprBits.StdInitListInitialization = StdInitListInitialization;
1066   CXXConstructExprBits.ZeroInitialization = ZeroInitialization;
1067   CXXConstructExprBits.ConstructionKind = ConstructKind;
1068   CXXConstructExprBits.Loc = Loc;
1069 
1070   Stmt **TrailingArgs = getTrailingArgs();
1071   for (unsigned I = 0, N = Args.size(); I != N; ++I) {
1072     assert(Args[I] && "NULL argument in CXXConstructExpr!");
1073     TrailingArgs[I] = Args[I];
1074   }
1075 
1076   setDependence(computeDependence(this));
1077 }
1078 
1079 CXXConstructExpr::CXXConstructExpr(StmtClass SC, EmptyShell Empty,
1080                                    unsigned NumArgs)
1081     : Expr(SC, Empty), NumArgs(NumArgs) {}
1082 
1083 LambdaCapture::LambdaCapture(SourceLocation Loc, bool Implicit,
1084                              LambdaCaptureKind Kind, VarDecl *Var,
1085                              SourceLocation EllipsisLoc)
1086     : DeclAndBits(Var, 0), Loc(Loc), EllipsisLoc(EllipsisLoc) {
1087   unsigned Bits = 0;
1088   if (Implicit)
1089     Bits |= Capture_Implicit;
1090 
1091   switch (Kind) {
1092   case LCK_StarThis:
1093     Bits |= Capture_ByCopy;
1094     LLVM_FALLTHROUGH;
1095   case LCK_This:
1096     assert(!Var && "'this' capture cannot have a variable!");
1097     Bits |= Capture_This;
1098     break;
1099 
1100   case LCK_ByCopy:
1101     Bits |= Capture_ByCopy;
1102     LLVM_FALLTHROUGH;
1103   case LCK_ByRef:
1104     assert(Var && "capture must have a variable!");
1105     break;
1106   case LCK_VLAType:
1107     assert(!Var && "VLA type capture cannot have a variable!");
1108     break;
1109   }
1110   DeclAndBits.setInt(Bits);
1111 }
1112 
1113 LambdaCaptureKind LambdaCapture::getCaptureKind() const {
1114   if (capturesVLAType())
1115     return LCK_VLAType;
1116   bool CapByCopy = DeclAndBits.getInt() & Capture_ByCopy;
1117   if (capturesThis())
1118     return CapByCopy ? LCK_StarThis : LCK_This;
1119   return CapByCopy ? LCK_ByCopy : LCK_ByRef;
1120 }
1121 
1122 LambdaExpr::LambdaExpr(QualType T, SourceRange IntroducerRange,
1123                        LambdaCaptureDefault CaptureDefault,
1124                        SourceLocation CaptureDefaultLoc, bool ExplicitParams,
1125                        bool ExplicitResultType, ArrayRef<Expr *> CaptureInits,
1126                        SourceLocation ClosingBrace,
1127                        bool ContainsUnexpandedParameterPack)
1128     : Expr(LambdaExprClass, T, VK_RValue, OK_Ordinary),
1129       IntroducerRange(IntroducerRange), CaptureDefaultLoc(CaptureDefaultLoc),
1130       ClosingBrace(ClosingBrace) {
1131   LambdaExprBits.NumCaptures = CaptureInits.size();
1132   LambdaExprBits.CaptureDefault = CaptureDefault;
1133   LambdaExprBits.ExplicitParams = ExplicitParams;
1134   LambdaExprBits.ExplicitResultType = ExplicitResultType;
1135 
1136   CXXRecordDecl *Class = getLambdaClass();
1137   (void)Class;
1138   assert(capture_size() == Class->capture_size() && "Wrong number of captures");
1139   assert(getCaptureDefault() == Class->getLambdaCaptureDefault());
1140 
1141   // Copy initialization expressions for the non-static data members.
1142   Stmt **Stored = getStoredStmts();
1143   for (unsigned I = 0, N = CaptureInits.size(); I != N; ++I)
1144     *Stored++ = CaptureInits[I];
1145 
1146   // Copy the body of the lambda.
1147   *Stored++ = getCallOperator()->getBody();
1148 
1149   setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
1150 }
1151 
1152 LambdaExpr::LambdaExpr(EmptyShell Empty, unsigned NumCaptures)
1153     : Expr(LambdaExprClass, Empty) {
1154   LambdaExprBits.NumCaptures = NumCaptures;
1155 
1156   // Initially don't initialize the body of the LambdaExpr. The body will
1157   // be lazily deserialized when needed.
1158   getStoredStmts()[NumCaptures] = nullptr; // Not one past the end.
1159 }
1160 
1161 LambdaExpr *LambdaExpr::Create(const ASTContext &Context, CXXRecordDecl *Class,
1162                                SourceRange IntroducerRange,
1163                                LambdaCaptureDefault CaptureDefault,
1164                                SourceLocation CaptureDefaultLoc,
1165                                bool ExplicitParams, bool ExplicitResultType,
1166                                ArrayRef<Expr *> CaptureInits,
1167                                SourceLocation ClosingBrace,
1168                                bool ContainsUnexpandedParameterPack) {
1169   // Determine the type of the expression (i.e., the type of the
1170   // function object we're creating).
1171   QualType T = Context.getTypeDeclType(Class);
1172 
1173   unsigned Size = totalSizeToAlloc<Stmt *>(CaptureInits.size() + 1);
1174   void *Mem = Context.Allocate(Size);
1175   return new (Mem)
1176       LambdaExpr(T, IntroducerRange, CaptureDefault, CaptureDefaultLoc,
1177                  ExplicitParams, ExplicitResultType, CaptureInits, ClosingBrace,
1178                  ContainsUnexpandedParameterPack);
1179 }
1180 
1181 LambdaExpr *LambdaExpr::CreateDeserialized(const ASTContext &C,
1182                                            unsigned NumCaptures) {
1183   unsigned Size = totalSizeToAlloc<Stmt *>(NumCaptures + 1);
1184   void *Mem = C.Allocate(Size);
1185   return new (Mem) LambdaExpr(EmptyShell(), NumCaptures);
1186 }
1187 
1188 void LambdaExpr::initBodyIfNeeded() const {
1189   if (!getStoredStmts()[capture_size()]) {
1190     auto *This = const_cast<LambdaExpr *>(this);
1191     This->getStoredStmts()[capture_size()] = getCallOperator()->getBody();
1192   }
1193 }
1194 
1195 Stmt *LambdaExpr::getBody() const {
1196   initBodyIfNeeded();
1197   return getStoredStmts()[capture_size()];
1198 }
1199 
1200 const CompoundStmt *LambdaExpr::getCompoundStmtBody() const {
1201   Stmt *Body = getBody();
1202   if (const auto *CoroBody = dyn_cast<CoroutineBodyStmt>(Body))
1203     return cast<CompoundStmt>(CoroBody->getBody());
1204   return cast<CompoundStmt>(Body);
1205 }
1206 
1207 bool LambdaExpr::isInitCapture(const LambdaCapture *C) const {
1208   return (C->capturesVariable() && C->getCapturedVar()->isInitCapture() &&
1209           (getCallOperator() == C->getCapturedVar()->getDeclContext()));
1210 }
1211 
1212 LambdaExpr::capture_iterator LambdaExpr::capture_begin() const {
1213   return getLambdaClass()->getLambdaData().Captures;
1214 }
1215 
1216 LambdaExpr::capture_iterator LambdaExpr::capture_end() const {
1217   return capture_begin() + capture_size();
1218 }
1219 
1220 LambdaExpr::capture_range LambdaExpr::captures() const {
1221   return capture_range(capture_begin(), capture_end());
1222 }
1223 
1224 LambdaExpr::capture_iterator LambdaExpr::explicit_capture_begin() const {
1225   return capture_begin();
1226 }
1227 
1228 LambdaExpr::capture_iterator LambdaExpr::explicit_capture_end() const {
1229   struct CXXRecordDecl::LambdaDefinitionData &Data
1230     = getLambdaClass()->getLambdaData();
1231   return Data.Captures + Data.NumExplicitCaptures;
1232 }
1233 
1234 LambdaExpr::capture_range LambdaExpr::explicit_captures() const {
1235   return capture_range(explicit_capture_begin(), explicit_capture_end());
1236 }
1237 
1238 LambdaExpr::capture_iterator LambdaExpr::implicit_capture_begin() const {
1239   return explicit_capture_end();
1240 }
1241 
1242 LambdaExpr::capture_iterator LambdaExpr::implicit_capture_end() const {
1243   return capture_end();
1244 }
1245 
1246 LambdaExpr::capture_range LambdaExpr::implicit_captures() const {
1247   return capture_range(implicit_capture_begin(), implicit_capture_end());
1248 }
1249 
1250 CXXRecordDecl *LambdaExpr::getLambdaClass() const {
1251   return getType()->getAsCXXRecordDecl();
1252 }
1253 
1254 CXXMethodDecl *LambdaExpr::getCallOperator() const {
1255   CXXRecordDecl *Record = getLambdaClass();
1256   return Record->getLambdaCallOperator();
1257 }
1258 
1259 FunctionTemplateDecl *LambdaExpr::getDependentCallOperator() const {
1260   CXXRecordDecl *Record = getLambdaClass();
1261   return Record->getDependentLambdaCallOperator();
1262 }
1263 
1264 TemplateParameterList *LambdaExpr::getTemplateParameterList() const {
1265   CXXRecordDecl *Record = getLambdaClass();
1266   return Record->getGenericLambdaTemplateParameterList();
1267 }
1268 
1269 ArrayRef<NamedDecl *> LambdaExpr::getExplicitTemplateParameters() const {
1270   const CXXRecordDecl *Record = getLambdaClass();
1271   return Record->getLambdaExplicitTemplateParameters();
1272 }
1273 
1274 Expr *LambdaExpr::getTrailingRequiresClause() const {
1275   return getCallOperator()->getTrailingRequiresClause();
1276 }
1277 
1278 bool LambdaExpr::isMutable() const { return !getCallOperator()->isConst(); }
1279 
1280 LambdaExpr::child_range LambdaExpr::children() {
1281   initBodyIfNeeded();
1282   return child_range(getStoredStmts(), getStoredStmts() + capture_size() + 1);
1283 }
1284 
1285 LambdaExpr::const_child_range LambdaExpr::children() const {
1286   initBodyIfNeeded();
1287   return const_child_range(getStoredStmts(),
1288                            getStoredStmts() + capture_size() + 1);
1289 }
1290 
1291 ExprWithCleanups::ExprWithCleanups(Expr *subexpr,
1292                                    bool CleanupsHaveSideEffects,
1293                                    ArrayRef<CleanupObject> objects)
1294     : FullExpr(ExprWithCleanupsClass, subexpr) {
1295   ExprWithCleanupsBits.CleanupsHaveSideEffects = CleanupsHaveSideEffects;
1296   ExprWithCleanupsBits.NumObjects = objects.size();
1297   for (unsigned i = 0, e = objects.size(); i != e; ++i)
1298     getTrailingObjects<CleanupObject>()[i] = objects[i];
1299 }
1300 
1301 ExprWithCleanups *ExprWithCleanups::Create(const ASTContext &C, Expr *subexpr,
1302                                            bool CleanupsHaveSideEffects,
1303                                            ArrayRef<CleanupObject> objects) {
1304   void *buffer = C.Allocate(totalSizeToAlloc<CleanupObject>(objects.size()),
1305                             alignof(ExprWithCleanups));
1306   return new (buffer)
1307       ExprWithCleanups(subexpr, CleanupsHaveSideEffects, objects);
1308 }
1309 
1310 ExprWithCleanups::ExprWithCleanups(EmptyShell empty, unsigned numObjects)
1311     : FullExpr(ExprWithCleanupsClass, empty) {
1312   ExprWithCleanupsBits.NumObjects = numObjects;
1313 }
1314 
1315 ExprWithCleanups *ExprWithCleanups::Create(const ASTContext &C,
1316                                            EmptyShell empty,
1317                                            unsigned numObjects) {
1318   void *buffer = C.Allocate(totalSizeToAlloc<CleanupObject>(numObjects),
1319                             alignof(ExprWithCleanups));
1320   return new (buffer) ExprWithCleanups(empty, numObjects);
1321 }
1322 
1323 CXXUnresolvedConstructExpr::CXXUnresolvedConstructExpr(QualType T,
1324                                                        TypeSourceInfo *TSI,
1325                                                        SourceLocation LParenLoc,
1326                                                        ArrayRef<Expr *> Args,
1327                                                        SourceLocation RParenLoc)
1328     : Expr(CXXUnresolvedConstructExprClass, T,
1329            (TSI->getType()->isLValueReferenceType()
1330                 ? VK_LValue
1331                 : TSI->getType()->isRValueReferenceType() ? VK_XValue
1332                                                           : VK_RValue),
1333            OK_Ordinary),
1334       TSI(TSI), LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
1335   CXXUnresolvedConstructExprBits.NumArgs = Args.size();
1336   auto **StoredArgs = getTrailingObjects<Expr *>();
1337   for (unsigned I = 0; I != Args.size(); ++I)
1338     StoredArgs[I] = Args[I];
1339   setDependence(computeDependence(this));
1340 }
1341 
1342 CXXUnresolvedConstructExpr *CXXUnresolvedConstructExpr::Create(
1343     const ASTContext &Context, QualType T, TypeSourceInfo *TSI, SourceLocation LParenLoc,
1344     ArrayRef<Expr *> Args, SourceLocation RParenLoc) {
1345   void *Mem = Context.Allocate(totalSizeToAlloc<Expr *>(Args.size()));
1346   return new (Mem)
1347       CXXUnresolvedConstructExpr(T, TSI, LParenLoc, Args, RParenLoc);
1348 }
1349 
1350 CXXUnresolvedConstructExpr *
1351 CXXUnresolvedConstructExpr::CreateEmpty(const ASTContext &Context,
1352                                         unsigned NumArgs) {
1353   void *Mem = Context.Allocate(totalSizeToAlloc<Expr *>(NumArgs));
1354   return new (Mem) CXXUnresolvedConstructExpr(EmptyShell(), NumArgs);
1355 }
1356 
1357 SourceLocation CXXUnresolvedConstructExpr::getBeginLoc() const {
1358   return TSI->getTypeLoc().getBeginLoc();
1359 }
1360 
1361 CXXDependentScopeMemberExpr::CXXDependentScopeMemberExpr(
1362     const ASTContext &Ctx, Expr *Base, QualType BaseType, bool IsArrow,
1363     SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc,
1364     SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope,
1365     DeclarationNameInfo MemberNameInfo,
1366     const TemplateArgumentListInfo *TemplateArgs)
1367     : Expr(CXXDependentScopeMemberExprClass, Ctx.DependentTy, VK_LValue,
1368            OK_Ordinary),
1369       Base(Base), BaseType(BaseType), QualifierLoc(QualifierLoc),
1370       MemberNameInfo(MemberNameInfo) {
1371   CXXDependentScopeMemberExprBits.IsArrow = IsArrow;
1372   CXXDependentScopeMemberExprBits.HasTemplateKWAndArgsInfo =
1373       (TemplateArgs != nullptr) || TemplateKWLoc.isValid();
1374   CXXDependentScopeMemberExprBits.HasFirstQualifierFoundInScope =
1375       FirstQualifierFoundInScope != nullptr;
1376   CXXDependentScopeMemberExprBits.OperatorLoc = OperatorLoc;
1377 
1378   if (TemplateArgs) {
1379     auto Deps = TemplateArgumentDependence::None;
1380     getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1381         TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(),
1382         Deps);
1383   } else if (TemplateKWLoc.isValid()) {
1384     getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1385         TemplateKWLoc);
1386   }
1387 
1388   if (hasFirstQualifierFoundInScope())
1389     *getTrailingObjects<NamedDecl *>() = FirstQualifierFoundInScope;
1390   setDependence(computeDependence(this));
1391 }
1392 
1393 CXXDependentScopeMemberExpr::CXXDependentScopeMemberExpr(
1394     EmptyShell Empty, bool HasTemplateKWAndArgsInfo,
1395     bool HasFirstQualifierFoundInScope)
1396     : Expr(CXXDependentScopeMemberExprClass, Empty) {
1397   CXXDependentScopeMemberExprBits.HasTemplateKWAndArgsInfo =
1398       HasTemplateKWAndArgsInfo;
1399   CXXDependentScopeMemberExprBits.HasFirstQualifierFoundInScope =
1400       HasFirstQualifierFoundInScope;
1401 }
1402 
1403 CXXDependentScopeMemberExpr *CXXDependentScopeMemberExpr::Create(
1404     const ASTContext &Ctx, Expr *Base, QualType BaseType, bool IsArrow,
1405     SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc,
1406     SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope,
1407     DeclarationNameInfo MemberNameInfo,
1408     const TemplateArgumentListInfo *TemplateArgs) {
1409   bool HasTemplateKWAndArgsInfo =
1410       (TemplateArgs != nullptr) || TemplateKWLoc.isValid();
1411   unsigned NumTemplateArgs = TemplateArgs ? TemplateArgs->size() : 0;
1412   bool HasFirstQualifierFoundInScope = FirstQualifierFoundInScope != nullptr;
1413 
1414   unsigned Size = totalSizeToAlloc<ASTTemplateKWAndArgsInfo,
1415                                    TemplateArgumentLoc, NamedDecl *>(
1416       HasTemplateKWAndArgsInfo, NumTemplateArgs, HasFirstQualifierFoundInScope);
1417 
1418   void *Mem = Ctx.Allocate(Size, alignof(CXXDependentScopeMemberExpr));
1419   return new (Mem) CXXDependentScopeMemberExpr(
1420       Ctx, Base, BaseType, IsArrow, OperatorLoc, QualifierLoc, TemplateKWLoc,
1421       FirstQualifierFoundInScope, MemberNameInfo, TemplateArgs);
1422 }
1423 
1424 CXXDependentScopeMemberExpr *CXXDependentScopeMemberExpr::CreateEmpty(
1425     const ASTContext &Ctx, bool HasTemplateKWAndArgsInfo,
1426     unsigned NumTemplateArgs, bool HasFirstQualifierFoundInScope) {
1427   assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);
1428 
1429   unsigned Size = totalSizeToAlloc<ASTTemplateKWAndArgsInfo,
1430                                    TemplateArgumentLoc, NamedDecl *>(
1431       HasTemplateKWAndArgsInfo, NumTemplateArgs, HasFirstQualifierFoundInScope);
1432 
1433   void *Mem = Ctx.Allocate(Size, alignof(CXXDependentScopeMemberExpr));
1434   return new (Mem) CXXDependentScopeMemberExpr(
1435       EmptyShell(), HasTemplateKWAndArgsInfo, HasFirstQualifierFoundInScope);
1436 }
1437 
1438 static bool hasOnlyNonStaticMemberFunctions(UnresolvedSetIterator begin,
1439                                             UnresolvedSetIterator end) {
1440   do {
1441     NamedDecl *decl = *begin;
1442     if (isa<UnresolvedUsingValueDecl>(decl))
1443       return false;
1444 
1445     // Unresolved member expressions should only contain methods and
1446     // method templates.
1447     if (cast<CXXMethodDecl>(decl->getUnderlyingDecl()->getAsFunction())
1448             ->isStatic())
1449       return false;
1450   } while (++begin != end);
1451 
1452   return true;
1453 }
1454 
1455 UnresolvedMemberExpr::UnresolvedMemberExpr(
1456     const ASTContext &Context, bool HasUnresolvedUsing, Expr *Base,
1457     QualType BaseType, bool IsArrow, SourceLocation OperatorLoc,
1458     NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
1459     const DeclarationNameInfo &MemberNameInfo,
1460     const TemplateArgumentListInfo *TemplateArgs, UnresolvedSetIterator Begin,
1461     UnresolvedSetIterator End)
1462     : OverloadExpr(
1463           UnresolvedMemberExprClass, Context, QualifierLoc, TemplateKWLoc,
1464           MemberNameInfo, TemplateArgs, Begin, End,
1465           // Dependent
1466           ((Base && Base->isTypeDependent()) || BaseType->isDependentType()),
1467           ((Base && Base->isInstantiationDependent()) ||
1468            BaseType->isInstantiationDependentType()),
1469           // Contains unexpanded parameter pack
1470           ((Base && Base->containsUnexpandedParameterPack()) ||
1471            BaseType->containsUnexpandedParameterPack())),
1472       Base(Base), BaseType(BaseType), OperatorLoc(OperatorLoc) {
1473   UnresolvedMemberExprBits.IsArrow = IsArrow;
1474   UnresolvedMemberExprBits.HasUnresolvedUsing = HasUnresolvedUsing;
1475 
1476   // Check whether all of the members are non-static member functions,
1477   // and if so, mark give this bound-member type instead of overload type.
1478   if (hasOnlyNonStaticMemberFunctions(Begin, End))
1479     setType(Context.BoundMemberTy);
1480 }
1481 
1482 UnresolvedMemberExpr::UnresolvedMemberExpr(EmptyShell Empty,
1483                                            unsigned NumResults,
1484                                            bool HasTemplateKWAndArgsInfo)
1485     : OverloadExpr(UnresolvedMemberExprClass, Empty, NumResults,
1486                    HasTemplateKWAndArgsInfo) {}
1487 
1488 bool UnresolvedMemberExpr::isImplicitAccess() const {
1489   if (!Base)
1490     return true;
1491 
1492   return cast<Expr>(Base)->isImplicitCXXThis();
1493 }
1494 
1495 UnresolvedMemberExpr *UnresolvedMemberExpr::Create(
1496     const ASTContext &Context, bool HasUnresolvedUsing, Expr *Base,
1497     QualType BaseType, bool IsArrow, SourceLocation OperatorLoc,
1498     NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
1499     const DeclarationNameInfo &MemberNameInfo,
1500     const TemplateArgumentListInfo *TemplateArgs, UnresolvedSetIterator Begin,
1501     UnresolvedSetIterator End) {
1502   unsigned NumResults = End - Begin;
1503   bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
1504   unsigned NumTemplateArgs = TemplateArgs ? TemplateArgs->size() : 0;
1505   unsigned Size = totalSizeToAlloc<DeclAccessPair, ASTTemplateKWAndArgsInfo,
1506                                    TemplateArgumentLoc>(
1507       NumResults, HasTemplateKWAndArgsInfo, NumTemplateArgs);
1508   void *Mem = Context.Allocate(Size, alignof(UnresolvedMemberExpr));
1509   return new (Mem) UnresolvedMemberExpr(
1510       Context, HasUnresolvedUsing, Base, BaseType, IsArrow, OperatorLoc,
1511       QualifierLoc, TemplateKWLoc, MemberNameInfo, TemplateArgs, Begin, End);
1512 }
1513 
1514 UnresolvedMemberExpr *UnresolvedMemberExpr::CreateEmpty(
1515     const ASTContext &Context, unsigned NumResults,
1516     bool HasTemplateKWAndArgsInfo, unsigned NumTemplateArgs) {
1517   assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);
1518   unsigned Size = totalSizeToAlloc<DeclAccessPair, ASTTemplateKWAndArgsInfo,
1519                                    TemplateArgumentLoc>(
1520       NumResults, HasTemplateKWAndArgsInfo, NumTemplateArgs);
1521   void *Mem = Context.Allocate(Size, alignof(UnresolvedMemberExpr));
1522   return new (Mem)
1523       UnresolvedMemberExpr(EmptyShell(), NumResults, HasTemplateKWAndArgsInfo);
1524 }
1525 
1526 CXXRecordDecl *UnresolvedMemberExpr::getNamingClass() {
1527   // Unlike for UnresolvedLookupExpr, it is very easy to re-derive this.
1528 
1529   // If there was a nested name specifier, it names the naming class.
1530   // It can't be dependent: after all, we were actually able to do the
1531   // lookup.
1532   CXXRecordDecl *Record = nullptr;
1533   auto *NNS = getQualifier();
1534   if (NNS && NNS->getKind() != NestedNameSpecifier::Super) {
1535     const Type *T = getQualifier()->getAsType();
1536     assert(T && "qualifier in member expression does not name type");
1537     Record = T->getAsCXXRecordDecl();
1538     assert(Record && "qualifier in member expression does not name record");
1539   }
1540   // Otherwise the naming class must have been the base class.
1541   else {
1542     QualType BaseType = getBaseType().getNonReferenceType();
1543     if (isArrow())
1544       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
1545 
1546     Record = BaseType->getAsCXXRecordDecl();
1547     assert(Record && "base of member expression does not name record");
1548   }
1549 
1550   return Record;
1551 }
1552 
1553 SizeOfPackExpr *
1554 SizeOfPackExpr::Create(ASTContext &Context, SourceLocation OperatorLoc,
1555                        NamedDecl *Pack, SourceLocation PackLoc,
1556                        SourceLocation RParenLoc,
1557                        Optional<unsigned> Length,
1558                        ArrayRef<TemplateArgument> PartialArgs) {
1559   void *Storage =
1560       Context.Allocate(totalSizeToAlloc<TemplateArgument>(PartialArgs.size()));
1561   return new (Storage) SizeOfPackExpr(Context.getSizeType(), OperatorLoc, Pack,
1562                                       PackLoc, RParenLoc, Length, PartialArgs);
1563 }
1564 
1565 SizeOfPackExpr *SizeOfPackExpr::CreateDeserialized(ASTContext &Context,
1566                                                    unsigned NumPartialArgs) {
1567   void *Storage =
1568       Context.Allocate(totalSizeToAlloc<TemplateArgument>(NumPartialArgs));
1569   return new (Storage) SizeOfPackExpr(EmptyShell(), NumPartialArgs);
1570 }
1571 
1572 QualType SubstNonTypeTemplateParmExpr::getParameterType(
1573     const ASTContext &Context) const {
1574   // Note that, for a class type NTTP, we will have an lvalue of type 'const
1575   // T', so we can't just compute this from the type and value category.
1576   if (isReferenceParameter())
1577     return Context.getLValueReferenceType(getType());
1578   return getType().getUnqualifiedType();
1579 }
1580 
1581 SubstNonTypeTemplateParmPackExpr::SubstNonTypeTemplateParmPackExpr(
1582     QualType T, ExprValueKind ValueKind, NonTypeTemplateParmDecl *Param,
1583     SourceLocation NameLoc, const TemplateArgument &ArgPack)
1584     : Expr(SubstNonTypeTemplateParmPackExprClass, T, ValueKind, OK_Ordinary),
1585       Param(Param), Arguments(ArgPack.pack_begin()),
1586       NumArguments(ArgPack.pack_size()), NameLoc(NameLoc) {
1587   setDependence(ExprDependence::TypeValueInstantiation |
1588                 ExprDependence::UnexpandedPack);
1589 }
1590 
1591 TemplateArgument SubstNonTypeTemplateParmPackExpr::getArgumentPack() const {
1592   return TemplateArgument(llvm::makeArrayRef(Arguments, NumArguments));
1593 }
1594 
1595 FunctionParmPackExpr::FunctionParmPackExpr(QualType T, VarDecl *ParamPack,
1596                                            SourceLocation NameLoc,
1597                                            unsigned NumParams,
1598                                            VarDecl *const *Params)
1599     : Expr(FunctionParmPackExprClass, T, VK_LValue, OK_Ordinary),
1600       ParamPack(ParamPack), NameLoc(NameLoc), NumParameters(NumParams) {
1601   if (Params)
1602     std::uninitialized_copy(Params, Params + NumParams,
1603                             getTrailingObjects<VarDecl *>());
1604   setDependence(ExprDependence::TypeValueInstantiation |
1605                 ExprDependence::UnexpandedPack);
1606 }
1607 
1608 FunctionParmPackExpr *
1609 FunctionParmPackExpr::Create(const ASTContext &Context, QualType T,
1610                              VarDecl *ParamPack, SourceLocation NameLoc,
1611                              ArrayRef<VarDecl *> Params) {
1612   return new (Context.Allocate(totalSizeToAlloc<VarDecl *>(Params.size())))
1613       FunctionParmPackExpr(T, ParamPack, NameLoc, Params.size(), Params.data());
1614 }
1615 
1616 FunctionParmPackExpr *
1617 FunctionParmPackExpr::CreateEmpty(const ASTContext &Context,
1618                                   unsigned NumParams) {
1619   return new (Context.Allocate(totalSizeToAlloc<VarDecl *>(NumParams)))
1620       FunctionParmPackExpr(QualType(), nullptr, SourceLocation(), 0, nullptr);
1621 }
1622 
1623 MaterializeTemporaryExpr::MaterializeTemporaryExpr(
1624     QualType T, Expr *Temporary, bool BoundToLvalueReference,
1625     LifetimeExtendedTemporaryDecl *MTD)
1626     : Expr(MaterializeTemporaryExprClass, T,
1627            BoundToLvalueReference ? VK_LValue : VK_XValue, OK_Ordinary) {
1628   if (MTD) {
1629     State = MTD;
1630     MTD->ExprWithTemporary = Temporary;
1631     return;
1632   }
1633   State = Temporary;
1634   setDependence(computeDependence(this));
1635 }
1636 
1637 void MaterializeTemporaryExpr::setExtendingDecl(ValueDecl *ExtendedBy,
1638                                                 unsigned ManglingNumber) {
1639   // We only need extra state if we have to remember more than just the Stmt.
1640   if (!ExtendedBy)
1641     return;
1642 
1643   // We may need to allocate extra storage for the mangling number and the
1644   // extended-by ValueDecl.
1645   if (!State.is<LifetimeExtendedTemporaryDecl *>())
1646     State = LifetimeExtendedTemporaryDecl::Create(
1647         cast<Expr>(State.get<Stmt *>()), ExtendedBy, ManglingNumber);
1648 
1649   auto ES = State.get<LifetimeExtendedTemporaryDecl *>();
1650   ES->ExtendingDecl = ExtendedBy;
1651   ES->ManglingNumber = ManglingNumber;
1652 }
1653 
1654 bool MaterializeTemporaryExpr::isUsableInConstantExpressions(
1655     const ASTContext &Context) const {
1656   // C++20 [expr.const]p4:
1657   //   An object or reference is usable in constant expressions if it is [...]
1658   //   a temporary object of non-volatile const-qualified literal type
1659   //   whose lifetime is extended to that of a variable that is usable
1660   //   in constant expressions
1661   auto *VD = dyn_cast_or_null<VarDecl>(getExtendingDecl());
1662   return VD && getType().isConstant(Context) &&
1663          !getType().isVolatileQualified() &&
1664          getType()->isLiteralType(Context) &&
1665          VD->isUsableInConstantExpressions(Context);
1666 }
1667 
1668 TypeTraitExpr::TypeTraitExpr(QualType T, SourceLocation Loc, TypeTrait Kind,
1669                              ArrayRef<TypeSourceInfo *> Args,
1670                              SourceLocation RParenLoc, bool Value)
1671     : Expr(TypeTraitExprClass, T, VK_RValue, OK_Ordinary), Loc(Loc),
1672       RParenLoc(RParenLoc) {
1673   assert(Kind <= TT_Last && "invalid enum value!");
1674   TypeTraitExprBits.Kind = Kind;
1675   assert(static_cast<unsigned>(Kind) == TypeTraitExprBits.Kind &&
1676          "TypeTraitExprBits.Kind overflow!");
1677   TypeTraitExprBits.Value = Value;
1678   TypeTraitExprBits.NumArgs = Args.size();
1679   assert(Args.size() == TypeTraitExprBits.NumArgs &&
1680          "TypeTraitExprBits.NumArgs overflow!");
1681 
1682   auto **ToArgs = getTrailingObjects<TypeSourceInfo *>();
1683   for (unsigned I = 0, N = Args.size(); I != N; ++I)
1684     ToArgs[I] = Args[I];
1685 
1686   setDependence(computeDependence(this));
1687 }
1688 
1689 TypeTraitExpr *TypeTraitExpr::Create(const ASTContext &C, QualType T,
1690                                      SourceLocation Loc,
1691                                      TypeTrait Kind,
1692                                      ArrayRef<TypeSourceInfo *> Args,
1693                                      SourceLocation RParenLoc,
1694                                      bool Value) {
1695   void *Mem = C.Allocate(totalSizeToAlloc<TypeSourceInfo *>(Args.size()));
1696   return new (Mem) TypeTraitExpr(T, Loc, Kind, Args, RParenLoc, Value);
1697 }
1698 
1699 TypeTraitExpr *TypeTraitExpr::CreateDeserialized(const ASTContext &C,
1700                                                  unsigned NumArgs) {
1701   void *Mem = C.Allocate(totalSizeToAlloc<TypeSourceInfo *>(NumArgs));
1702   return new (Mem) TypeTraitExpr(EmptyShell());
1703 }
1704 
1705 CUDAKernelCallExpr::CUDAKernelCallExpr(Expr *Fn, CallExpr *Config,
1706                                        ArrayRef<Expr *> Args, QualType Ty,
1707                                        ExprValueKind VK, SourceLocation RP,
1708                                        FPOptionsOverride FPFeatures,
1709                                        unsigned MinNumArgs)
1710     : CallExpr(CUDAKernelCallExprClass, Fn, /*PreArgs=*/Config, Args, Ty, VK,
1711                RP, FPFeatures, MinNumArgs, NotADL) {}
1712 
1713 CUDAKernelCallExpr::CUDAKernelCallExpr(unsigned NumArgs, bool HasFPFeatures,
1714                                        EmptyShell Empty)
1715     : CallExpr(CUDAKernelCallExprClass, /*NumPreArgs=*/END_PREARG, NumArgs,
1716                HasFPFeatures, Empty) {}
1717 
1718 CUDAKernelCallExpr *
1719 CUDAKernelCallExpr::Create(const ASTContext &Ctx, Expr *Fn, CallExpr *Config,
1720                            ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
1721                            SourceLocation RP, FPOptionsOverride FPFeatures,
1722                            unsigned MinNumArgs) {
1723   // Allocate storage for the trailing objects of CallExpr.
1724   unsigned NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1725   unsigned SizeOfTrailingObjects = CallExpr::sizeOfTrailingObjects(
1726       /*NumPreArgs=*/END_PREARG, NumArgs, FPFeatures.requiresTrailingStorage());
1727   void *Mem = Ctx.Allocate(sizeof(CUDAKernelCallExpr) + SizeOfTrailingObjects,
1728                            alignof(CUDAKernelCallExpr));
1729   return new (Mem)
1730       CUDAKernelCallExpr(Fn, Config, Args, Ty, VK, RP, FPFeatures, MinNumArgs);
1731 }
1732 
1733 CUDAKernelCallExpr *CUDAKernelCallExpr::CreateEmpty(const ASTContext &Ctx,
1734                                                     unsigned NumArgs,
1735                                                     bool HasFPFeatures,
1736                                                     EmptyShell Empty) {
1737   // Allocate storage for the trailing objects of CallExpr.
1738   unsigned SizeOfTrailingObjects = CallExpr::sizeOfTrailingObjects(
1739       /*NumPreArgs=*/END_PREARG, NumArgs, HasFPFeatures);
1740   void *Mem = Ctx.Allocate(sizeof(CUDAKernelCallExpr) + SizeOfTrailingObjects,
1741                            alignof(CUDAKernelCallExpr));
1742   return new (Mem) CUDAKernelCallExpr(NumArgs, HasFPFeatures, Empty);
1743 }
1744