Bug Summary

File:clang/lib/CodeGen/CGExprCXX.cpp
Warning:line 1175, column 34
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CGExprCXX.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/CodeGen -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/llvm/include -D NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/CodeGen -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-09-04-040900-46481-1 -x c++ /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/lib/CodeGen/CGExprCXX.cpp

/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/lib/CodeGen/CGExprCXX.cpp

1//===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
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 contains code dealing with code generation of C++ expressions
10//
11//===----------------------------------------------------------------------===//
12
13#include "CGCUDARuntime.h"
14#include "CGCXXABI.h"
15#include "CGDebugInfo.h"
16#include "CGObjCRuntime.h"
17#include "CodeGenFunction.h"
18#include "ConstantEmitter.h"
19#include "TargetInfo.h"
20#include "clang/Basic/CodeGenOptions.h"
21#include "clang/CodeGen/CGFunctionInfo.h"
22#include "llvm/IR/Intrinsics.h"
23
24using namespace clang;
25using namespace CodeGen;
26
27namespace {
28struct MemberCallInfo {
29 RequiredArgs ReqArgs;
30 // Number of prefix arguments for the call. Ignores the `this` pointer.
31 unsigned PrefixSize;
32};
33}
34
35static MemberCallInfo
36commonEmitCXXMemberOrOperatorCall(CodeGenFunction &CGF, const CXXMethodDecl *MD,
37 llvm::Value *This, llvm::Value *ImplicitParam,
38 QualType ImplicitParamTy, const CallExpr *CE,
39 CallArgList &Args, CallArgList *RtlArgs) {
40 assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) ||(static_cast<void> (0))
41 isa<CXXOperatorCallExpr>(CE))(static_cast<void> (0));
42 assert(MD->isInstance() &&(static_cast<void> (0))
43 "Trying to emit a member or operator call expr on a static method!")(static_cast<void> (0));
44
45 // Push the this ptr.
46 const CXXRecordDecl *RD =
47 CGF.CGM.getCXXABI().getThisArgumentTypeForMethod(MD);
48 Args.add(RValue::get(This), CGF.getTypes().DeriveThisType(RD, MD));
49
50 // If there is an implicit parameter (e.g. VTT), emit it.
51 if (ImplicitParam) {
52 Args.add(RValue::get(ImplicitParam), ImplicitParamTy);
53 }
54
55 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
56 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size());
57 unsigned PrefixSize = Args.size() - 1;
58
59 // And the rest of the call args.
60 if (RtlArgs) {
61 // Special case: if the caller emitted the arguments right-to-left already
62 // (prior to emitting the *this argument), we're done. This happens for
63 // assignment operators.
64 Args.addFrom(*RtlArgs);
65 } else if (CE) {
66 // Special case: skip first argument of CXXOperatorCall (it is "this").
67 unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0;
68 CGF.EmitCallArgs(Args, FPT, drop_begin(CE->arguments(), ArgsToSkip),
69 CE->getDirectCallee());
70 } else {
71 assert((static_cast<void> (0))
72 FPT->getNumParams() == 0 &&(static_cast<void> (0))
73 "No CallExpr specified for function with non-zero number of arguments")(static_cast<void> (0));
74 }
75 return {required, PrefixSize};
76}
77
78RValue CodeGenFunction::EmitCXXMemberOrOperatorCall(
79 const CXXMethodDecl *MD, const CGCallee &Callee,
80 ReturnValueSlot ReturnValue,
81 llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,
82 const CallExpr *CE, CallArgList *RtlArgs) {
83 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
84 CallArgList Args;
85 MemberCallInfo CallInfo = commonEmitCXXMemberOrOperatorCall(
86 *this, MD, This, ImplicitParam, ImplicitParamTy, CE, Args, RtlArgs);
87 auto &FnInfo = CGM.getTypes().arrangeCXXMethodCall(
88 Args, FPT, CallInfo.ReqArgs, CallInfo.PrefixSize);
89 return EmitCall(FnInfo, Callee, ReturnValue, Args, nullptr,
90 CE && CE == MustTailCall,
91 CE ? CE->getExprLoc() : SourceLocation());
92}
93
94RValue CodeGenFunction::EmitCXXDestructorCall(
95 GlobalDecl Dtor, const CGCallee &Callee, llvm::Value *This, QualType ThisTy,
96 llvm::Value *ImplicitParam, QualType ImplicitParamTy, const CallExpr *CE) {
97 const CXXMethodDecl *DtorDecl = cast<CXXMethodDecl>(Dtor.getDecl());
98
99 assert(!ThisTy.isNull())(static_cast<void> (0));
100 assert(ThisTy->getAsCXXRecordDecl() == DtorDecl->getParent() &&(static_cast<void> (0))
101 "Pointer/Object mixup")(static_cast<void> (0));
102
103 LangAS SrcAS = ThisTy.getAddressSpace();
104 LangAS DstAS = DtorDecl->getMethodQualifiers().getAddressSpace();
105 if (SrcAS != DstAS) {
106 QualType DstTy = DtorDecl->getThisType();
107 llvm::Type *NewType = CGM.getTypes().ConvertType(DstTy);
108 This = getTargetHooks().performAddrSpaceCast(*this, This, SrcAS, DstAS,
109 NewType);
110 }
111
112 CallArgList Args;
113 commonEmitCXXMemberOrOperatorCall(*this, DtorDecl, This, ImplicitParam,
114 ImplicitParamTy, CE, Args, nullptr);
115 return EmitCall(CGM.getTypes().arrangeCXXStructorDeclaration(Dtor), Callee,
116 ReturnValueSlot(), Args, nullptr, CE && CE == MustTailCall,
117 CE ? CE->getExprLoc() : SourceLocation{});
118}
119
120RValue CodeGenFunction::EmitCXXPseudoDestructorExpr(
121 const CXXPseudoDestructorExpr *E) {
122 QualType DestroyedType = E->getDestroyedType();
123 if (DestroyedType.hasStrongOrWeakObjCLifetime()) {
124 // Automatic Reference Counting:
125 // If the pseudo-expression names a retainable object with weak or
126 // strong lifetime, the object shall be released.
127 Expr *BaseExpr = E->getBase();
128 Address BaseValue = Address::invalid();
129 Qualifiers BaseQuals;
130
131 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
132 if (E->isArrow()) {
133 BaseValue = EmitPointerWithAlignment(BaseExpr);
134 const auto *PTy = BaseExpr->getType()->castAs<PointerType>();
135 BaseQuals = PTy->getPointeeType().getQualifiers();
136 } else {
137 LValue BaseLV = EmitLValue(BaseExpr);
138 BaseValue = BaseLV.getAddress(*this);
139 QualType BaseTy = BaseExpr->getType();
140 BaseQuals = BaseTy.getQualifiers();
141 }
142
143 switch (DestroyedType.getObjCLifetime()) {
144 case Qualifiers::OCL_None:
145 case Qualifiers::OCL_ExplicitNone:
146 case Qualifiers::OCL_Autoreleasing:
147 break;
148
149 case Qualifiers::OCL_Strong:
150 EmitARCRelease(Builder.CreateLoad(BaseValue,
151 DestroyedType.isVolatileQualified()),
152 ARCPreciseLifetime);
153 break;
154
155 case Qualifiers::OCL_Weak:
156 EmitARCDestroyWeak(BaseValue);
157 break;
158 }
159 } else {
160 // C++ [expr.pseudo]p1:
161 // The result shall only be used as the operand for the function call
162 // operator (), and the result of such a call has type void. The only
163 // effect is the evaluation of the postfix-expression before the dot or
164 // arrow.
165 EmitIgnoredExpr(E->getBase());
166 }
167
168 return RValue::get(nullptr);
169}
170
171static CXXRecordDecl *getCXXRecord(const Expr *E) {
172 QualType T = E->getType();
173 if (const PointerType *PTy = T->getAs<PointerType>())
174 T = PTy->getPointeeType();
175 const RecordType *Ty = T->castAs<RecordType>();
176 return cast<CXXRecordDecl>(Ty->getDecl());
177}
178
179// Note: This function also emit constructor calls to support a MSVC
180// extensions allowing explicit constructor function call.
181RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
182 ReturnValueSlot ReturnValue) {
183 const Expr *callee = CE->getCallee()->IgnoreParens();
184
185 if (isa<BinaryOperator>(callee))
186 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
187
188 const MemberExpr *ME = cast<MemberExpr>(callee);
189 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
190
191 if (MD->isStatic()) {
192 // The method is static, emit it as we would a regular call.
193 CGCallee callee =
194 CGCallee::forDirect(CGM.GetAddrOfFunction(MD), GlobalDecl(MD));
195 return EmitCall(getContext().getPointerType(MD->getType()), callee, CE,
196 ReturnValue);
197 }
198
199 bool HasQualifier = ME->hasQualifier();
200 NestedNameSpecifier *Qualifier = HasQualifier ? ME->getQualifier() : nullptr;
201 bool IsArrow = ME->isArrow();
202 const Expr *Base = ME->getBase();
203
204 return EmitCXXMemberOrOperatorMemberCallExpr(
205 CE, MD, ReturnValue, HasQualifier, Qualifier, IsArrow, Base);
206}
207
208RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr(
209 const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue,
210 bool HasQualifier, NestedNameSpecifier *Qualifier, bool IsArrow,
211 const Expr *Base) {
212 assert(isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE))(static_cast<void> (0));
213
214 // Compute the object pointer.
215 bool CanUseVirtualCall = MD->isVirtual() && !HasQualifier;
216
217 const CXXMethodDecl *DevirtualizedMethod = nullptr;
218 if (CanUseVirtualCall &&
219 MD->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) {
220 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
221 DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
222 assert(DevirtualizedMethod)(static_cast<void> (0));
223 const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
224 const Expr *Inner = Base->IgnoreParenBaseCasts();
225 if (DevirtualizedMethod->getReturnType().getCanonicalType() !=
226 MD->getReturnType().getCanonicalType())
227 // If the return types are not the same, this might be a case where more
228 // code needs to run to compensate for it. For example, the derived
229 // method might return a type that inherits form from the return
230 // type of MD and has a prefix.
231 // For now we just avoid devirtualizing these covariant cases.
232 DevirtualizedMethod = nullptr;
233 else if (getCXXRecord(Inner) == DevirtualizedClass)
234 // If the class of the Inner expression is where the dynamic method
235 // is defined, build the this pointer from it.
236 Base = Inner;
237 else if (getCXXRecord(Base) != DevirtualizedClass) {
238 // If the method is defined in a class that is not the best dynamic
239 // one or the one of the full expression, we would have to build
240 // a derived-to-base cast to compute the correct this pointer, but
241 // we don't have support for that yet, so do a virtual call.
242 DevirtualizedMethod = nullptr;
243 }
244 }
245
246 bool TrivialForCodegen =
247 MD->isTrivial() || (MD->isDefaulted() && MD->getParent()->isUnion());
248 bool TrivialAssignment =
249 TrivialForCodegen &&
250 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
251 !MD->getParent()->mayInsertExtraPadding();
252
253 // C++17 demands that we evaluate the RHS of a (possibly-compound) assignment
254 // operator before the LHS.
255 CallArgList RtlArgStorage;
256 CallArgList *RtlArgs = nullptr;
257 LValue TrivialAssignmentRHS;
258 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
259 if (OCE->isAssignmentOp()) {
260 if (TrivialAssignment) {
261 TrivialAssignmentRHS = EmitLValue(CE->getArg(1));
262 } else {
263 RtlArgs = &RtlArgStorage;
264 EmitCallArgs(*RtlArgs, MD->getType()->castAs<FunctionProtoType>(),
265 drop_begin(CE->arguments(), 1), CE->getDirectCallee(),
266 /*ParamsToSkip*/0, EvaluationOrder::ForceRightToLeft);
267 }
268 }
269 }
270
271 LValue This;
272 if (IsArrow) {
273 LValueBaseInfo BaseInfo;
274 TBAAAccessInfo TBAAInfo;
275 Address ThisValue = EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo);
276 This = MakeAddrLValue(ThisValue, Base->getType(), BaseInfo, TBAAInfo);
277 } else {
278 This = EmitLValue(Base);
279 }
280
281 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
282 // This is the MSVC p->Ctor::Ctor(...) extension. We assume that's
283 // constructing a new complete object of type Ctor.
284 assert(!RtlArgs)(static_cast<void> (0));
285 assert(ReturnValue.isNull() && "Constructor shouldn't have return value")(static_cast<void> (0));
286 CallArgList Args;
287 commonEmitCXXMemberOrOperatorCall(
288 *this, Ctor, This.getPointer(*this), /*ImplicitParam=*/nullptr,
289 /*ImplicitParamTy=*/QualType(), CE, Args, nullptr);
290
291 EmitCXXConstructorCall(Ctor, Ctor_Complete, /*ForVirtualBase=*/false,
292 /*Delegating=*/false, This.getAddress(*this), Args,
293 AggValueSlot::DoesNotOverlap, CE->getExprLoc(),
294 /*NewPointerIsChecked=*/false);
295 return RValue::get(nullptr);
296 }
297
298 if (TrivialForCodegen) {
299 if (isa<CXXDestructorDecl>(MD))
300 return RValue::get(nullptr);
301
302 if (TrivialAssignment) {
303 // We don't like to generate the trivial copy/move assignment operator
304 // when it isn't necessary; just produce the proper effect here.
305 // It's important that we use the result of EmitLValue here rather than
306 // emitting call arguments, in order to preserve TBAA information from
307 // the RHS.
308 LValue RHS = isa<CXXOperatorCallExpr>(CE)
309 ? TrivialAssignmentRHS
310 : EmitLValue(*CE->arg_begin());
311 EmitAggregateAssign(This, RHS, CE->getType());
312 return RValue::get(This.getPointer(*this));
313 }
314
315 assert(MD->getParent()->mayInsertExtraPadding() &&(static_cast<void> (0))
316 "unknown trivial member function")(static_cast<void> (0));
317 }
318
319 // Compute the function type we're calling.
320 const CXXMethodDecl *CalleeDecl =
321 DevirtualizedMethod ? DevirtualizedMethod : MD;
322 const CGFunctionInfo *FInfo = nullptr;
323 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
324 FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
325 GlobalDecl(Dtor, Dtor_Complete));
326 else
327 FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
328
329 llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
330
331 // C++11 [class.mfct.non-static]p2:
332 // If a non-static member function of a class X is called for an object that
333 // is not of type X, or of a type derived from X, the behavior is undefined.
334 SourceLocation CallLoc;
335 ASTContext &C = getContext();
336 if (CE)
337 CallLoc = CE->getExprLoc();
338
339 SanitizerSet SkippedChecks;
340 if (const auto *CMCE = dyn_cast<CXXMemberCallExpr>(CE)) {
341 auto *IOA = CMCE->getImplicitObjectArgument();
342 bool IsImplicitObjectCXXThis = IsWrappedCXXThis(IOA);
343 if (IsImplicitObjectCXXThis)
344 SkippedChecks.set(SanitizerKind::Alignment, true);
345 if (IsImplicitObjectCXXThis || isa<DeclRefExpr>(IOA))
346 SkippedChecks.set(SanitizerKind::Null, true);
347 }
348 EmitTypeCheck(CodeGenFunction::TCK_MemberCall, CallLoc,
349 This.getPointer(*this),
350 C.getRecordType(CalleeDecl->getParent()),
351 /*Alignment=*/CharUnits::Zero(), SkippedChecks);
352
353 // C++ [class.virtual]p12:
354 // Explicit qualification with the scope operator (5.1) suppresses the
355 // virtual call mechanism.
356 //
357 // We also don't emit a virtual call if the base expression has a record type
358 // because then we know what the type is.
359 bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
360
361 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl)) {
362 assert(CE->arg_begin() == CE->arg_end() &&(static_cast<void> (0))
363 "Destructor shouldn't have explicit parameters")(static_cast<void> (0));
364 assert(ReturnValue.isNull() && "Destructor shouldn't have return value")(static_cast<void> (0));
365 if (UseVirtualCall) {
366 CGM.getCXXABI().EmitVirtualDestructorCall(*this, Dtor, Dtor_Complete,
367 This.getAddress(*this),
368 cast<CXXMemberCallExpr>(CE));
369 } else {
370 GlobalDecl GD(Dtor, Dtor_Complete);
371 CGCallee Callee;
372 if (getLangOpts().AppleKext && Dtor->isVirtual() && HasQualifier)
373 Callee = BuildAppleKextVirtualCall(Dtor, Qualifier, Ty);
374 else if (!DevirtualizedMethod)
375 Callee =
376 CGCallee::forDirect(CGM.getAddrOfCXXStructor(GD, FInfo, Ty), GD);
377 else {
378 Callee = CGCallee::forDirect(CGM.GetAddrOfFunction(GD, Ty), GD);
379 }
380
381 QualType ThisTy =
382 IsArrow ? Base->getType()->getPointeeType() : Base->getType();
383 EmitCXXDestructorCall(GD, Callee, This.getPointer(*this), ThisTy,
384 /*ImplicitParam=*/nullptr,
385 /*ImplicitParamTy=*/QualType(), CE);
386 }
387 return RValue::get(nullptr);
388 }
389
390 // FIXME: Uses of 'MD' past this point need to be audited. We may need to use
391 // 'CalleeDecl' instead.
392
393 CGCallee Callee;
394 if (UseVirtualCall) {
395 Callee = CGCallee::forVirtual(CE, MD, This.getAddress(*this), Ty);
396 } else {
397 if (SanOpts.has(SanitizerKind::CFINVCall) &&
398 MD->getParent()->isDynamicClass()) {
399 llvm::Value *VTable;
400 const CXXRecordDecl *RD;
401 std::tie(VTable, RD) = CGM.getCXXABI().LoadVTablePtr(
402 *this, This.getAddress(*this), CalleeDecl->getParent());
403 EmitVTablePtrCheckForCall(RD, VTable, CFITCK_NVCall, CE->getBeginLoc());
404 }
405
406 if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
407 Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
408 else if (!DevirtualizedMethod)
409 Callee =
410 CGCallee::forDirect(CGM.GetAddrOfFunction(MD, Ty), GlobalDecl(MD));
411 else {
412 Callee =
413 CGCallee::forDirect(CGM.GetAddrOfFunction(DevirtualizedMethod, Ty),
414 GlobalDecl(DevirtualizedMethod));
415 }
416 }
417
418 if (MD->isVirtual()) {
419 Address NewThisAddr =
420 CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
421 *this, CalleeDecl, This.getAddress(*this), UseVirtualCall);
422 This.setAddress(NewThisAddr);
423 }
424
425 return EmitCXXMemberOrOperatorCall(
426 CalleeDecl, Callee, ReturnValue, This.getPointer(*this),
427 /*ImplicitParam=*/nullptr, QualType(), CE, RtlArgs);
428}
429
430RValue
431CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
432 ReturnValueSlot ReturnValue) {
433 const BinaryOperator *BO =
434 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
435 const Expr *BaseExpr = BO->getLHS();
436 const Expr *MemFnExpr = BO->getRHS();
437
438 const auto *MPT = MemFnExpr->getType()->castAs<MemberPointerType>();
439 const auto *FPT = MPT->getPointeeType()->castAs<FunctionProtoType>();
440 const auto *RD =
441 cast<CXXRecordDecl>(MPT->getClass()->castAs<RecordType>()->getDecl());
442
443 // Emit the 'this' pointer.
444 Address This = Address::invalid();
445 if (BO->getOpcode() == BO_PtrMemI)
446 This = EmitPointerWithAlignment(BaseExpr);
447 else
448 This = EmitLValue(BaseExpr).getAddress(*this);
449
450 EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This.getPointer(),
451 QualType(MPT->getClass(), 0));
452
453 // Get the member function pointer.
454 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
455
456 // Ask the ABI to load the callee. Note that This is modified.
457 llvm::Value *ThisPtrForCall = nullptr;
458 CGCallee Callee =
459 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This,
460 ThisPtrForCall, MemFnPtr, MPT);
461
462 CallArgList Args;
463
464 QualType ThisType =
465 getContext().getPointerType(getContext().getTagDeclType(RD));
466
467 // Push the this ptr.
468 Args.add(RValue::get(ThisPtrForCall), ThisType);
469
470 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1);
471
472 // And the rest of the call args
473 EmitCallArgs(Args, FPT, E->arguments());
474 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required,
475 /*PrefixSize=*/0),
476 Callee, ReturnValue, Args, nullptr, E == MustTailCall,
477 E->getExprLoc());
478}
479
480RValue
481CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
482 const CXXMethodDecl *MD,
483 ReturnValueSlot ReturnValue) {
484 assert(MD->isInstance() &&(static_cast<void> (0))
485 "Trying to emit a member call expr on a static method!")(static_cast<void> (0));
486 return EmitCXXMemberOrOperatorMemberCallExpr(
487 E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr,
488 /*IsArrow=*/false, E->getArg(0));
489}
490
491RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
492 ReturnValueSlot ReturnValue) {
493 return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
494}
495
496static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
497 Address DestPtr,
498 const CXXRecordDecl *Base) {
499 if (Base->isEmpty())
500 return;
501
502 DestPtr = CGF.Builder.CreateElementBitCast(DestPtr, CGF.Int8Ty);
503
504 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
505 CharUnits NVSize = Layout.getNonVirtualSize();
506
507 // We cannot simply zero-initialize the entire base sub-object if vbptrs are
508 // present, they are initialized by the most derived class before calling the
509 // constructor.
510 SmallVector<std::pair<CharUnits, CharUnits>, 1> Stores;
511 Stores.emplace_back(CharUnits::Zero(), NVSize);
512
513 // Each store is split by the existence of a vbptr.
514 CharUnits VBPtrWidth = CGF.getPointerSize();
515 std::vector<CharUnits> VBPtrOffsets =
516 CGF.CGM.getCXXABI().getVBPtrOffsets(Base);
517 for (CharUnits VBPtrOffset : VBPtrOffsets) {
518 // Stop before we hit any virtual base pointers located in virtual bases.
519 if (VBPtrOffset >= NVSize)
520 break;
521 std::pair<CharUnits, CharUnits> LastStore = Stores.pop_back_val();
522 CharUnits LastStoreOffset = LastStore.first;
523 CharUnits LastStoreSize = LastStore.second;
524
525 CharUnits SplitBeforeOffset = LastStoreOffset;
526 CharUnits SplitBeforeSize = VBPtrOffset - SplitBeforeOffset;
527 assert(!SplitBeforeSize.isNegative() && "negative store size!")(static_cast<void> (0));
528 if (!SplitBeforeSize.isZero())
529 Stores.emplace_back(SplitBeforeOffset, SplitBeforeSize);
530
531 CharUnits SplitAfterOffset = VBPtrOffset + VBPtrWidth;
532 CharUnits SplitAfterSize = LastStoreSize - SplitAfterOffset;
533 assert(!SplitAfterSize.isNegative() && "negative store size!")(static_cast<void> (0));
534 if (!SplitAfterSize.isZero())
535 Stores.emplace_back(SplitAfterOffset, SplitAfterSize);
536 }
537
538 // If the type contains a pointer to data member we can't memset it to zero.
539 // Instead, create a null constant and copy it to the destination.
540 // TODO: there are other patterns besides zero that we can usefully memset,
541 // like -1, which happens to be the pattern used by member-pointers.
542 // TODO: isZeroInitializable can be over-conservative in the case where a
543 // virtual base contains a member pointer.
544 llvm::Constant *NullConstantForBase = CGF.CGM.EmitNullConstantForBase(Base);
545 if (!NullConstantForBase->isNullValue()) {
546 llvm::GlobalVariable *NullVariable = new llvm::GlobalVariable(
547 CGF.CGM.getModule(), NullConstantForBase->getType(),
548 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage,
549 NullConstantForBase, Twine());
550
551 CharUnits Align = std::max(Layout.getNonVirtualAlignment(),
552 DestPtr.getAlignment());
553 NullVariable->setAlignment(Align.getAsAlign());
554
555 Address SrcPtr = Address(CGF.EmitCastToVoidPtr(NullVariable), Align);
556
557 // Get and call the appropriate llvm.memcpy overload.
558 for (std::pair<CharUnits, CharUnits> Store : Stores) {
559 CharUnits StoreOffset = Store.first;
560 CharUnits StoreSize = Store.second;
561 llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
562 CGF.Builder.CreateMemCpy(
563 CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
564 CGF.Builder.CreateConstInBoundsByteGEP(SrcPtr, StoreOffset),
565 StoreSizeVal);
566 }
567
568 // Otherwise, just memset the whole thing to zero. This is legal
569 // because in LLVM, all default initializers (other than the ones we just
570 // handled above) are guaranteed to have a bit pattern of all zeros.
571 } else {
572 for (std::pair<CharUnits, CharUnits> Store : Stores) {
573 CharUnits StoreOffset = Store.first;
574 CharUnits StoreSize = Store.second;
575 llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
576 CGF.Builder.CreateMemSet(
577 CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
578 CGF.Builder.getInt8(0), StoreSizeVal);
579 }
580 }
581}
582
583void
584CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
585 AggValueSlot Dest) {
586 assert(!Dest.isIgnored() && "Must have a destination!")(static_cast<void> (0));
587 const CXXConstructorDecl *CD = E->getConstructor();
588
589 // If we require zero initialization before (or instead of) calling the
590 // constructor, as can be the case with a non-user-provided default
591 // constructor, emit the zero initialization now, unless destination is
592 // already zeroed.
593 if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
594 switch (E->getConstructionKind()) {
595 case CXXConstructExpr::CK_Delegating:
596 case CXXConstructExpr::CK_Complete:
597 EmitNullInitialization(Dest.getAddress(), E->getType());
598 break;
599 case CXXConstructExpr::CK_VirtualBase:
600 case CXXConstructExpr::CK_NonVirtualBase:
601 EmitNullBaseClassInitialization(*this, Dest.getAddress(),
602 CD->getParent());
603 break;
604 }
605 }
606
607 // If this is a call to a trivial default constructor, do nothing.
608 if (CD->isTrivial() && CD->isDefaultConstructor())
609 return;
610
611 // Elide the constructor if we're constructing from a temporary.
612 // The temporary check is required because Sema sets this on NRVO
613 // returns.
614 if (getLangOpts().ElideConstructors && E->isElidable()) {
615 assert(getContext().hasSameUnqualifiedType(E->getType(),(static_cast<void> (0))
616 E->getArg(0)->getType()))(static_cast<void> (0));
617 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
618 EmitAggExpr(E->getArg(0), Dest);
619 return;
620 }
621 }
622
623 if (const ArrayType *arrayType
624 = getContext().getAsArrayType(E->getType())) {
625 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddress(), E,
626 Dest.isSanitizerChecked());
627 } else {
628 CXXCtorType Type = Ctor_Complete;
629 bool ForVirtualBase = false;
630 bool Delegating = false;
631
632 switch (E->getConstructionKind()) {
633 case CXXConstructExpr::CK_Delegating:
634 // We should be emitting a constructor; GlobalDecl will assert this
635 Type = CurGD.getCtorType();
636 Delegating = true;
637 break;
638
639 case CXXConstructExpr::CK_Complete:
640 Type = Ctor_Complete;
641 break;
642
643 case CXXConstructExpr::CK_VirtualBase:
644 ForVirtualBase = true;
645 LLVM_FALLTHROUGH[[gnu::fallthrough]];
646
647 case CXXConstructExpr::CK_NonVirtualBase:
648 Type = Ctor_Base;
649 }
650
651 // Call the constructor.
652 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating, Dest, E);
653 }
654}
655
656void CodeGenFunction::EmitSynthesizedCXXCopyCtor(Address Dest, Address Src,
657 const Expr *Exp) {
658 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
659 Exp = E->getSubExpr();
660 assert(isa<CXXConstructExpr>(Exp) &&(static_cast<void> (0))
661 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr")(static_cast<void> (0));
662 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
663 const CXXConstructorDecl *CD = E->getConstructor();
664 RunCleanupsScope Scope(*this);
665
666 // If we require zero initialization before (or instead of) calling the
667 // constructor, as can be the case with a non-user-provided default
668 // constructor, emit the zero initialization now.
669 // FIXME. Do I still need this for a copy ctor synthesis?
670 if (E->requiresZeroInitialization())
671 EmitNullInitialization(Dest, E->getType());
672
673 assert(!getContext().getAsConstantArrayType(E->getType())(static_cast<void> (0))
674 && "EmitSynthesizedCXXCopyCtor - Copied-in Array")(static_cast<void> (0));
675 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E);
676}
677
678static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
679 const CXXNewExpr *E) {
680 if (!E->isArray())
681 return CharUnits::Zero();
682
683 // No cookie is required if the operator new[] being used is the
684 // reserved placement operator new[].
685 if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
686 return CharUnits::Zero();
687
688 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
689}
690
691static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
692 const CXXNewExpr *e,
693 unsigned minElements,
694 llvm::Value *&numElements,
695 llvm::Value *&sizeWithoutCookie) {
696 QualType type = e->getAllocatedType();
697
698 if (!e->isArray()) {
4
Taking true branch
699 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
700 sizeWithoutCookie
701 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
702 return sizeWithoutCookie;
5
Returning without writing to 'numElements'
703 }
704
705 // The width of size_t.
706 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
707
708 // Figure out the cookie size.
709 llvm::APInt cookieSize(sizeWidth,
710 CalculateCookiePadding(CGF, e).getQuantity());
711
712 // Emit the array size expression.
713 // We multiply the size of all dimensions for NumElements.
714 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
715 numElements =
716 ConstantEmitter(CGF).tryEmitAbstract(*e->getArraySize(), e->getType());
717 if (!numElements)
718 numElements = CGF.EmitScalarExpr(*e->getArraySize());
719 assert(isa<llvm::IntegerType>(numElements->getType()))(static_cast<void> (0));
720
721 // The number of elements can be have an arbitrary integer type;
722 // essentially, we need to multiply it by a constant factor, add a
723 // cookie size, and verify that the result is representable as a
724 // size_t. That's just a gloss, though, and it's wrong in one
725 // important way: if the count is negative, it's an error even if
726 // the cookie size would bring the total size >= 0.
727 bool isSigned
728 = (*e->getArraySize())->getType()->isSignedIntegerOrEnumerationType();
729 llvm::IntegerType *numElementsType
730 = cast<llvm::IntegerType>(numElements->getType());
731 unsigned numElementsWidth = numElementsType->getBitWidth();
732
733 // Compute the constant factor.
734 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
735 while (const ConstantArrayType *CAT
736 = CGF.getContext().getAsConstantArrayType(type)) {
737 type = CAT->getElementType();
738 arraySizeMultiplier *= CAT->getSize();
739 }
740
741 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
742 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
743 typeSizeMultiplier *= arraySizeMultiplier;
744
745 // This will be a size_t.
746 llvm::Value *size;
747
748 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
749 // Don't bloat the -O0 code.
750 if (llvm::ConstantInt *numElementsC =
751 dyn_cast<llvm::ConstantInt>(numElements)) {
752 const llvm::APInt &count = numElementsC->getValue();
753
754 bool hasAnyOverflow = false;
755
756 // If 'count' was a negative number, it's an overflow.
757 if (isSigned && count.isNegative())
758 hasAnyOverflow = true;
759
760 // We want to do all this arithmetic in size_t. If numElements is
761 // wider than that, check whether it's already too big, and if so,
762 // overflow.
763 else if (numElementsWidth > sizeWidth &&
764 numElementsWidth - sizeWidth > count.countLeadingZeros())
765 hasAnyOverflow = true;
766
767 // Okay, compute a count at the right width.
768 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
769
770 // If there is a brace-initializer, we cannot allocate fewer elements than
771 // there are initializers. If we do, that's treated like an overflow.
772 if (adjustedCount.ult(minElements))
773 hasAnyOverflow = true;
774
775 // Scale numElements by that. This might overflow, but we don't
776 // care because it only overflows if allocationSize does, too, and
777 // if that overflows then we shouldn't use this.
778 numElements = llvm::ConstantInt::get(CGF.SizeTy,
779 adjustedCount * arraySizeMultiplier);
780
781 // Compute the size before cookie, and track whether it overflowed.
782 bool overflow;
783 llvm::APInt allocationSize
784 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
785 hasAnyOverflow |= overflow;
786
787 // Add in the cookie, and check whether it's overflowed.
788 if (cookieSize != 0) {
789 // Save the current size without a cookie. This shouldn't be
790 // used if there was overflow.
791 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
792
793 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
794 hasAnyOverflow |= overflow;
795 }
796
797 // On overflow, produce a -1 so operator new will fail.
798 if (hasAnyOverflow) {
799 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
800 } else {
801 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
802 }
803
804 // Otherwise, we might need to use the overflow intrinsics.
805 } else {
806 // There are up to five conditions we need to test for:
807 // 1) if isSigned, we need to check whether numElements is negative;
808 // 2) if numElementsWidth > sizeWidth, we need to check whether
809 // numElements is larger than something representable in size_t;
810 // 3) if minElements > 0, we need to check whether numElements is smaller
811 // than that.
812 // 4) we need to compute
813 // sizeWithoutCookie := numElements * typeSizeMultiplier
814 // and check whether it overflows; and
815 // 5) if we need a cookie, we need to compute
816 // size := sizeWithoutCookie + cookieSize
817 // and check whether it overflows.
818
819 llvm::Value *hasOverflow = nullptr;
820
821 // If numElementsWidth > sizeWidth, then one way or another, we're
822 // going to have to do a comparison for (2), and this happens to
823 // take care of (1), too.
824 if (numElementsWidth > sizeWidth) {
825 llvm::APInt threshold(numElementsWidth, 1);
826 threshold <<= sizeWidth;
827
828 llvm::Value *thresholdV
829 = llvm::ConstantInt::get(numElementsType, threshold);
830
831 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
832 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
833
834 // Otherwise, if we're signed, we want to sext up to size_t.
835 } else if (isSigned) {
836 if (numElementsWidth < sizeWidth)
837 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
838
839 // If there's a non-1 type size multiplier, then we can do the
840 // signedness check at the same time as we do the multiply
841 // because a negative number times anything will cause an
842 // unsigned overflow. Otherwise, we have to do it here. But at least
843 // in this case, we can subsume the >= minElements check.
844 if (typeSizeMultiplier == 1)
845 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
846 llvm::ConstantInt::get(CGF.SizeTy, minElements));
847
848 // Otherwise, zext up to size_t if necessary.
849 } else if (numElementsWidth < sizeWidth) {
850 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
851 }
852
853 assert(numElements->getType() == CGF.SizeTy)(static_cast<void> (0));
854
855 if (minElements) {
856 // Don't allow allocation of fewer elements than we have initializers.
857 if (!hasOverflow) {
858 hasOverflow = CGF.Builder.CreateICmpULT(numElements,
859 llvm::ConstantInt::get(CGF.SizeTy, minElements));
860 } else if (numElementsWidth > sizeWidth) {
861 // The other existing overflow subsumes this check.
862 // We do an unsigned comparison, since any signed value < -1 is
863 // taken care of either above or below.
864 hasOverflow = CGF.Builder.CreateOr(hasOverflow,
865 CGF.Builder.CreateICmpULT(numElements,
866 llvm::ConstantInt::get(CGF.SizeTy, minElements)));
867 }
868 }
869
870 size = numElements;
871
872 // Multiply by the type size if necessary. This multiplier
873 // includes all the factors for nested arrays.
874 //
875 // This step also causes numElements to be scaled up by the
876 // nested-array factor if necessary. Overflow on this computation
877 // can be ignored because the result shouldn't be used if
878 // allocation fails.
879 if (typeSizeMultiplier != 1) {
880 llvm::Function *umul_with_overflow
881 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
882
883 llvm::Value *tsmV =
884 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
885 llvm::Value *result =
886 CGF.Builder.CreateCall(umul_with_overflow, {size, tsmV});
887
888 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
889 if (hasOverflow)
890 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
891 else
892 hasOverflow = overflowed;
893
894 size = CGF.Builder.CreateExtractValue(result, 0);
895
896 // Also scale up numElements by the array size multiplier.
897 if (arraySizeMultiplier != 1) {
898 // If the base element type size is 1, then we can re-use the
899 // multiply we just did.
900 if (typeSize.isOne()) {
901 assert(arraySizeMultiplier == typeSizeMultiplier)(static_cast<void> (0));
902 numElements = size;
903
904 // Otherwise we need a separate multiply.
905 } else {
906 llvm::Value *asmV =
907 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
908 numElements = CGF.Builder.CreateMul(numElements, asmV);
909 }
910 }
911 } else {
912 // numElements doesn't need to be scaled.
913 assert(arraySizeMultiplier == 1)(static_cast<void> (0));
914 }
915
916 // Add in the cookie size if necessary.
917 if (cookieSize != 0) {
918 sizeWithoutCookie = size;
919
920 llvm::Function *uadd_with_overflow
921 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
922
923 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
924 llvm::Value *result =
925 CGF.Builder.CreateCall(uadd_with_overflow, {size, cookieSizeV});
926
927 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
928 if (hasOverflow)
929 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
930 else
931 hasOverflow = overflowed;
932
933 size = CGF.Builder.CreateExtractValue(result, 0);
934 }
935
936 // If we had any possibility of dynamic overflow, make a select to
937 // overwrite 'size' with an all-ones value, which should cause
938 // operator new to throw.
939 if (hasOverflow)
940 size = CGF.Builder.CreateSelect(hasOverflow,
941 llvm::Constant::getAllOnesValue(CGF.SizeTy),
942 size);
943 }
944
945 if (cookieSize == 0)
946 sizeWithoutCookie = size;
947 else
948 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?")(static_cast<void> (0));
949
950 return size;
951}
952
953static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
954 QualType AllocType, Address NewPtr,
955 AggValueSlot::Overlap_t MayOverlap) {
956 // FIXME: Refactor with EmitExprAsInit.
957 switch (CGF.getEvaluationKind(AllocType)) {
958 case TEK_Scalar:
959 CGF.EmitScalarInit(Init, nullptr,
960 CGF.MakeAddrLValue(NewPtr, AllocType), false);
961 return;
962 case TEK_Complex:
963 CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType),
964 /*isInit*/ true);
965 return;
966 case TEK_Aggregate: {
967 AggValueSlot Slot
968 = AggValueSlot::forAddr(NewPtr, AllocType.getQualifiers(),
969 AggValueSlot::IsDestructed,
970 AggValueSlot::DoesNotNeedGCBarriers,
971 AggValueSlot::IsNotAliased,
972 MayOverlap, AggValueSlot::IsNotZeroed,
973 AggValueSlot::IsSanitizerChecked);
974 CGF.EmitAggExpr(Init, Slot);
975 return;
976 }
977 }
978 llvm_unreachable("bad evaluation kind")__builtin_unreachable();
979}
980
981void CodeGenFunction::EmitNewArrayInitializer(
982 const CXXNewExpr *E, QualType ElementType, llvm::Type *ElementTy,
983 Address BeginPtr, llvm::Value *NumElements,
984 llvm::Value *AllocSizeWithoutCookie) {
985 // If we have a type with trivial initialization and no initializer,
986 // there's nothing to do.
987 if (!E->hasInitializer())
27
Calling 'CXXNewExpr::hasInitializer'
30
Returning from 'CXXNewExpr::hasInitializer'
31
Taking false branch
988 return;
989
990 Address CurPtr = BeginPtr;
991
992 unsigned InitListElements = 0;
993
994 const Expr *Init = E->getInitializer();
995 Address EndOfInit = Address::invalid();
996 QualType::DestructionKind DtorKind = ElementType.isDestructedType();
997 EHScopeStack::stable_iterator Cleanup;
998 llvm::Instruction *CleanupDominator = nullptr;
999
1000 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementType);
1001 CharUnits ElementAlign =
1002 BeginPtr.getAlignment().alignmentOfArrayElement(ElementSize);
1003
1004 // Attempt to perform zero-initialization using memset.
1005 auto TryMemsetInitialization = [&]() -> bool {
1006 // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
1007 // we can initialize with a memset to -1.
1008 if (!CGM.getTypes().isZeroInitializable(ElementType))
1009 return false;
1010
1011 // Optimization: since zero initialization will just set the memory
1012 // to all zeroes, generate a single memset to do it in one shot.
1013
1014 // Subtract out the size of any elements we've already initialized.
1015 auto *RemainingSize = AllocSizeWithoutCookie;
1016 if (InitListElements) {
1017 // We know this can't overflow; we check this when doing the allocation.
1018 auto *InitializedSize = llvm::ConstantInt::get(
1019 RemainingSize->getType(),
1020 getContext().getTypeSizeInChars(ElementType).getQuantity() *
1021 InitListElements);
1022 RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
1023 }
1024
1025 // Create the memset.
1026 Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize, false);
1027 return true;
1028 };
1029
1030 // If the initializer is an initializer list, first do the explicit elements.
1031 if (const InitListExpr *ILE
32.1
'ILE' is non-null
32.1
'ILE' is non-null
= dyn_cast<InitListExpr>(Init)) {
32
Assuming 'Init' is a 'InitListExpr'
33
Taking true branch
1032 // Initializing from a (braced) string literal is a special case; the init
1033 // list element does not initialize a (single) array element.
1034 if (ILE->isStringLiteralInit()) {
34
Assuming the condition is false
35
Taking false branch
1035 // Initialize the initial portion of length equal to that of the string
1036 // literal. The allocation must be for at least this much; we emitted a
1037 // check for that earlier.
1038 AggValueSlot Slot =
1039 AggValueSlot::forAddr(CurPtr, ElementType.getQualifiers(),
1040 AggValueSlot::IsDestructed,
1041 AggValueSlot::DoesNotNeedGCBarriers,
1042 AggValueSlot::IsNotAliased,
1043 AggValueSlot::DoesNotOverlap,
1044 AggValueSlot::IsNotZeroed,
1045 AggValueSlot::IsSanitizerChecked);
1046 EmitAggExpr(ILE->getInit(0), Slot);
1047
1048 // Move past these elements.
1049 InitListElements =
1050 cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe())
1051 ->getSize().getZExtValue();
1052 CurPtr =
1053 Address(Builder.CreateInBoundsGEP(CurPtr.getElementType(),
1054 CurPtr.getPointer(),
1055 Builder.getSize(InitListElements),
1056 "string.init.end"),
1057 CurPtr.getAlignment().alignmentAtOffset(InitListElements *
1058 ElementSize));
1059
1060 // Zero out the rest, if any remain.
1061 llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
1062 if (!ConstNum || !ConstNum->equalsInt(InitListElements)) {
1063 bool OK = TryMemsetInitialization();
1064 (void)OK;
1065 assert(OK && "couldn't memset character type?")(static_cast<void> (0));
1066 }
1067 return;
1068 }
1069
1070 InitListElements = ILE->getNumInits();
1071
1072 // If this is a multi-dimensional array new, we will initialize multiple
1073 // elements with each init list element.
1074 QualType AllocType = E->getAllocatedType();
1075 if (const ConstantArrayType *CAT
36.1
'CAT' is null
36.1
'CAT' is null
= dyn_cast_or_null<ConstantArrayType>(
36
Assuming null pointer is passed into cast
37
Taking false branch
1076 AllocType->getAsArrayTypeUnsafe())) {
1077 ElementTy = ConvertTypeForMem(AllocType);
1078 CurPtr = Builder.CreateElementBitCast(CurPtr, ElementTy);
1079 InitListElements *= getContext().getConstantArrayElementCount(CAT);
1080 }
1081
1082 // Enter a partial-destruction Cleanup if necessary.
1083 if (needsEHCleanup(DtorKind)) {
38
Taking false branch
1084 // In principle we could tell the Cleanup where we are more
1085 // directly, but the control flow can get so varied here that it
1086 // would actually be quite complex. Therefore we go through an
1087 // alloca.
1088 EndOfInit = CreateTempAlloca(BeginPtr.getType(), getPointerAlign(),
1089 "array.init.end");
1090 CleanupDominator = Builder.CreateStore(BeginPtr.getPointer(), EndOfInit);
1091 pushIrregularPartialArrayCleanup(BeginPtr.getPointer(), EndOfInit,
1092 ElementType, ElementAlign,
1093 getDestroyer(DtorKind));
1094 Cleanup = EHStack.stable_begin();
1095 }
1096
1097 CharUnits StartAlign = CurPtr.getAlignment();
1098 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
39
Assuming 'i' is equal to 'e'
40
Loop condition is false. Execution continues on line 1121
1099 // Tell the cleanup that it needs to destroy up to this
1100 // element. TODO: some of these stores can be trivially
1101 // observed to be unnecessary.
1102 if (EndOfInit.isValid()) {
1103 auto FinishedPtr =
1104 Builder.CreateBitCast(CurPtr.getPointer(), BeginPtr.getType());
1105 Builder.CreateStore(FinishedPtr, EndOfInit);
1106 }
1107 // FIXME: If the last initializer is an incomplete initializer list for
1108 // an array, and we have an array filler, we can fold together the two
1109 // initialization loops.
1110 StoreAnyExprIntoOneUnit(*this, ILE->getInit(i),
1111 ILE->getInit(i)->getType(), CurPtr,
1112 AggValueSlot::DoesNotOverlap);
1113 CurPtr = Address(Builder.CreateInBoundsGEP(CurPtr.getElementType(),
1114 CurPtr.getPointer(),
1115 Builder.getSize(1),
1116 "array.exp.next"),
1117 StartAlign.alignmentAtOffset((i + 1) * ElementSize));
1118 }
1119
1120 // The remaining elements are filled with the array filler expression.
1121 Init = ILE->getArrayFiller();
1122
1123 // Extract the initializer for the individual array elements by pulling
1124 // out the array filler from all the nested initializer lists. This avoids
1125 // generating a nested loop for the initialization.
1126 while (Init && Init->getType()->isConstantArrayType()) {
41
Assuming 'Init' is null
42
Loop condition is false. Execution continues on line 1135
1127 auto *SubILE = dyn_cast<InitListExpr>(Init);
1128 if (!SubILE)
1129 break;
1130 assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?")(static_cast<void> (0));
1131 Init = SubILE->getArrayFiller();
1132 }
1133
1134 // Switch back to initializing one base element at a time.
1135 CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr.getType());
1136 }
1137
1138 // If all elements have already been initialized, skip any further
1139 // initialization.
1140 llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
1141 if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
43
Assuming 'ConstNum' is null
1142 // If there was a Cleanup, deactivate it.
1143 if (CleanupDominator)
1144 DeactivateCleanupBlock(Cleanup, CleanupDominator);
1145 return;
1146 }
1147
1148 assert(Init && "have trailing elements to initialize but no initializer")(static_cast<void> (0));
1149
1150 // If this is a constructor call, try to optimize it out, and failing that
1151 // emit a single loop to initialize all remaining elements.
1152 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
44
Assuming 'CCE' is non-null
45
Taking true branch
1153 CXXConstructorDecl *Ctor = CCE->getConstructor();
1154 if (Ctor->isTrivial()) {
46
Assuming the condition is false
47
Taking false branch
1155 // If new expression did not specify value-initialization, then there
1156 // is no initialization.
1157 if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
1158 return;
1159
1160 if (TryMemsetInitialization())
1161 return;
1162 }
1163
1164 // Store the new Cleanup position for irregular Cleanups.
1165 //
1166 // FIXME: Share this cleanup with the constructor call emission rather than
1167 // having it create a cleanup of its own.
1168 if (EndOfInit.isValid())
48
Taking false branch
1169 Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
1170
1171 // Emit a constructor call loop to initialize the remaining elements.
1172 if (InitListElements)
49
Assuming 'InitListElements' is not equal to 0
50
Taking true branch
1173 NumElements = Builder.CreateSub(
1174 NumElements,
1175 llvm::ConstantInt::get(NumElements->getType(), InitListElements));
51
Called C++ object pointer is null
1176 EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,
1177 /*NewPointerIsChecked*/true,
1178 CCE->requiresZeroInitialization());
1179 return;
1180 }
1181
1182 // If this is value-initialization, we can usually use memset.
1183 ImplicitValueInitExpr IVIE(ElementType);
1184 if (isa<ImplicitValueInitExpr>(Init)) {
1185 if (TryMemsetInitialization())
1186 return;
1187
1188 // Switch to an ImplicitValueInitExpr for the element type. This handles
1189 // only one case: multidimensional array new of pointers to members. In
1190 // all other cases, we already have an initializer for the array element.
1191 Init = &IVIE;
1192 }
1193
1194 // At this point we should have found an initializer for the individual
1195 // elements of the array.
1196 assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&(static_cast<void> (0))
1197 "got wrong type of element to initialize")(static_cast<void> (0));
1198
1199 // If we have an empty initializer list, we can usually use memset.
1200 if (auto *ILE = dyn_cast<InitListExpr>(Init))
1201 if (ILE->getNumInits() == 0 && TryMemsetInitialization())
1202 return;
1203
1204 // If we have a struct whose every field is value-initialized, we can
1205 // usually use memset.
1206 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
1207 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
1208 if (RType->getDecl()->isStruct()) {
1209 unsigned NumElements = 0;
1210 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RType->getDecl()))
1211 NumElements = CXXRD->getNumBases();
1212 for (auto *Field : RType->getDecl()->fields())
1213 if (!Field->isUnnamedBitfield())
1214 ++NumElements;
1215 // FIXME: Recurse into nested InitListExprs.
1216 if (ILE->getNumInits() == NumElements)
1217 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
1218 if (!isa<ImplicitValueInitExpr>(ILE->getInit(i)))
1219 --NumElements;
1220 if (ILE->getNumInits() == NumElements && TryMemsetInitialization())
1221 return;
1222 }
1223 }
1224 }
1225
1226 // Create the loop blocks.
1227 llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
1228 llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
1229 llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
1230
1231 // Find the end of the array, hoisted out of the loop.
1232 llvm::Value *EndPtr =
1233 Builder.CreateInBoundsGEP(BeginPtr.getElementType(), BeginPtr.getPointer(),
1234 NumElements, "array.end");
1235
1236 // If the number of elements isn't constant, we have to now check if there is
1237 // anything left to initialize.
1238 if (!ConstNum) {
1239 llvm::Value *IsEmpty =
1240 Builder.CreateICmpEQ(CurPtr.getPointer(), EndPtr, "array.isempty");
1241 Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
1242 }
1243
1244 // Enter the loop.
1245 EmitBlock(LoopBB);
1246
1247 // Set up the current-element phi.
1248 llvm::PHINode *CurPtrPhi =
1249 Builder.CreatePHI(CurPtr.getType(), 2, "array.cur");
1250 CurPtrPhi->addIncoming(CurPtr.getPointer(), EntryBB);
1251
1252 CurPtr = Address(CurPtrPhi, ElementAlign);
1253
1254 // Store the new Cleanup position for irregular Cleanups.
1255 if (EndOfInit.isValid())
1256 Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
1257
1258 // Enter a partial-destruction Cleanup if necessary.
1259 if (!CleanupDominator && needsEHCleanup(DtorKind)) {
1260 pushRegularPartialArrayCleanup(BeginPtr.getPointer(), CurPtr.getPointer(),
1261 ElementType, ElementAlign,
1262 getDestroyer(DtorKind));
1263 Cleanup = EHStack.stable_begin();
1264 CleanupDominator = Builder.CreateUnreachable();
1265 }
1266
1267 // Emit the initializer into this element.
1268 StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr,
1269 AggValueSlot::DoesNotOverlap);
1270
1271 // Leave the Cleanup if we entered one.
1272 if (CleanupDominator) {
1273 DeactivateCleanupBlock(Cleanup, CleanupDominator);
1274 CleanupDominator->eraseFromParent();
1275 }
1276
1277 // Advance to the next element by adjusting the pointer type as necessary.
1278 llvm::Value *NextPtr =
1279 Builder.CreateConstInBoundsGEP1_32(ElementTy, CurPtr.getPointer(), 1,
1280 "array.next");
1281
1282 // Check whether we've gotten to the end of the array and, if so,
1283 // exit the loop.
1284 llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
1285 Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
1286 CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
1287
1288 EmitBlock(ContBB);
1289}
1290
1291static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
1292 QualType ElementType, llvm::Type *ElementTy,
1293 Address NewPtr, llvm::Value *NumElements,
1294 llvm::Value *AllocSizeWithoutCookie) {
1295 ApplyDebugLocation DL(CGF, E);
1296 if (E->isArray())
23
Assuming the condition is true
24
Taking true branch
1297 CGF.EmitNewArrayInitializer(E, ElementType, ElementTy, NewPtr, NumElements,
25
Passing null pointer value via 5th parameter 'NumElements'
26
Calling 'CodeGenFunction::EmitNewArrayInitializer'
1298 AllocSizeWithoutCookie);
1299 else if (const Expr *Init = E->getInitializer())
1300 StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr,
1301 AggValueSlot::DoesNotOverlap);
1302}
1303
1304/// Emit a call to an operator new or operator delete function, as implicitly
1305/// created by new-expressions and delete-expressions.
1306static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
1307 const FunctionDecl *CalleeDecl,
1308 const FunctionProtoType *CalleeType,
1309 const CallArgList &Args) {
1310 llvm::CallBase *CallOrInvoke;
1311 llvm::Constant *CalleePtr = CGF.CGM.GetAddrOfFunction(CalleeDecl);
1312 CGCallee Callee = CGCallee::forDirect(CalleePtr, GlobalDecl(CalleeDecl));
1313 RValue RV =
1314 CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(
1315 Args, CalleeType, /*ChainCall=*/false),
1316 Callee, ReturnValueSlot(), Args, &CallOrInvoke);
1317
1318 /// C++1y [expr.new]p10:
1319 /// [In a new-expression,] an implementation is allowed to omit a call
1320 /// to a replaceable global allocation function.
1321 ///
1322 /// We model such elidable calls with the 'builtin' attribute.
1323 llvm::Function *Fn = dyn_cast<llvm::Function>(CalleePtr);
1324 if (CalleeDecl->isReplaceableGlobalAllocationFunction() &&
1325 Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
1326 CallOrInvoke->addFnAttr(llvm::Attribute::Builtin);
1327 }
1328
1329 return RV;
1330}
1331
1332RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
1333 const CallExpr *TheCall,
1334 bool IsDelete) {
1335 CallArgList Args;
1336 EmitCallArgs(Args, Type, TheCall->arguments());
1337 // Find the allocation or deallocation function that we're calling.
1338 ASTContext &Ctx = getContext();
1339 DeclarationName Name = Ctx.DeclarationNames
1340 .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
1341
1342 for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
1343 if (auto *FD = dyn_cast<FunctionDecl>(Decl))
1344 if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
1345 return EmitNewDeleteCall(*this, FD, Type, Args);
1346 llvm_unreachable("predeclared global operator new/delete is missing")__builtin_unreachable();
1347}
1348
1349namespace {
1350/// The parameters to pass to a usual operator delete.
1351struct UsualDeleteParams {
1352 bool DestroyingDelete = false;
1353 bool Size = false;
1354 bool Alignment = false;
1355};
1356}
1357
1358static UsualDeleteParams getUsualDeleteParams(const FunctionDecl *FD) {
1359 UsualDeleteParams Params;
1360
1361 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
1362 auto AI = FPT->param_type_begin(), AE = FPT->param_type_end();
1363
1364 // The first argument is always a void*.
1365 ++AI;
1366
1367 // The next parameter may be a std::destroying_delete_t.
1368 if (FD->isDestroyingOperatorDelete()) {
1369 Params.DestroyingDelete = true;
1370 assert(AI != AE)(static_cast<void> (0));
1371 ++AI;
1372 }
1373
1374 // Figure out what other parameters we should be implicitly passing.
1375 if (AI != AE && (*AI)->isIntegerType()) {
1376 Params.Size = true;
1377 ++AI;
1378 }
1379
1380 if (AI != AE && (*AI)->isAlignValT()) {
1381 Params.Alignment = true;
1382 ++AI;
1383 }
1384
1385 assert(AI == AE && "unexpected usual deallocation function parameter")(static_cast<void> (0));
1386 return Params;
1387}
1388
1389namespace {
1390 /// A cleanup to call the given 'operator delete' function upon abnormal
1391 /// exit from a new expression. Templated on a traits type that deals with
1392 /// ensuring that the arguments dominate the cleanup if necessary.
1393 template<typename Traits>
1394 class CallDeleteDuringNew final : public EHScopeStack::Cleanup {
1395 /// Type used to hold llvm::Value*s.
1396 typedef typename Traits::ValueTy ValueTy;
1397 /// Type used to hold RValues.
1398 typedef typename Traits::RValueTy RValueTy;
1399 struct PlacementArg {
1400 RValueTy ArgValue;
1401 QualType ArgType;
1402 };
1403
1404 unsigned NumPlacementArgs : 31;
1405 unsigned PassAlignmentToPlacementDelete : 1;
1406 const FunctionDecl *OperatorDelete;
1407 ValueTy Ptr;
1408 ValueTy AllocSize;
1409 CharUnits AllocAlign;
1410
1411 PlacementArg *getPlacementArgs() {
1412 return reinterpret_cast<PlacementArg *>(this + 1);
1413 }
1414
1415 public:
1416 static size_t getExtraSize(size_t NumPlacementArgs) {
1417 return NumPlacementArgs * sizeof(PlacementArg);
1418 }
1419
1420 CallDeleteDuringNew(size_t NumPlacementArgs,
1421 const FunctionDecl *OperatorDelete, ValueTy Ptr,
1422 ValueTy AllocSize, bool PassAlignmentToPlacementDelete,
1423 CharUnits AllocAlign)
1424 : NumPlacementArgs(NumPlacementArgs),
1425 PassAlignmentToPlacementDelete(PassAlignmentToPlacementDelete),
1426 OperatorDelete(OperatorDelete), Ptr(Ptr), AllocSize(AllocSize),
1427 AllocAlign(AllocAlign) {}
1428
1429 void setPlacementArg(unsigned I, RValueTy Arg, QualType Type) {
1430 assert(I < NumPlacementArgs && "index out of range")(static_cast<void> (0));
1431 getPlacementArgs()[I] = {Arg, Type};
1432 }
1433
1434 void Emit(CodeGenFunction &CGF, Flags flags) override {
1435 const auto *FPT = OperatorDelete->getType()->castAs<FunctionProtoType>();
1436 CallArgList DeleteArgs;
1437
1438 // The first argument is always a void* (or C* for a destroying operator
1439 // delete for class type C).
1440 DeleteArgs.add(Traits::get(CGF, Ptr), FPT->getParamType(0));
1441
1442 // Figure out what other parameters we should be implicitly passing.
1443 UsualDeleteParams Params;
1444 if (NumPlacementArgs) {
1445 // A placement deallocation function is implicitly passed an alignment
1446 // if the placement allocation function was, but is never passed a size.
1447 Params.Alignment = PassAlignmentToPlacementDelete;
1448 } else {
1449 // For a non-placement new-expression, 'operator delete' can take a
1450 // size and/or an alignment if it has the right parameters.
1451 Params = getUsualDeleteParams(OperatorDelete);
1452 }
1453
1454 assert(!Params.DestroyingDelete &&(static_cast<void> (0))
1455 "should not call destroying delete in a new-expression")(static_cast<void> (0));
1456
1457 // The second argument can be a std::size_t (for non-placement delete).
1458 if (Params.Size)
1459 DeleteArgs.add(Traits::get(CGF, AllocSize),
1460 CGF.getContext().getSizeType());
1461
1462 // The next (second or third) argument can be a std::align_val_t, which
1463 // is an enum whose underlying type is std::size_t.
1464 // FIXME: Use the right type as the parameter type. Note that in a call
1465 // to operator delete(size_t, ...), we may not have it available.
1466 if (Params.Alignment)
1467 DeleteArgs.add(RValue::get(llvm::ConstantInt::get(
1468 CGF.SizeTy, AllocAlign.getQuantity())),
1469 CGF.getContext().getSizeType());
1470
1471 // Pass the rest of the arguments, which must match exactly.
1472 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
1473 auto Arg = getPlacementArgs()[I];
1474 DeleteArgs.add(Traits::get(CGF, Arg.ArgValue), Arg.ArgType);
1475 }
1476
1477 // Call 'operator delete'.
1478 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
1479 }
1480 };
1481}
1482
1483/// Enter a cleanup to call 'operator delete' if the initializer in a
1484/// new-expression throws.
1485static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1486 const CXXNewExpr *E,
1487 Address NewPtr,
1488 llvm::Value *AllocSize,
1489 CharUnits AllocAlign,
1490 const CallArgList &NewArgs) {
1491 unsigned NumNonPlacementArgs = E->passAlignment() ? 2 : 1;
1492
1493 // If we're not inside a conditional branch, then the cleanup will
1494 // dominate and we can do the easier (and more efficient) thing.
1495 if (!CGF.isInConditionalBranch()) {
1496 struct DirectCleanupTraits {
1497 typedef llvm::Value *ValueTy;
1498 typedef RValue RValueTy;
1499 static RValue get(CodeGenFunction &, ValueTy V) { return RValue::get(V); }
1500 static RValue get(CodeGenFunction &, RValueTy V) { return V; }
1501 };
1502
1503 typedef CallDeleteDuringNew<DirectCleanupTraits> DirectCleanup;
1504
1505 DirectCleanup *Cleanup = CGF.EHStack
1506 .pushCleanupWithExtra<DirectCleanup>(EHCleanup,
1507 E->getNumPlacementArgs(),
1508 E->getOperatorDelete(),
1509 NewPtr.getPointer(),
1510 AllocSize,
1511 E->passAlignment(),
1512 AllocAlign);
1513 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
1514 auto &Arg = NewArgs[I + NumNonPlacementArgs];
1515 Cleanup->setPlacementArg(I, Arg.getRValue(CGF), Arg.Ty);
1516 }
1517
1518 return;
1519 }
1520
1521 // Otherwise, we need to save all this stuff.
1522 DominatingValue<RValue>::saved_type SavedNewPtr =
1523 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr.getPointer()));
1524 DominatingValue<RValue>::saved_type SavedAllocSize =
1525 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
1526
1527 struct ConditionalCleanupTraits {
1528 typedef DominatingValue<RValue>::saved_type ValueTy;
1529 typedef DominatingValue<RValue>::saved_type RValueTy;
1530 static RValue get(CodeGenFunction &CGF, ValueTy V) {
1531 return V.restore(CGF);
1532 }
1533 };
1534 typedef CallDeleteDuringNew<ConditionalCleanupTraits> ConditionalCleanup;
1535
1536 ConditionalCleanup *Cleanup = CGF.EHStack
1537 .pushCleanupWithExtra<ConditionalCleanup>(EHCleanup,
1538 E->getNumPlacementArgs(),
1539 E->getOperatorDelete(),
1540 SavedNewPtr,
1541 SavedAllocSize,
1542 E->passAlignment(),
1543 AllocAlign);
1544 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
1545 auto &Arg = NewArgs[I + NumNonPlacementArgs];
1546 Cleanup->setPlacementArg(
1547 I, DominatingValue<RValue>::save(CGF, Arg.getRValue(CGF)), Arg.Ty);
1548 }
1549
1550 CGF.initFullExprCleanup();
1551}
1552
1553llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
1554 // The element type being allocated.
1555 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
1556
1557 // 1. Build a call to the allocation function.
1558 FunctionDecl *allocator = E->getOperatorNew();
1559
1560 // If there is a brace-initializer, cannot allocate fewer elements than inits.
1561 unsigned minElements = 0;
1562 if (E->isArray() && E->hasInitializer()) {
1
Assuming the condition is false
1563 const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer());
1564 if (ILE && ILE->isStringLiteralInit())
1565 minElements =
1566 cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe())
1567 ->getSize().getZExtValue();
1568 else if (ILE)
1569 minElements = ILE->getNumInits();
1570 }
1571
1572 llvm::Value *numElements = nullptr;
2
'numElements' initialized to a null pointer value
1573 llvm::Value *allocSizeWithoutCookie = nullptr;
1574 llvm::Value *allocSize =
1575 EmitCXXNewAllocSize(*this, E, minElements, numElements,
3
Calling 'EmitCXXNewAllocSize'
6
Returning from 'EmitCXXNewAllocSize'
1576 allocSizeWithoutCookie);
1577 CharUnits allocAlign = getContext().getPreferredTypeAlignInChars(allocType);
1578
1579 // Emit the allocation call. If the allocator is a global placement
1580 // operator, just "inline" it directly.
1581 Address allocation = Address::invalid();
1582 CallArgList allocatorArgs;
1583 if (allocator->isReservedGlobalPlacementOperator()) {
7
Assuming the condition is false
8
Taking false branch
1584 assert(E->getNumPlacementArgs() == 1)(static_cast<void> (0));
1585 const Expr *arg = *E->placement_arguments().begin();
1586
1587 LValueBaseInfo BaseInfo;
1588 allocation = EmitPointerWithAlignment(arg, &BaseInfo);
1589
1590 // The pointer expression will, in many cases, be an opaque void*.
1591 // In these cases, discard the computed alignment and use the
1592 // formal alignment of the allocated type.
1593 if (BaseInfo.getAlignmentSource() != AlignmentSource::Decl)
1594 allocation = Address(allocation.getPointer(), allocAlign);
1595
1596 // Set up allocatorArgs for the call to operator delete if it's not
1597 // the reserved global operator.
1598 if (E->getOperatorDelete() &&
1599 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
1600 allocatorArgs.add(RValue::get(allocSize), getContext().getSizeType());
1601 allocatorArgs.add(RValue::get(allocation.getPointer()), arg->getType());
1602 }
1603
1604 } else {
1605 const FunctionProtoType *allocatorType =
1606 allocator->getType()->castAs<FunctionProtoType>();
9
The object is a 'FunctionProtoType'
1607 unsigned ParamsToSkip = 0;
1608
1609 // The allocation size is the first argument.
1610 QualType sizeType = getContext().getSizeType();
1611 allocatorArgs.add(RValue::get(allocSize), sizeType);
1612 ++ParamsToSkip;
1613
1614 if (allocSize
9.1
'allocSize' is equal to 'allocSizeWithoutCookie'
9.1
'allocSize' is equal to 'allocSizeWithoutCookie'
!= allocSizeWithoutCookie) {
10
Taking false branch
1615 CharUnits cookieAlign = getSizeAlign(); // FIXME: Ask the ABI.
1616 allocAlign = std::max(allocAlign, cookieAlign);
1617 }
1618
1619 // The allocation alignment may be passed as the second argument.
1620 if (E->passAlignment()) {
11
Assuming the condition is false
12
Taking false branch
1621 QualType AlignValT = sizeType;
1622 if (allocatorType->getNumParams() > 1) {
1623 AlignValT = allocatorType->getParamType(1);
1624 assert(getContext().hasSameUnqualifiedType((static_cast<void> (0))
1625 AlignValT->castAs<EnumType>()->getDecl()->getIntegerType(),(static_cast<void> (0))
1626 sizeType) &&(static_cast<void> (0))
1627 "wrong type for alignment parameter")(static_cast<void> (0));
1628 ++ParamsToSkip;
1629 } else {
1630 // Corner case, passing alignment to 'operator new(size_t, ...)'.
1631 assert(allocator->isVariadic() && "can't pass alignment to allocator")(static_cast<void> (0));
1632 }
1633 allocatorArgs.add(
1634 RValue::get(llvm::ConstantInt::get(SizeTy, allocAlign.getQuantity())),
1635 AlignValT);
1636 }
1637
1638 // FIXME: Why do we not pass a CalleeDecl here?
1639 EmitCallArgs(allocatorArgs, allocatorType, E->placement_arguments(),
1640 /*AC*/AbstractCallee(), /*ParamsToSkip*/ParamsToSkip);
1641
1642 RValue RV =
1643 EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
1644
1645 // Set !heapallocsite metadata on the call to operator new.
1646 if (getDebugInfo())
13
Assuming the condition is false
14
Taking false branch
1647 if (auto *newCall = dyn_cast<llvm::CallBase>(RV.getScalarVal()))
1648 getDebugInfo()->addHeapAllocSiteMetadata(newCall, allocType,
1649 E->getExprLoc());
1650
1651 // If this was a call to a global replaceable allocation function that does
1652 // not take an alignment argument, the allocator is known to produce
1653 // storage that's suitably aligned for any object that fits, up to a known
1654 // threshold. Otherwise assume it's suitably aligned for the allocated type.
1655 CharUnits allocationAlign = allocAlign;
1656 if (!E->passAlignment() &&
15
Assuming the condition is false
1657 allocator->isReplaceableGlobalAllocationFunction()) {
1658 unsigned AllocatorAlign = llvm::PowerOf2Floor(std::min<uint64_t>(
1659 Target.getNewAlign(), getContext().getTypeSize(allocType)));
1660 allocationAlign = std::max(
1661 allocationAlign, getContext().toCharUnitsFromBits(AllocatorAlign));
1662 }
1663
1664 allocation = Address(RV.getScalarVal(), allocationAlign);
1665 }
1666
1667 // Emit a null check on the allocation result if the allocation
1668 // function is allowed to return null (because it has a non-throwing
1669 // exception spec or is the reserved placement new) and we have an
1670 // interesting initializer will be running sanitizers on the initialization.
1671 bool nullCheck = E->shouldNullCheckAllocation() &&
16
Assuming the condition is false
1672 (!allocType.isPODType(getContext()) || E->hasInitializer() ||
1673 sanitizePerformTypeCheck());
1674
1675 llvm::BasicBlock *nullCheckBB = nullptr;
1676 llvm::BasicBlock *contBB = nullptr;
1677
1678 // The null-check means that the initializer is conditionally
1679 // evaluated.
1680 ConditionalEvaluation conditional(*this);
1681
1682 if (nullCheck
16.1
'nullCheck' is false
16.1
'nullCheck' is false
) {
17
Taking false branch
1683 conditional.begin(*this);
1684
1685 nullCheckBB = Builder.GetInsertBlock();
1686 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1687 contBB = createBasicBlock("new.cont");
1688
1689 llvm::Value *isNull =
1690 Builder.CreateIsNull(allocation.getPointer(), "new.isnull");
1691 Builder.CreateCondBr(isNull, contBB, notNullBB);
1692 EmitBlock(notNullBB);
1693 }
1694
1695 // If there's an operator delete, enter a cleanup to call it if an
1696 // exception is thrown.
1697 EHScopeStack::stable_iterator operatorDeleteCleanup;
1698 llvm::Instruction *cleanupDominator = nullptr;
1699 if (E->getOperatorDelete() &&
18
Assuming the condition is false
1700 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
1701 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocAlign,
1702 allocatorArgs);
1703 operatorDeleteCleanup = EHStack.stable_begin();
1704 cleanupDominator = Builder.CreateUnreachable();
1705 }
1706
1707 assert((allocSize == allocSizeWithoutCookie) ==(static_cast<void> (0))
1708 CalculateCookiePadding(*this, E).isZero())(static_cast<void> (0));
1709 if (allocSize
18.1
'allocSize' is equal to 'allocSizeWithoutCookie'
18.1
'allocSize' is equal to 'allocSizeWithoutCookie'
!= allocSizeWithoutCookie) {
19
Taking false branch
1710 assert(E->isArray())(static_cast<void> (0));
1711 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1712 numElements,
1713 E, allocType);
1714 }
1715
1716 llvm::Type *elementTy = ConvertTypeForMem(allocType);
1717 Address result = Builder.CreateElementBitCast(allocation, elementTy);
1718
1719 // Passing pointer through launder.invariant.group to avoid propagation of
1720 // vptrs information which may be included in previous type.
1721 // To not break LTO with different optimizations levels, we do it regardless
1722 // of optimization level.
1723 if (CGM.getCodeGenOpts().StrictVTablePointers &&
20
Assuming field 'StrictVTablePointers' is 0
1724 allocator->isReservedGlobalPlacementOperator())
1725 result = Address(Builder.CreateLaunderInvariantGroup(result.getPointer()),
1726 result.getAlignment());
1727
1728 // Emit sanitizer checks for pointer value now, so that in the case of an
1729 // array it was checked only once and not at each constructor call. We may
1730 // have already checked that the pointer is non-null.
1731 // FIXME: If we have an array cookie and a potentially-throwing allocator,
1732 // we'll null check the wrong pointer here.
1733 SanitizerSet SkippedChecks;
1734 SkippedChecks.set(SanitizerKind::Null, nullCheck);
1735 EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall,
1736 E->getAllocatedTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1737 result.getPointer(), allocType, result.getAlignment(),
1738 SkippedChecks, numElements);
1739
1740 EmitNewInitializer(*this, E, allocType, elementTy, result, numElements,
21
Passing null pointer value via 6th parameter 'NumElements'
22
Calling 'EmitNewInitializer'
1741 allocSizeWithoutCookie);
1742 if (E->isArray()) {
1743 // NewPtr is a pointer to the base element type. If we're
1744 // allocating an array of arrays, we'll need to cast back to the
1745 // array pointer type.
1746 llvm::Type *resultType = ConvertTypeForMem(E->getType());
1747 if (result.getType() != resultType)
1748 result = Builder.CreateBitCast(result, resultType);
1749 }
1750
1751 // Deactivate the 'operator delete' cleanup if we finished
1752 // initialization.
1753 if (operatorDeleteCleanup.isValid()) {
1754 DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1755 cleanupDominator->eraseFromParent();
1756 }
1757
1758 llvm::Value *resultPtr = result.getPointer();
1759 if (nullCheck) {
1760 conditional.end(*this);
1761
1762 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1763 EmitBlock(contBB);
1764
1765 llvm::PHINode *PHI = Builder.CreatePHI(resultPtr->getType(), 2);
1766 PHI->addIncoming(resultPtr, notNullBB);
1767 PHI->addIncoming(llvm::Constant::getNullValue(resultPtr->getType()),
1768 nullCheckBB);
1769
1770 resultPtr = PHI;
1771 }
1772
1773 return resultPtr;
1774}
1775
1776void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1777 llvm::Value *Ptr, QualType DeleteTy,
1778 llvm::Value *NumElements,
1779 CharUnits CookieSize) {
1780 assert((!NumElements && CookieSize.isZero()) ||(static_cast<void> (0))
1781 DeleteFD->getOverloadedOperator() == OO_Array_Delete)(static_cast<void> (0));
1782
1783 const auto *DeleteFTy = DeleteFD->getType()->castAs<FunctionProtoType>();
1784 CallArgList DeleteArgs;
1785
1786 auto Params = getUsualDeleteParams(DeleteFD);
1787 auto ParamTypeIt = DeleteFTy->param_type_begin();
1788
1789 // Pass the pointer itself.
1790 QualType ArgTy = *ParamTypeIt++;
1791 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
1792 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
1793
1794 // Pass the std::destroying_delete tag if present.
1795 llvm::AllocaInst *DestroyingDeleteTag = nullptr;
1796 if (Params.DestroyingDelete) {
1797 QualType DDTag = *ParamTypeIt++;
1798 llvm::Type *Ty = getTypes().ConvertType(DDTag);
1799 CharUnits Align = CGM.getNaturalTypeAlignment(DDTag);
1800 DestroyingDeleteTag = CreateTempAlloca(Ty, "destroying.delete.tag");
1801 DestroyingDeleteTag->setAlignment(Align.getAsAlign());
1802 DeleteArgs.add(RValue::getAggregate(Address(DestroyingDeleteTag, Align)), DDTag);
1803 }
1804
1805 // Pass the size if the delete function has a size_t parameter.
1806 if (Params.Size) {
1807 QualType SizeType = *ParamTypeIt++;
1808 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1809 llvm::Value *Size = llvm::ConstantInt::get(ConvertType(SizeType),
1810 DeleteTypeSize.getQuantity());
1811
1812 // For array new, multiply by the number of elements.
1813 if (NumElements)
1814 Size = Builder.CreateMul(Size, NumElements);
1815
1816 // If there is a cookie, add the cookie size.
1817 if (!CookieSize.isZero())
1818 Size = Builder.CreateAdd(
1819 Size, llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity()));
1820
1821 DeleteArgs.add(RValue::get(Size), SizeType);
1822 }
1823
1824 // Pass the alignment if the delete function has an align_val_t parameter.
1825 if (Params.Alignment) {
1826 QualType AlignValType = *ParamTypeIt++;
1827 CharUnits DeleteTypeAlign =
1828 getContext().toCharUnitsFromBits(getContext().getTypeAlignIfKnown(
1829 DeleteTy, true /* NeedsPreferredAlignment */));
1830 llvm::Value *Align = llvm::ConstantInt::get(ConvertType(AlignValType),
1831 DeleteTypeAlign.getQuantity());
1832 DeleteArgs.add(RValue::get(Align), AlignValType);
1833 }
1834
1835 assert(ParamTypeIt == DeleteFTy->param_type_end() &&(static_cast<void> (0))
1836 "unknown parameter to usual delete function")(static_cast<void> (0));
1837
1838 // Emit the call to delete.
1839 EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
1840
1841 // If call argument lowering didn't use the destroying_delete_t alloca,
1842 // remove it again.
1843 if (DestroyingDeleteTag && DestroyingDeleteTag->use_empty())
1844 DestroyingDeleteTag->eraseFromParent();
1845}
1846
1847namespace {
1848 /// Calls the given 'operator delete' on a single object.
1849 struct CallObjectDelete final : EHScopeStack::Cleanup {
1850 llvm::Value *Ptr;
1851 const FunctionDecl *OperatorDelete;
1852 QualType ElementType;
1853
1854 CallObjectDelete(llvm::Value *Ptr,
1855 const FunctionDecl *OperatorDelete,
1856 QualType ElementType)
1857 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1858
1859 void Emit(CodeGenFunction &CGF, Flags flags) override {
1860 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1861 }
1862 };
1863}
1864
1865void
1866CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
1867 llvm::Value *CompletePtr,
1868 QualType ElementType) {
1869 EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr,
1870 OperatorDelete, ElementType);
1871}
1872
1873/// Emit the code for deleting a single object with a destroying operator
1874/// delete. If the element type has a non-virtual destructor, Ptr has already
1875/// been converted to the type of the parameter of 'operator delete'. Otherwise
1876/// Ptr points to an object of the static type.
1877static void EmitDestroyingObjectDelete(CodeGenFunction &CGF,
1878 const CXXDeleteExpr *DE, Address Ptr,
1879 QualType ElementType) {
1880 auto *Dtor = ElementType->getAsCXXRecordDecl()->getDestructor();
1881 if (Dtor && Dtor->isVirtual())
1882 CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
1883 Dtor);
1884 else
1885 CGF.EmitDeleteCall(DE->getOperatorDelete(), Ptr.getPointer(), ElementType);
1886}
1887
1888/// Emit the code for deleting a single object.
1889/// \return \c true if we started emitting UnconditionalDeleteBlock, \c false
1890/// if not.
1891static bool EmitObjectDelete(CodeGenFunction &CGF,
1892 const CXXDeleteExpr *DE,
1893 Address Ptr,
1894 QualType ElementType,
1895 llvm::BasicBlock *UnconditionalDeleteBlock) {
1896 // C++11 [expr.delete]p3:
1897 // If the static type of the object to be deleted is different from its
1898 // dynamic type, the static type shall be a base class of the dynamic type
1899 // of the object to be deleted and the static type shall have a virtual
1900 // destructor or the behavior is undefined.
1901 CGF.EmitTypeCheck(CodeGenFunction::TCK_MemberCall,
1902 DE->getExprLoc(), Ptr.getPointer(),
1903 ElementType);
1904
1905 const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
1906 assert(!OperatorDelete->isDestroyingOperatorDelete())(static_cast<void> (0));
1907
1908 // Find the destructor for the type, if applicable. If the
1909 // destructor is virtual, we'll just emit the vcall and return.
1910 const CXXDestructorDecl *Dtor = nullptr;
1911 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1912 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1913 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
1914 Dtor = RD->getDestructor();
1915
1916 if (Dtor->isVirtual()) {
1917 bool UseVirtualCall = true;
1918 const Expr *Base = DE->getArgument();
1919 if (auto *DevirtualizedDtor =
1920 dyn_cast_or_null<const CXXDestructorDecl>(
1921 Dtor->getDevirtualizedMethod(
1922 Base, CGF.CGM.getLangOpts().AppleKext))) {
1923 UseVirtualCall = false;
1924 const CXXRecordDecl *DevirtualizedClass =
1925 DevirtualizedDtor->getParent();
1926 if (declaresSameEntity(getCXXRecord(Base), DevirtualizedClass)) {
1927 // Devirtualized to the class of the base type (the type of the
1928 // whole expression).
1929 Dtor = DevirtualizedDtor;
1930 } else {
1931 // Devirtualized to some other type. Would need to cast the this
1932 // pointer to that type but we don't have support for that yet, so
1933 // do a virtual call. FIXME: handle the case where it is
1934 // devirtualized to the derived type (the type of the inner
1935 // expression) as in EmitCXXMemberOrOperatorMemberCallExpr.
1936 UseVirtualCall = true;
1937 }
1938 }
1939 if (UseVirtualCall) {
1940 CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
1941 Dtor);
1942 return false;
1943 }
1944 }
1945 }
1946 }
1947
1948 // Make sure that we call delete even if the dtor throws.
1949 // This doesn't have to a conditional cleanup because we're going
1950 // to pop it off in a second.
1951 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1952 Ptr.getPointer(),
1953 OperatorDelete, ElementType);
1954
1955 if (Dtor)
1956 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1957 /*ForVirtualBase=*/false,
1958 /*Delegating=*/false,
1959 Ptr, ElementType);
1960 else if (auto Lifetime = ElementType.getObjCLifetime()) {
1961 switch (Lifetime) {
1962 case Qualifiers::OCL_None:
1963 case Qualifiers::OCL_ExplicitNone:
1964 case Qualifiers::OCL_Autoreleasing:
1965 break;
1966
1967 case Qualifiers::OCL_Strong:
1968 CGF.EmitARCDestroyStrong(Ptr, ARCPreciseLifetime);
1969 break;
1970
1971 case Qualifiers::OCL_Weak:
1972 CGF.EmitARCDestroyWeak(Ptr);
1973 break;
1974 }
1975 }
1976
1977 // When optimizing for size, call 'operator delete' unconditionally.
1978 if (CGF.CGM.getCodeGenOpts().OptimizeSize > 1) {
1979 CGF.EmitBlock(UnconditionalDeleteBlock);
1980 CGF.PopCleanupBlock();
1981 return true;
1982 }
1983
1984 CGF.PopCleanupBlock();
1985 return false;
1986}
1987
1988namespace {
1989 /// Calls the given 'operator delete' on an array of objects.
1990 struct CallArrayDelete final : EHScopeStack::Cleanup {
1991 llvm::Value *Ptr;
1992 const FunctionDecl *OperatorDelete;
1993 llvm::Value *NumElements;
1994 QualType ElementType;
1995 CharUnits CookieSize;
1996
1997 CallArrayDelete(llvm::Value *Ptr,
1998 const FunctionDecl *OperatorDelete,
1999 llvm::Value *NumElements,
2000 QualType ElementType,
2001 CharUnits CookieSize)
2002 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
2003 ElementType(ElementType), CookieSize(CookieSize) {}
2004
2005 void Emit(CodeGenFunction &CGF, Flags flags) override {
2006 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType, NumElements,
2007 CookieSize);
2008 }
2009 };
2010}
2011
2012/// Emit the code for deleting an array of objects.
2013static void EmitArrayDelete(CodeGenFunction &CGF,
2014 const CXXDeleteExpr *E,
2015 Address deletedPtr,
2016 QualType elementType) {
2017 llvm::Value *numElements = nullptr;
2018 llvm::Value *allocatedPtr = nullptr;
2019 CharUnits cookieSize;
2020 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
2021 numElements, allocatedPtr, cookieSize);
2022
2023 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer")(static_cast<void> (0));
2024
2025 // Make sure that we call delete even if one of the dtors throws.
2026 const FunctionDecl *operatorDelete = E->getOperatorDelete();
2027 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
2028 allocatedPtr, operatorDelete,
2029 numElements, elementType,
2030 cookieSize);
2031
2032 // Destroy the elements.
2033 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
2034 assert(numElements && "no element count for a type with a destructor!")(static_cast<void> (0));
2035
2036 CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
2037 CharUnits elementAlign =
2038 deletedPtr.getAlignment().alignmentOfArrayElement(elementSize);
2039
2040 llvm::Value *arrayBegin = deletedPtr.getPointer();
2041 llvm::Value *arrayEnd = CGF.Builder.CreateInBoundsGEP(
2042 deletedPtr.getElementType(), arrayBegin, numElements, "delete.end");
2043
2044 // Note that it is legal to allocate a zero-length array, and we
2045 // can never fold the check away because the length should always
2046 // come from a cookie.
2047 CGF.emitArrayDestroy(arrayBegin, arrayEnd, elementType, elementAlign,
2048 CGF.getDestroyer(dtorKind),
2049 /*checkZeroLength*/ true,
2050 CGF.needsEHCleanup(dtorKind));
2051 }
2052
2053 // Pop the cleanup block.
2054 CGF.PopCleanupBlock();
2055}
2056
2057void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
2058 const Expr *Arg = E->getArgument();
2059 Address Ptr = EmitPointerWithAlignment(Arg);
2060
2061 // Null check the pointer.
2062 //
2063 // We could avoid this null check if we can determine that the object
2064 // destruction is trivial and doesn't require an array cookie; we can
2065 // unconditionally perform the operator delete call in that case. For now, we
2066 // assume that deleted pointers are null rarely enough that it's better to
2067 // keep the branch. This might be worth revisiting for a -O0 code size win.
2068 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
2069 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
2070
2071 llvm::Value *IsNull = Builder.CreateIsNull(Ptr.getPointer(), "isnull");
2072
2073 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
2074 EmitBlock(DeleteNotNull);
2075
2076 QualType DeleteTy = E->getDestroyedType();
2077
2078 // A destroying operator delete overrides the entire operation of the
2079 // delete expression.
2080 if (E->getOperatorDelete()->isDestroyingOperatorDelete()) {
2081 EmitDestroyingObjectDelete(*this, E, Ptr, DeleteTy);
2082 EmitBlock(DeleteEnd);
2083 return;
2084 }
2085
2086 // We might be deleting a pointer to array. If so, GEP down to the
2087 // first non-array element.
2088 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
2089 if (DeleteTy->isConstantArrayType()) {
2090 llvm::Value *Zero = Builder.getInt32(0);
2091 SmallVector<llvm::Value*,8> GEP;
2092
2093 GEP.push_back(Zero); // point at the outermost array
2094
2095 // For each layer of array type we're pointing at:
2096 while (const ConstantArrayType *Arr
2097 = getContext().getAsConstantArrayType(DeleteTy)) {
2098 // 1. Unpeel the array type.
2099 DeleteTy = Arr->getElementType();
2100
2101 // 2. GEP to the first element of the array.
2102 GEP.push_back(Zero);
2103 }
2104
2105 Ptr = Address(Builder.CreateInBoundsGEP(Ptr.getElementType(),
2106 Ptr.getPointer(), GEP, "del.first"),
2107 Ptr.getAlignment());
2108 }
2109
2110 assert(ConvertTypeForMem(DeleteTy) == Ptr.getElementType())(static_cast<void> (0));
2111
2112 if (E->isArrayForm()) {
2113 EmitArrayDelete(*this, E, Ptr, DeleteTy);
2114 EmitBlock(DeleteEnd);
2115 } else {
2116 if (!EmitObjectDelete(*this, E, Ptr, DeleteTy, DeleteEnd))
2117 EmitBlock(DeleteEnd);
2118 }
2119}
2120
2121static bool isGLValueFromPointerDeref(const Expr *E) {
2122 E = E->IgnoreParens();
2123
2124 if (const auto *CE = dyn_cast<CastExpr>(E)) {
2125 if (!CE->getSubExpr()->isGLValue())
2126 return false;
2127 return isGLValueFromPointerDeref(CE->getSubExpr());
2128 }
2129
2130 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
2131 return isGLValueFromPointerDeref(OVE->getSourceExpr());
2132
2133 if (const auto *BO = dyn_cast<BinaryOperator>(E))
2134 if (BO->getOpcode() == BO_Comma)
2135 return isGLValueFromPointerDeref(BO->getRHS());
2136
2137 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E))
2138 return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
2139 isGLValueFromPointerDeref(ACO->getFalseExpr());
2140
2141 // C++11 [expr.sub]p1:
2142 // The expression E1[E2] is identical (by definition) to *((E1)+(E2))
2143 if (isa<ArraySubscriptExpr>(E))
2144 return true;
2145
2146 if (const auto *UO = dyn_cast<UnaryOperator>(E))
2147 if (UO->getOpcode() == UO_Deref)
2148 return true;
2149
2150 return false;
2151}
2152
2153static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
2154 llvm::Type *StdTypeInfoPtrTy) {
2155 // Get the vtable pointer.
2156 Address ThisPtr = CGF.EmitLValue(E).getAddress(CGF);
2157
2158 QualType SrcRecordTy = E->getType();
2159
2160 // C++ [class.cdtor]p4:
2161 // If the operand of typeid refers to the object under construction or
2162 // destruction and the static type of the operand is neither the constructor
2163 // or destructor’s class nor one of its bases, the behavior is undefined.
2164 CGF.EmitTypeCheck(CodeGenFunction::TCK_DynamicOperation, E->getExprLoc(),
2165 ThisPtr.getPointer(), SrcRecordTy);
2166
2167 // C++ [expr.typeid]p2:
2168 // If the glvalue expression is obtained by applying the unary * operator to
2169 // a pointer and the pointer is a null pointer value, the typeid expression
2170 // throws the std::bad_typeid exception.
2171 //
2172 // However, this paragraph's intent is not clear. We choose a very generous
2173 // interpretation which implores us to consider comma operators, conditional
2174 // operators, parentheses and other such constructs.
2175 if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(
2176 isGLValueFromPointerDeref(E), SrcRecordTy)) {
2177 llvm::BasicBlock *BadTypeidBlock =
2178 CGF.createBasicBlock("typeid.bad_typeid");
2179 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
2180
2181 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr.getPointer());
2182 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
2183
2184 CGF.EmitBlock(BadTypeidBlock);
2185 CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
2186 CGF.EmitBlock(EndBlock);
2187 }
2188
2189 return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
2190 StdTypeInfoPtrTy);
2191}
2192
2193llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
2194 llvm::Type *StdTypeInfoPtrTy =
2195 ConvertType(E->getType())->getPointerTo();
2196
2197 if (E->isTypeOperand()) {
2198 llvm::Constant *TypeInfo =
2199 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
2200 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
2201 }
2202
2203 // C++ [expr.typeid]p2:
2204 // When typeid is applied to a glvalue expression whose type is a
2205 // polymorphic class type, the result refers to a std::type_info object
2206 // representing the type of the most derived object (that is, the dynamic
2207 // type) to which the glvalue refers.
2208 // If the operand is already most derived object, no need to look up vtable.
2209 if (E->isPotentiallyEvaluated() && !E->isMostDerived(getContext()))
2210 return EmitTypeidFromVTable(*this, E->getExprOperand(),
2211 StdTypeInfoPtrTy);
2212
2213 QualType OperandTy = E->getExprOperand()->getType();
2214 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
2215 StdTypeInfoPtrTy);
2216}
2217
2218static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
2219 QualType DestTy) {
2220 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
2221 if (DestTy->isPointerType())
2222 return llvm::Constant::getNullValue(DestLTy);
2223
2224 /// C++ [expr.dynamic.cast]p9:
2225 /// A failed cast to reference type throws std::bad_cast
2226 if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
2227 return nullptr;
2228
2229 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
2230 return llvm::UndefValue::get(DestLTy);
2231}
2232
2233llvm::Value *CodeGenFunction::EmitDynamicCast(Address ThisAddr,
2234 const CXXDynamicCastExpr *DCE) {
2235 CGM.EmitExplicitCastExprType(DCE, this);
2236 QualType DestTy = DCE->getTypeAsWritten();
2237
2238 QualType SrcTy = DCE->getSubExpr()->getType();
2239
2240 // C++ [expr.dynamic.cast]p7:
2241 // If T is "pointer to cv void," then the result is a pointer to the most
2242 // derived object pointed to by v.
2243 const PointerType *DestPTy = DestTy->getAs<PointerType>();
2244
2245 bool isDynamicCastToVoid;
2246 QualType SrcRecordTy;
2247 QualType DestRecordTy;
2248 if (DestPTy) {
2249 isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType();
2250 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
2251 DestRecordTy = DestPTy->getPointeeType();
2252 } else {
2253 isDynamicCastToVoid = false;
2254 SrcRecordTy = SrcTy;
2255 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
2256 }
2257
2258 // C++ [class.cdtor]p5:
2259 // If the operand of the dynamic_cast refers to the object under
2260 // construction or destruction and the static type of the operand is not a
2261 // pointer to or object of the constructor or destructor’s own class or one
2262 // of its bases, the dynamic_cast results in undefined behavior.
2263 EmitTypeCheck(TCK_DynamicOperation, DCE->getExprLoc(), ThisAddr.getPointer(),
2264 SrcRecordTy);
2265
2266 if (DCE->isAlwaysNull())
2267 if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy))
2268 return T;
2269
2270 assert(SrcRecordTy->isRecordType() && "source type must be a record type!")(static_cast<void> (0));
2271
2272 // C++ [expr.dynamic.cast]p4:
2273 // If the value of v is a null pointer value in the pointer case, the result
2274 // is the null pointer value of type T.
2275 bool ShouldNullCheckSrcValue =
2276 CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(),
2277 SrcRecordTy);
2278
2279 llvm::BasicBlock *CastNull = nullptr;
2280 llvm::BasicBlock *CastNotNull = nullptr;
2281 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
2282
2283 if (ShouldNullCheckSrcValue) {
2284 CastNull = createBasicBlock("dynamic_cast.null");
2285 CastNotNull = createBasicBlock("dynamic_cast.notnull");
2286
2287 llvm::Value *IsNull = Builder.CreateIsNull(ThisAddr.getPointer());
2288 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
2289 EmitBlock(CastNotNull);
2290 }
2291
2292 llvm::Value *Value;
2293 if (isDynamicCastToVoid) {
2294 Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, ThisAddr, SrcRecordTy,
2295 DestTy);
2296 } else {
2297 assert(DestRecordTy->isRecordType() &&(static_cast<void> (0))
2298 "destination type must be a record type!")(static_cast<void> (0));
2299 Value = CGM.getCXXABI().EmitDynamicCastCall(*this, ThisAddr, SrcRecordTy,
2300 DestTy, DestRecordTy, CastEnd);
2301 CastNotNull = Builder.GetInsertBlock();
2302 }
2303
2304 if (ShouldNullCheckSrcValue) {
2305 EmitBranch(CastEnd);
2306
2307 EmitBlock(CastNull);
2308 EmitBranch(CastEnd);
2309 }
2310
2311 EmitBlock(CastEnd);
2312
2313 if (ShouldNullCheckSrcValue) {
2314 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
2315 PHI->addIncoming(Value, CastNotNull);
2316 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
2317
2318 Value = PHI;
2319 }
2320
2321 return Value;
2322}

