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