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