/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/include/clang/AST/ExprCXX.h

1//===- ExprCXX.h - Classes for representing expressions ---------*- C++ -*-===//
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/// \file
10/// Defines the clang::Expr interface and subclasses for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_EXPRCXX_H
15#define LLVM_CLANG_AST_EXPRCXX_H
16
17#include "clang/AST/ASTConcept.h"
18#include "clang/AST/ComputeDependence.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclBase.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclTemplate.h"
23#include "clang/AST/DeclarationName.h"
24#include "clang/AST/DependenceFlags.h"
25#include "clang/AST/Expr.h"
26#include "clang/AST/NestedNameSpecifier.h"
27#include "clang/AST/OperationKinds.h"
28#include "clang/AST/Stmt.h"
29#include "clang/AST/StmtCXX.h"
30#include "clang/AST/TemplateBase.h"
31#include "clang/AST/Type.h"
32#include "clang/AST/UnresolvedSet.h"
33#include "clang/Basic/ExceptionSpecificationType.h"
34#include "clang/Basic/ExpressionTraits.h"
35#include "clang/Basic/LLVM.h"
36#include "clang/Basic/Lambda.h"
37#include "clang/Basic/LangOptions.h"
38#include "clang/Basic/OperatorKinds.h"
39#include "clang/Basic/SourceLocation.h"
40#include "clang/Basic/Specifiers.h"
41#include "clang/Basic/TypeTraits.h"
42#include "llvm/ADT/ArrayRef.h"
43#include "llvm/ADT/None.h"
44#include "llvm/ADT/Optional.h"
45#include "llvm/ADT/PointerUnion.h"
46#include "llvm/ADT/StringRef.h"
47#include "llvm/ADT/iterator_range.h"
48#include "llvm/Support/Casting.h"
49#include "llvm/Support/Compiler.h"
50#include "llvm/Support/TrailingObjects.h"
51#include <cassert>
52#include <cstddef>
53#include <cstdint>
54#include <memory>
55
56namespace clang {
57
58class ASTContext;
59class DeclAccessPair;
60class IdentifierInfo;
61class LambdaCapture;
62class NonTypeTemplateParmDecl;
63class TemplateParameterList;
64
65//===--------------------------------------------------------------------===//
66// C++ Expressions.
67//===--------------------------------------------------------------------===//
68
69/// A call to an overloaded operator written using operator
70/// syntax.
71///
72/// Represents a call to an overloaded operator written using operator
73/// syntax, e.g., "x + y" or "*p". While semantically equivalent to a
74/// normal call, this AST node provides better information about the
75/// syntactic representation of the call.
76///
77/// In a C++ template, this expression node kind will be used whenever
78/// any of the arguments are type-dependent. In this case, the
79/// function itself will be a (possibly empty) set of functions and
80/// function templates that were found by name lookup at template
81/// definition time.
82class CXXOperatorCallExpr final : public CallExpr {
83 friend class ASTStmtReader;
84 friend class ASTStmtWriter;
85
86 SourceRange Range;
87
88 // CXXOperatorCallExpr has some trailing objects belonging
89 // to CallExpr. See CallExpr for the details.
90
91 SourceRange getSourceRangeImpl() const LLVM_READONLY__attribute__((__pure__));
92
93 CXXOperatorCallExpr(OverloadedOperatorKind OpKind, Expr *Fn,
94 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
95 SourceLocation OperatorLoc, FPOptionsOverride FPFeatures,
96 ADLCallKind UsesADL);
97
98 CXXOperatorCallExpr(unsigned NumArgs, bool HasFPFeatures, EmptyShell Empty);
99
100public:
101 static CXXOperatorCallExpr *
102 Create(const ASTContext &Ctx, OverloadedOperatorKind OpKind, Expr *Fn,
103 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
104 SourceLocation OperatorLoc, FPOptionsOverride FPFeatures,
105 ADLCallKind UsesADL = NotADL);
106
107 static CXXOperatorCallExpr *CreateEmpty(const ASTContext &Ctx,
108 unsigned NumArgs, bool HasFPFeatures,
109 EmptyShell Empty);
110
111 /// Returns the kind of overloaded operator that this expression refers to.
112 OverloadedOperatorKind getOperator() const {
113 return static_cast<OverloadedOperatorKind>(
114 CXXOperatorCallExprBits.OperatorKind);
115 }
116
117 static bool isAssignmentOp(OverloadedOperatorKind Opc) {
118 return Opc == OO_Equal || Opc == OO_StarEqual || Opc == OO_SlashEqual ||
119 Opc == OO_PercentEqual || Opc == OO_PlusEqual ||
120 Opc == OO_MinusEqual || Opc == OO_LessLessEqual ||
121 Opc == OO_GreaterGreaterEqual || Opc == OO_AmpEqual ||
122 Opc == OO_CaretEqual || Opc == OO_PipeEqual;
123 }
124 bool isAssignmentOp() const { return isAssignmentOp(getOperator()); }
125
126 static bool isComparisonOp(OverloadedOperatorKind Opc) {
127 switch (Opc) {
128 case OO_EqualEqual:
129 case OO_ExclaimEqual:
130 case OO_Greater:
131 case OO_GreaterEqual:
132 case OO_Less:
133 case OO_LessEqual:
134 case OO_Spaceship:
135 return true;
136 default:
137 return false;
138 }
139 }
140 bool isComparisonOp() const { return isComparisonOp(getOperator()); }
141
142 /// Is this written as an infix binary operator?
143 bool isInfixBinaryOp() const;
144
145 /// Returns the location of the operator symbol in the expression.
146 ///
147 /// When \c getOperator()==OO_Call, this is the location of the right
148 /// parentheses; when \c getOperator()==OO_Subscript, this is the location
149 /// of the right bracket.
150 SourceLocation getOperatorLoc() const { return getRParenLoc(); }
151
152 SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__)) {
153 OverloadedOperatorKind Operator = getOperator();
154 return (Operator < OO_Plus || Operator >= OO_Arrow ||
155 Operator == OO_PlusPlus || Operator == OO_MinusMinus)
156 ? getBeginLoc()
157 : getOperatorLoc();
158 }
159
160 SourceLocation getBeginLoc() const { return Range.getBegin(); }
161 SourceLocation getEndLoc() const { return Range.getEnd(); }
162 SourceRange getSourceRange() const { return Range; }
163
164 static bool classof(const Stmt *T) {
165 return T->getStmtClass() == CXXOperatorCallExprClass;
166 }
167};
168
169/// Represents a call to a member function that
170/// may be written either with member call syntax (e.g., "obj.func()"
171/// or "objptr->func()") or with normal function-call syntax
172/// ("func()") within a member function that ends up calling a member
173/// function. The callee in either case is a MemberExpr that contains
174/// both the object argument and the member function, while the
175/// arguments are the arguments within the parentheses (not including
176/// the object argument).
177class CXXMemberCallExpr final : public CallExpr {
178 // CXXMemberCallExpr has some trailing objects belonging
179 // to CallExpr. See CallExpr for the details.
180
181 CXXMemberCallExpr(Expr *Fn, ArrayRef<Expr *> Args, QualType Ty,
182 ExprValueKind VK, SourceLocation RP,
183 FPOptionsOverride FPOptions, unsigned MinNumArgs);
184
185 CXXMemberCallExpr(unsigned NumArgs, bool HasFPFeatures, EmptyShell Empty);
186
187public:
188 static CXXMemberCallExpr *Create(const ASTContext &Ctx, Expr *Fn,
189 ArrayRef<Expr *> Args, QualType Ty,
190 ExprValueKind VK, SourceLocation RP,
191 FPOptionsOverride FPFeatures,
192 unsigned MinNumArgs = 0);
193
194 static CXXMemberCallExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
195 bool HasFPFeatures, EmptyShell Empty);
196
197 /// Retrieve the implicit object argument for the member call.
198 ///
199 /// For example, in "x.f(5)", this returns the sub-expression "x".
200 Expr *getImplicitObjectArgument() const;
201
202 /// Retrieve the type of the object argument.
203 ///
204 /// Note that this always returns a non-pointer type.
205 QualType getObjectType() const;
206
207 /// Retrieve the declaration of the called method.
208 CXXMethodDecl *getMethodDecl() const;
209
210 /// Retrieve the CXXRecordDecl for the underlying type of
211 /// the implicit object argument.
212 ///
213 /// Note that this is may not be the same declaration as that of the class
214 /// context of the CXXMethodDecl which this function is calling.
215 /// FIXME: Returns 0 for member pointer call exprs.
216 CXXRecordDecl *getRecordDecl() const;
217
218 SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__)) {
219 SourceLocation CLoc = getCallee()->getExprLoc();
220 if (CLoc.isValid())
221 return CLoc;
222
223 return getBeginLoc();
224 }
225
226 static bool classof(const Stmt *T) {
227 return T->getStmtClass() == CXXMemberCallExprClass;
228 }
229};
230
231/// Represents a call to a CUDA kernel function.
232class CUDAKernelCallExpr final : public CallExpr {
233 friend class ASTStmtReader;
234
235 enum { CONFIG, END_PREARG };
236
237 // CUDAKernelCallExpr has some trailing objects belonging
238 // to CallExpr. See CallExpr for the details.
239
240 CUDAKernelCallExpr(Expr *Fn, CallExpr *Config, ArrayRef<Expr *> Args,
241 QualType Ty, ExprValueKind VK, SourceLocation RP,
242 FPOptionsOverride FPFeatures, unsigned MinNumArgs);
243
244 CUDAKernelCallExpr(unsigned NumArgs, bool HasFPFeatures, EmptyShell Empty);
245
246public:
247 static CUDAKernelCallExpr *Create(const ASTContext &Ctx, Expr *Fn,
248 CallExpr *Config, ArrayRef<Expr *> Args,
249 QualType Ty, ExprValueKind VK,
250 SourceLocation RP,
251 FPOptionsOverride FPFeatures,
252 unsigned MinNumArgs = 0);
253
254 static CUDAKernelCallExpr *CreateEmpty(const ASTContext &Ctx,
255 unsigned NumArgs, bool HasFPFeatures,
256 EmptyShell Empty);
257
258 const CallExpr *getConfig() const {
259 return cast_or_null<CallExpr>(getPreArg(CONFIG));
260 }
261 CallExpr *getConfig() { return cast_or_null<CallExpr>(getPreArg(CONFIG)); }
262
263 static bool classof(const Stmt *T) {
264 return T->getStmtClass() == CUDAKernelCallExprClass;
265 }
266};
267
268/// A rewritten comparison expression that was originally written using
269/// operator syntax.
270///
271/// In C++20, the following rewrites are performed:
272/// - <tt>a == b</tt> -> <tt>b == a</tt>
273/// - <tt>a != b</tt> -> <tt>!(a == b)</tt>
274/// - <tt>a != b</tt> -> <tt>!(b == a)</tt>
275/// - For \c \@ in \c <, \c <=, \c >, \c >=, \c <=>:
276/// - <tt>a @ b</tt> -> <tt>(a <=> b) @ 0</tt>
277/// - <tt>a @ b</tt> -> <tt>0 @ (b <=> a)</tt>
278///
279/// This expression provides access to both the original syntax and the
280/// rewritten expression.
281///
282/// Note that the rewritten calls to \c ==, \c <=>, and \c \@ are typically
283/// \c CXXOperatorCallExprs, but could theoretically be \c BinaryOperators.
284class CXXRewrittenBinaryOperator : public Expr {
285 friend class ASTStmtReader;
286
287 /// The rewritten semantic form.
288 Stmt *SemanticForm;
289
290public:
291 CXXRewrittenBinaryOperator(Expr *SemanticForm, bool IsReversed)
292 : Expr(CXXRewrittenBinaryOperatorClass, SemanticForm->getType(),
293 SemanticForm->getValueKind(), SemanticForm->getObjectKind()),
294 SemanticForm(SemanticForm) {
295 CXXRewrittenBinaryOperatorBits.IsReversed = IsReversed;
296 setDependence(computeDependence(this));
297 }
298 CXXRewrittenBinaryOperator(EmptyShell Empty)
299 : Expr(CXXRewrittenBinaryOperatorClass, Empty), SemanticForm() {}
300
301 /// Get an equivalent semantic form for this expression.
302 Expr *getSemanticForm() { return cast<Expr>(SemanticForm); }
303 const Expr *getSemanticForm() const { return cast<Expr>(SemanticForm); }
304
305 struct DecomposedForm {
306 /// The original opcode, prior to rewriting.
307 BinaryOperatorKind Opcode;
308 /// The original left-hand side.
309 const Expr *LHS;
310 /// The original right-hand side.
311 const Expr *RHS;
312 /// The inner \c == or \c <=> operator expression.
313 const Expr *InnerBinOp;
314 };
315
316 /// Decompose this operator into its syntactic form.
317 DecomposedForm getDecomposedForm() const LLVM_READONLY__attribute__((__pure__));
318
319 /// Determine whether this expression was rewritten in reverse form.
320 bool isReversed() const { return CXXRewrittenBinaryOperatorBits.IsReversed; }
321
322 BinaryOperatorKind getOperator() const { return getDecomposedForm().Opcode; }
323 BinaryOperatorKind getOpcode() const { return getOperator(); }
324 static StringRef getOpcodeStr(BinaryOperatorKind Op) {
325 return BinaryOperator::getOpcodeStr(Op);
326 }
327 StringRef getOpcodeStr() const {
328 return BinaryOperator::getOpcodeStr(getOpcode());
329 }
330 bool isComparisonOp() const { return true; }
331 bool isAssignmentOp() const { return false; }
332
333 const Expr *getLHS() const { return getDecomposedForm().LHS; }
334 const Expr *getRHS() const { return getDecomposedForm().RHS; }
335
336 SourceLocation getOperatorLoc() const LLVM_READONLY__attribute__((__pure__)) {
337 return getDecomposedForm().InnerBinOp->getExprLoc();
338 }
339 SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__)) { return getOperatorLoc(); }
340
341 /// Compute the begin and end locations from the decomposed form.
342 /// The locations of the semantic form are not reliable if this is
343 /// a reversed expression.
344 //@{
345 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
346 return getDecomposedForm().LHS->getBeginLoc();
347 }
348 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
349 return getDecomposedForm().RHS->getEndLoc();
350 }
351 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) {
352 DecomposedForm DF = getDecomposedForm();
353 return SourceRange(DF.LHS->getBeginLoc(), DF.RHS->getEndLoc());
354 }
355 //@}
356
357 child_range children() {
358 return child_range(&SemanticForm, &SemanticForm + 1);
359 }
360
361 static bool classof(const Stmt *T) {
362 return T->getStmtClass() == CXXRewrittenBinaryOperatorClass;
363 }
364};
365
366/// Abstract class common to all of the C++ "named"/"keyword" casts.
367///
368/// This abstract class is inherited by all of the classes
369/// representing "named" casts: CXXStaticCastExpr for \c static_cast,
370/// CXXDynamicCastExpr for \c dynamic_cast, CXXReinterpretCastExpr for
371/// reinterpret_cast, CXXConstCastExpr for \c const_cast and
372/// CXXAddrspaceCastExpr for addrspace_cast (in OpenCL).
373class CXXNamedCastExpr : public ExplicitCastExpr {
374private:
375 // the location of the casting op
376 SourceLocation Loc;
377
378 // the location of the right parenthesis
379 SourceLocation RParenLoc;
380
381 // range for '<' '>'
382 SourceRange AngleBrackets;
383
384protected:
385 friend class ASTStmtReader;
386
387 CXXNamedCastExpr(StmtClass SC, QualType ty, ExprValueKind VK, CastKind kind,
388 Expr *op, unsigned PathSize, bool HasFPFeatures,
389 TypeSourceInfo *writtenTy, SourceLocation l,
390 SourceLocation RParenLoc, SourceRange AngleBrackets)
391 : ExplicitCastExpr(SC, ty, VK, kind, op, PathSize, HasFPFeatures,
392 writtenTy),
393 Loc(l), RParenLoc(RParenLoc), AngleBrackets(AngleBrackets) {}
394
395 explicit CXXNamedCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize,
396 bool HasFPFeatures)
397 : ExplicitCastExpr(SC, Shell, PathSize, HasFPFeatures) {}
398
399public:
400 const char *getCastName() const;
401
402 /// Retrieve the location of the cast operator keyword, e.g.,
403 /// \c static_cast.
404 SourceLocation getOperatorLoc() const { return Loc; }
405
406 /// Retrieve the location of the closing parenthesis.
407 SourceLocation getRParenLoc() const { return RParenLoc; }
408
409 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
410 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; }
411 SourceRange getAngleBrackets() const LLVM_READONLY__attribute__((__pure__)) { return AngleBrackets; }
412
413 static bool classof(const Stmt *T) {
414 switch (T->getStmtClass()) {
415 case CXXStaticCastExprClass:
416 case CXXDynamicCastExprClass:
417 case CXXReinterpretCastExprClass:
418 case CXXConstCastExprClass:
419 case CXXAddrspaceCastExprClass:
420 return true;
421 default:
422 return false;
423 }
424 }
425};
426
427/// A C++ \c static_cast expression (C++ [expr.static.cast]).
428///
429/// This expression node represents a C++ static cast, e.g.,
430/// \c static_cast<int>(1.0).
431class CXXStaticCastExpr final
432 : public CXXNamedCastExpr,
433 private llvm::TrailingObjects<CXXStaticCastExpr, CXXBaseSpecifier *,
434 FPOptionsOverride> {
435 CXXStaticCastExpr(QualType ty, ExprValueKind vk, CastKind kind, Expr *op,
436 unsigned pathSize, TypeSourceInfo *writtenTy,
437 FPOptionsOverride FPO, SourceLocation l,
438 SourceLocation RParenLoc, SourceRange AngleBrackets)
439 : CXXNamedCastExpr(CXXStaticCastExprClass, ty, vk, kind, op, pathSize,
440 FPO.requiresTrailingStorage(), writtenTy, l, RParenLoc,
441 AngleBrackets) {
442 if (hasStoredFPFeatures())
443 *getTrailingFPFeatures() = FPO;
444 }
445
446 explicit CXXStaticCastExpr(EmptyShell Empty, unsigned PathSize,
447 bool HasFPFeatures)
448 : CXXNamedCastExpr(CXXStaticCastExprClass, Empty, PathSize,
449 HasFPFeatures) {}
450
451 unsigned numTrailingObjects(OverloadToken<CXXBaseSpecifier *>) const {
452 return path_size();
453 }
454
455public:
456 friend class CastExpr;
457 friend TrailingObjects;
458
459 static CXXStaticCastExpr *
460 Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind K,
461 Expr *Op, const CXXCastPath *Path, TypeSourceInfo *Written,
462 FPOptionsOverride FPO, SourceLocation L, SourceLocation RParenLoc,
463 SourceRange AngleBrackets);
464 static CXXStaticCastExpr *CreateEmpty(const ASTContext &Context,
465 unsigned PathSize, bool hasFPFeatures);
466
467 static bool classof(const Stmt *T) {
468 return T->getStmtClass() == CXXStaticCastExprClass;
469 }
470};
471
472/// A C++ @c dynamic_cast expression (C++ [expr.dynamic.cast]).
473///
474/// This expression node represents a dynamic cast, e.g.,
475/// \c dynamic_cast<Derived*>(BasePtr). Such a cast may perform a run-time
476/// check to determine how to perform the type conversion.
477class CXXDynamicCastExpr final
478 : public CXXNamedCastExpr,
479 private llvm::TrailingObjects<CXXDynamicCastExpr, CXXBaseSpecifier *> {
480 CXXDynamicCastExpr(QualType ty, ExprValueKind VK, CastKind kind, Expr *op,
481 unsigned pathSize, TypeSourceInfo *writtenTy,
482 SourceLocation l, SourceLocation RParenLoc,
483 SourceRange AngleBrackets)
484 : CXXNamedCastExpr(CXXDynamicCastExprClass, ty, VK, kind, op, pathSize,
485 /*HasFPFeatures*/ false, writtenTy, l, RParenLoc,
486 AngleBrackets) {}
487
488 explicit CXXDynamicCastExpr(EmptyShell Empty, unsigned pathSize)
489 : CXXNamedCastExpr(CXXDynamicCastExprClass, Empty, pathSize,
490 /*HasFPFeatures*/ false) {}
491
492public:
493 friend class CastExpr;
494 friend TrailingObjects;
495
496 static CXXDynamicCastExpr *Create(const ASTContext &Context, QualType T,
497 ExprValueKind VK, CastKind Kind, Expr *Op,
498 const CXXCastPath *Path,
499 TypeSourceInfo *Written, SourceLocation L,
500 SourceLocation RParenLoc,
501 SourceRange AngleBrackets);
502
503 static CXXDynamicCastExpr *CreateEmpty(const ASTContext &Context,
504 unsigned pathSize);
505
506 bool isAlwaysNull() const;
507
508 static bool classof(const Stmt *T) {
509 return T->getStmtClass() == CXXDynamicCastExprClass;
510 }
511};
512
513/// A C++ @c reinterpret_cast expression (C++ [expr.reinterpret.cast]).
514///
515/// This expression node represents a reinterpret cast, e.g.,
516/// @c reinterpret_cast<int>(VoidPtr).
517///
518/// A reinterpret_cast provides a differently-typed view of a value but
519/// (in Clang, as in most C++ implementations) performs no actual work at
520/// run time.
521class CXXReinterpretCastExpr final
522 : public CXXNamedCastExpr,
523 private llvm::TrailingObjects<CXXReinterpretCastExpr,
524 CXXBaseSpecifier *> {
525 CXXReinterpretCastExpr(QualType ty, ExprValueKind vk, CastKind kind, Expr *op,
526 unsigned pathSize, TypeSourceInfo *writtenTy,
527 SourceLocation l, SourceLocation RParenLoc,
528 SourceRange AngleBrackets)
529 : CXXNamedCastExpr(CXXReinterpretCastExprClass, ty, vk, kind, op,
530 pathSize, /*HasFPFeatures*/ false, writtenTy, l,
531 RParenLoc, AngleBrackets) {}
532
533 CXXReinterpretCastExpr(EmptyShell Empty, unsigned pathSize)
534 : CXXNamedCastExpr(CXXReinterpretCastExprClass, Empty, pathSize,
535 /*HasFPFeatures*/ false) {}
536
537public:
538 friend class CastExpr;
539 friend TrailingObjects;
540
541 static CXXReinterpretCastExpr *Create(const ASTContext &Context, QualType T,
542 ExprValueKind VK, CastKind Kind,
543 Expr *Op, const CXXCastPath *Path,
544 TypeSourceInfo *WrittenTy, SourceLocation L,
545 SourceLocation RParenLoc,
546 SourceRange AngleBrackets);
547 static CXXReinterpretCastExpr *CreateEmpty(const ASTContext &Context,
548 unsigned pathSize);
549
550 static bool classof(const Stmt *T) {
551 return T->getStmtClass() == CXXReinterpretCastExprClass;
552 }
553};
554
555/// A C++ \c const_cast expression (C++ [expr.const.cast]).
556///
557/// This expression node represents a const cast, e.g.,
558/// \c const_cast<char*>(PtrToConstChar).
559///
560/// A const_cast can remove type qualifiers but does not change the underlying
561/// value.
562class CXXConstCastExpr final
563 : public CXXNamedCastExpr,
564 private llvm::TrailingObjects<CXXConstCastExpr, CXXBaseSpecifier *> {
565 CXXConstCastExpr(QualType ty, ExprValueKind VK, Expr *op,
566 TypeSourceInfo *writtenTy, SourceLocation l,
567 SourceLocation RParenLoc, SourceRange AngleBrackets)
568 : CXXNamedCastExpr(CXXConstCastExprClass, ty, VK, CK_NoOp, op, 0,
569 /*HasFPFeatures*/ false, writtenTy, l, RParenLoc,
570 AngleBrackets) {}
571
572 explicit CXXConstCastExpr(EmptyShell Empty)
573 : CXXNamedCastExpr(CXXConstCastExprClass, Empty, 0,
574 /*HasFPFeatures*/ false) {}
575
576public:
577 friend class CastExpr;
578 friend TrailingObjects;
579
580 static CXXConstCastExpr *Create(const ASTContext &Context, QualType T,
581 ExprValueKind VK, Expr *Op,
582 TypeSourceInfo *WrittenTy, SourceLocation L,
583 SourceLocation RParenLoc,
584 SourceRange AngleBrackets);
585 static CXXConstCastExpr *CreateEmpty(const ASTContext &Context);
586
587 static bool classof(const Stmt *T) {
588 return T->getStmtClass() == CXXConstCastExprClass;
589 }
590};
591
592/// A C++ addrspace_cast expression (currently only enabled for OpenCL).
593///
594/// This expression node represents a cast between pointers to objects in
595/// different address spaces e.g.,
596/// \c addrspace_cast<global int*>(PtrToGenericInt).
597///
598/// A addrspace_cast can cast address space type qualifiers but does not change
599/// the underlying value.
600class CXXAddrspaceCastExpr final
601 : public CXXNamedCastExpr,
602 private llvm::TrailingObjects<CXXAddrspaceCastExpr, CXXBaseSpecifier *> {
603 CXXAddrspaceCastExpr(QualType ty, ExprValueKind VK, CastKind Kind, Expr *op,
604 TypeSourceInfo *writtenTy, SourceLocation l,
605 SourceLocation RParenLoc, SourceRange AngleBrackets)
606 : CXXNamedCastExpr(CXXAddrspaceCastExprClass, ty, VK, Kind, op, 0,
607 /*HasFPFeatures*/ false, writtenTy, l, RParenLoc,
608 AngleBrackets) {}
609
610 explicit CXXAddrspaceCastExpr(EmptyShell Empty)
611 : CXXNamedCastExpr(CXXAddrspaceCastExprClass, Empty, 0,
612 /*HasFPFeatures*/ false) {}
613
614public:
615 friend class CastExpr;
616 friend TrailingObjects;
617
618 static CXXAddrspaceCastExpr *
619 Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind Kind,
620 Expr *Op, TypeSourceInfo *WrittenTy, SourceLocation L,
621 SourceLocation RParenLoc, SourceRange AngleBrackets);
622 static CXXAddrspaceCastExpr *CreateEmpty(const ASTContext &Context);
623
624 static bool classof(const Stmt *T) {
625 return T->getStmtClass() == CXXAddrspaceCastExprClass;
626 }
627};
628
629/// A call to a literal operator (C++11 [over.literal])
630/// written as a user-defined literal (C++11 [lit.ext]).
631///
632/// Represents a user-defined literal, e.g. "foo"_bar or 1.23_xyz. While this
633/// is semantically equivalent to a normal call, this AST node provides better
634/// information about the syntactic representation of the literal.
635///
636/// Since literal operators are never found by ADL and can only be declared at
637/// namespace scope, a user-defined literal is never dependent.
638class UserDefinedLiteral final : public CallExpr {
639 friend class ASTStmtReader;
640 friend class ASTStmtWriter;
641
642 /// The location of a ud-suffix within the literal.
643 SourceLocation UDSuffixLoc;
644
645 // UserDefinedLiteral has some trailing objects belonging
646 // to CallExpr. See CallExpr for the details.
647
648 UserDefinedLiteral(Expr *Fn, ArrayRef<Expr *> Args, QualType Ty,
649 ExprValueKind VK, SourceLocation LitEndLoc,
650 SourceLocation SuffixLoc, FPOptionsOverride FPFeatures);
651
652 UserDefinedLiteral(unsigned NumArgs, bool HasFPFeatures, EmptyShell Empty);
653
654public:
655 static UserDefinedLiteral *Create(const ASTContext &Ctx, Expr *Fn,
656 ArrayRef<Expr *> Args, QualType Ty,
657 ExprValueKind VK, SourceLocation LitEndLoc,
658 SourceLocation SuffixLoc,
659 FPOptionsOverride FPFeatures);
660
661 static UserDefinedLiteral *CreateEmpty(const ASTContext &Ctx,
662 unsigned NumArgs, bool HasFPOptions,
663 EmptyShell Empty);
664
665 /// The kind of literal operator which is invoked.
666 enum LiteralOperatorKind {
667 /// Raw form: operator "" X (const char *)
668 LOK_Raw,
669
670 /// Raw form: operator "" X<cs...> ()
671 LOK_Template,
672
673 /// operator "" X (unsigned long long)
674 LOK_Integer,
675
676 /// operator "" X (long double)
677 LOK_Floating,
678
679 /// operator "" X (const CharT *, size_t)
680 LOK_String,
681
682 /// operator "" X (CharT)
683 LOK_Character
684 };
685
686 /// Returns the kind of literal operator invocation
687 /// which this expression represents.
688 LiteralOperatorKind getLiteralOperatorKind() const;
689
690 /// If this is not a raw user-defined literal, get the
691 /// underlying cooked literal (representing the literal with the suffix
692 /// removed).
693 Expr *getCookedLiteral();
694 const Expr *getCookedLiteral() const {
695 return const_cast<UserDefinedLiteral*>(this)->getCookedLiteral();
696 }
697
698 SourceLocation getBeginLoc() const {
699 if (getLiteralOperatorKind() == LOK_Template)
700 return getRParenLoc();
701 return getArg(0)->getBeginLoc();
702 }
703
704 SourceLocation getEndLoc() const { return getRParenLoc(); }
705
706 /// Returns the location of a ud-suffix in the expression.
707 ///
708 /// For a string literal, there may be multiple identical suffixes. This
709 /// returns the first.
710 SourceLocation getUDSuffixLoc() const { return UDSuffixLoc; }
711
712 /// Returns the ud-suffix specified for this literal.
713 const IdentifierInfo *getUDSuffix() const;
714
715 static bool classof(const Stmt *S) {
716 return S->getStmtClass() == UserDefinedLiteralClass;
717 }
718};
719
720/// A boolean literal, per ([C++ lex.bool] Boolean literals).
721class CXXBoolLiteralExpr : public Expr {
722public:
723 CXXBoolLiteralExpr(bool Val, QualType Ty, SourceLocation Loc)
724 : Expr(CXXBoolLiteralExprClass, Ty, VK_PRValue, OK_Ordinary) {
725 CXXBoolLiteralExprBits.Value = Val;
726 CXXBoolLiteralExprBits.Loc = Loc;
727 setDependence(ExprDependence::None);
728 }
729
730 explicit CXXBoolLiteralExpr(EmptyShell Empty)
731 : Expr(CXXBoolLiteralExprClass, Empty) {}
732
733 bool getValue() const { return CXXBoolLiteralExprBits.Value; }
734 void setValue(bool V) { CXXBoolLiteralExprBits.Value = V; }
735
736 SourceLocation getBeginLoc() const { return getLocation(); }
737 SourceLocation getEndLoc() const { return getLocation(); }
738
739 SourceLocation getLocation() const { return CXXBoolLiteralExprBits.Loc; }
740 void setLocation(SourceLocation L) { CXXBoolLiteralExprBits.Loc = L; }
741
742 static bool classof(const Stmt *T) {
743 return T->getStmtClass() == CXXBoolLiteralExprClass;
744 }
745
746 // Iterators
747 child_range children() {
748 return child_range(child_iterator(), child_iterator());
749 }
750
751 const_child_range children() const {
752 return const_child_range(const_child_iterator(), const_child_iterator());
753 }
754};
755
756/// The null pointer literal (C++11 [lex.nullptr])
757///
758/// Introduced in C++11, the only literal of type \c nullptr_t is \c nullptr.
759class CXXNullPtrLiteralExpr : public Expr {
760public:
761 CXXNullPtrLiteralExpr(QualType Ty, SourceLocation Loc)
762 : Expr(CXXNullPtrLiteralExprClass, Ty, VK_PRValue, OK_Ordinary) {
763 CXXNullPtrLiteralExprBits.Loc = Loc;
764 setDependence(ExprDependence::None);
765 }
766
767 explicit CXXNullPtrLiteralExpr(EmptyShell Empty)
768 : Expr(CXXNullPtrLiteralExprClass, Empty) {}
769
770 SourceLocation getBeginLoc() const { return getLocation(); }
771 SourceLocation getEndLoc() const { return getLocation(); }
772
773 SourceLocation getLocation() const { return CXXNullPtrLiteralExprBits.Loc; }
774 void setLocation(SourceLocation L) { CXXNullPtrLiteralExprBits.Loc = L; }
775
776 static bool classof(const Stmt *T) {
777 return T->getStmtClass() == CXXNullPtrLiteralExprClass;
778 }
779
780 child_range children() {
781 return child_range(child_iterator(), child_iterator());
782 }
783
784 const_child_range children() const {
785 return const_child_range(const_child_iterator(), const_child_iterator());
786 }
787};
788
789/// Implicit construction of a std::initializer_list<T> object from an
790/// array temporary within list-initialization (C++11 [dcl.init.list]p5).
791class CXXStdInitializerListExpr : public Expr {
792 Stmt *SubExpr = nullptr;
793
794 CXXStdInitializerListExpr(EmptyShell Empty)
795 : Expr(CXXStdInitializerListExprClass, Empty) {}
796
797public:
798 friend class ASTReader;
799 friend class ASTStmtReader;
800
801 CXXStdInitializerListExpr(QualType Ty, Expr *SubExpr)
802 : Expr(CXXStdInitializerListExprClass, Ty, VK_PRValue, OK_Ordinary),
803 SubExpr(SubExpr) {
804 setDependence(computeDependence(this));
805 }
806
807 Expr *getSubExpr() { return static_cast<Expr*>(SubExpr); }
808 const Expr *getSubExpr() const { return static_cast<const Expr*>(SubExpr); }
809
810 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
811 return SubExpr->getBeginLoc();
812 }
813
814 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
815 return SubExpr->getEndLoc();
816 }
817
818 /// Retrieve the source range of the expression.
819 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) {
820 return SubExpr->getSourceRange();
821 }
822
823 static bool classof(const Stmt *S) {
824 return S->getStmtClass() == CXXStdInitializerListExprClass;
825 }
826
827 child_range children() { return child_range(&SubExpr, &SubExpr + 1); }
828
829 const_child_range children() const {
830 return const_child_range(&SubExpr, &SubExpr + 1);
831 }
832};
833
834/// A C++ \c typeid expression (C++ [expr.typeid]), which gets
835/// the \c type_info that corresponds to the supplied type, or the (possibly
836/// dynamic) type of the supplied expression.
837///
838/// This represents code like \c typeid(int) or \c typeid(*objPtr)
839class CXXTypeidExpr : public Expr {
840 friend class ASTStmtReader;
841
842private:
843 llvm::PointerUnion<Stmt *, TypeSourceInfo *> Operand;
844 SourceRange Range;
845
846public:
847 CXXTypeidExpr(QualType Ty, TypeSourceInfo *Operand, SourceRange R)
848 : Expr(CXXTypeidExprClass, Ty, VK_LValue, OK_Ordinary), Operand(Operand),
849 Range(R) {
850 setDependence(computeDependence(this));
851 }
852
853 CXXTypeidExpr(QualType Ty, Expr *Operand, SourceRange R)
854 : Expr(CXXTypeidExprClass, Ty, VK_LValue, OK_Ordinary), Operand(Operand),
855 Range(R) {
856 setDependence(computeDependence(this));
857 }
858
859 CXXTypeidExpr(EmptyShell Empty, bool isExpr)
860 : Expr(CXXTypeidExprClass, Empty) {
861 if (isExpr)
862 Operand = (Expr*)nullptr;
863 else
864 Operand = (TypeSourceInfo*)nullptr;
865 }
866
867 /// Determine whether this typeid has a type operand which is potentially
868 /// evaluated, per C++11 [expr.typeid]p3.
869 bool isPotentiallyEvaluated() const;
870
871 /// Best-effort check if the expression operand refers to a most derived
872 /// object. This is not a strong guarantee.
873 bool isMostDerived(ASTContext &Context) const;
874
875 bool isTypeOperand() const { return Operand.is<TypeSourceInfo *>(); }
876
877 /// Retrieves the type operand of this typeid() expression after
878 /// various required adjustments (removing reference types, cv-qualifiers).
879 QualType getTypeOperand(ASTContext &Context) const;
880
881 /// Retrieve source information for the type operand.
882 TypeSourceInfo *getTypeOperandSourceInfo() const {
883 assert(isTypeOperand() && "Cannot call getTypeOperand for typeid(expr)")(static_cast<void> (0));
884 return Operand.get<TypeSourceInfo *>();
885 }
886 Expr *getExprOperand() const {
887 assert(!isTypeOperand() && "Cannot call getExprOperand for typeid(type)")(static_cast<void> (0));
888 return static_cast<Expr*>(Operand.get<Stmt *>());
889 }
890
891 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getBegin(); }
892 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getEnd(); }
893 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) { return Range; }
894 void setSourceRange(SourceRange R) { Range = R; }
895
896 static bool classof(const Stmt *T) {
897 return T->getStmtClass() == CXXTypeidExprClass;
898 }
899
900 // Iterators
901 child_range children() {
902 if (isTypeOperand())
903 return child_range(child_iterator(), child_iterator());
904 auto **begin = reinterpret_cast<Stmt **>(&Operand);
905 return child_range(begin, begin + 1);
906 }
907
908 const_child_range children() const {
909 if (isTypeOperand())
910 return const_child_range(const_child_iterator(), const_child_iterator());
911
912 auto **begin =
913 reinterpret_cast<Stmt **>(&const_cast<CXXTypeidExpr *>(this)->Operand);
914 return const_child_range(begin, begin + 1);
915 }
916};
917
918/// A member reference to an MSPropertyDecl.
919///
920/// This expression always has pseudo-object type, and therefore it is
921/// typically not encountered in a fully-typechecked expression except
922/// within the syntactic form of a PseudoObjectExpr.
923class MSPropertyRefExpr : public Expr {
924 Expr *BaseExpr;
925 MSPropertyDecl *TheDecl;
926 SourceLocation MemberLoc;
927 bool IsArrow;
928 NestedNameSpecifierLoc QualifierLoc;
929
930public:
931 friend class ASTStmtReader;
932
933 MSPropertyRefExpr(Expr *baseExpr, MSPropertyDecl *decl, bool isArrow,
934 QualType ty, ExprValueKind VK,
935 NestedNameSpecifierLoc qualifierLoc, SourceLocation nameLoc)
936 : Expr(MSPropertyRefExprClass, ty, VK, OK_Ordinary), BaseExpr(baseExpr),
937 TheDecl(decl), MemberLoc(nameLoc), IsArrow(isArrow),
938 QualifierLoc(qualifierLoc) {
939 setDependence(computeDependence(this));
940 }
941
942 MSPropertyRefExpr(EmptyShell Empty) : Expr(MSPropertyRefExprClass, Empty) {}
943
944 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) {
945 return SourceRange(getBeginLoc(), getEndLoc());
946 }
947
948 bool isImplicitAccess() const {
949 return getBaseExpr() && getBaseExpr()->isImplicitCXXThis();
950 }
951
952 SourceLocation getBeginLoc() const {
953 if (!isImplicitAccess())
954 return BaseExpr->getBeginLoc();
955 else if (QualifierLoc)
956 return QualifierLoc.getBeginLoc();
957 else
958 return MemberLoc;
959 }
960
961 SourceLocation getEndLoc() const { return getMemberLoc(); }
962
963 child_range children() {
964 return child_range((Stmt**)&BaseExpr, (Stmt**)&BaseExpr + 1);
965 }
966
967 const_child_range children() const {
968 auto Children = const_cast<MSPropertyRefExpr *>(this)->children();
969 return const_child_range(Children.begin(), Children.end());
970 }
971
972 static bool classof(const Stmt *T) {
973 return T->getStmtClass() == MSPropertyRefExprClass;
974 }
975
976 Expr *getBaseExpr() const { return BaseExpr; }
977 MSPropertyDecl *getPropertyDecl() const { return TheDecl; }
978 bool isArrow() const { return IsArrow; }
979 SourceLocation getMemberLoc() const { return MemberLoc; }
980 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
981};
982
983/// MS property subscript expression.
984/// MSVC supports 'property' attribute and allows to apply it to the
985/// declaration of an empty array in a class or structure definition.
986/// For example:
987/// \code
988/// __declspec(property(get=GetX, put=PutX)) int x[];
989/// \endcode
990/// The above statement indicates that x[] can be used with one or more array
991/// indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), and
992/// p->x[a][b] = i will be turned into p->PutX(a, b, i).
993/// This is a syntactic pseudo-object expression.
994class MSPropertySubscriptExpr : public Expr {
995 friend class ASTStmtReader;
996
997 enum { BASE_EXPR, IDX_EXPR, NUM_SUBEXPRS = 2 };
998
999 Stmt *SubExprs[NUM_SUBEXPRS];
1000 SourceLocation RBracketLoc;
1001
1002 void setBase(Expr *Base) { SubExprs[BASE_EXPR] = Base; }
1003 void setIdx(Expr *Idx) { SubExprs[IDX_EXPR] = Idx; }
1004
1005public:
1006 MSPropertySubscriptExpr(Expr *Base, Expr *Idx, QualType Ty, ExprValueKind VK,
1007 ExprObjectKind OK, SourceLocation RBracketLoc)
1008 : Expr(MSPropertySubscriptExprClass, Ty, VK, OK),
1009 RBracketLoc(RBracketLoc) {
1010 SubExprs[BASE_EXPR] = Base;
1011 SubExprs[IDX_EXPR] = Idx;
1012 setDependence(computeDependence(this));
1013 }
1014
1015 /// Create an empty array subscript expression.
1016 explicit MSPropertySubscriptExpr(EmptyShell Shell)
1017 : Expr(MSPropertySubscriptExprClass, Shell) {}
1018
1019 Expr *getBase() { return cast<Expr>(SubExprs[BASE_EXPR]); }
1020 const Expr *getBase() const { return cast<Expr>(SubExprs[BASE_EXPR]); }
1021
1022 Expr *getIdx() { return cast<Expr>(SubExprs[IDX_EXPR]); }
1023 const Expr *getIdx() const { return cast<Expr>(SubExprs[IDX_EXPR]); }
1024
1025 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
1026 return getBase()->getBeginLoc();
1027 }
1028
1029 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RBracketLoc; }
1030
1031 SourceLocation getRBracketLoc() const { return RBracketLoc; }
1032 void setRBracketLoc(SourceLocation L) { RBracketLoc = L; }
1033
1034 SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__)) {
1035 return getBase()->getExprLoc();
1036 }
1037
1038 static bool classof(const Stmt *T) {
1039 return T->getStmtClass() == MSPropertySubscriptExprClass;
1040 }
1041
1042 // Iterators
1043 child_range children() {
1044 return child_range(&SubExprs[0], &SubExprs[0] + NUM_SUBEXPRS);
1045 }
1046
1047 const_child_range children() const {
1048 return const_child_range(&SubExprs[0], &SubExprs[0] + NUM_SUBEXPRS);
1049 }
1050};
1051
1052/// A Microsoft C++ @c __uuidof expression, which gets
1053/// the _GUID that corresponds to the supplied type or expression.
1054///
1055/// This represents code like @c __uuidof(COMTYPE) or @c __uuidof(*comPtr)
1056class CXXUuidofExpr : public Expr {
1057 friend class ASTStmtReader;
1058
1059private:
1060 llvm::PointerUnion<Stmt *, TypeSourceInfo *> Operand;
1061 MSGuidDecl *Guid;
1062 SourceRange Range;
1063
1064public:
1065 CXXUuidofExpr(QualType Ty, TypeSourceInfo *Operand, MSGuidDecl *Guid,
1066 SourceRange R)
1067 : Expr(CXXUuidofExprClass, Ty, VK_LValue, OK_Ordinary), Operand(Operand),
1068 Guid(Guid), Range(R) {
1069 setDependence(computeDependence(this));
1070 }
1071
1072 CXXUuidofExpr(QualType Ty, Expr *Operand, MSGuidDecl *Guid, SourceRange R)
1073 : Expr(CXXUuidofExprClass, Ty, VK_LValue, OK_Ordinary), Operand(Operand),
1074 Guid(Guid), Range(R) {
1075 setDependence(computeDependence(this));
1076 }
1077
1078 CXXUuidofExpr(EmptyShell Empty, bool isExpr)
1079 : Expr(CXXUuidofExprClass, Empty) {
1080 if (isExpr)
1081 Operand = (Expr*)nullptr;
1082 else
1083 Operand = (TypeSourceInfo*)nullptr;
1084 }
1085
1086 bool isTypeOperand() const { return Operand.is<TypeSourceInfo *>(); }
1087
1088 /// Retrieves the type operand of this __uuidof() expression after
1089 /// various required adjustments (removing reference types, cv-qualifiers).
1090 QualType getTypeOperand(ASTContext &Context) const;
1091
1092 /// Retrieve source information for the type operand.
1093 TypeSourceInfo *getTypeOperandSourceInfo() const {
1094 assert(isTypeOperand() && "Cannot call getTypeOperand for __uuidof(expr)")(static_cast<void> (0));
1095 return Operand.get<TypeSourceInfo *>();
1096 }
1097 Expr *getExprOperand() const {
1098 assert(!isTypeOperand() && "Cannot call getExprOperand for __uuidof(type)")(static_cast<void> (0));
1099 return static_cast<Expr*>(Operand.get<Stmt *>());
1100 }
1101
1102 MSGuidDecl *getGuidDecl() const { return Guid; }
1103
1104 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getBegin(); }
1105 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getEnd(); }
1106 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) { return Range; }
1107 void setSourceRange(SourceRange R) { Range = R; }
1108
1109 static bool classof(const Stmt *T) {
1110 return T->getStmtClass() == CXXUuidofExprClass;
1111 }
1112
1113 // Iterators
1114 child_range children() {
1115 if (isTypeOperand())
1116 return child_range(child_iterator(), child_iterator());
1117 auto **begin = reinterpret_cast<Stmt **>(&Operand);
1118 return child_range(begin, begin + 1);
1119 }
1120
1121 const_child_range children() const {
1122 if (isTypeOperand())
1123 return const_child_range(const_child_iterator(), const_child_iterator());
1124 auto **begin =
1125 reinterpret_cast<Stmt **>(&const_cast<CXXUuidofExpr *>(this)->Operand);
1126 return const_child_range(begin, begin + 1);
1127 }
1128};
1129
1130/// Represents the \c this expression in C++.
1131///
1132/// This is a pointer to the object on which the current member function is
1133/// executing (C++ [expr.prim]p3). Example:
1134///
1135/// \code
1136/// class Foo {
1137/// public:
1138/// void bar();
1139/// void test() { this->bar(); }
1140/// };
1141/// \endcode
1142class CXXThisExpr : public Expr {
1143public:
1144 CXXThisExpr(SourceLocation L, QualType Ty, bool IsImplicit)
1145 : Expr(CXXThisExprClass, Ty, VK_PRValue, OK_Ordinary) {
1146 CXXThisExprBits.IsImplicit = IsImplicit;
1147 CXXThisExprBits.Loc = L;
1148 setDependence(computeDependence(this));
1149 }
1150
1151 CXXThisExpr(EmptyShell Empty) : Expr(CXXThisExprClass, Empty) {}
1152
1153 SourceLocation getLocation() const { return CXXThisExprBits.Loc; }
1154 void setLocation(SourceLocation L) { CXXThisExprBits.Loc = L; }
1155
1156 SourceLocation getBeginLoc() const { return getLocation(); }
1157 SourceLocation getEndLoc() const { return getLocation(); }
1158
1159 bool isImplicit() const { return CXXThisExprBits.IsImplicit; }
1160 void setImplicit(bool I) { CXXThisExprBits.IsImplicit = I; }
1161
1162 static bool classof(const Stmt *T) {
1163 return T->getStmtClass() == CXXThisExprClass;
1164 }
1165
1166 // Iterators
1167 child_range children() {
1168 return child_range(child_iterator(), child_iterator());
1169 }
1170
1171 const_child_range children() const {
1172 return const_child_range(const_child_iterator(), const_child_iterator());
1173 }
1174};
1175
1176/// A C++ throw-expression (C++ [except.throw]).
1177///
1178/// This handles 'throw' (for re-throwing the current exception) and
1179/// 'throw' assignment-expression. When assignment-expression isn't
1180/// present, Op will be null.
1181class CXXThrowExpr : public Expr {
1182 friend class ASTStmtReader;
1183
1184 /// The optional expression in the throw statement.
1185 Stmt *Operand;
1186
1187public:
1188 // \p Ty is the void type which is used as the result type of the
1189 // expression. The \p Loc is the location of the throw keyword.
1190 // \p Operand is the expression in the throw statement, and can be
1191 // null if not present.
1192 CXXThrowExpr(Expr *Operand, QualType Ty, SourceLocation Loc,
1193 bool IsThrownVariableInScope)
1194 : Expr(CXXThrowExprClass, Ty, VK_PRValue, OK_Ordinary), Operand(Operand) {
1195 CXXThrowExprBits.ThrowLoc = Loc;
1196 CXXThrowExprBits.IsThrownVariableInScope = IsThrownVariableInScope;
1197 setDependence(computeDependence(this));
1198 }
1199 CXXThrowExpr(EmptyShell Empty) : Expr(CXXThrowExprClass, Empty) {}
1200
1201 const Expr *getSubExpr() const { return cast_or_null<Expr>(Operand); }
1202 Expr *getSubExpr() { return cast_or_null<Expr>(Operand); }
1203
1204 SourceLocation getThrowLoc() const { return CXXThrowExprBits.ThrowLoc; }
1205
1206 /// Determines whether the variable thrown by this expression (if any!)
1207 /// is within the innermost try block.
1208 ///
1209 /// This information is required to determine whether the NRVO can apply to
1210 /// this variable.
1211 bool isThrownVariableInScope() const {
1212 return CXXThrowExprBits.IsThrownVariableInScope;
1213 }
1214
1215 SourceLocation getBeginLoc() const { return getThrowLoc(); }
1216 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
1217 if (!getSubExpr())
1218 return getThrowLoc();
1219 return getSubExpr()->getEndLoc();
1220 }
1221
1222 static bool classof(const Stmt *T) {
1223 return T->getStmtClass() == CXXThrowExprClass;
1224 }
1225
1226 // Iterators
1227 child_range children() {
1228 return child_range(&Operand, Operand ? &Operand + 1 : &Operand);
1229 }
1230
1231 const_child_range children() const {
1232 return const_child_range(&Operand, Operand ? &Operand + 1 : &Operand);
1233 }
1234};
1235
1236/// A default argument (C++ [dcl.fct.default]).
1237///
1238/// This wraps up a function call argument that was created from the
1239/// corresponding parameter's default argument, when the call did not
1240/// explicitly supply arguments for all of the parameters.
1241class CXXDefaultArgExpr final : public Expr {
1242 friend class ASTStmtReader;
1243
1244 /// The parameter whose default is being used.
1245 ParmVarDecl *Param;
1246
1247 /// The context where the default argument expression was used.
1248 DeclContext *UsedContext;
1249
1250 CXXDefaultArgExpr(StmtClass SC, SourceLocation Loc, ParmVarDecl *Param,
1251 DeclContext *UsedContext)
1252 : Expr(SC,
1253 Param->hasUnparsedDefaultArg()
1254 ? Param->getType().getNonReferenceType()
1255 : Param->getDefaultArg()->getType(),
1256 Param->getDefaultArg()->getValueKind(),
1257 Param->getDefaultArg()->getObjectKind()),
1258 Param(Param), UsedContext(UsedContext) {
1259 CXXDefaultArgExprBits.Loc = Loc;
1260 setDependence(computeDependence(this));
1261 }
1262
1263public:
1264 CXXDefaultArgExpr(EmptyShell Empty) : Expr(CXXDefaultArgExprClass, Empty) {}
1265
1266 // \p Param is the parameter whose default argument is used by this
1267 // expression.
1268 static CXXDefaultArgExpr *Create(const ASTContext &C, SourceLocation Loc,
1269 ParmVarDecl *Param,
1270 DeclContext *UsedContext) {
1271 return new (C)
1272 CXXDefaultArgExpr(CXXDefaultArgExprClass, Loc, Param, UsedContext);
1273 }
1274
1275 // Retrieve the parameter that the argument was created from.
1276 const ParmVarDecl *getParam() const { return Param; }
1277 ParmVarDecl *getParam() { return Param; }
1278
1279 // Retrieve the actual argument to the function call.
1280 const Expr *getExpr() const { return getParam()->getDefaultArg(); }
1281 Expr *getExpr() { return getParam()->getDefaultArg(); }
1282
1283 const DeclContext *getUsedContext() const { return UsedContext; }
1284 DeclContext *getUsedContext() { return UsedContext; }
1285
1286 /// Retrieve the location where this default argument was actually used.
1287 SourceLocation getUsedLocation() const { return CXXDefaultArgExprBits.Loc; }
1288
1289 /// Default argument expressions have no representation in the
1290 /// source, so they have an empty source range.
1291 SourceLocation getBeginLoc() const { return SourceLocation(); }
1292 SourceLocation getEndLoc() const { return SourceLocation(); }
1293
1294 SourceLocation getExprLoc() const { return getUsedLocation(); }
1295
1296 static bool classof(const Stmt *T) {
1297 return T->getStmtClass() == CXXDefaultArgExprClass;
1298 }
1299
1300 // Iterators
1301 child_range children() {
1302 return child_range(child_iterator(), child_iterator());
1303 }
1304
1305 const_child_range children() const {
1306 return const_child_range(const_child_iterator(), const_child_iterator());
1307 }
1308};
1309
1310/// A use of a default initializer in a constructor or in aggregate
1311/// initialization.
1312///
1313/// This wraps a use of a C++ default initializer (technically,
1314/// a brace-or-equal-initializer for a non-static data member) when it
1315/// is implicitly used in a mem-initializer-list in a constructor
1316/// (C++11 [class.base.init]p8) or in aggregate initialization
1317/// (C++1y [dcl.init.aggr]p7).
1318class CXXDefaultInitExpr : public Expr {
1319 friend class ASTReader;
1320 friend class ASTStmtReader;
1321
1322 /// The field whose default is being used.
1323 FieldDecl *Field;
1324
1325 /// The context where the default initializer expression was used.
1326 DeclContext *UsedContext;
1327
1328 CXXDefaultInitExpr(const ASTContext &Ctx, SourceLocation Loc,
1329 FieldDecl *Field, QualType Ty, DeclContext *UsedContext);
1330
1331 CXXDefaultInitExpr(EmptyShell Empty) : Expr(CXXDefaultInitExprClass, Empty) {}
1332
1333public:
1334 /// \p Field is the non-static data member whose default initializer is used
1335 /// by this expression.
1336 static CXXDefaultInitExpr *Create(const ASTContext &Ctx, SourceLocation Loc,
1337 FieldDecl *Field, DeclContext *UsedContext) {
1338 return new (Ctx) CXXDefaultInitExpr(Ctx, Loc, Field, Field->getType(), UsedContext);
1339 }
1340
1341 /// Get the field whose initializer will be used.
1342 FieldDecl *getField() { return Field; }
1343 const FieldDecl *getField() const { return Field; }
1344
1345 /// Get the initialization expression that will be used.
1346 const Expr *getExpr() const {
1347 assert(Field->getInClassInitializer() && "initializer hasn't been parsed")(static_cast<void> (0));
1348 return Field->getInClassInitializer();
1349 }
1350 Expr *getExpr() {
1351 assert(Field->getInClassInitializer() && "initializer hasn't been parsed")(static_cast<void> (0));
1352 return Field->getInClassInitializer();
1353 }
1354
1355 const DeclContext *getUsedContext() const { return UsedContext; }
1356 DeclContext *getUsedContext() { return UsedContext; }
1357
1358 /// Retrieve the location where this default initializer expression was
1359 /// actually used.
1360 SourceLocation getUsedLocation() const { return getBeginLoc(); }
1361
1362 SourceLocation getBeginLoc() const { return CXXDefaultInitExprBits.Loc; }
1363 SourceLocation getEndLoc() const { return CXXDefaultInitExprBits.Loc; }
1364
1365 static bool classof(const Stmt *T) {
1366 return T->getStmtClass() == CXXDefaultInitExprClass;
1367 }
1368
1369 // Iterators
1370 child_range children() {
1371 return child_range(child_iterator(), child_iterator());
1372 }
1373
1374 const_child_range children() const {
1375 return const_child_range(const_child_iterator(), const_child_iterator());
1376 }
1377};
1378
1379/// Represents a C++ temporary.
1380class CXXTemporary {
1381 /// The destructor that needs to be called.
1382 const CXXDestructorDecl *Destructor;
1383
1384 explicit CXXTemporary(const CXXDestructorDecl *destructor)
1385 : Destructor(destructor) {}
1386
1387public:
1388 static CXXTemporary *Create(const ASTContext &C,
1389 const CXXDestructorDecl *Destructor);
1390
1391 const CXXDestructorDecl *getDestructor() const { return Destructor; }
1392
1393 void setDestructor(const CXXDestructorDecl *Dtor) {
1394 Destructor = Dtor;
1395 }
1396};
1397
1398/// Represents binding an expression to a temporary.
1399///
1400/// This ensures the destructor is called for the temporary. It should only be
1401/// needed for non-POD, non-trivially destructable class types. For example:
1402///
1403/// \code
1404/// struct S {
1405/// S() { } // User defined constructor makes S non-POD.
1406/// ~S() { } // User defined destructor makes it non-trivial.
1407/// };
1408/// void test() {
1409/// const S &s_ref = S(); // Requires a CXXBindTemporaryExpr.
1410/// }
1411/// \endcode
1412class CXXBindTemporaryExpr : public Expr {
1413 CXXTemporary *Temp = nullptr;
1414 Stmt *SubExpr = nullptr;
1415
1416 CXXBindTemporaryExpr(CXXTemporary *temp, Expr *SubExpr)
1417 : Expr(CXXBindTemporaryExprClass, SubExpr->getType(), VK_PRValue,
1418 OK_Ordinary),
1419 Temp(temp), SubExpr(SubExpr) {
1420 setDependence(computeDependence(this));
1421 }
1422
1423public:
1424 CXXBindTemporaryExpr(EmptyShell Empty)
1425 : Expr(CXXBindTemporaryExprClass, Empty) {}
1426
1427 static CXXBindTemporaryExpr *Create(const ASTContext &C, CXXTemporary *Temp,
1428 Expr* SubExpr);
1429
1430 CXXTemporary *getTemporary() { return Temp; }
1431 const CXXTemporary *getTemporary() const { return Temp; }
1432 void setTemporary(CXXTemporary *T) { Temp = T; }
1433
1434 const Expr *getSubExpr() const { return cast<Expr>(SubExpr); }
1435 Expr *getSubExpr() { return cast<Expr>(SubExpr); }
1436 void setSubExpr(Expr *E) { SubExpr = E; }
1437
1438 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
1439 return SubExpr->getBeginLoc();
1440 }
1441
1442 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
1443 return SubExpr->getEndLoc();
1444 }
1445
1446 // Implement isa/cast/dyncast/etc.
1447 static bool classof(const Stmt *T) {
1448 return T->getStmtClass() == CXXBindTemporaryExprClass;
1449 }
1450
1451 // Iterators
1452 child_range children() { return child_range(&SubExpr, &SubExpr + 1); }
1453
1454 const_child_range children() const {
1455 return const_child_range(&SubExpr, &SubExpr + 1);
1456 }
1457};
1458
1459/// Represents a call to a C++ constructor.
1460class CXXConstructExpr : public Expr {
1461 friend class ASTStmtReader;
1462
1463public:
1464 enum ConstructionKind {
1465 CK_Complete,
1466 CK_NonVirtualBase,
1467 CK_VirtualBase,
1468 CK_Delegating
1469 };
1470
1471private:
1472 /// A pointer to the constructor which will be ultimately called.
1473 CXXConstructorDecl *Constructor;
1474
1475 SourceRange ParenOrBraceRange;
1476
1477 /// The number of arguments.
1478 unsigned NumArgs;
1479
1480 // We would like to stash the arguments of the constructor call after
1481 // CXXConstructExpr. However CXXConstructExpr is used as a base class of
1482 // CXXTemporaryObjectExpr which makes the use of llvm::TrailingObjects
1483 // impossible.
1484 //
1485 // Instead we manually stash the trailing object after the full object
1486 // containing CXXConstructExpr (that is either CXXConstructExpr or
1487 // CXXTemporaryObjectExpr).
1488 //
1489 // The trailing objects are:
1490 //
1491 // * An array of getNumArgs() "Stmt *" for the arguments of the
1492 // constructor call.
1493
1494 /// Return a pointer to the start of the trailing arguments.
1495 /// Defined just after CXXTemporaryObjectExpr.
1496 inline Stmt **getTrailingArgs();
1497 const Stmt *const *getTrailingArgs() const {
1498 return const_cast<CXXConstructExpr *>(this)->getTrailingArgs();
1499 }
1500
1501protected:
1502 /// Build a C++ construction expression.
1503 CXXConstructExpr(StmtClass SC, QualType Ty, SourceLocation Loc,
1504 CXXConstructorDecl *Ctor, bool Elidable,
1505 ArrayRef<Expr *> Args, bool HadMultipleCandidates,
1506 bool ListInitialization, bool StdInitListInitialization,
1507 bool ZeroInitialization, ConstructionKind ConstructKind,
1508 SourceRange ParenOrBraceRange);
1509
1510 /// Build an empty C++ construction expression.
1511 CXXConstructExpr(StmtClass SC, EmptyShell Empty, unsigned NumArgs);
1512
1513 /// Return the size in bytes of the trailing objects. Used by
1514 /// CXXTemporaryObjectExpr to allocate the right amount of storage.
1515 static unsigned sizeOfTrailingObjects(unsigned NumArgs) {
1516 return NumArgs * sizeof(Stmt *);
1517 }
1518
1519public:
1520 /// Create a C++ construction expression.
1521 static CXXConstructExpr *
1522 Create(const ASTContext &Ctx, QualType Ty, SourceLocation Loc,
1523 CXXConstructorDecl *Ctor, bool Elidable, ArrayRef<Expr *> Args,
1524 bool HadMultipleCandidates, bool ListInitialization,
1525 bool StdInitListInitialization, bool ZeroInitialization,
1526 ConstructionKind ConstructKind, SourceRange ParenOrBraceRange);
1527
1528 /// Create an empty C++ construction expression.
1529 static CXXConstructExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumArgs);
1530
1531 /// Get the constructor that this expression will (ultimately) call.
1532 CXXConstructorDecl *getConstructor() const { return Constructor; }
1533
1534 SourceLocation getLocation() const { return CXXConstructExprBits.Loc; }
1535 void setLocation(SourceLocation Loc) { CXXConstructExprBits.Loc = Loc; }
1536
1537 /// Whether this construction is elidable.
1538 bool isElidable() const { return CXXConstructExprBits.Elidable; }
1539 void setElidable(bool E) { CXXConstructExprBits.Elidable = E; }
1540
1541 /// Whether the referred constructor was resolved from
1542 /// an overloaded set having size greater than 1.
1543 bool hadMultipleCandidates() const {
1544 return CXXConstructExprBits.HadMultipleCandidates;
1545 }
1546 void setHadMultipleCandidates(bool V) {
1547 CXXConstructExprBits.HadMultipleCandidates = V;
1548 }
1549
1550 /// Whether this constructor call was written as list-initialization.
1551 bool isListInitialization() const {
1552 return CXXConstructExprBits.ListInitialization;
1553 }
1554 void setListInitialization(bool V) {
1555 CXXConstructExprBits.ListInitialization = V;
1556 }
1557
1558 /// Whether this constructor call was written as list-initialization,
1559 /// but was interpreted as forming a std::initializer_list<T> from the list
1560 /// and passing that as a single constructor argument.
1561 /// See C++11 [over.match.list]p1 bullet 1.
1562 bool isStdInitListInitialization() const {
1563 return CXXConstructExprBits.StdInitListInitialization;
1564 }
1565 void setStdInitListInitialization(bool V) {
1566 CXXConstructExprBits.StdInitListInitialization = V;
1567 }
1568
1569 /// Whether this construction first requires
1570 /// zero-initialization before the initializer is called.
1571 bool requiresZeroInitialization() const {
1572 return CXXConstructExprBits.ZeroInitialization;
1573 }
1574 void setRequiresZeroInitialization(bool ZeroInit) {
1575 CXXConstructExprBits.ZeroInitialization = ZeroInit;
1576 }
1577
1578 /// Determine whether this constructor is actually constructing
1579 /// a base class (rather than a complete object).
1580 ConstructionKind getConstructionKind() const {
1581 return static_cast<ConstructionKind>(CXXConstructExprBits.ConstructionKind);
1582 }
1583 void setConstructionKind(ConstructionKind CK) {
1584 CXXConstructExprBits.ConstructionKind = CK;
1585 }
1586
1587 using arg_iterator = ExprIterator;
1588 using const_arg_iterator = ConstExprIterator;
1589 using arg_range = llvm::iterator_range<arg_iterator>;
1590 using const_arg_range = llvm::iterator_range<const_arg_iterator>;
1591
1592 arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
1593 const_arg_range arguments() const {
1594 return const_arg_range(arg_begin(), arg_end());
1595 }
1596
1597 arg_iterator arg_begin() { return getTrailingArgs(); }
1598 arg_iterator arg_end() { return arg_begin() + getNumArgs(); }
1599 const_arg_iterator arg_begin() const { return getTrailingArgs(); }
1600 const_arg_iterator arg_end() const { return arg_begin() + getNumArgs(); }
1601
1602 Expr **getArgs() { return reinterpret_cast<Expr **>(getTrailingArgs()); }
1603 const Expr *const *getArgs() const {
1604 return reinterpret_cast<const Expr *const *>(getTrailingArgs());
1605 }
1606
1607 /// Return the number of arguments to the constructor call.
1608 unsigned getNumArgs() const { return NumArgs; }
1609
1610 /// Return the specified argument.
1611 Expr *getArg(unsigned Arg) {
1612 assert(Arg < getNumArgs() && "Arg access out of range!")(static_cast<void> (0));
1613 return getArgs()[Arg];
1614 }
1615 const Expr *getArg(unsigned Arg) const {
1616 assert(Arg < getNumArgs() && "Arg access out of range!")(static_cast<void> (0));
1617 return getArgs()[Arg];
1618 }
1619
1620 /// Set the specified argument.
1621 void setArg(unsigned Arg, Expr *ArgExpr) {
1622 assert(Arg < getNumArgs() && "Arg access out of range!")(static_cast<void> (0));
1623 getArgs()[Arg] = ArgExpr;
1624 }
1625
1626 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__));
1627 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__));
1628 SourceRange getParenOrBraceRange() const { return ParenOrBraceRange; }
1629 void setParenOrBraceRange(SourceRange Range) { ParenOrBraceRange = Range; }
1630
1631 static bool classof(const Stmt *T) {
1632 return T->getStmtClass() == CXXConstructExprClass ||
1633 T->getStmtClass() == CXXTemporaryObjectExprClass;
1634 }
1635
1636 // Iterators
1637 child_range children() {
1638 return child_range(getTrailingArgs(), getTrailingArgs() + getNumArgs());
1639 }
1640
1641 const_child_range children() const {
1642 auto Children = const_cast<CXXConstructExpr *>(this)->children();
1643 return const_child_range(Children.begin(), Children.end());
1644 }
1645};
1646
1647/// Represents a call to an inherited base class constructor from an
1648/// inheriting constructor. This call implicitly forwards the arguments from
1649/// the enclosing context (an inheriting constructor) to the specified inherited
1650/// base class constructor.
1651class CXXInheritedCtorInitExpr : public Expr {
1652private:
1653 CXXConstructorDecl *Constructor = nullptr;
1654
1655 /// The location of the using declaration.
1656 SourceLocation Loc;
1657
1658 /// Whether this is the construction of a virtual base.
1659 unsigned ConstructsVirtualBase : 1;
1660
1661 /// Whether the constructor is inherited from a virtual base class of the
1662 /// class that we construct.
1663 unsigned InheritedFromVirtualBase : 1;
1664
1665public:
1666 friend class ASTStmtReader;
1667
1668 /// Construct a C++ inheriting construction expression.
1669 CXXInheritedCtorInitExpr(SourceLocation Loc, QualType T,
1670 CXXConstructorDecl *Ctor, bool ConstructsVirtualBase,
1671 bool InheritedFromVirtualBase)
1672 : Expr(CXXInheritedCtorInitExprClass, T, VK_PRValue, OK_Ordinary),
1673 Constructor(Ctor), Loc(Loc),
1674 ConstructsVirtualBase(ConstructsVirtualBase),
1675 InheritedFromVirtualBase(InheritedFromVirtualBase) {
1676 assert(!T->isDependentType())(static_cast<void> (0));
1677 setDependence(ExprDependence::None);
1678 }
1679
1680 /// Construct an empty C++ inheriting construction expression.
1681 explicit CXXInheritedCtorInitExpr(EmptyShell Empty)
1682 : Expr(CXXInheritedCtorInitExprClass, Empty),
1683 ConstructsVirtualBase(false), InheritedFromVirtualBase(false) {}
1684
1685 /// Get the constructor that this expression will call.
1686 CXXConstructorDecl *getConstructor() const { return Constructor; }
1687
1688 /// Determine whether this constructor is actually constructing
1689 /// a base class (rather than a complete object).
1690 bool constructsVBase() const { return ConstructsVirtualBase; }
1691 CXXConstructExpr::ConstructionKind getConstructionKind() const {
1692 return ConstructsVirtualBase ? CXXConstructExpr::CK_VirtualBase
1693 : CXXConstructExpr::CK_NonVirtualBase;
1694 }
1695
1696 /// Determine whether the inherited constructor is inherited from a
1697 /// virtual base of the object we construct. If so, we are not responsible
1698 /// for calling the inherited constructor (the complete object constructor
1699 /// does that), and so we don't need to pass any arguments.
1700 bool inheritedFromVBase() const { return InheritedFromVirtualBase; }
1701
1702 SourceLocation getLocation() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1703 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1704 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1705
1706 static bool classof(const Stmt *T) {
1707 return T->getStmtClass() == CXXInheritedCtorInitExprClass;
1708 }
1709
1710 child_range children() {
1711 return child_range(child_iterator(), child_iterator());
1712 }
1713
1714 const_child_range children() const {
1715 return const_child_range(const_child_iterator(), const_child_iterator());
1716 }
1717};
1718
1719/// Represents an explicit C++ type conversion that uses "functional"
1720/// notation (C++ [expr.type.conv]).
1721///
1722/// Example:
1723/// \code
1724/// x = int(0.5);
1725/// \endcode
1726class CXXFunctionalCastExpr final
1727 : public ExplicitCastExpr,
1728 private llvm::TrailingObjects<CXXFunctionalCastExpr, CXXBaseSpecifier *,
1729 FPOptionsOverride> {
1730 SourceLocation LParenLoc;
1731 SourceLocation RParenLoc;
1732
1733 CXXFunctionalCastExpr(QualType ty, ExprValueKind VK,
1734 TypeSourceInfo *writtenTy, CastKind kind,
1735 Expr *castExpr, unsigned pathSize,
1736 FPOptionsOverride FPO, SourceLocation lParenLoc,
1737 SourceLocation rParenLoc)
1738 : ExplicitCastExpr(CXXFunctionalCastExprClass, ty, VK, kind, castExpr,
1739 pathSize, FPO.requiresTrailingStorage(), writtenTy),
1740 LParenLoc(lParenLoc), RParenLoc(rParenLoc) {
1741 if (hasStoredFPFeatures())
1742 *getTrailingFPFeatures() = FPO;
1743 }
1744
1745 explicit CXXFunctionalCastExpr(EmptyShell Shell, unsigned PathSize,
1746 bool HasFPFeatures)
1747 : ExplicitCastExpr(CXXFunctionalCastExprClass, Shell, PathSize,
1748 HasFPFeatures) {}
1749
1750 unsigned numTrailingObjects(OverloadToken<CXXBaseSpecifier *>) const {
1751 return path_size();
1752 }
1753
1754public:
1755 friend class CastExpr;
1756 friend TrailingObjects;
1757
1758 static CXXFunctionalCastExpr *
1759 Create(const ASTContext &Context, QualType T, ExprValueKind VK,
1760 TypeSourceInfo *Written, CastKind Kind, Expr *Op,
1761 const CXXCastPath *Path, FPOptionsOverride FPO, SourceLocation LPLoc,
1762 SourceLocation RPLoc);
1763 static CXXFunctionalCastExpr *
1764 CreateEmpty(const ASTContext &Context, unsigned PathSize, bool HasFPFeatures);
1765
1766 SourceLocation getLParenLoc() const { return LParenLoc; }
1767 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
1768 SourceLocation getRParenLoc() const { return RParenLoc; }
1769 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
1770
1771 /// Determine whether this expression models list-initialization.
1772 bool isListInitialization() const { return LParenLoc.isInvalid(); }
1773
1774 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__));
1775 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__));
1776
1777 static bool classof(const Stmt *T) {
1778 return T->getStmtClass() == CXXFunctionalCastExprClass;
1779 }
1780};
1781
1782/// Represents a C++ functional cast expression that builds a
1783/// temporary object.
1784///
1785/// This expression type represents a C++ "functional" cast
1786/// (C++[expr.type.conv]) with N != 1 arguments that invokes a
1787/// constructor to build a temporary object. With N == 1 arguments the
1788/// functional cast expression will be represented by CXXFunctionalCastExpr.
1789/// Example:
1790/// \code
1791/// struct X { X(int, float); }
1792///
1793/// X create_X() {
1794/// return X(1, 3.14f); // creates a CXXTemporaryObjectExpr
1795/// };
1796/// \endcode
1797class CXXTemporaryObjectExpr final : public CXXConstructExpr {
1798 friend class ASTStmtReader;
1799
1800 // CXXTemporaryObjectExpr has some trailing objects belonging
1801 // to CXXConstructExpr. See the comment inside CXXConstructExpr
1802 // for more details.
1803
1804 TypeSourceInfo *TSI;
1805
1806 CXXTemporaryObjectExpr(CXXConstructorDecl *Cons, QualType Ty,
1807 TypeSourceInfo *TSI, ArrayRef<Expr *> Args,
1808 SourceRange ParenOrBraceRange,
1809 bool HadMultipleCandidates, bool ListInitialization,
1810 bool StdInitListInitialization,
1811 bool ZeroInitialization);
1812
1813 CXXTemporaryObjectExpr(EmptyShell Empty, unsigned NumArgs);
1814
1815public:
1816 static CXXTemporaryObjectExpr *
1817 Create(const ASTContext &Ctx, CXXConstructorDecl *Cons, QualType Ty,
1818 TypeSourceInfo *TSI, ArrayRef<Expr *> Args,
1819 SourceRange ParenOrBraceRange, bool HadMultipleCandidates,
1820 bool ListInitialization, bool StdInitListInitialization,
1821 bool ZeroInitialization);
1822
1823 static CXXTemporaryObjectExpr *CreateEmpty(const ASTContext &Ctx,
1824 unsigned NumArgs);
1825
1826 TypeSourceInfo *getTypeSourceInfo() const { return TSI; }
1827
1828 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__));
1829 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__));
1830
1831 static bool classof(const Stmt *T) {
1832 return T->getStmtClass() == CXXTemporaryObjectExprClass;
1833 }
1834};
1835
1836Stmt **CXXConstructExpr::getTrailingArgs() {
1837 if (auto *E = dyn_cast<CXXTemporaryObjectExpr>(this))
1838 return reinterpret_cast<Stmt **>(E + 1);
1839 assert((getStmtClass() == CXXConstructExprClass) &&(static_cast<void> (0))
1840 "Unexpected class deriving from CXXConstructExpr!")(static_cast<void> (0));
1841 return reinterpret_cast<Stmt **>(this + 1);
1842}
1843
1844/// A C++ lambda expression, which produces a function object
1845/// (of unspecified type) that can be invoked later.
1846///
1847/// Example:
1848/// \code
1849/// void low_pass_filter(std::vector<double> &values, double cutoff) {
1850/// values.erase(std::remove_if(values.begin(), values.end(),
1851/// [=](double value) { return value > cutoff; });
1852/// }
1853/// \endcode
1854///
1855/// C++11 lambda expressions can capture local variables, either by copying
1856/// the values of those local variables at the time the function
1857/// object is constructed (not when it is called!) or by holding a
1858/// reference to the local variable. These captures can occur either
1859/// implicitly or can be written explicitly between the square
1860/// brackets ([...]) that start the lambda expression.
1861///
1862/// C++1y introduces a new form of "capture" called an init-capture that
1863/// includes an initializing expression (rather than capturing a variable),
1864/// and which can never occur implicitly.
1865class LambdaExpr final : public Expr,
1866 private llvm::TrailingObjects<LambdaExpr, Stmt *> {
1867 // LambdaExpr has some data stored in LambdaExprBits.
1868
1869 /// The source range that covers the lambda introducer ([...]).
1870 SourceRange IntroducerRange;
1871
1872 /// The source location of this lambda's capture-default ('=' or '&').
1873 SourceLocation CaptureDefaultLoc;
1874
1875 /// The location of the closing brace ('}') that completes
1876 /// the lambda.
1877 ///
1878 /// The location of the brace is also available by looking up the
1879 /// function call operator in the lambda class. However, it is
1880 /// stored here to improve the performance of getSourceRange(), and
1881 /// to avoid having to deserialize the function call operator from a
1882 /// module file just to determine the source range.
1883 SourceLocation ClosingBrace;
1884
1885 /// Construct a lambda expression.
1886 LambdaExpr(QualType T, SourceRange IntroducerRange,
1887 LambdaCaptureDefault CaptureDefault,
1888 SourceLocation CaptureDefaultLoc, bool ExplicitParams,
1889 bool ExplicitResultType, ArrayRef<Expr *> CaptureInits,
1890 SourceLocation ClosingBrace, bool ContainsUnexpandedParameterPack);
1891
1892 /// Construct an empty lambda expression.
1893 LambdaExpr(EmptyShell Empty, unsigned NumCaptures);
1894
1895 Stmt **getStoredStmts() { return getTrailingObjects<Stmt *>(); }
1896 Stmt *const *getStoredStmts() const { return getTrailingObjects<Stmt *>(); }
1897
1898 void initBodyIfNeeded() const;
1899
1900public:
1901 friend class ASTStmtReader;
1902 friend class ASTStmtWriter;
1903 friend TrailingObjects;
1904
1905 /// Construct a new lambda expression.
1906 static LambdaExpr *
1907 Create(const ASTContext &C, CXXRecordDecl *Class, SourceRange IntroducerRange,
1908 LambdaCaptureDefault CaptureDefault, SourceLocation CaptureDefaultLoc,
1909 bool ExplicitParams, bool ExplicitResultType,
1910 ArrayRef<Expr *> CaptureInits, SourceLocation ClosingBrace,
1911 bool ContainsUnexpandedParameterPack);
1912
1913 /// Construct a new lambda expression that will be deserialized from
1914 /// an external source.
1915 static LambdaExpr *CreateDeserialized(const ASTContext &C,
1916 unsigned NumCaptures);
1917
1918 /// Determine the default capture kind for this lambda.
1919 LambdaCaptureDefault getCaptureDefault() const {
1920 return static_cast<LambdaCaptureDefault>(LambdaExprBits.CaptureDefault);
1921 }
1922
1923 /// Retrieve the location of this lambda's capture-default, if any.
1924 SourceLocation getCaptureDefaultLoc() const { return CaptureDefaultLoc; }
1925
1926 /// Determine whether one of this lambda's captures is an init-capture.
1927 bool isInitCapture(const LambdaCapture *Capture) const;
1928
1929 /// An iterator that walks over the captures of the lambda,
1930 /// both implicit and explicit.
1931 using capture_iterator = const LambdaCapture *;
1932
1933 /// An iterator over a range of lambda captures.
1934 using capture_range = llvm::iterator_range<capture_iterator>;
1935
1936 /// Retrieve this lambda's captures.
1937 capture_range captures() const;
1938
1939 /// Retrieve an iterator pointing to the first lambda capture.
1940 capture_iterator capture_begin() const;
1941
1942 /// Retrieve an iterator pointing past the end of the
1943 /// sequence of lambda captures.
1944 capture_iterator capture_end() const;
1945
1946 /// Determine the number of captures in this lambda.
1947 unsigned capture_size() const { return LambdaExprBits.NumCaptures; }
1948
1949 /// Retrieve this lambda's explicit captures.
1950 capture_range explicit_captures() const;
1951
1952 /// Retrieve an iterator pointing to the first explicit
1953 /// lambda capture.
1954 capture_iterator explicit_capture_begin() const;
1955
1956 /// Retrieve an iterator pointing past the end of the sequence of
1957 /// explicit lambda captures.
1958 capture_iterator explicit_capture_end() const;
1959
1960 /// Retrieve this lambda's implicit captures.
1961 capture_range implicit_captures() const;
1962
1963 /// Retrieve an iterator pointing to the first implicit
1964 /// lambda capture.
1965 capture_iterator implicit_capture_begin() const;
1966
1967 /// Retrieve an iterator pointing past the end of the sequence of
1968 /// implicit lambda captures.
1969 capture_iterator implicit_capture_end() const;
1970
1971 /// Iterator that walks over the capture initialization
1972 /// arguments.
1973 using capture_init_iterator = Expr **;
1974
1975 /// Const iterator that walks over the capture initialization
1976 /// arguments.
1977 /// FIXME: This interface is prone to being used incorrectly.
1978 using const_capture_init_iterator = Expr *const *;
1979
1980 /// Retrieve the initialization expressions for this lambda's captures.
1981 llvm::iterator_range<capture_init_iterator> capture_inits() {
1982 return llvm::make_range(capture_init_begin(), capture_init_end());
1983 }
1984
1985 /// Retrieve the initialization expressions for this lambda's captures.
1986 llvm::iterator_range<const_capture_init_iterator> capture_inits() const {
1987 return llvm::make_range(capture_init_begin(), capture_init_end());
1988 }
1989
1990 /// Retrieve the first initialization argument for this
1991 /// lambda expression (which initializes the first capture field).
1992 capture_init_iterator capture_init_begin() {
1993 return reinterpret_cast<Expr **>(getStoredStmts());
1994 }
1995
1996 /// Retrieve the first initialization argument for this
1997 /// lambda expression (which initializes the first capture field).
1998 const_capture_init_iterator capture_init_begin() const {
1999 return reinterpret_cast<Expr *const *>(getStoredStmts());
2000 }
2001
2002 /// Retrieve the iterator pointing one past the last
2003 /// initialization argument for this lambda expression.
2004 capture_init_iterator capture_init_end() {
2005 return capture_init_begin() + capture_size();
2006 }
2007
2008 /// Retrieve the iterator pointing one past the last
2009 /// initialization argument for this lambda expression.
2010 const_capture_init_iterator capture_init_end() const {
2011 return capture_init_begin() + capture_size();
2012 }
2013
2014 /// Retrieve the source range covering the lambda introducer,
2015 /// which contains the explicit capture list surrounded by square
2016 /// brackets ([...]).
2017 SourceRange getIntroducerRange() const { return IntroducerRange; }
2018
2019 /// Retrieve the class that corresponds to the lambda.
2020 ///
2021 /// This is the "closure type" (C++1y [expr.prim.lambda]), and stores the
2022 /// captures in its fields and provides the various operations permitted
2023 /// on a lambda (copying, calling).
2024 CXXRecordDecl *getLambdaClass() const;
2025
2026 /// Retrieve the function call operator associated with this
2027 /// lambda expression.
2028 CXXMethodDecl *getCallOperator() const;
2029
2030 /// Retrieve the function template call operator associated with this
2031 /// lambda expression.
2032 FunctionTemplateDecl *getDependentCallOperator() const;
2033
2034 /// If this is a generic lambda expression, retrieve the template
2035 /// parameter list associated with it, or else return null.
2036 TemplateParameterList *getTemplateParameterList() const;
2037
2038 /// Get the template parameters were explicitly specified (as opposed to being
2039 /// invented by use of an auto parameter).
2040 ArrayRef<NamedDecl *> getExplicitTemplateParameters() const;
2041
2042 /// Get the trailing requires clause, if any.
2043 Expr *getTrailingRequiresClause() const;
2044
2045 /// Whether this is a generic lambda.
2046 bool isGenericLambda() const { return getTemplateParameterList(); }
2047
2048 /// Retrieve the body of the lambda. This will be most of the time
2049 /// a \p CompoundStmt, but can also be \p CoroutineBodyStmt wrapping
2050 /// a \p CompoundStmt. Note that unlike functions, lambda-expressions
2051 /// cannot have a function-try-block.
2052 Stmt *getBody() const;
2053
2054 /// Retrieve the \p CompoundStmt representing the body of the lambda.
2055 /// This is a convenience function for callers who do not need
2056 /// to handle node(s) which may wrap a \p CompoundStmt.
2057 const CompoundStmt *getCompoundStmtBody() const;
2058 CompoundStmt *getCompoundStmtBody() {
2059 const auto *ConstThis = this;
2060 return const_cast<CompoundStmt *>(ConstThis->getCompoundStmtBody());
2061 }
2062
2063 /// Determine whether the lambda is mutable, meaning that any
2064 /// captures values can be modified.
2065 bool isMutable() const;
2066
2067 /// Determine whether this lambda has an explicit parameter
2068 /// list vs. an implicit (empty) parameter list.
2069 bool hasExplicitParameters() const { return LambdaExprBits.ExplicitParams; }
2070
2071 /// Whether this lambda had its result type explicitly specified.
2072 bool hasExplicitResultType() const {
2073 return LambdaExprBits.ExplicitResultType;
2074 }
2075
2076 static bool classof(const Stmt *T) {
2077 return T->getStmtClass() == LambdaExprClass;
2078 }
2079
2080 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
2081 return IntroducerRange.getBegin();
2082 }
2083
2084 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return ClosingBrace; }
2085
2086 /// Includes the captures and the body of the lambda.
2087 child_range children();
2088 const_child_range children() const;
2089};
2090
2091/// An expression "T()" which creates a value-initialized rvalue of type
2092/// T, which is a non-class type. See (C++98 [5.2.3p2]).
2093class CXXScalarValueInitExpr : public Expr {
2094 friend class ASTStmtReader;
2095
2096 TypeSourceInfo *TypeInfo;
2097
2098public:
2099 /// Create an explicitly-written scalar-value initialization
2100 /// expression.
2101 CXXScalarValueInitExpr(QualType Type, TypeSourceInfo *TypeInfo,
2102 SourceLocation RParenLoc)
2103 : Expr(CXXScalarValueInitExprClass, Type, VK_PRValue, OK_Ordinary),
2104 TypeInfo(TypeInfo) {
2105 CXXScalarValueInitExprBits.RParenLoc = RParenLoc;
2106 setDependence(computeDependence(this));
2107 }
2108
2109 explicit CXXScalarValueInitExpr(EmptyShell Shell)
2110 : Expr(CXXScalarValueInitExprClass, Shell) {}
2111
2112 TypeSourceInfo *getTypeSourceInfo() const {
2113 return TypeInfo;
2114 }
2115
2116 SourceLocation getRParenLoc() const {
2117 return CXXScalarValueInitExprBits.RParenLoc;
2118 }
2119
2120 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__));
2121 SourceLocation getEndLoc() const { return getRParenLoc(); }
2122
2123 static bool classof(const Stmt *T) {
2124 return T->getStmtClass() == CXXScalarValueInitExprClass;
2125 }
2126
2127 // Iterators
2128 child_range children() {
2129 return child_range(child_iterator(), child_iterator());
2130 }
2131
2132 const_child_range children() const {
2133 return const_child_range(const_child_iterator(), const_child_iterator());
2134 }
2135};
2136
2137/// Represents a new-expression for memory allocation and constructor
2138/// calls, e.g: "new CXXNewExpr(foo)".
2139class CXXNewExpr final
2140 : public Expr,
2141 private llvm::TrailingObjects<CXXNewExpr, Stmt *, SourceRange> {
2142 friend class ASTStmtReader;
2143 friend class ASTStmtWriter;
2144 friend TrailingObjects;
2145
2146 /// Points to the allocation function used.
2147 FunctionDecl *OperatorNew;
2148
2149 /// Points to the deallocation function used in case of error. May be null.
2150 FunctionDecl *OperatorDelete;
2151
2152 /// The allocated type-source information, as written in the source.
2153 TypeSourceInfo *AllocatedTypeInfo;
2154
2155 /// Range of the entire new expression.
2156 SourceRange Range;
2157
2158 /// Source-range of a paren-delimited initializer.
2159 SourceRange DirectInitRange;
2160
2161 // CXXNewExpr is followed by several optional trailing objects.
2162 // They are in order:
2163 //
2164 // * An optional "Stmt *" for the array size expression.
2165 // Present if and ony if isArray().
2166 //
2167 // * An optional "Stmt *" for the init expression.
2168 // Present if and only if hasInitializer().
2169 //
2170 // * An array of getNumPlacementArgs() "Stmt *" for the placement new
2171 // arguments, if any.
2172 //
2173 // * An optional SourceRange for the range covering the parenthesized type-id
2174 // if the allocated type was expressed as a parenthesized type-id.
2175 // Present if and only if isParenTypeId().
2176 unsigned arraySizeOffset() const { return 0; }
2177 unsigned initExprOffset() const { return arraySizeOffset() + isArray(); }
2178 unsigned placementNewArgsOffset() const {
2179 return initExprOffset() + hasInitializer();
2180 }
2181
2182 unsigned numTrailingObjects(OverloadToken<Stmt *>) const {
2183 return isArray() + hasInitializer() + getNumPlacementArgs();
2184 }
2185
2186 unsigned numTrailingObjects(OverloadToken<SourceRange>) const {
2187 return isParenTypeId();
2188 }
2189
2190public:
2191 enum InitializationStyle {
2192 /// New-expression has no initializer as written.
2193 NoInit,
2194
2195 /// New-expression has a C++98 paren-delimited initializer.
2196 CallInit,
2197
2198 /// New-expression has a C++11 list-initializer.
2199 ListInit
2200 };
2201
2202private:
2203 /// Build a c++ new expression.
2204 CXXNewExpr(bool IsGlobalNew, FunctionDecl *OperatorNew,
2205 FunctionDecl *OperatorDelete, bool ShouldPassAlignment,
2206 bool UsualArrayDeleteWantsSize, ArrayRef<Expr *> PlacementArgs,
2207 SourceRange TypeIdParens, Optional<Expr *> ArraySize,
2208 InitializationStyle InitializationStyle, Expr *Initializer,
2209 QualType Ty, TypeSourceInfo *AllocatedTypeInfo, SourceRange Range,
2210 SourceRange DirectInitRange);
2211
2212 /// Build an empty c++ new expression.
2213 CXXNewExpr(EmptyShell Empty, bool IsArray, unsigned NumPlacementArgs,
2214 bool IsParenTypeId);
2215
2216public:
2217 /// Create a c++ new expression.
2218 static CXXNewExpr *
2219 Create(const ASTContext &Ctx, bool IsGlobalNew, FunctionDecl *OperatorNew,
2220 FunctionDecl *OperatorDelete, bool ShouldPassAlignment,
2221 bool UsualArrayDeleteWantsSize, ArrayRef<Expr *> PlacementArgs,
2222 SourceRange TypeIdParens, Optional<Expr *> ArraySize,
2223 InitializationStyle InitializationStyle, Expr *Initializer,
2224 QualType Ty, TypeSourceInfo *AllocatedTypeInfo, SourceRange Range,
2225 SourceRange DirectInitRange);
2226
2227 /// Create an empty c++ new expression.
2228 static CXXNewExpr *CreateEmpty(const ASTContext &Ctx, bool IsArray,
2229 bool HasInit, unsigned NumPlacementArgs,
2230 bool IsParenTypeId);
2231
2232 QualType getAllocatedType() const {
2233 return getType()->castAs<PointerType>()->getPointeeType();
2234 }
2235
2236 TypeSourceInfo *getAllocatedTypeSourceInfo() const {
2237 return AllocatedTypeInfo;
2238 }
2239
2240 /// True if the allocation result needs to be null-checked.
2241 ///
2242 /// C++11 [expr.new]p13:
2243 /// If the allocation function returns null, initialization shall
2244 /// not be done, the deallocation function shall not be called,
2245 /// and the value of the new-expression shall be null.
2246 ///
2247 /// C++ DR1748:
2248 /// If the allocation function is a reserved placement allocation
2249 /// function that returns null, the behavior is undefined.
2250 ///
2251 /// An allocation function is not allowed to return null unless it
2252 /// has a non-throwing exception-specification. The '03 rule is
2253 /// identical except that the definition of a non-throwing
2254 /// exception specification is just "is it throw()?".
2255 bool shouldNullCheckAllocation() const;
2256
2257 FunctionDecl *getOperatorNew() const { return OperatorNew; }
2258 void setOperatorNew(FunctionDecl *D) { OperatorNew = D; }
2259 FunctionDecl *getOperatorDelete() const { return OperatorDelete; }
2260 void setOperatorDelete(FunctionDecl *D) { OperatorDelete = D; }
2261
2262 bool isArray() const { return CXXNewExprBits.IsArray; }
2263
2264 Optional<Expr *> getArraySize() {
2265 if (!isArray())
2266 return None;
2267 return cast_or_null<Expr>(getTrailingObjects<Stmt *>()[arraySizeOffset()]);
2268 }
2269 Optional<const Expr *> getArraySize() const {
2270 if (!isArray())
2271 return None;
2272 return cast_or_null<Expr>(getTrailingObjects<Stmt *>()[arraySizeOffset()]);
2273 }
2274
2275 unsigned getNumPlacementArgs() const {
2276 return CXXNewExprBits.NumPlacementArgs;
2277 }
2278
2279 Expr **getPlacementArgs() {
2280 return reinterpret_cast<Expr **>(getTrailingObjects<Stmt *>() +
2281 placementNewArgsOffset());
2282 }
2283
2284 Expr *getPlacementArg(unsigned I) {
2285 assert((I < getNumPlacementArgs()) && "Index out of range!")(static_cast<void> (0));
2286 return getPlacementArgs()[I];
2287 }
2288 const Expr *getPlacementArg(unsigned I) const {
2289 return const_cast<CXXNewExpr *>(this)->getPlacementArg(I);
2290 }
2291
2292 bool isParenTypeId() const { return CXXNewExprBits.IsParenTypeId; }
2293 SourceRange getTypeIdParens() const {
2294 return isParenTypeId() ? getTrailingObjects<SourceRange>()[0]
2295 : SourceRange();
2296 }
2297
2298 bool isGlobalNew() const { return CXXNewExprBits.IsGlobalNew; }
2299
2300 /// Whether this new-expression has any initializer at all.
2301 bool hasInitializer() const {
2302 return CXXNewExprBits.StoredInitializationStyle > 0;
28
Assuming field 'StoredInitializationStyle' is > 0
29
Returning the value 1, which participates in a condition later
2303 }
2304
2305 /// The kind of initializer this new-expression has.
2306 InitializationStyle getInitializationStyle() const {
2307 if (CXXNewExprBits.StoredInitializationStyle == 0)
2308 return NoInit;
2309 return static_cast<InitializationStyle>(
2310 CXXNewExprBits.StoredInitializationStyle - 1);
2311 }
2312
2313 /// The initializer of this new-expression.
2314 Expr *getInitializer() {
2315 return hasInitializer()
2316 ? cast<Expr>(getTrailingObjects<Stmt *>()[initExprOffset()])
2317 : nullptr;
2318 }
2319 const Expr *getInitializer() const {
2320 return hasInitializer()
2321 ? cast<Expr>(getTrailingObjects<Stmt *>()[initExprOffset()])
2322 : nullptr;
2323 }
2324
2325 /// Returns the CXXConstructExpr from this new-expression, or null.
2326 const CXXConstructExpr *getConstructExpr() const {
2327 return dyn_cast_or_null<CXXConstructExpr>(getInitializer());
2328 }
2329
2330 /// Indicates whether the required alignment should be implicitly passed to
2331 /// the allocation function.
2332 bool passAlignment() const { return CXXNewExprBits.ShouldPassAlignment; }
2333
2334 /// Answers whether the usual array deallocation function for the
2335 /// allocated type expects the size of the allocation as a
2336 /// parameter.
2337 bool doesUsualArrayDeleteWantSize() const {
2338 return CXXNewExprBits.UsualArrayDeleteWantsSize;
2339 }
2340
2341 using arg_iterator = ExprIterator;
2342 using const_arg_iterator = ConstExprIterator;
2343
2344 llvm::iterator_range<arg_iterator> placement_arguments() {
2345 return llvm::make_range(placement_arg_begin(), placement_arg_end());
2346 }
2347
2348 llvm::iterator_range<const_arg_iterator> placement_arguments() const {
2349 return llvm::make_range(placement_arg_begin(), placement_arg_end());
2350 }
2351
2352 arg_iterator placement_arg_begin() {
2353 return getTrailingObjects<Stmt *>() + placementNewArgsOffset();
2354 }
2355 arg_iterator placement_arg_end() {
2356 return placement_arg_begin() + getNumPlacementArgs();
2357 }
2358 const_arg_iterator placement_arg_begin() const {
2359 return getTrailingObjects<Stmt *>() + placementNewArgsOffset();
2360 }
2361 const_arg_iterator placement_arg_end() const {
2362 return placement_arg_begin() + getNumPlacementArgs();
2363 }
2364
2365 using raw_arg_iterator = Stmt **;
2366
2367 raw_arg_iterator raw_arg_begin() { return getTrailingObjects<Stmt *>(); }
2368 raw_arg_iterator raw_arg_end() {
2369 return raw_arg_begin() + numTrailingObjects(OverloadToken<Stmt *>());
2370 }
2371 const_arg_iterator raw_arg_begin() const {
2372 return getTrailingObjects<Stmt *>();
2373 }
2374 const_arg_iterator raw_arg_end() const {
2375 return raw_arg_begin() + numTrailingObjects(OverloadToken<Stmt *>());
2376 }
2377
2378 SourceLocation getBeginLoc() const { return Range.getBegin(); }
2379 SourceLocation getEndLoc() const { return Range.getEnd(); }
2380
2381 SourceRange getDirectInitRange() const { return DirectInitRange; }
2382 SourceRange getSourceRange() const { return Range; }
2383
2384 static bool classof(const Stmt *T) {
2385 return T->getStmtClass() == CXXNewExprClass;
2386 }
2387
2388 // Iterators
2389 child_range children() { return child_range(raw_arg_begin(), raw_arg_end()); }
2390
2391 const_child_range children() const {
2392 return const_child_range(const_cast<CXXNewExpr *>(this)->children());
2393 }
2394};
2395
2396/// Represents a \c delete expression for memory deallocation and
2397/// destructor calls, e.g. "delete[] pArray".
2398class CXXDeleteExpr : public Expr {
2399 friend class ASTStmtReader;
2400
2401 /// Points to the operator delete overload that is used. Could be a member.
2402 FunctionDecl *OperatorDelete = nullptr;
2403
2404 /// The pointer expression to be deleted.
2405 Stmt *Argument = nullptr;
2406
2407public:
2408 CXXDeleteExpr(QualType Ty, bool GlobalDelete, bool ArrayForm,
2409 bool ArrayFormAsWritten, bool UsualArrayDeleteWantsSize,
2410 FunctionDecl *OperatorDelete, Expr *Arg, SourceLocation Loc)
2411 : Expr(CXXDeleteExprClass, Ty, VK_PRValue, OK_Ordinary),
2412 OperatorDelete(OperatorDelete), Argument(Arg) {
2413 CXXDeleteExprBits.GlobalDelete = GlobalDelete;
2414 CXXDeleteExprBits.ArrayForm = ArrayForm;
2415 CXXDeleteExprBits.ArrayFormAsWritten = ArrayFormAsWritten;
2416 CXXDeleteExprBits.UsualArrayDeleteWantsSize = UsualArrayDeleteWantsSize;
2417 CXXDeleteExprBits.Loc = Loc;
2418 setDependence(computeDependence(this));
2419 }
2420
2421 explicit CXXDeleteExpr(EmptyShell Shell) : Expr(CXXDeleteExprClass, Shell) {}
2422
2423 bool isGlobalDelete() const { return CXXDeleteExprBits.GlobalDelete; }
2424 bool isArrayForm() const { return CXXDeleteExprBits.ArrayForm; }
2425 bool isArrayFormAsWritten() const {
2426 return CXXDeleteExprBits.ArrayFormAsWritten;
2427 }
2428
2429 /// Answers whether the usual array deallocation function for the
2430 /// allocated type expects the size of the allocation as a
2431 /// parameter. This can be true even if the actual deallocation
2432 /// function that we're using doesn't want a size.
2433 bool doesUsualArrayDeleteWantSize() const {
2434 return CXXDeleteExprBits.UsualArrayDeleteWantsSize;
2435 }
2436
2437 FunctionDecl *getOperatorDelete() const { return OperatorDelete; }
2438
2439 Expr *getArgument() { return cast<Expr>(Argument); }
2440 const Expr *getArgument() const { return cast<Expr>(Argument); }
2441
2442 /// Retrieve the type being destroyed.
2443 ///
2444 /// If the type being destroyed is a dependent type which may or may not
2445 /// be a pointer, return an invalid type.
2446 QualType getDestroyedType() const;
2447
2448 SourceLocation getBeginLoc() const { return CXXDeleteExprBits.Loc; }
2449 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
2450 return Argument->getEndLoc();
2451 }
2452
2453 static bool classof(const Stmt *T) {
2454 return T->getStmtClass() == CXXDeleteExprClass;
2455 }
2456
2457 // Iterators
2458 child_range children() { return child_range(&Argument, &Argument + 1); }
2459
2460 const_child_range children() const {
2461 return const_child_range(&Argument, &Argument + 1);
2462 }
2463};
2464
2465/// Stores the type being destroyed by a pseudo-destructor expression.
2466class PseudoDestructorTypeStorage {
2467 /// Either the type source information or the name of the type, if
2468 /// it couldn't be resolved due to type-dependence.
2469 llvm::PointerUnion<TypeSourceInfo *, IdentifierInfo *> Type;
2470
2471 /// The starting source location of the pseudo-destructor type.
2472 SourceLocation Location;
2473
2474public:
2475 PseudoDestructorTypeStorage() = default;
2476
2477 PseudoDestructorTypeStorage(IdentifierInfo *II, SourceLocation Loc)
2478 : Type(II), Location(Loc) {}
2479
2480 PseudoDestructorTypeStorage(TypeSourceInfo *Info);
2481
2482 TypeSourceInfo *getTypeSourceInfo() const {
2483 return Type.dyn_cast<TypeSourceInfo *>();
2484 }
2485
2486 IdentifierInfo *getIdentifier() const {
2487 return Type.dyn_cast<IdentifierInfo *>();
2488 }
2489
2490 SourceLocation getLocation() const { return Location; }
2491};
2492
2493/// Represents a C++ pseudo-destructor (C++ [expr.pseudo]).
2494///
2495/// A pseudo-destructor is an expression that looks like a member access to a
2496/// destructor of a scalar type, except that scalar types don't have
2497/// destructors. For example:
2498///
2499/// \code
2500/// typedef int T;
2501/// void f(int *p) {
2502/// p->T::~T();
2503/// }
2504/// \endcode
2505///
2506/// Pseudo-destructors typically occur when instantiating templates such as:
2507///
2508/// \code
2509/// template<typename T>
2510/// void destroy(T* ptr) {
2511/// ptr->T::~T();
2512/// }
2513/// \endcode
2514///
2515/// for scalar types. A pseudo-destructor expression has no run-time semantics
2516/// beyond evaluating the base expression.
2517class CXXPseudoDestructorExpr : public Expr {
2518 friend class ASTStmtReader;
2519
2520 /// The base expression (that is being destroyed).
2521 Stmt *Base = nullptr;
2522
2523 /// Whether the operator was an arrow ('->'); otherwise, it was a
2524 /// period ('.').
2525 bool IsArrow : 1;
2526
2527 /// The location of the '.' or '->' operator.
2528 SourceLocation OperatorLoc;
2529
2530 /// The nested-name-specifier that follows the operator, if present.
2531 NestedNameSpecifierLoc QualifierLoc;
2532
2533 /// The type that precedes the '::' in a qualified pseudo-destructor
2534 /// expression.
2535 TypeSourceInfo *ScopeType = nullptr;
2536
2537 /// The location of the '::' in a qualified pseudo-destructor
2538 /// expression.
2539 SourceLocation ColonColonLoc;
2540
2541 /// The location of the '~'.
2542 SourceLocation TildeLoc;
2543
2544 /// The type being destroyed, or its name if we were unable to
2545 /// resolve the name.
2546 PseudoDestructorTypeStorage DestroyedType;
2547
2548public:
2549 CXXPseudoDestructorExpr(const ASTContext &Context,
2550 Expr *Base, bool isArrow, SourceLocation OperatorLoc,
2551 NestedNameSpecifierLoc QualifierLoc,
2552 TypeSourceInfo *ScopeType,
2553 SourceLocation ColonColonLoc,
2554 SourceLocation TildeLoc,
2555 PseudoDestructorTypeStorage DestroyedType);
2556
2557 explicit CXXPseudoDestructorExpr(EmptyShell Shell)
2558 : Expr(CXXPseudoDestructorExprClass, Shell), IsArrow(false) {}
2559
2560 Expr *getBase() const { return cast<Expr>(Base); }
2561
2562 /// Determines whether this member expression actually had
2563 /// a C++ nested-name-specifier prior to the name of the member, e.g.,
2564 /// x->Base::foo.
2565 bool hasQualifier() const { return QualifierLoc.hasQualifier(); }
2566
2567 /// Retrieves the nested-name-specifier that qualifies the type name,
2568 /// with source-location information.
2569 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
2570
2571 /// If the member name was qualified, retrieves the
2572 /// nested-name-specifier that precedes the member name. Otherwise, returns
2573 /// null.
2574 NestedNameSpecifier *getQualifier() const {
2575 return QualifierLoc.getNestedNameSpecifier();
2576 }
2577
2578 /// Determine whether this pseudo-destructor expression was written
2579 /// using an '->' (otherwise, it used a '.').
2580 bool isArrow() const { return IsArrow; }
2581
2582 /// Retrieve the location of the '.' or '->' operator.
2583 SourceLocation getOperatorLoc() const { return OperatorLoc; }
2584
2585 /// Retrieve the scope type in a qualified pseudo-destructor
2586 /// expression.
2587 ///
2588 /// Pseudo-destructor expressions can have extra qualification within them
2589 /// that is not part of the nested-name-specifier, e.g., \c p->T::~T().
2590 /// Here, if the object type of the expression is (or may be) a scalar type,
2591 /// \p T may also be a scalar type and, therefore, cannot be part of a
2592 /// nested-name-specifier. It is stored as the "scope type" of the pseudo-
2593 /// destructor expression.
2594 TypeSourceInfo *getScopeTypeInfo() const { return ScopeType; }
2595
2596 /// Retrieve the location of the '::' in a qualified pseudo-destructor
2597 /// expression.
2598 SourceLocation getColonColonLoc() const { return ColonColonLoc; }
2599
2600 /// Retrieve the location of the '~'.
2601 SourceLocation getTildeLoc() const { return TildeLoc; }
2602
2603 /// Retrieve the source location information for the type
2604 /// being destroyed.
2605 ///
2606 /// This type-source information is available for non-dependent
2607 /// pseudo-destructor expressions and some dependent pseudo-destructor
2608 /// expressions. Returns null if we only have the identifier for a
2609 /// dependent pseudo-destructor expression.
2610 TypeSourceInfo *getDestroyedTypeInfo() const {
2611 return DestroyedType.getTypeSourceInfo();
2612 }
2613
2614 /// In a dependent pseudo-destructor expression for which we do not
2615 /// have full type information on the destroyed type, provides the name
2616 /// of the destroyed type.
2617 IdentifierInfo *getDestroyedTypeIdentifier() const {
2618 return DestroyedType.getIdentifier();
2619 }
2620
2621 /// Retrieve the type being destroyed.
2622 QualType getDestroyedType() const;
2623
2624 /// Retrieve the starting location of the type being destroyed.
2625 SourceLocation getDestroyedTypeLoc() const {
2626 return DestroyedType.getLocation();
2627 }
2628
2629 /// Set the name of destroyed type for a dependent pseudo-destructor
2630 /// expression.
2631 void setDestroyedType(IdentifierInfo *II, SourceLocation Loc) {
2632 DestroyedType = PseudoDestructorTypeStorage(II, Loc);
2633 }
2634
2635 /// Set the destroyed type.
2636 void setDestroyedType(TypeSourceInfo *Info) {
2637 DestroyedType = PseudoDestructorTypeStorage(Info);
2638 }
2639
2640 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
2641 return Base->getBeginLoc();
2642 }
2643 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__));
2644
2645 static bool classof(const Stmt *T) {
2646 return T->getStmtClass() == CXXPseudoDestructorExprClass;
2647 }
2648
2649 // Iterators
2650 child_range children() { return child_range(&Base, &Base + 1); }
2651
2652 const_child_range children() const {
2653 return const_child_range(&Base, &Base + 1);
2654 }
2655};
2656
2657/// A type trait used in the implementation of various C++11 and
2658/// Library TR1 trait templates.
2659///
2660/// \code
2661/// __is_pod(int) == true
2662/// __is_enum(std::string) == false
2663/// __is_trivially_constructible(vector<int>, int*, int*)
2664/// \endcode
2665class TypeTraitExpr final
2666 : public Expr,
2667 private llvm::TrailingObjects<TypeTraitExpr, TypeSourceInfo *> {
2668 /// The location of the type trait keyword.
2669 SourceLocation Loc;
2670
2671 /// The location of the closing parenthesis.
2672 SourceLocation RParenLoc;
2673
2674 // Note: The TypeSourceInfos for the arguments are allocated after the
2675 // TypeTraitExpr.
2676
2677 TypeTraitExpr(QualType T, SourceLocation Loc, TypeTrait Kind,
2678 ArrayRef<TypeSourceInfo *> Args,
2679 SourceLocation RParenLoc,
2680 bool Value);
2681
2682 TypeTraitExpr(EmptyShell Empty) : Expr(TypeTraitExprClass, Empty) {}
2683
2684 size_t numTrailingObjects(OverloadToken<TypeSourceInfo *>) const {
2685 return getNumArgs();
2686 }
2687
2688public:
2689 friend class ASTStmtReader;
2690 friend class ASTStmtWriter;
2691 friend TrailingObjects;
2692
2693 /// Create a new type trait expression.
2694 static TypeTraitExpr *Create(const ASTContext &C, QualType T,
2695 SourceLocation Loc, TypeTrait Kind,
2696 ArrayRef<TypeSourceInfo *> Args,
2697 SourceLocation RParenLoc,
2698 bool Value);
2699
2700 static TypeTraitExpr *CreateDeserialized(const ASTContext &C,
2701 unsigned NumArgs);
2702
2703 /// Determine which type trait this expression uses.
2704 TypeTrait getTrait() const {
2705 return static_cast<TypeTrait>(TypeTraitExprBits.Kind);
2706 }
2707
2708 bool getValue() const {
2709 assert(!isValueDependent())(static_cast<void> (0));
2710 return TypeTraitExprBits.Value;
2711 }
2712
2713 /// Determine the number of arguments to this type trait.
2714 unsigned getNumArgs() const { return TypeTraitExprBits.NumArgs; }
2715
2716 /// Retrieve the Ith argument.
2717 TypeSourceInfo *getArg(unsigned I) const {
2718 assert(I < getNumArgs() && "Argument out-of-range")(static_cast<void> (0));
2719 return getArgs()[I];
2720 }
2721
2722 /// Retrieve the argument types.
2723 ArrayRef<TypeSourceInfo *> getArgs() const {
2724 return llvm::makeArrayRef(getTrailingObjects<TypeSourceInfo *>(),
2725 getNumArgs());
2726 }
2727
2728 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
2729 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; }
2730
2731 static bool classof(const Stmt *T) {
2732 return T->getStmtClass() == TypeTraitExprClass;
2733 }
2734
2735 // Iterators
2736 child_range children() {
2737 return child_range(child_iterator(), child_iterator());
2738 }
2739
2740 const_child_range children() const {
2741 return const_child_range(const_child_iterator(), const_child_iterator());
2742 }
2743};
2744
2745/// An Embarcadero array type trait, as used in the implementation of
2746/// __array_rank and __array_extent.
2747///
2748/// Example:
2749/// \code
2750/// __array_rank(int[10][20]) == 2
2751/// __array_extent(int, 1) == 20
2752/// \endcode
2753class ArrayTypeTraitExpr : public Expr {
2754 /// The trait. An ArrayTypeTrait enum in MSVC compat unsigned.
2755 unsigned ATT : 2;
2756
2757 /// The value of the type trait. Unspecified if dependent.
2758 uint64_t Value = 0;
2759
2760 /// The array dimension being queried, or -1 if not used.
2761 Expr *Dimension;
2762
2763 /// The location of the type trait keyword.
2764 SourceLocation Loc;
2765
2766 /// The location of the closing paren.
2767 SourceLocation RParen;
2768
2769 /// The type being queried.
2770 TypeSourceInfo *QueriedType = nullptr;
2771
2772public:
2773 friend class ASTStmtReader;
2774
2775 ArrayTypeTraitExpr(SourceLocation loc, ArrayTypeTrait att,
2776 TypeSourceInfo *queried, uint64_t value, Expr *dimension,
2777 SourceLocation rparen, QualType ty)
2778 : Expr(ArrayTypeTraitExprClass, ty, VK_PRValue, OK_Ordinary), ATT(att),
2779 Value(value), Dimension(dimension), Loc(loc), RParen(rparen),
2780 QueriedType(queried) {
2781 assert(att <= ATT_Last && "invalid enum value!")(static_cast<void> (0));
2782 assert(static_cast<unsigned>(att) == ATT && "ATT overflow!")(static_cast<void> (0));
2783 setDependence(computeDependence(this));
2784 }
2785
2786 explicit ArrayTypeTraitExpr(EmptyShell Empty)
2787 : Expr(ArrayTypeTraitExprClass, Empty), ATT(0) {}
2788
2789 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
2790 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParen; }
2791
2792 ArrayTypeTrait getTrait() const { return static_cast<ArrayTypeTrait>(ATT); }
2793
2794 QualType getQueriedType() const { return QueriedType->getType(); }
2795
2796 TypeSourceInfo *getQueriedTypeSourceInfo() const { return QueriedType; }
2797
2798 uint64_t getValue() const { assert(!isTypeDependent())(static_cast<void> (0)); return Value; }
2799
2800 Expr *getDimensionExpression() const { return Dimension; }
2801
2802 static bool classof(const Stmt *T) {
2803 return T->getStmtClass() == ArrayTypeTraitExprClass;
2804 }
2805
2806 // Iterators
2807 child_range children() {
2808 return child_range(child_iterator(), child_iterator());
2809 }
2810
2811 const_child_range children() const {
2812 return const_child_range(const_child_iterator(), const_child_iterator());
2813 }
2814};
2815
2816/// An expression trait intrinsic.
2817///
2818/// Example:
2819/// \code
2820/// __is_lvalue_expr(std::cout) == true
2821/// __is_lvalue_expr(1) == false
2822/// \endcode
2823class ExpressionTraitExpr : public Expr {
2824 /// The trait. A ExpressionTrait enum in MSVC compatible unsigned.
2825 unsigned ET : 31;
2826
2827 /// The value of the type trait. Unspecified if dependent.
2828 unsigned Value : 1;
2829
2830 /// The location of the type trait keyword.
2831 SourceLocation Loc;
2832
2833 /// The location of the closing paren.
2834 SourceLocation RParen;
2835
2836 /// The expression being queried.
2837 Expr* QueriedExpression = nullptr;
2838
2839public:
2840 friend class ASTStmtReader;
2841
2842 ExpressionTraitExpr(SourceLocation loc, ExpressionTrait et, Expr *queried,
2843 bool value, SourceLocation rparen, QualType resultType)
2844 : Expr(ExpressionTraitExprClass, resultType, VK_PRValue, OK_Ordinary),
2845 ET(et), Value(value), Loc(loc), RParen(rparen),
2846 QueriedExpression(queried) {
2847 assert(et <= ET_Last && "invalid enum value!")(static_cast<void> (0));
2848 assert(static_cast<unsigned>(et) == ET && "ET overflow!")(static_cast<void> (0));
2849 setDependence(computeDependence(this));
2850 }
2851
2852 explicit ExpressionTraitExpr(EmptyShell Empty)
2853 : Expr(ExpressionTraitExprClass, Empty), ET(0), Value(false) {}
2854
2855 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
2856 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParen; }
2857
2858 ExpressionTrait getTrait() const { return static_cast<ExpressionTrait>(ET); }
2859
2860 Expr *getQueriedExpression() const { return QueriedExpression; }
2861
2862 bool getValue() const { return Value; }
2863
2864 static bool classof(const Stmt *T) {
2865 return T->getStmtClass() == ExpressionTraitExprClass;
2866 }
2867
2868 // Iterators
2869 child_range children() {
2870 return child_range(child_iterator(), child_iterator());
2871 }
2872
2873 const_child_range children() const {
2874 return const_child_range(const_child_iterator(), const_child_iterator());
2875 }
2876};
2877
2878/// A reference to an overloaded function set, either an
2879/// \c UnresolvedLookupExpr or an \c UnresolvedMemberExpr.
2880class OverloadExpr : public Expr {
2881 friend class ASTStmtReader;
2882 friend class ASTStmtWriter;
2883
2884 /// The common name of these declarations.
2885 DeclarationNameInfo NameInfo;
2886
2887 /// The nested-name-specifier that qualifies the name, if any.
2888 NestedNameSpecifierLoc QualifierLoc;
2889
2890protected:
2891 OverloadExpr(StmtClass SC, const ASTContext &Context,
2892 NestedNameSpecifierLoc QualifierLoc,
2893 SourceLocation TemplateKWLoc,
2894 const DeclarationNameInfo &NameInfo,
2895 const TemplateArgumentListInfo *TemplateArgs,
2896 UnresolvedSetIterator Begin, UnresolvedSetIterator End,
2897 bool KnownDependent, bool KnownInstantiationDependent,
2898 bool KnownContainsUnexpandedParameterPack);
2899
2900 OverloadExpr(StmtClass SC, EmptyShell Empty, unsigned NumResults,
2901 bool HasTemplateKWAndArgsInfo);
2902
2903 /// Return the results. Defined after UnresolvedMemberExpr.
2904 inline DeclAccessPair *getTrailingResults();
2905 const DeclAccessPair *getTrailingResults() const {
2906 return const_cast<OverloadExpr *>(this)->getTrailingResults();
2907 }
2908
2909 /// Return the optional template keyword and arguments info.
2910 /// Defined after UnresolvedMemberExpr.
2911 inline ASTTemplateKWAndArgsInfo *getTrailingASTTemplateKWAndArgsInfo();
2912 const ASTTemplateKWAndArgsInfo *getTrailingASTTemplateKWAndArgsInfo() const {
2913 return const_cast<OverloadExpr *>(this)
2914 ->getTrailingASTTemplateKWAndArgsInfo();
2915 }
2916
2917 /// Return the optional template arguments. Defined after
2918 /// UnresolvedMemberExpr.
2919 inline TemplateArgumentLoc *getTrailingTemplateArgumentLoc();
2920 const TemplateArgumentLoc *getTrailingTemplateArgumentLoc() const {
2921 return const_cast<OverloadExpr *>(this)->getTrailingTemplateArgumentLoc();
2922 }
2923
2924 bool hasTemplateKWAndArgsInfo() const {
2925 return OverloadExprBits.HasTemplateKWAndArgsInfo;
2926 }
2927
2928public:
2929 struct FindResult {
2930 OverloadExpr *Expression;
2931 bool IsAddressOfOperand;
2932 bool HasFormOfMemberPointer;
2933 };
2934
2935 /// Finds the overloaded expression in the given expression \p E of
2936 /// OverloadTy.
2937 ///
2938 /// \return the expression (which must be there) and true if it has
2939 /// the particular form of a member pointer expression
2940 static FindResult find(Expr *E) {
2941 assert(E->getType()->isSpecificBuiltinType(BuiltinType::Overload))(static_cast<void> (0));
2942
2943 FindResult Result;
2944
2945 E = E->IgnoreParens();
2946 if (isa<UnaryOperator>(E)) {
2947 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf)(static_cast<void> (0));
2948 E = cast<UnaryOperator>(E)->getSubExpr();
2949 auto *Ovl = cast<OverloadExpr>(E->IgnoreParens());
2950
2951 Result.HasFormOfMemberPointer = (E == Ovl && Ovl->getQualifier());
2952 Result.IsAddressOfOperand = true;
2953 Result.Expression = Ovl;
2954 } else {
2955 Result.HasFormOfMemberPointer = false;
2956 Result.IsAddressOfOperand = false;
2957 Result.Expression = cast<OverloadExpr>(E);
2958 }
2959
2960 return Result;
2961 }
2962
2963 /// Gets the naming class of this lookup, if any.
2964 /// Defined after UnresolvedMemberExpr.
2965 inline CXXRecordDecl *getNamingClass();
2966 const CXXRecordDecl *getNamingClass() const {
2967 return const_cast<OverloadExpr *>(this)->getNamingClass();
2968 }
2969
2970 using decls_iterator = UnresolvedSetImpl::iterator;
2971
2972 decls_iterator decls_begin() const {
2973 return UnresolvedSetIterator(getTrailingResults());
2974 }
2975 decls_iterator decls_end() const {
2976 return UnresolvedSetIterator(getTrailingResults() + getNumDecls());
2977 }
2978 llvm::iterator_range<decls_iterator> decls() const {
2979 return llvm::make_range(decls_begin(), decls_end());
2980 }
2981
2982 /// Gets the number of declarations in the unresolved set.
2983 unsigned getNumDecls() const { return OverloadExprBits.NumResults; }
2984
2985 /// Gets the full name info.
2986 const DeclarationNameInfo &getNameInfo() const { return NameInfo; }
2987
2988 /// Gets the name looked up.
2989 DeclarationName getName() const { return NameInfo.getName(); }
2990
2991 /// Gets the location of the name.
2992 SourceLocation getNameLoc() const { return NameInfo.getLoc(); }
2993
2994 /// Fetches the nested-name qualifier, if one was given.
2995 NestedNameSpecifier *getQualifier() const {
2996 return QualifierLoc.getNestedNameSpecifier();
2997 }
2998
2999 /// Fetches the nested-name qualifier with source-location
3000 /// information, if one was given.
3001 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3002
3003 /// Retrieve the location of the template keyword preceding
3004 /// this name, if any.
3005 SourceLocation getTemplateKeywordLoc() const {
3006 if (!hasTemplateKWAndArgsInfo())
3007 return SourceLocation();
3008 return getTrailingASTTemplateKWAndArgsInfo()->TemplateKWLoc;
3009 }
3010
3011 /// Retrieve the location of the left angle bracket starting the
3012 /// explicit template argument list following the name, if any.
3013 SourceLocation getLAngleLoc() const {
3014 if (!hasTemplateKWAndArgsInfo())
3015 return SourceLocation();
3016 return getTrailingASTTemplateKWAndArgsInfo()->LAngleLoc;
3017 }
3018
3019 /// Retrieve the location of the right angle bracket ending the
3020 /// explicit template argument list following the name, if any.
3021 SourceLocation getRAngleLoc() const {
3022 if (!hasTemplateKWAndArgsInfo())
3023 return SourceLocation();
3024 return getTrailingASTTemplateKWAndArgsInfo()->RAngleLoc;
3025 }
3026
3027 /// Determines whether the name was preceded by the template keyword.
3028 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
3029
3030 /// Determines whether this expression had explicit template arguments.
3031 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
3032
3033 TemplateArgumentLoc const *getTemplateArgs() const {
3034 if (!hasExplicitTemplateArgs())
3035 return nullptr;
3036 return const_cast<OverloadExpr *>(this)->getTrailingTemplateArgumentLoc();
3037 }
3038
3039 unsigned getNumTemplateArgs() const {
3040 if (!hasExplicitTemplateArgs())
3041 return 0;
3042
3043 return getTrailingASTTemplateKWAndArgsInfo()->NumTemplateArgs;
3044 }
3045
3046 ArrayRef<TemplateArgumentLoc> template_arguments() const {
3047 return {getTemplateArgs(), getNumTemplateArgs()};
3048 }
3049
3050 /// Copies the template arguments into the given structure.
3051 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
3052 if (hasExplicitTemplateArgs())
3053 getTrailingASTTemplateKWAndArgsInfo()->copyInto(getTemplateArgs(), List);
3054 }
3055
3056 static bool classof(const Stmt *T) {
3057 return T->getStmtClass() == UnresolvedLookupExprClass ||
3058 T->getStmtClass() == UnresolvedMemberExprClass;
3059 }
3060};
3061
3062/// A reference to a name which we were able to look up during
3063/// parsing but could not resolve to a specific declaration.
3064///
3065/// This arises in several ways:
3066/// * we might be waiting for argument-dependent lookup;
3067/// * the name might resolve to an overloaded function;
3068/// and eventually:
3069/// * the lookup might have included a function template.
3070///
3071/// These never include UnresolvedUsingValueDecls, which are always class
3072/// members and therefore appear only in UnresolvedMemberLookupExprs.
3073class UnresolvedLookupExpr final
3074 : public OverloadExpr,
3075 private llvm::TrailingObjects<UnresolvedLookupExpr, DeclAccessPair,
3076 ASTTemplateKWAndArgsInfo,
3077 TemplateArgumentLoc> {
3078 friend class ASTStmtReader;
3079 friend class OverloadExpr;
3080 friend TrailingObjects;
3081
3082 /// The naming class (C++ [class.access.base]p5) of the lookup, if
3083 /// any. This can generally be recalculated from the context chain,
3084 /// but that can be fairly expensive for unqualified lookups.
3085 CXXRecordDecl *NamingClass;
3086
3087 // UnresolvedLookupExpr is followed by several trailing objects.
3088 // They are in order:
3089 //
3090 // * An array of getNumResults() DeclAccessPair for the results. These are
3091 // undesugared, which is to say, they may include UsingShadowDecls.
3092 // Access is relative to the naming class.
3093 //
3094 // * An optional ASTTemplateKWAndArgsInfo for the explicitly specified
3095 // template keyword and arguments. Present if and only if
3096 // hasTemplateKWAndArgsInfo().
3097 //
3098 // * An array of getNumTemplateArgs() TemplateArgumentLoc containing
3099 // location information for the explicitly specified template arguments.
3100
3101 UnresolvedLookupExpr(const ASTContext &Context, CXXRecordDecl *NamingClass,
3102 NestedNameSpecifierLoc QualifierLoc,
3103 SourceLocation TemplateKWLoc,
3104 const DeclarationNameInfo &NameInfo, bool RequiresADL,
3105 bool Overloaded,
3106 const TemplateArgumentListInfo *TemplateArgs,
3107 UnresolvedSetIterator Begin, UnresolvedSetIterator End);
3108
3109 UnresolvedLookupExpr(EmptyShell Empty, unsigned NumResults,
3110 bool HasTemplateKWAndArgsInfo);
3111
3112 unsigned numTrailingObjects(OverloadToken<DeclAccessPair>) const {
3113 return getNumDecls();
3114 }
3115
3116 unsigned numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
3117 return hasTemplateKWAndArgsInfo();
3118 }
3119
3120public:
3121 static UnresolvedLookupExpr *
3122 Create(const ASTContext &Context, CXXRecordDecl *NamingClass,
3123 NestedNameSpecifierLoc QualifierLoc,
3124 const DeclarationNameInfo &NameInfo, bool RequiresADL, bool Overloaded,
3125 UnresolvedSetIterator Begin, UnresolvedSetIterator End);
3126
3127 static UnresolvedLookupExpr *
3128 Create(const ASTContext &Context, CXXRecordDecl *NamingClass,
3129 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
3130 const DeclarationNameInfo &NameInfo, bool RequiresADL,
3131 const TemplateArgumentListInfo *Args, UnresolvedSetIterator Begin,
3132 UnresolvedSetIterator End);
3133
3134 static UnresolvedLookupExpr *CreateEmpty(const ASTContext &Context,
3135 unsigned NumResults,
3136 bool HasTemplateKWAndArgsInfo,
3137 unsigned NumTemplateArgs);
3138
3139 /// True if this declaration should be extended by
3140 /// argument-dependent lookup.
3141 bool requiresADL() const { return UnresolvedLookupExprBits.RequiresADL; }
3142
3143 /// True if this lookup is overloaded.
3144 bool isOverloaded() const { return UnresolvedLookupExprBits.Overloaded; }
3145
3146 /// Gets the 'naming class' (in the sense of C++0x
3147 /// [class.access.base]p5) of the lookup. This is the scope
3148 /// that was looked in to find these results.
3149 CXXRecordDecl *getNamingClass() { return NamingClass; }
3150 const CXXRecordDecl *getNamingClass() const { return NamingClass; }
3151
3152 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
3153 if (NestedNameSpecifierLoc l = getQualifierLoc())
3154 return l.getBeginLoc();
3155 return getNameInfo().getBeginLoc();
3156 }
3157
3158 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
3159 if (hasExplicitTemplateArgs())
3160 return getRAngleLoc();
3161 return getNameInfo().getEndLoc();
3162 }
3163
3164 child_range children() {
3165 return child_range(child_iterator(), child_iterator());
3166 }
3167
3168 const_child_range children() const {
3169 return const_child_range(const_child_iterator(), const_child_iterator());
3170 }
3171
3172 static bool classof(const Stmt *T) {
3173 return T->getStmtClass() == UnresolvedLookupExprClass;
3174 }
3175};
3176
3177/// A qualified reference to a name whose declaration cannot
3178/// yet be resolved.
3179///
3180/// DependentScopeDeclRefExpr is similar to DeclRefExpr in that
3181/// it expresses a reference to a declaration such as
3182/// X<T>::value. The difference, however, is that an
3183/// DependentScopeDeclRefExpr node is used only within C++ templates when
3184/// the qualification (e.g., X<T>::) refers to a dependent type. In
3185/// this case, X<T>::value cannot resolve to a declaration because the
3186/// declaration will differ from one instantiation of X<T> to the
3187/// next. Therefore, DependentScopeDeclRefExpr keeps track of the
3188/// qualifier (X<T>::) and the name of the entity being referenced
3189/// ("value"). Such expressions will instantiate to a DeclRefExpr once the
3190/// declaration can be found.
3191class DependentScopeDeclRefExpr final
3192 : public Expr,
3193 private llvm::TrailingObjects<DependentScopeDeclRefExpr,
3194 ASTTemplateKWAndArgsInfo,
3195 TemplateArgumentLoc> {
3196 friend class ASTStmtReader;
3197 friend class ASTStmtWriter;
3198 friend TrailingObjects;
3199
3200 /// The nested-name-specifier that qualifies this unresolved
3201 /// declaration name.
3202 NestedNameSpecifierLoc QualifierLoc;
3203
3204 /// The name of the entity we will be referencing.
3205 DeclarationNameInfo NameInfo;
3206
3207 DependentScopeDeclRefExpr(QualType Ty, NestedNameSpecifierLoc QualifierLoc,
3208 SourceLocation TemplateKWLoc,
3209 const DeclarationNameInfo &NameInfo,
3210 const TemplateArgumentListInfo *Args);
3211
3212 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
3213 return hasTemplateKWAndArgsInfo();
3214 }
3215
3216 bool hasTemplateKWAndArgsInfo() const {
3217 return DependentScopeDeclRefExprBits.HasTemplateKWAndArgsInfo;
3218 }
3219
3220public:
3221 static DependentScopeDeclRefExpr *
3222 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
3223 SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo,
3224 const TemplateArgumentListInfo *TemplateArgs);
3225
3226 static DependentScopeDeclRefExpr *CreateEmpty(const ASTContext &Context,
3227 bool HasTemplateKWAndArgsInfo,
3228 unsigned NumTemplateArgs);
3229
3230 /// Retrieve the name that this expression refers to.
3231 const DeclarationNameInfo &getNameInfo() const { return NameInfo; }
3232
3233 /// Retrieve the name that this expression refers to.
3234 DeclarationName getDeclName() const { return NameInfo.getName(); }
3235
3236 /// Retrieve the location of the name within the expression.
3237 ///
3238 /// For example, in "X<T>::value" this is the location of "value".
3239 SourceLocation getLocation() const { return NameInfo.getLoc(); }
3240
3241 /// Retrieve the nested-name-specifier that qualifies the
3242 /// name, with source location information.
3243 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3244
3245 /// Retrieve the nested-name-specifier that qualifies this
3246 /// declaration.
3247 NestedNameSpecifier *getQualifier() const {
3248 return QualifierLoc.getNestedNameSpecifier();
3249 }
3250
3251 /// Retrieve the location of the template keyword preceding
3252 /// this name, if any.
3253 SourceLocation getTemplateKeywordLoc() const {
3254 if (!hasTemplateKWAndArgsInfo())
3255 return SourceLocation();
3256 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
3257 }
3258
3259 /// Retrieve the location of the left angle bracket starting the
3260 /// explicit template argument list following the name, if any.
3261 SourceLocation getLAngleLoc() const {
3262 if (!hasTemplateKWAndArgsInfo())
3263 return SourceLocation();
3264 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
3265 }
3266
3267 /// Retrieve the location of the right angle bracket ending the
3268 /// explicit template argument list following the name, if any.
3269 SourceLocation getRAngleLoc() const {
3270 if (!hasTemplateKWAndArgsInfo())
3271 return SourceLocation();
3272 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
3273 }
3274
3275 /// Determines whether the name was preceded by the template keyword.
3276 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
3277
3278 /// Determines whether this lookup had explicit template arguments.
3279 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
3280
3281 /// Copies the template arguments (if present) into the given
3282 /// structure.
3283 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
3284 if (hasExplicitTemplateArgs())
3285 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
3286 getTrailingObjects<TemplateArgumentLoc>(), List);
3287 }
3288
3289 TemplateArgumentLoc const *getTemplateArgs() const {
3290 if (!hasExplicitTemplateArgs())
3291 return nullptr;
3292
3293 return getTrailingObjects<TemplateArgumentLoc>();
3294 }
3295
3296 unsigned getNumTemplateArgs() const {
3297 if (!hasExplicitTemplateArgs())
3298 return 0;
3299
3300 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
3301 }
3302
3303 ArrayRef<TemplateArgumentLoc> template_arguments() const {
3304 return {getTemplateArgs(), getNumTemplateArgs()};
3305 }
3306
3307 /// Note: getBeginLoc() is the start of the whole DependentScopeDeclRefExpr,
3308 /// and differs from getLocation().getStart().
3309 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
3310 return QualifierLoc.getBeginLoc();
3311 }
3312
3313 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
3314 if (hasExplicitTemplateArgs())
3315 return getRAngleLoc();
3316 return getLocation();
3317 }
3318
3319 static bool classof(const Stmt *T) {
3320 return T->getStmtClass() == DependentScopeDeclRefExprClass;
3321 }
3322
3323 child_range children() {
3324 return child_range(child_iterator(), child_iterator());
3325 }
3326
3327 const_child_range children() const {
3328 return const_child_range(const_child_iterator(), const_child_iterator());
3329 }
3330};
3331
3332/// Represents an expression -- generally a full-expression -- that
3333/// introduces cleanups to be run at the end of the sub-expression's
3334/// evaluation. The most common source of expression-introduced
3335/// cleanups is temporary objects in C++, but several other kinds of
3336/// expressions can create cleanups, including basically every
3337/// call in ARC that returns an Objective-C pointer.
3338///
3339/// This expression also tracks whether the sub-expression contains a
3340/// potentially-evaluated block literal. The lifetime of a block
3341/// literal is the extent of the enclosing scope.
3342class ExprWithCleanups final
3343 : public FullExpr,
3344 private llvm::TrailingObjects<
3345 ExprWithCleanups,
3346 llvm::PointerUnion<BlockDecl *, CompoundLiteralExpr *>> {
3347public:
3348 /// The type of objects that are kept in the cleanup.
3349 /// It's useful to remember the set of blocks and block-scoped compound
3350 /// literals; we could also remember the set of temporaries, but there's
3351 /// currently no need.
3352 using CleanupObject = llvm::PointerUnion<BlockDecl *, CompoundLiteralExpr *>;
3353
3354private:
3355 friend class ASTStmtReader;
3356 friend TrailingObjects;
3357
3358 ExprWithCleanups(EmptyShell, unsigned NumObjects);
3359 ExprWithCleanups(Expr *SubExpr, bool CleanupsHaveSideEffects,
3360 ArrayRef<CleanupObject> Objects);
3361
3362public:
3363 static ExprWithCleanups *Create(const ASTContext &C, EmptyShell empty,
3364 unsigned numObjects);
3365
3366 static ExprWithCleanups *Create(const ASTContext &C, Expr *subexpr,
3367 bool CleanupsHaveSideEffects,
3368 ArrayRef<CleanupObject> objects);
3369
3370 ArrayRef<CleanupObject> getObjects() const {
3371 return llvm::makeArrayRef(getTrailingObjects<CleanupObject>(),
3372 getNumObjects());
3373 }
3374
3375 unsigned getNumObjects() const { return ExprWithCleanupsBits.NumObjects; }
3376
3377 CleanupObject getObject(unsigned i) const {
3378 assert(i < getNumObjects() && "Index out of range")(static_cast<void> (0));
3379 return getObjects()[i];
3380 }
3381
3382 bool cleanupsHaveSideEffects() const {
3383 return ExprWithCleanupsBits.CleanupsHaveSideEffects;
3384 }
3385
3386 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
3387 return SubExpr->getBeginLoc();
3388 }
3389
3390 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
3391 return SubExpr->getEndLoc();
3392 }
3393
3394 // Implement isa/cast/dyncast/etc.
3395 static bool classof(const Stmt *T) {
3396 return T->getStmtClass() == ExprWithCleanupsClass;
3397 }
3398
3399 // Iterators
3400 child_range children() { return child_range(&SubExpr, &SubExpr + 1); }
3401
3402 const_child_range children() const {
3403 return const_child_range(&SubExpr, &SubExpr + 1);
3404 }
3405};
3406
3407/// Describes an explicit type conversion that uses functional
3408/// notion but could not be resolved because one or more arguments are
3409/// type-dependent.
3410///
3411/// The explicit type conversions expressed by
3412/// CXXUnresolvedConstructExpr have the form <tt>T(a1, a2, ..., aN)</tt>,
3413/// where \c T is some type and \c a1, \c a2, ..., \c aN are values, and
3414/// either \c T is a dependent type or one or more of the <tt>a</tt>'s is
3415/// type-dependent. For example, this would occur in a template such
3416/// as:
3417///
3418/// \code
3419/// template<typename T, typename A1>
3420/// inline T make_a(const A1& a1) {
3421/// return T(a1);
3422/// }
3423/// \endcode
3424///
3425/// When the returned expression is instantiated, it may resolve to a
3426/// constructor call, conversion function call, or some kind of type
3427/// conversion.
3428class CXXUnresolvedConstructExpr final
3429 : public Expr,
3430 private llvm::TrailingObjects<CXXUnresolvedConstructExpr, Expr *> {
3431 friend class ASTStmtReader;
3432 friend TrailingObjects;
3433
3434 /// The type being constructed.
3435 TypeSourceInfo *TSI;
3436
3437 /// The location of the left parentheses ('(').
3438 SourceLocation LParenLoc;
3439
3440 /// The location of the right parentheses (')').
3441 SourceLocation RParenLoc;
3442
3443 CXXUnresolvedConstructExpr(QualType T, TypeSourceInfo *TSI,
3444 SourceLocation LParenLoc, ArrayRef<Expr *> Args,
3445 SourceLocation RParenLoc);
3446
3447 CXXUnresolvedConstructExpr(EmptyShell Empty, unsigned NumArgs)
3448 : Expr(CXXUnresolvedConstructExprClass, Empty), TSI(nullptr) {
3449 CXXUnresolvedConstructExprBits.NumArgs = NumArgs;
3450 }
3451
3452public:
3453 static CXXUnresolvedConstructExpr *Create(const ASTContext &Context,
3454 QualType T, TypeSourceInfo *TSI,
3455 SourceLocation LParenLoc,
3456 ArrayRef<Expr *> Args,
3457 SourceLocation RParenLoc);
3458
3459 static CXXUnresolvedConstructExpr *CreateEmpty(const ASTContext &Context,
3460 unsigned NumArgs);
3461
3462 /// Retrieve the type that is being constructed, as specified
3463 /// in the source code.
3464 QualType getTypeAsWritten() const { return TSI->getType(); }
3465
3466 /// Retrieve the type source information for the type being
3467 /// constructed.
3468 TypeSourceInfo *getTypeSourceInfo() const { return TSI; }
3469
3470 /// Retrieve the location of the left parentheses ('(') that
3471 /// precedes the argument list.
3472 SourceLocation getLParenLoc() const { return LParenLoc; }
3473 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
3474
3475 /// Retrieve the location of the right parentheses (')') that
3476 /// follows the argument list.
3477 SourceLocation getRParenLoc() const { return RParenLoc; }
3478 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3479
3480 /// Determine whether this expression models list-initialization.
3481 /// If so, there will be exactly one subexpression, which will be
3482 /// an InitListExpr.
3483 bool isListInitialization() const { return LParenLoc.isInvalid(); }
3484
3485 /// Retrieve the number of arguments.
3486 unsigned getNumArgs() const { return CXXUnresolvedConstructExprBits.NumArgs; }
3487
3488 using arg_iterator = Expr **;
3489 using arg_range = llvm::iterator_range<arg_iterator>;
3490
3491 arg_iterator arg_begin() { return getTrailingObjects<Expr *>(); }
3492 arg_iterator arg_end() { return arg_begin() + getNumArgs(); }
3493 arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
3494
3495 using const_arg_iterator = const Expr* const *;
3496 using const_arg_range = llvm::iterator_range<const_arg_iterator>;
3497
3498 const_arg_iterator arg_begin() const { return getTrailingObjects<Expr *>(); }
3499 const_arg_iterator arg_end() const { return arg_begin() + getNumArgs(); }
3500 const_arg_range arguments() const {
3501 return const_arg_range(arg_begin(), arg_end());
3502 }
3503
3504 Expr *getArg(unsigned I) {
3505 assert(I < getNumArgs() && "Argument index out-of-range")(static_cast<void> (0));
3506 return arg_begin()[I];
3507 }
3508
3509 const Expr *getArg(unsigned I) const {
3510 assert(I < getNumArgs() && "Argument index out-of-range")(static_cast<void> (0));
3511 return arg_begin()[I];
3512 }
3513
3514 void setArg(unsigned I, Expr *E) {
3515 assert(I < getNumArgs() && "Argument index out-of-range"