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