Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -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 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/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-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/lib/CodeGen -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-01-13-084841-49055-1 -x c++ /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/CodeGen/CGExprCXX.cpp

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

/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/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/Decl.h"
19#include "clang/AST/DeclBase.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/DeclarationName.h"
23#include "clang/AST/Expr.h"
24#include "clang/AST/NestedNameSpecifier.h"
25#include "clang/AST/OperationKinds.h"
26#include "clang/AST/Stmt.h"
27#include "clang/AST/TemplateBase.h"
28#include "clang/AST/Type.h"
29#include "clang/AST/UnresolvedSet.h"
30#include "clang/Basic/ExceptionSpecificationType.h"
31#include "clang/Basic/ExpressionTraits.h"
32#include "clang/Basic/LLVM.h"
33#include "clang/Basic/Lambda.h"
34#include "clang/Basic/LangOptions.h"
35#include "clang/Basic/OperatorKinds.h"
36#include "clang/Basic/SourceLocation.h"
37#include "clang/Basic/Specifiers.h"
38#include "clang/Basic/TypeTraits.h"
39#include "llvm/ADT/ArrayRef.h"
40#include "llvm/ADT/None.h"
41#include "llvm/ADT/Optional.h"
42#include "llvm/ADT/PointerUnion.h"
43#include "llvm/ADT/StringRef.h"
44#include "llvm/ADT/iterator_range.h"
45#include "llvm/Support/Casting.h"
46#include "llvm/Support/Compiler.h"
47#include "llvm/Support/TrailingObjects.h"
48#include <cassert>
49#include <cstddef>
50#include <cstdint>
51#include <memory>
52
53namespace clang {
54
55class ASTContext;
56class DeclAccessPair;
57class IdentifierInfo;
58class LambdaCapture;
59class NonTypeTemplateParmDecl;
60class TemplateParameterList;
61
62//===--------------------------------------------------------------------===//
63// C++ Expressions.
64//===--------------------------------------------------------------------===//
65
66/// A call to an overloaded operator written using operator
67/// syntax.
68///
69/// Represents a call to an overloaded operator written using operator
70/// syntax, e.g., "x + y" or "*p". While semantically equivalent to a
71/// normal call, this AST node provides better information about the
72/// syntactic representation of the call.
73///
74/// In a C++ template, this expression node kind will be used whenever
75/// any of the arguments are type-dependent. In this case, the
76/// function itself will be a (possibly empty) set of functions and
77/// function templates that were found by name lookup at template
78/// definition time.
79class CXXOperatorCallExpr final : public CallExpr {
80 friend class ASTStmtReader;
81 friend class ASTStmtWriter;
82
83 SourceRange Range;
84
85 // CXXOperatorCallExpr has some trailing objects belonging
86 // to CallExpr. See CallExpr for the details.
87
88 SourceRange getSourceRangeImpl() const LLVM_READONLY__attribute__((__pure__));
89
90 CXXOperatorCallExpr(OverloadedOperatorKind OpKind, Expr *Fn,
91 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
92 SourceLocation OperatorLoc, FPOptions FPFeatures,
93 ADLCallKind UsesADL);
94
95 CXXOperatorCallExpr(unsigned NumArgs, EmptyShell Empty);
96
97public:
98 static CXXOperatorCallExpr *
99 Create(const ASTContext &Ctx, OverloadedOperatorKind OpKind, Expr *Fn,
100 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
101 SourceLocation OperatorLoc, FPOptions FPFeatures,
102 ADLCallKind UsesADL = NotADL);
103
104 static CXXOperatorCallExpr *CreateEmpty(const ASTContext &Ctx,
105 unsigned NumArgs, EmptyShell Empty);
106
107 /// Returns the kind of overloaded operator that this expression refers to.
108 OverloadedOperatorKind getOperator() const {
109 return static_cast<OverloadedOperatorKind>(
110 CXXOperatorCallExprBits.OperatorKind);
111 }
112
113 static bool isAssignmentOp(OverloadedOperatorKind Opc) {
114 return Opc == OO_Equal || Opc == OO_StarEqual || Opc == OO_SlashEqual ||
115 Opc == OO_PercentEqual || Opc == OO_PlusEqual ||
116 Opc == OO_MinusEqual || Opc == OO_LessLessEqual ||
117 Opc == OO_GreaterGreaterEqual || Opc == OO_AmpEqual ||
118 Opc == OO_CaretEqual || Opc == OO_PipeEqual;
119 }
120 bool isAssignmentOp() const { return isAssignmentOp(getOperator()); }
121
122 /// Is this written as an infix binary operator?
123 bool isInfixBinaryOp() const;
124
125 /// Returns the location of the operator symbol in the expression.
126 ///
127 /// When \c getOperator()==OO_Call, this is the location of the right
128 /// parentheses; when \c getOperator()==OO_Subscript, this is the location
129 /// of the right bracket.
130 SourceLocation getOperatorLoc() const { return getRParenLoc(); }
131
132 SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__)) {
133 OverloadedOperatorKind Operator = getOperator();
134 return (Operator < OO_Plus || Operator >= OO_Arrow ||
135 Operator == OO_PlusPlus || Operator == OO_MinusMinus)
136 ? getBeginLoc()
137 : getOperatorLoc();
138 }
139
140 SourceLocation getBeginLoc() const { return Range.getBegin(); }
141 SourceLocation getEndLoc() const { return Range.getEnd(); }
142 SourceRange getSourceRange() const { return Range; }
143
144 static bool classof(const Stmt *T) {
145 return T->getStmtClass() == CXXOperatorCallExprClass;
146 }
147
148 // Set the FP contractability status of this operator. Only meaningful for
149 // operations on floating point types.
150 void setFPFeatures(FPOptions F) {
151 CXXOperatorCallExprBits.FPFeatures = F.getInt();
152 }
153 FPOptions getFPFeatures() const {
154 return FPOptions(CXXOperatorCallExprBits.FPFeatures);
155 }
156
157 // Get the FP contractability status of this operator. Only meaningful for
158 // operations on floating point types.
159 bool isFPContractableWithinStatement() const {
160 return getFPFeatures().allowFPContractWithinStatement();
161 }
162};
163
164/// Represents a call to a member function that
165/// may be written either with member call syntax (e.g., "obj.func()"
166/// or "objptr->func()") or with normal function-call syntax
167/// ("func()") within a member function that ends up calling a member
168/// function. The callee in either case is a MemberExpr that contains
169/// both the object argument and the member function, while the
170/// arguments are the arguments within the parentheses (not including
171/// the object argument).
172class CXXMemberCallExpr final : public CallExpr {
173 // CXXMemberCallExpr has some trailing objects belonging
174 // to CallExpr. See CallExpr for the details.
175
176 CXXMemberCallExpr(Expr *Fn, ArrayRef<Expr *> Args, QualType Ty,
177 ExprValueKind VK, SourceLocation RP, unsigned MinNumArgs);
178
179 CXXMemberCallExpr(unsigned NumArgs, EmptyShell Empty);
180
181public:
182 static CXXMemberCallExpr *Create(const ASTContext &Ctx, Expr *Fn,
183 ArrayRef<Expr *> Args, QualType Ty,
184 ExprValueKind VK, SourceLocation RP,
185 unsigned MinNumArgs = 0);
186
187 static CXXMemberCallExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
188 EmptyShell Empty);
189
190 /// Retrieve the implicit object argument for the member call.
191 ///
192 /// For example, in "x.f(5)", this returns the sub-expression "x".
193 Expr *getImplicitObjectArgument() const;
194
195 /// Retrieve the type of the object argument.
196 ///
197 /// Note that this always returns a non-pointer type.
198 QualType getObjectType() const;
199
200 /// Retrieve the declaration of the called method.
201 CXXMethodDecl *getMethodDecl() const;
202
203 /// Retrieve the CXXRecordDecl for the underlying type of
204 /// the implicit object argument.
205 ///
206 /// Note that this is may not be the same declaration as that of the class
207 /// context of the CXXMethodDecl which this function is calling.
208 /// FIXME: Returns 0 for member pointer call exprs.
209 CXXRecordDecl *getRecordDecl() const;
210
211 SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__)) {
212 SourceLocation CLoc = getCallee()->getExprLoc();
213 if (CLoc.isValid())
214 return CLoc;
215
216 return getBeginLoc();
217 }
218
219 static bool classof(const Stmt *T) {
220 return T->getStmtClass() == CXXMemberCallExprClass;
221 }
222};
223
224/// Represents a call to a CUDA kernel function.
225class CUDAKernelCallExpr final : public CallExpr {
226 friend class ASTStmtReader;
227
228 enum { CONFIG, END_PREARG };
229
230 // CUDAKernelCallExpr has some trailing objects belonging
231 // to CallExpr. See CallExpr for the details.
232
233 CUDAKernelCallExpr(Expr *Fn, CallExpr *Config, ArrayRef<Expr *> Args,
234 QualType Ty, ExprValueKind VK, SourceLocation RP,
235 unsigned MinNumArgs);
236
237 CUDAKernelCallExpr(unsigned NumArgs, EmptyShell Empty);
238
239public:
240 static CUDAKernelCallExpr *Create(const ASTContext &Ctx, Expr *Fn,
241 CallExpr *Config, ArrayRef<Expr *> Args,
242 QualType Ty, ExprValueKind VK,
243 SourceLocation RP, unsigned MinNumArgs = 0);
244
245 static CUDAKernelCallExpr *CreateEmpty(const ASTContext &Ctx,
246 unsigned NumArgs, EmptyShell Empty);
247
248 const CallExpr *getConfig() const {
249 return cast_or_null<CallExpr>(getPreArg(CONFIG));
250 }
251 CallExpr *getConfig() { return cast_or_null<CallExpr>(getPreArg(CONFIG)); }
252
253 static bool classof(const Stmt *T) {
254 return T->getStmtClass() == CUDAKernelCallExprClass;
255 }
256};
257
258/// A rewritten comparison expression that was originally written using
259/// operator syntax.
260///
261/// In C++20, the following rewrites are performed:
262/// - <tt>a == b</tt> -> <tt>b == a</tt>
263/// - <tt>a != b</tt> -> <tt>!(a == b)</tt>
264/// - <tt>a != b</tt> -> <tt>!(b == a)</tt>
265/// - For \c \@ in \c <, \c <=, \c >, \c >=, \c <=>:
266/// - <tt>a @ b</tt> -> <tt>(a <=> b) @ 0</tt>
267/// - <tt>a @ b</tt> -> <tt>0 @ (b <=> a)</tt>
268///
269/// This expression provides access to both the original syntax and the
270/// rewritten expression.
271///
272/// Note that the rewritten calls to \c ==, \c <=>, and \c \@ are typically
273/// \c CXXOperatorCallExprs, but could theoretically be \c BinaryOperators.
274class CXXRewrittenBinaryOperator : public Expr {
275 friend class ASTStmtReader;
276
277 /// The rewritten semantic form.
278 Stmt *SemanticForm;
279
280public:
281 CXXRewrittenBinaryOperator(Expr *SemanticForm, bool IsReversed)
282 : Expr(CXXRewrittenBinaryOperatorClass, SemanticForm->getType(),
283 SemanticForm->getValueKind(), SemanticForm->getObjectKind(),
284 SemanticForm->isTypeDependent(), SemanticForm->isValueDependent(),
285 SemanticForm->isInstantiationDependent(),
286 SemanticForm->containsUnexpandedParameterPack()),
287 SemanticForm(SemanticForm) {
288 CXXRewrittenBinaryOperatorBits.IsReversed = IsReversed;
289 }
290 CXXRewrittenBinaryOperator(EmptyShell Empty)
291 : Expr(CXXRewrittenBinaryOperatorClass, Empty), SemanticForm() {}
292
293 /// Get an equivalent semantic form for this expression.
294 Expr *getSemanticForm() { return cast<Expr>(SemanticForm); }
295 const Expr *getSemanticForm() const { return cast<Expr>(SemanticForm); }
296
297 struct DecomposedForm {
298 /// The original opcode, prior to rewriting.
299 BinaryOperatorKind Opcode;
300 /// The original left-hand side.
301 const Expr *LHS;
302 /// The original right-hand side.
303 const Expr *RHS;
304 /// The inner \c == or \c <=> operator expression.
305 const Expr *InnerBinOp;
306 };
307
308 /// Decompose this operator into its syntactic form.
309 DecomposedForm getDecomposedForm() const LLVM_READONLY__attribute__((__pure__));
310
311 /// Determine whether this expression was rewritten in reverse form.
312 bool isReversed() const { return CXXRewrittenBinaryOperatorBits.IsReversed; }
313
314 BinaryOperatorKind getOperator() const { return getDecomposedForm().Opcode; }
315 const Expr *getLHS() const { return getDecomposedForm().LHS; }
316 const Expr *getRHS() const { return getDecomposedForm().RHS; }
317
318 SourceLocation getOperatorLoc() const LLVM_READONLY__attribute__((__pure__)) {
319 return getDecomposedForm().InnerBinOp->getExprLoc();
320 }
321 SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__)) { return getOperatorLoc(); }
322
323 /// Compute the begin and end locations from the decomposed form.
324 /// The locations of the semantic form are not reliable if this is
325 /// a reversed expression.
326 //@{
327 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
328 return getDecomposedForm().LHS->getBeginLoc();
329 }
330 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
331 return getDecomposedForm().RHS->getEndLoc();
332 }
333 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) {
334 DecomposedForm DF = getDecomposedForm();
335 return SourceRange(DF.LHS->getBeginLoc(), DF.RHS->getEndLoc());
336 }
337 //@}
338
339 child_range children() {
340 return child_range(&SemanticForm, &SemanticForm + 1);
341 }
342
343 static bool classof(const Stmt *T) {
344 return T->getStmtClass() == CXXRewrittenBinaryOperatorClass;
345 }
346};
347
348/// Abstract class common to all of the C++ "named"/"keyword" casts.
349///
350/// This abstract class is inherited by all of the classes
351/// representing "named" casts: CXXStaticCastExpr for \c static_cast,
352/// CXXDynamicCastExpr for \c dynamic_cast, CXXReinterpretCastExpr for
353/// reinterpret_cast, and CXXConstCastExpr for \c const_cast.
354class CXXNamedCastExpr : public ExplicitCastExpr {
355private:
356 // the location of the casting op
357 SourceLocation Loc;
358
359 // the location of the right parenthesis
360 SourceLocation RParenLoc;
361
362 // range for '<' '>'
363 SourceRange AngleBrackets;
364
365protected:
366 friend class ASTStmtReader;
367
368 CXXNamedCastExpr(StmtClass SC, QualType ty, ExprValueKind VK,
369 CastKind kind, Expr *op, unsigned PathSize,
370 TypeSourceInfo *writtenTy, SourceLocation l,
371 SourceLocation RParenLoc,
372 SourceRange AngleBrackets)
373 : ExplicitCastExpr(SC, ty, VK, kind, op, PathSize, writtenTy), Loc(l),
374 RParenLoc(RParenLoc), AngleBrackets(AngleBrackets) {}
375
376 explicit CXXNamedCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize)
377 : ExplicitCastExpr(SC, Shell, PathSize) {}
378
379public:
380 const char *getCastName() const;
381
382 /// Retrieve the location of the cast operator keyword, e.g.,
383 /// \c static_cast.
384 SourceLocation getOperatorLoc() const { return Loc; }
385
386 /// Retrieve the location of the closing parenthesis.
387 SourceLocation getRParenLoc() const { return RParenLoc; }
388
389 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
390 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; }
391 SourceRange getAngleBrackets() const LLVM_READONLY__attribute__((__pure__)) { return AngleBrackets; }
392
393 static bool classof(const Stmt *T) {
394 switch (T->getStmtClass()) {
395 case CXXStaticCastExprClass:
396 case CXXDynamicCastExprClass:
397 case CXXReinterpretCastExprClass:
398 case CXXConstCastExprClass:
399 return true;
400 default:
401 return false;
402 }
403 }
404};
405
406/// A C++ \c static_cast expression (C++ [expr.static.cast]).
407///
408/// This expression node represents a C++ static cast, e.g.,
409/// \c static_cast<int>(1.0).
410class CXXStaticCastExpr final
411 : public CXXNamedCastExpr,
412 private llvm::TrailingObjects<CXXStaticCastExpr, CXXBaseSpecifier *> {
413 CXXStaticCastExpr(QualType ty, ExprValueKind vk, CastKind kind, Expr *op,
414 unsigned pathSize, TypeSourceInfo *writtenTy,
415 SourceLocation l, SourceLocation RParenLoc,
416 SourceRange AngleBrackets)
417 : CXXNamedCastExpr(CXXStaticCastExprClass, ty, vk, kind, op, pathSize,
418 writtenTy, l, RParenLoc, AngleBrackets) {}
419
420 explicit CXXStaticCastExpr(EmptyShell Empty, unsigned PathSize)
421 : CXXNamedCastExpr(CXXStaticCastExprClass, Empty, PathSize) {}
422
423public:
424 friend class CastExpr;
425 friend TrailingObjects;
426
427 static CXXStaticCastExpr *Create(const ASTContext &Context, QualType T,
428 ExprValueKind VK, CastKind K, Expr *Op,
429 const CXXCastPath *Path,
430 TypeSourceInfo *Written, SourceLocation L,
431 SourceLocation RParenLoc,
432 SourceRange AngleBrackets);
433 static CXXStaticCastExpr *CreateEmpty(const ASTContext &Context,
434 unsigned PathSize);
435
436 static bool classof(const Stmt *T) {
437 return T->getStmtClass() == CXXStaticCastExprClass;
438 }
439};
440
441/// A C++ @c dynamic_cast expression (C++ [expr.dynamic.cast]).
442///
443/// This expression node represents a dynamic cast, e.g.,
444/// \c dynamic_cast<Derived*>(BasePtr). Such a cast may perform a run-time
445/// check to determine how to perform the type conversion.
446class CXXDynamicCastExpr final
447 : public CXXNamedCastExpr,
448 private llvm::TrailingObjects<CXXDynamicCastExpr, CXXBaseSpecifier *> {
449 CXXDynamicCastExpr(QualType ty, ExprValueKind VK, CastKind kind,
450 Expr *op, unsigned pathSize, TypeSourceInfo *writtenTy,
451 SourceLocation l, SourceLocation RParenLoc,
452 SourceRange AngleBrackets)
453 : CXXNamedCastExpr(CXXDynamicCastExprClass, ty, VK, kind, op, pathSize,
454 writtenTy, l, RParenLoc, AngleBrackets) {}
455
456 explicit CXXDynamicCastExpr(EmptyShell Empty, unsigned pathSize)
457 : CXXNamedCastExpr(CXXDynamicCastExprClass, Empty, pathSize) {}
458
459public:
460 friend class CastExpr;
461 friend TrailingObjects;
462
463 static CXXDynamicCastExpr *Create(const ASTContext &Context, QualType T,
464 ExprValueKind VK, CastKind Kind, Expr *Op,
465 const CXXCastPath *Path,
466 TypeSourceInfo *Written, SourceLocation L,
467 SourceLocation RParenLoc,
468 SourceRange AngleBrackets);
469
470 static CXXDynamicCastExpr *CreateEmpty(const ASTContext &Context,
471 unsigned pathSize);
472
473 bool isAlwaysNull() const;
474
475 static bool classof(const Stmt *T) {
476 return T->getStmtClass() == CXXDynamicCastExprClass;
477 }
478};
479
480/// A C++ @c reinterpret_cast expression (C++ [expr.reinterpret.cast]).
481///
482/// This expression node represents a reinterpret cast, e.g.,
483/// @c reinterpret_cast<int>(VoidPtr).
484///
485/// A reinterpret_cast provides a differently-typed view of a value but
486/// (in Clang, as in most C++ implementations) performs no actual work at
487/// run time.
488class CXXReinterpretCastExpr final
489 : public CXXNamedCastExpr,
490 private llvm::TrailingObjects<CXXReinterpretCastExpr,
491 CXXBaseSpecifier *> {
492 CXXReinterpretCastExpr(QualType ty, ExprValueKind vk, CastKind kind,
493 Expr *op, unsigned pathSize,
494 TypeSourceInfo *writtenTy, SourceLocation l,
495 SourceLocation RParenLoc,
496 SourceRange AngleBrackets)
497 : CXXNamedCastExpr(CXXReinterpretCastExprClass, ty, vk, kind, op,
498 pathSize, writtenTy, l, RParenLoc, AngleBrackets) {}
499
500 CXXReinterpretCastExpr(EmptyShell Empty, unsigned pathSize)
501 : CXXNamedCastExpr(CXXReinterpretCastExprClass, Empty, pathSize) {}
502
503public:
504 friend class CastExpr;
505 friend TrailingObjects;
506
507 static CXXReinterpretCastExpr *Create(const ASTContext &Context, QualType T,
508 ExprValueKind VK, CastKind Kind,
509 Expr *Op, const CXXCastPath *Path,
510 TypeSourceInfo *WrittenTy, SourceLocation L,
511 SourceLocation RParenLoc,
512 SourceRange AngleBrackets);
513 static CXXReinterpretCastExpr *CreateEmpty(const ASTContext &Context,
514 unsigned pathSize);
515
516 static bool classof(const Stmt *T) {
517 return T->getStmtClass() == CXXReinterpretCastExprClass;
518 }
519};
520
521/// A C++ \c const_cast expression (C++ [expr.const.cast]).
522///
523/// This expression node represents a const cast, e.g.,
524/// \c const_cast<char*>(PtrToConstChar).
525///
526/// A const_cast can remove type qualifiers but does not change the underlying
527/// value.
528class CXXConstCastExpr final
529 : public CXXNamedCastExpr,
530 private llvm::TrailingObjects<CXXConstCastExpr, CXXBaseSpecifier *> {
531 CXXConstCastExpr(QualType ty, ExprValueKind VK, Expr *op,
532 TypeSourceInfo *writtenTy, SourceLocation l,
533 SourceLocation RParenLoc, SourceRange AngleBrackets)
534 : CXXNamedCastExpr(CXXConstCastExprClass, ty, VK, CK_NoOp, op,
535 0, writtenTy, l, RParenLoc, AngleBrackets) {}
536
537 explicit CXXConstCastExpr(EmptyShell Empty)
538 : CXXNamedCastExpr(CXXConstCastExprClass, Empty, 0) {}
539
540public:
541 friend class CastExpr;
542 friend TrailingObjects;
543
544 static CXXConstCastExpr *Create(const ASTContext &Context, QualType T,
545 ExprValueKind VK, Expr *Op,
546 TypeSourceInfo *WrittenTy, SourceLocation L,
547 SourceLocation RParenLoc,
548 SourceRange AngleBrackets);
549 static CXXConstCastExpr *CreateEmpty(const ASTContext &Context);
550
551 static bool classof(const Stmt *T) {
552 return T->getStmtClass() == CXXConstCastExprClass;
553 }
554};
555
556/// A call to a literal operator (C++11 [over.literal])
557/// written as a user-defined literal (C++11 [lit.ext]).
558///
559/// Represents a user-defined literal, e.g. "foo"_bar or 1.23_xyz. While this
560/// is semantically equivalent to a normal call, this AST node provides better
561/// information about the syntactic representation of the literal.
562///
563/// Since literal operators are never found by ADL and can only be declared at
564/// namespace scope, a user-defined literal is never dependent.
565class UserDefinedLiteral final : public CallExpr {
566 friend class ASTStmtReader;
567 friend class ASTStmtWriter;
568
569 /// The location of a ud-suffix within the literal.
570 SourceLocation UDSuffixLoc;
571
572 // UserDefinedLiteral has some trailing objects belonging
573 // to CallExpr. See CallExpr for the details.
574
575 UserDefinedLiteral(Expr *Fn, ArrayRef<Expr *> Args, QualType Ty,
576 ExprValueKind VK, SourceLocation LitEndLoc,
577 SourceLocation SuffixLoc);
578
579 UserDefinedLiteral(unsigned NumArgs, EmptyShell Empty);
580
581public:
582 static UserDefinedLiteral *Create(const ASTContext &Ctx, Expr *Fn,
583 ArrayRef<Expr *> Args, QualType Ty,
584 ExprValueKind VK, SourceLocation LitEndLoc,
585 SourceLocation SuffixLoc);
586
587 static UserDefinedLiteral *CreateEmpty(const ASTContext &Ctx,
588 unsigned NumArgs, EmptyShell Empty);
589
590 /// The kind of literal operator which is invoked.
591 enum LiteralOperatorKind {
592 /// Raw form: operator "" X (const char *)
593 LOK_Raw,
594
595 /// Raw form: operator "" X<cs...> ()
596 LOK_Template,
597
598 /// operator "" X (unsigned long long)
599 LOK_Integer,
600
601 /// operator "" X (long double)
602 LOK_Floating,
603
604 /// operator "" X (const CharT *, size_t)
605 LOK_String,
606
607 /// operator "" X (CharT)
608 LOK_Character
609 };
610
611 /// Returns the kind of literal operator invocation
612 /// which this expression represents.
613 LiteralOperatorKind getLiteralOperatorKind() const;
614
615 /// If this is not a raw user-defined literal, get the
616 /// underlying cooked literal (representing the literal with the suffix
617 /// removed).
618 Expr *getCookedLiteral();
619 const Expr *getCookedLiteral() const {
620 return const_cast<UserDefinedLiteral*>(this)->getCookedLiteral();
621 }
622
623 SourceLocation getBeginLoc() const {
624 if (getLiteralOperatorKind() == LOK_Template)
625 return getRParenLoc();
626 return getArg(0)->getBeginLoc();
627 }
628
629 SourceLocation getEndLoc() const { return getRParenLoc(); }
630
631 /// Returns the location of a ud-suffix in the expression.
632 ///
633 /// For a string literal, there may be multiple identical suffixes. This
634 /// returns the first.
635 SourceLocation getUDSuffixLoc() const { return UDSuffixLoc; }
636
637 /// Returns the ud-suffix specified for this literal.
638 const IdentifierInfo *getUDSuffix() const;
639
640 static bool classof(const Stmt *S) {
641 return S->getStmtClass() == UserDefinedLiteralClass;
642 }
643};
644
645/// A boolean literal, per ([C++ lex.bool] Boolean literals).
646class CXXBoolLiteralExpr : public Expr {
647public:
648 CXXBoolLiteralExpr(bool Val, QualType Ty, SourceLocation Loc)
649 : Expr(CXXBoolLiteralExprClass, Ty, VK_RValue, OK_Ordinary, false, false,
650 false, false) {
651 CXXBoolLiteralExprBits.Value = Val;
652 CXXBoolLiteralExprBits.Loc = Loc;
653 }
654
655 explicit CXXBoolLiteralExpr(EmptyShell Empty)
656 : Expr(CXXBoolLiteralExprClass, Empty) {}
657
658 bool getValue() const { return CXXBoolLiteralExprBits.Value; }
659 void setValue(bool V) { CXXBoolLiteralExprBits.Value = V; }
660
661 SourceLocation getBeginLoc() const { return getLocation(); }
662 SourceLocation getEndLoc() const { return getLocation(); }
663
664 SourceLocation getLocation() const { return CXXBoolLiteralExprBits.Loc; }
665 void setLocation(SourceLocation L) { CXXBoolLiteralExprBits.Loc = L; }
666
667 static bool classof(const Stmt *T) {
668 return T->getStmtClass() == CXXBoolLiteralExprClass;
669 }
670
671 // Iterators
672 child_range children() {
673 return child_range(child_iterator(), child_iterator());
674 }
675
676 const_child_range children() const {
677 return const_child_range(const_child_iterator(), const_child_iterator());
678 }
679};
680
681/// The null pointer literal (C++11 [lex.nullptr])
682///
683/// Introduced in C++11, the only literal of type \c nullptr_t is \c nullptr.
684class CXXNullPtrLiteralExpr : public Expr {
685public:
686 CXXNullPtrLiteralExpr(QualType Ty, SourceLocation Loc)
687 : Expr(CXXNullPtrLiteralExprClass, Ty, VK_RValue, OK_Ordinary, false,
688 false, false, false) {
689 CXXNullPtrLiteralExprBits.Loc = Loc;
690 }
691
692 explicit CXXNullPtrLiteralExpr(EmptyShell Empty)
693 : Expr(CXXNullPtrLiteralExprClass, Empty) {}
694
695 SourceLocation getBeginLoc() const { return getLocation(); }
696 SourceLocation getEndLoc() const { return getLocation(); }
697
698 SourceLocation getLocation() const { return CXXNullPtrLiteralExprBits.Loc; }
699 void setLocation(SourceLocation L) { CXXNullPtrLiteralExprBits.Loc = L; }
700
701 static bool classof(const Stmt *T) {
702 return T->getStmtClass() == CXXNullPtrLiteralExprClass;
703 }
704
705 child_range children() {
706 return child_range(child_iterator(), child_iterator());
707 }
708
709 const_child_range children() const {
710 return const_child_range(const_child_iterator(), const_child_iterator());
711 }
712};
713
714/// Implicit construction of a std::initializer_list<T> object from an
715/// array temporary within list-initialization (C++11 [dcl.init.list]p5).
716class CXXStdInitializerListExpr : public Expr {
717 Stmt *SubExpr = nullptr;
718
719 CXXStdInitializerListExpr(EmptyShell Empty)
720 : Expr(CXXStdInitializerListExprClass, Empty) {}
721
722public:
723 friend class ASTReader;
724 friend class ASTStmtReader;
725
726 CXXStdInitializerListExpr(QualType Ty, Expr *SubExpr)
727 : Expr(CXXStdInitializerListExprClass, Ty, VK_RValue, OK_Ordinary,
728 Ty->isDependentType(), SubExpr->isValueDependent(),
729 SubExpr->isInstantiationDependent(),
730 SubExpr->containsUnexpandedParameterPack()),
731 SubExpr(SubExpr) {}
732
733 Expr *getSubExpr() { return static_cast<Expr*>(SubExpr); }
734 const Expr *getSubExpr() const { return static_cast<const Expr*>(SubExpr); }
735
736 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
737 return SubExpr->getBeginLoc();
738 }
739
740 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
741 return SubExpr->getEndLoc();
742 }
743
744 /// Retrieve the source range of the expression.
745 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) {
746 return SubExpr->getSourceRange();
747 }
748
749 static bool classof(const Stmt *S) {
750 return S->getStmtClass() == CXXStdInitializerListExprClass;
751 }
752
753 child_range children() { return child_range(&SubExpr, &SubExpr + 1); }
754
755 const_child_range children() const {
756 return const_child_range(&SubExpr, &SubExpr + 1);
757 }
758};
759
760/// A C++ \c typeid expression (C++ [expr.typeid]), which gets
761/// the \c type_info that corresponds to the supplied type, or the (possibly
762/// dynamic) type of the supplied expression.
763///
764/// This represents code like \c typeid(int) or \c typeid(*objPtr)
765class CXXTypeidExpr : public Expr {
766private:
767 llvm::PointerUnion<Stmt *, TypeSourceInfo *> Operand;
768 SourceRange Range;
769
770public:
771 CXXTypeidExpr(QualType Ty, TypeSourceInfo *Operand, SourceRange R)
772 : Expr(CXXTypeidExprClass, Ty, VK_LValue, OK_Ordinary,
773 // typeid is never type-dependent (C++ [temp.dep.expr]p4)
774 false,
775 // typeid is value-dependent if the type or expression are
776 // dependent
777 Operand->getType()->isDependentType(),
778 Operand->getType()->isInstantiationDependentType(),
779 Operand->getType()->containsUnexpandedParameterPack()),
780 Operand(Operand), Range(R) {}
781
782 CXXTypeidExpr(QualType Ty, Expr *Operand, SourceRange R)
783 : Expr(CXXTypeidExprClass, Ty, VK_LValue, OK_Ordinary,
784 // typeid is never type-dependent (C++ [temp.dep.expr]p4)
785 false,
786 // typeid is value-dependent if the type or expression are
787 // dependent
788 Operand->isTypeDependent() || Operand->isValueDependent(),
789 Operand->isInstantiationDependent(),
790 Operand->containsUnexpandedParameterPack()),
791 Operand(Operand), Range(R) {}
792
793 CXXTypeidExpr(EmptyShell Empty, bool isExpr)
794 : Expr(CXXTypeidExprClass, Empty) {
795 if (isExpr)
796 Operand = (Expr*)nullptr;
797 else
798 Operand = (TypeSourceInfo*)nullptr;
799 }
800
801 /// Determine whether this typeid has a type operand which is potentially
802 /// evaluated, per C++11 [expr.typeid]p3.
803 bool isPotentiallyEvaluated() const;
804
805 bool isTypeOperand() const { return Operand.is<TypeSourceInfo *>(); }
806
807 /// Retrieves the type operand of this typeid() expression after
808 /// various required adjustments (removing reference types, cv-qualifiers).
809 QualType getTypeOperand(ASTContext &Context) const;
810
811 /// Retrieve source information for the type operand.
812 TypeSourceInfo *getTypeOperandSourceInfo() const {
813 assert(isTypeOperand() && "Cannot call getTypeOperand for typeid(expr)")((isTypeOperand() && "Cannot call getTypeOperand for typeid(expr)"
) ? static_cast<void> (0) : __assert_fail ("isTypeOperand() && \"Cannot call getTypeOperand for typeid(expr)\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 813, __PRETTY_FUNCTION__))
;
814 return Operand.get<TypeSourceInfo *>();
815 }
816
817 void setTypeOperandSourceInfo(TypeSourceInfo *TSI) {
818 assert(isTypeOperand() && "Cannot call getTypeOperand for typeid(expr)")((isTypeOperand() && "Cannot call getTypeOperand for typeid(expr)"
) ? static_cast<void> (0) : __assert_fail ("isTypeOperand() && \"Cannot call getTypeOperand for typeid(expr)\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 818, __PRETTY_FUNCTION__))
;
819 Operand = TSI;
820 }
821
822 Expr *getExprOperand() const {
823 assert(!isTypeOperand() && "Cannot call getExprOperand for typeid(type)")((!isTypeOperand() && "Cannot call getExprOperand for typeid(type)"
) ? static_cast<void> (0) : __assert_fail ("!isTypeOperand() && \"Cannot call getExprOperand for typeid(type)\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 823, __PRETTY_FUNCTION__))
;
824 return static_cast<Expr*>(Operand.get<Stmt *>());
825 }
826
827 void setExprOperand(Expr *E) {
828 assert(!isTypeOperand() && "Cannot call getExprOperand for typeid(type)")((!isTypeOperand() && "Cannot call getExprOperand for typeid(type)"
) ? static_cast<void> (0) : __assert_fail ("!isTypeOperand() && \"Cannot call getExprOperand for typeid(type)\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 828, __PRETTY_FUNCTION__))
;
829 Operand = E;
830 }
831
832 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getBegin(); }
833 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getEnd(); }
834 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) { return Range; }
835 void setSourceRange(SourceRange R) { Range = R; }
836
837 static bool classof(const Stmt *T) {
838 return T->getStmtClass() == CXXTypeidExprClass;
839 }
840
841 // Iterators
842 child_range children() {
843 if (isTypeOperand())
844 return child_range(child_iterator(), child_iterator());
845 auto **begin = reinterpret_cast<Stmt **>(&Operand);
846 return child_range(begin, begin + 1);
847 }
848
849 const_child_range children() const {
850 if (isTypeOperand())
851 return const_child_range(const_child_iterator(), const_child_iterator());
852
853 auto **begin =
854 reinterpret_cast<Stmt **>(&const_cast<CXXTypeidExpr *>(this)->Operand);
855 return const_child_range(begin, begin + 1);
856 }
857};
858
859/// A member reference to an MSPropertyDecl.
860///
861/// This expression always has pseudo-object type, and therefore it is
862/// typically not encountered in a fully-typechecked expression except
863/// within the syntactic form of a PseudoObjectExpr.
864class MSPropertyRefExpr : public Expr {
865 Expr *BaseExpr;
866 MSPropertyDecl *TheDecl;
867 SourceLocation MemberLoc;
868 bool IsArrow;
869 NestedNameSpecifierLoc QualifierLoc;
870
871public:
872 friend class ASTStmtReader;
873
874 MSPropertyRefExpr(Expr *baseExpr, MSPropertyDecl *decl, bool isArrow,
875 QualType ty, ExprValueKind VK,
876 NestedNameSpecifierLoc qualifierLoc,
877 SourceLocation nameLoc)
878 : Expr(MSPropertyRefExprClass, ty, VK, OK_Ordinary,
879 /*type-dependent*/ false, baseExpr->isValueDependent(),
880 baseExpr->isInstantiationDependent(),
881 baseExpr->containsUnexpandedParameterPack()),
882 BaseExpr(baseExpr), TheDecl(decl),
883 MemberLoc(nameLoc), IsArrow(isArrow),
884 QualifierLoc(qualifierLoc) {}
885
886 MSPropertyRefExpr(EmptyShell Empty) : Expr(MSPropertyRefExprClass, Empty) {}
887
888 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) {
889 return SourceRange(getBeginLoc(), getEndLoc());
890 }
891
892 bool isImplicitAccess() const {
893 return getBaseExpr() && getBaseExpr()->isImplicitCXXThis();
894 }
895
896 SourceLocation getBeginLoc() const {
897 if (!isImplicitAccess())
898 return BaseExpr->getBeginLoc();
899 else if (QualifierLoc)
900 return QualifierLoc.getBeginLoc();
901 else
902 return MemberLoc;
903 }
904
905 SourceLocation getEndLoc() const { return getMemberLoc(); }
906
907 child_range children() {
908 return child_range((Stmt**)&BaseExpr, (Stmt**)&BaseExpr + 1);
909 }
910
911 const_child_range children() const {
912 auto Children = const_cast<MSPropertyRefExpr *>(this)->children();
913 return const_child_range(Children.begin(), Children.end());
914 }
915
916 static bool classof(const Stmt *T) {
917 return T->getStmtClass() == MSPropertyRefExprClass;
918 }
919
920 Expr *getBaseExpr() const { return BaseExpr; }
921 MSPropertyDecl *getPropertyDecl() const { return TheDecl; }
922 bool isArrow() const { return IsArrow; }
923 SourceLocation getMemberLoc() const { return MemberLoc; }
924 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
925};
926
927/// MS property subscript expression.
928/// MSVC supports 'property' attribute and allows to apply it to the
929/// declaration of an empty array in a class or structure definition.
930/// For example:
931/// \code
932/// __declspec(property(get=GetX, put=PutX)) int x[];
933/// \endcode
934/// The above statement indicates that x[] can be used with one or more array
935/// indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), and
936/// p->x[a][b] = i will be turned into p->PutX(a, b, i).
937/// This is a syntactic pseudo-object expression.
938class MSPropertySubscriptExpr : public Expr {
939 friend class ASTStmtReader;
940
941 enum { BASE_EXPR, IDX_EXPR, NUM_SUBEXPRS = 2 };
942
943 Stmt *SubExprs[NUM_SUBEXPRS];
944 SourceLocation RBracketLoc;
945
946 void setBase(Expr *Base) { SubExprs[BASE_EXPR] = Base; }
947 void setIdx(Expr *Idx) { SubExprs[IDX_EXPR] = Idx; }
948
949public:
950 MSPropertySubscriptExpr(Expr *Base, Expr *Idx, QualType Ty, ExprValueKind VK,
951 ExprObjectKind OK, SourceLocation RBracketLoc)
952 : Expr(MSPropertySubscriptExprClass, Ty, VK, OK, Idx->isTypeDependent(),
953 Idx->isValueDependent(), Idx->isInstantiationDependent(),
954 Idx->containsUnexpandedParameterPack()),
955 RBracketLoc(RBracketLoc) {
956 SubExprs[BASE_EXPR] = Base;
957 SubExprs[IDX_EXPR] = Idx;
958 }
959
960 /// Create an empty array subscript expression.
961 explicit MSPropertySubscriptExpr(EmptyShell Shell)
962 : Expr(MSPropertySubscriptExprClass, Shell) {}
963
964 Expr *getBase() { return cast<Expr>(SubExprs[BASE_EXPR]); }
965 const Expr *getBase() const { return cast<Expr>(SubExprs[BASE_EXPR]); }
966
967 Expr *getIdx() { return cast<Expr>(SubExprs[IDX_EXPR]); }
968 const Expr *getIdx() const { return cast<Expr>(SubExprs[IDX_EXPR]); }
969
970 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
971 return getBase()->getBeginLoc();
972 }
973
974 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RBracketLoc; }
975
976 SourceLocation getRBracketLoc() const { return RBracketLoc; }
977 void setRBracketLoc(SourceLocation L) { RBracketLoc = L; }
978
979 SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__)) {
980 return getBase()->getExprLoc();
981 }
982
983 static bool classof(const Stmt *T) {
984 return T->getStmtClass() == MSPropertySubscriptExprClass;
985 }
986
987 // Iterators
988 child_range children() {
989 return child_range(&SubExprs[0], &SubExprs[0] + NUM_SUBEXPRS);
990 }
991
992 const_child_range children() const {
993 return const_child_range(&SubExprs[0], &SubExprs[0] + NUM_SUBEXPRS);
994 }
995};
996
997/// A Microsoft C++ @c __uuidof expression, which gets
998/// the _GUID that corresponds to the supplied type or expression.
999///
1000/// This represents code like @c __uuidof(COMTYPE) or @c __uuidof(*comPtr)
1001class CXXUuidofExpr : public Expr {
1002private:
1003 llvm::PointerUnion<Stmt *, TypeSourceInfo *> Operand;
1004 StringRef UuidStr;
1005 SourceRange Range;
1006
1007public:
1008 CXXUuidofExpr(QualType Ty, TypeSourceInfo *Operand, StringRef UuidStr,
1009 SourceRange R)
1010 : Expr(CXXUuidofExprClass, Ty, VK_LValue, OK_Ordinary, false,
1011 Operand->getType()->isDependentType(),
1012 Operand->getType()->isInstantiationDependentType(),
1013 Operand->getType()->containsUnexpandedParameterPack()),
1014 Operand(Operand), UuidStr(UuidStr), Range(R) {}
1015
1016 CXXUuidofExpr(QualType Ty, Expr *Operand, StringRef UuidStr, SourceRange R)
1017 : Expr(CXXUuidofExprClass, Ty, VK_LValue, OK_Ordinary, false,
1018 Operand->isTypeDependent(), Operand->isInstantiationDependent(),
1019 Operand->containsUnexpandedParameterPack()),
1020 Operand(Operand), UuidStr(UuidStr), Range(R) {}
1021
1022 CXXUuidofExpr(EmptyShell Empty, bool isExpr)
1023 : Expr(CXXUuidofExprClass, Empty) {
1024 if (isExpr)
1025 Operand = (Expr*)nullptr;
1026 else
1027 Operand = (TypeSourceInfo*)nullptr;
1028 }
1029
1030 bool isTypeOperand() const { return Operand.is<TypeSourceInfo *>(); }
1031
1032 /// Retrieves the type operand of this __uuidof() expression after
1033 /// various required adjustments (removing reference types, cv-qualifiers).
1034 QualType getTypeOperand(ASTContext &Context) const;
1035
1036 /// Retrieve source information for the type operand.
1037 TypeSourceInfo *getTypeOperandSourceInfo() const {
1038 assert(isTypeOperand() && "Cannot call getTypeOperand for __uuidof(expr)")((isTypeOperand() && "Cannot call getTypeOperand for __uuidof(expr)"
) ? static_cast<void> (0) : __assert_fail ("isTypeOperand() && \"Cannot call getTypeOperand for __uuidof(expr)\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 1038, __PRETTY_FUNCTION__))
;
1039 return Operand.get<TypeSourceInfo *>();
1040 }
1041
1042 void setTypeOperandSourceInfo(TypeSourceInfo *TSI) {
1043 assert(isTypeOperand() && "Cannot call getTypeOperand for __uuidof(expr)")((isTypeOperand() && "Cannot call getTypeOperand for __uuidof(expr)"
) ? static_cast<void> (0) : __assert_fail ("isTypeOperand() && \"Cannot call getTypeOperand for __uuidof(expr)\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 1043, __PRETTY_FUNCTION__))
;
1044 Operand = TSI;
1045 }
1046
1047 Expr *getExprOperand() const {
1048 assert(!isTypeOperand() && "Cannot call getExprOperand for __uuidof(type)")((!isTypeOperand() && "Cannot call getExprOperand for __uuidof(type)"
) ? static_cast<void> (0) : __assert_fail ("!isTypeOperand() && \"Cannot call getExprOperand for __uuidof(type)\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 1048, __PRETTY_FUNCTION__))
;
1049 return static_cast<Expr*>(Operand.get<Stmt *>());
1050 }
1051
1052 void setExprOperand(Expr *E) {
1053 assert(!isTypeOperand() && "Cannot call getExprOperand for __uuidof(type)")((!isTypeOperand() && "Cannot call getExprOperand for __uuidof(type)"
) ? static_cast<void> (0) : __assert_fail ("!isTypeOperand() && \"Cannot call getExprOperand for __uuidof(type)\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 1053, __PRETTY_FUNCTION__))
;
1054 Operand = E;
1055 }
1056
1057 void setUuidStr(StringRef US) { UuidStr = US; }
1058 StringRef getUuidStr() const { return UuidStr; }
1059
1060 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getBegin(); }
1061 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getEnd(); }
1062 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) { return Range; }
1063 void setSourceRange(SourceRange R) { Range = R; }
1064
1065 static bool classof(const Stmt *T) {
1066 return T->getStmtClass() == CXXUuidofExprClass;
1067 }
1068
1069 // Iterators
1070 child_range children() {
1071 if (isTypeOperand())
1072 return child_range(child_iterator(), child_iterator());
1073 auto **begin = reinterpret_cast<Stmt **>(&Operand);
1074 return child_range(begin, begin + 1);
1075 }
1076
1077 const_child_range children() const {
1078 if (isTypeOperand())
1079 return const_child_range(const_child_iterator(), const_child_iterator());
1080 auto **begin =
1081 reinterpret_cast<Stmt **>(&const_cast<CXXUuidofExpr *>(this)->Operand);
1082 return const_child_range(begin, begin + 1);
1083 }
1084};
1085
1086/// Represents the \c this expression in C++.
1087///
1088/// This is a pointer to the object on which the current member function is
1089/// executing (C++ [expr.prim]p3). Example:
1090///
1091/// \code
1092/// class Foo {
1093/// public:
1094/// void bar();
1095/// void test() { this->bar(); }
1096/// };
1097/// \endcode
1098class CXXThisExpr : public Expr {
1099public:
1100 CXXThisExpr(SourceLocation L, QualType Ty, bool IsImplicit)
1101 : Expr(CXXThisExprClass, Ty, VK_RValue, OK_Ordinary,
1102 // 'this' is type-dependent if the class type of the enclosing
1103 // member function is dependent (C++ [temp.dep.expr]p2)
1104 Ty->isDependentType(), Ty->isDependentType(),
1105 Ty->isInstantiationDependentType(),
1106 /*ContainsUnexpandedParameterPack=*/false) {
1107 CXXThisExprBits.IsImplicit = IsImplicit;
1108 CXXThisExprBits.Loc = L;
1109 }
1110
1111 CXXThisExpr(EmptyShell Empty) : Expr(CXXThisExprClass, Empty) {}
1112
1113 SourceLocation getLocation() const { return CXXThisExprBits.Loc; }
1114 void setLocation(SourceLocation L) { CXXThisExprBits.Loc = L; }
1115
1116 SourceLocation getBeginLoc() const { return getLocation(); }
1117 SourceLocation getEndLoc() const { return getLocation(); }
1118
1119 bool isImplicit() const { return CXXThisExprBits.IsImplicit; }
1120 void setImplicit(bool I) { CXXThisExprBits.IsImplicit = I; }
1121
1122 static bool classof(const Stmt *T) {
1123 return T->getStmtClass() == CXXThisExprClass;
1124 }
1125
1126 // Iterators
1127 child_range children() {
1128 return child_range(child_iterator(), child_iterator());
1129 }
1130
1131 const_child_range children() const {
1132 return const_child_range(const_child_iterator(), const_child_iterator());
1133 }
1134};
1135
1136/// A C++ throw-expression (C++ [except.throw]).
1137///
1138/// This handles 'throw' (for re-throwing the current exception) and
1139/// 'throw' assignment-expression. When assignment-expression isn't
1140/// present, Op will be null.
1141class CXXThrowExpr : public Expr {
1142 friend class ASTStmtReader;
1143
1144 /// The optional expression in the throw statement.
1145 Stmt *Operand;
1146
1147public:
1148 // \p Ty is the void type which is used as the result type of the
1149 // expression. The \p Loc is the location of the throw keyword.
1150 // \p Operand is the expression in the throw statement, and can be
1151 // null if not present.
1152 CXXThrowExpr(Expr *Operand, QualType Ty, SourceLocation Loc,
1153 bool IsThrownVariableInScope)
1154 : Expr(CXXThrowExprClass, Ty, VK_RValue, OK_Ordinary, false, false,
1155 Operand && Operand->isInstantiationDependent(),
1156 Operand && Operand->containsUnexpandedParameterPack()),
1157 Operand(Operand) {
1158 CXXThrowExprBits.ThrowLoc = Loc;
1159 CXXThrowExprBits.IsThrownVariableInScope = IsThrownVariableInScope;
1160 }
1161 CXXThrowExpr(EmptyShell Empty) : Expr(CXXThrowExprClass, Empty) {}
1162
1163 const Expr *getSubExpr() const { return cast_or_null<Expr>(Operand); }
1164 Expr *getSubExpr() { return cast_or_null<Expr>(Operand); }
1165
1166 SourceLocation getThrowLoc() const { return CXXThrowExprBits.ThrowLoc; }
1167
1168 /// Determines whether the variable thrown by this expression (if any!)
1169 /// is within the innermost try block.
1170 ///
1171 /// This information is required to determine whether the NRVO can apply to
1172 /// this variable.
1173 bool isThrownVariableInScope() const {
1174 return CXXThrowExprBits.IsThrownVariableInScope;
1175 }
1176
1177 SourceLocation getBeginLoc() const { return getThrowLoc(); }
1178 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
1179 if (!getSubExpr())
1180 return getThrowLoc();
1181 return getSubExpr()->getEndLoc();
1182 }
1183
1184 static bool classof(const Stmt *T) {
1185 return T->getStmtClass() == CXXThrowExprClass;
1186 }
1187
1188 // Iterators
1189 child_range children() {
1190 return child_range(&Operand, Operand ? &Operand + 1 : &Operand);
1191 }
1192
1193 const_child_range children() const {
1194 return const_child_range(&Operand, Operand ? &Operand + 1 : &Operand);
1195 }
1196};
1197
1198/// A default argument (C++ [dcl.fct.default]).
1199///
1200/// This wraps up a function call argument that was created from the
1201/// corresponding parameter's default argument, when the call did not
1202/// explicitly supply arguments for all of the parameters.
1203class CXXDefaultArgExpr final : public Expr {
1204 friend class ASTStmtReader;
1205
1206 /// The parameter whose default is being used.
1207 ParmVarDecl *Param;
1208
1209 /// The context where the default argument expression was used.
1210 DeclContext *UsedContext;
1211
1212 CXXDefaultArgExpr(StmtClass SC, SourceLocation Loc, ParmVarDecl *Param,
1213 DeclContext *UsedContext)
1214 : Expr(SC,
1215 Param->hasUnparsedDefaultArg()
1216 ? Param->getType().getNonReferenceType()
1217 : Param->getDefaultArg()->getType(),
1218 Param->getDefaultArg()->getValueKind(),
1219 Param->getDefaultArg()->getObjectKind(), false, false, false,
1220 false),
1221 Param(Param), UsedContext(UsedContext) {
1222 CXXDefaultArgExprBits.Loc = Loc;
1223 }
1224
1225public:
1226 CXXDefaultArgExpr(EmptyShell Empty) : Expr(CXXDefaultArgExprClass, Empty) {}
1227
1228 // \p Param is the parameter whose default argument is used by this
1229 // expression.
1230 static CXXDefaultArgExpr *Create(const ASTContext &C, SourceLocation Loc,
1231 ParmVarDecl *Param,
1232 DeclContext *UsedContext) {
1233 return new (C)
1234 CXXDefaultArgExpr(CXXDefaultArgExprClass, Loc, Param, UsedContext);
1235 }
1236
1237 // Retrieve the parameter that the argument was created from.
1238 const ParmVarDecl *getParam() const { return Param; }
1239 ParmVarDecl *getParam() { return Param; }
1240
1241 // Retrieve the actual argument to the function call.
1242 const Expr *getExpr() const { return getParam()->getDefaultArg(); }
1243 Expr *getExpr() { return getParam()->getDefaultArg(); }
1244
1245 const DeclContext *getUsedContext() const { return UsedContext; }
1246 DeclContext *getUsedContext() { return UsedContext; }
1247
1248 /// Retrieve the location where this default argument was actually used.
1249 SourceLocation getUsedLocation() const { return CXXDefaultArgExprBits.Loc; }
1250
1251 /// Default argument expressions have no representation in the
1252 /// source, so they have an empty source range.
1253 SourceLocation getBeginLoc() const { return SourceLocation(); }
1254 SourceLocation getEndLoc() const { return SourceLocation(); }
1255
1256 SourceLocation getExprLoc() const { return getUsedLocation(); }
1257
1258 static bool classof(const Stmt *T) {
1259 return T->getStmtClass() == CXXDefaultArgExprClass;
1260 }
1261
1262 // Iterators
1263 child_range children() {
1264 return child_range(child_iterator(), child_iterator());
1265 }
1266
1267 const_child_range children() const {
1268 return const_child_range(const_child_iterator(), const_child_iterator());
1269 }
1270};
1271
1272/// A use of a default initializer in a constructor or in aggregate
1273/// initialization.
1274///
1275/// This wraps a use of a C++ default initializer (technically,
1276/// a brace-or-equal-initializer for a non-static data member) when it
1277/// is implicitly used in a mem-initializer-list in a constructor
1278/// (C++11 [class.base.init]p8) or in aggregate initialization
1279/// (C++1y [dcl.init.aggr]p7).
1280class CXXDefaultInitExpr : public Expr {
1281 friend class ASTReader;
1282 friend class ASTStmtReader;
1283
1284 /// The field whose default is being used.
1285 FieldDecl *Field;
1286
1287 /// The context where the default initializer expression was used.
1288 DeclContext *UsedContext;
1289
1290 CXXDefaultInitExpr(const ASTContext &Ctx, SourceLocation Loc,
1291 FieldDecl *Field, QualType Ty, DeclContext *UsedContext);
1292
1293 CXXDefaultInitExpr(EmptyShell Empty) : Expr(CXXDefaultInitExprClass, Empty) {}
1294
1295public:
1296 /// \p Field is the non-static data member whose default initializer is used
1297 /// by this expression.
1298 static CXXDefaultInitExpr *Create(const ASTContext &Ctx, SourceLocation Loc,
1299 FieldDecl *Field, DeclContext *UsedContext) {
1300 return new (Ctx) CXXDefaultInitExpr(Ctx, Loc, Field, Field->getType(), UsedContext);
1301 }
1302
1303 /// Get the field whose initializer will be used.
1304 FieldDecl *getField() { return Field; }
1305 const FieldDecl *getField() const { return Field; }
1306
1307 /// Get the initialization expression that will be used.
1308 const Expr *getExpr() const {
1309 assert(Field->getInClassInitializer() && "initializer hasn't been parsed")((Field->getInClassInitializer() && "initializer hasn't been parsed"
) ? static_cast<void> (0) : __assert_fail ("Field->getInClassInitializer() && \"initializer hasn't been parsed\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 1309, __PRETTY_FUNCTION__))
;
1310 return Field->getInClassInitializer();
1311 }
1312 Expr *getExpr() {
1313 assert(Field->getInClassInitializer() && "initializer hasn't been parsed")((Field->getInClassInitializer() && "initializer hasn't been parsed"
) ? static_cast<void> (0) : __assert_fail ("Field->getInClassInitializer() && \"initializer hasn't been parsed\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 1313, __PRETTY_FUNCTION__))
;
1314 return Field->getInClassInitializer();
1315 }
1316
1317 const DeclContext *getUsedContext() const { return UsedContext; }
1318 DeclContext *getUsedContext() { return UsedContext; }
1319
1320 /// Retrieve the location where this default initializer expression was
1321 /// actually used.
1322 SourceLocation getUsedLocation() const { return getBeginLoc(); }
1323
1324 SourceLocation getBeginLoc() const { return CXXDefaultInitExprBits.Loc; }
1325 SourceLocation getEndLoc() const { return CXXDefaultInitExprBits.Loc; }
1326
1327 static bool classof(const Stmt *T) {
1328 return T->getStmtClass() == CXXDefaultInitExprClass;
1329 }
1330
1331 // Iterators
1332 child_range children() {
1333 return child_range(child_iterator(), child_iterator());
1334 }
1335
1336 const_child_range children() const {
1337 return const_child_range(const_child_iterator(), const_child_iterator());
1338 }
1339};
1340
1341/// Represents a C++ temporary.
1342class CXXTemporary {
1343 /// The destructor that needs to be called.
1344 const CXXDestructorDecl *Destructor;
1345
1346 explicit CXXTemporary(const CXXDestructorDecl *destructor)
1347 : Destructor(destructor) {}
1348
1349public:
1350 static CXXTemporary *Create(const ASTContext &C,
1351 const CXXDestructorDecl *Destructor);
1352
1353 const CXXDestructorDecl *getDestructor() const { return Destructor; }
1354
1355 void setDestructor(const CXXDestructorDecl *Dtor) {
1356 Destructor = Dtor;
1357 }
1358};
1359
1360/// Represents binding an expression to a temporary.
1361///
1362/// This ensures the destructor is called for the temporary. It should only be
1363/// needed for non-POD, non-trivially destructable class types. For example:
1364///
1365/// \code
1366/// struct S {
1367/// S() { } // User defined constructor makes S non-POD.
1368/// ~S() { } // User defined destructor makes it non-trivial.
1369/// };
1370/// void test() {
1371/// const S &s_ref = S(); // Requires a CXXBindTemporaryExpr.
1372/// }
1373/// \endcode
1374class CXXBindTemporaryExpr : public Expr {
1375 CXXTemporary *Temp = nullptr;
1376 Stmt *SubExpr = nullptr;
1377
1378 CXXBindTemporaryExpr(CXXTemporary *temp, Expr* SubExpr)
1379 : Expr(CXXBindTemporaryExprClass, SubExpr->getType(),
1380 VK_RValue, OK_Ordinary, SubExpr->isTypeDependent(),
1381 SubExpr->isValueDependent(),
1382 SubExpr->isInstantiationDependent(),
1383 SubExpr->containsUnexpandedParameterPack()),
1384 Temp(temp), SubExpr(SubExpr) {}
1385
1386public:
1387 CXXBindTemporaryExpr(EmptyShell Empty)
1388 : Expr(CXXBindTemporaryExprClass, Empty) {}
1389
1390 static CXXBindTemporaryExpr *Create(const ASTContext &C, CXXTemporary *Temp,
1391 Expr* SubExpr);
1392
1393 CXXTemporary *getTemporary() { return Temp; }
1394 const CXXTemporary *getTemporary() const { return Temp; }
1395 void setTemporary(CXXTemporary *T) { Temp = T; }
1396
1397 const Expr *getSubExpr() const { return cast<Expr>(SubExpr); }
1398 Expr *getSubExpr() { return cast<Expr>(SubExpr); }
1399 void setSubExpr(Expr *E) { SubExpr = E; }
1400
1401 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
1402 return SubExpr->getBeginLoc();
1403 }
1404
1405 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
1406 return SubExpr->getEndLoc();
1407 }
1408
1409 // Implement isa/cast/dyncast/etc.
1410 static bool classof(const Stmt *T) {
1411 return T->getStmtClass() == CXXBindTemporaryExprClass;
1412 }
1413
1414 // Iterators
1415 child_range children() { return child_range(&SubExpr, &SubExpr + 1); }
1416
1417 const_child_range children() const {
1418 return const_child_range(&SubExpr, &SubExpr + 1);
1419 }
1420};
1421
1422/// Represents a call to a C++ constructor.
1423class CXXConstructExpr : public Expr {
1424 friend class ASTStmtReader;
1425
1426public:
1427 enum ConstructionKind {
1428 CK_Complete,
1429 CK_NonVirtualBase,
1430 CK_VirtualBase,
1431 CK_Delegating
1432 };
1433
1434private:
1435 /// A pointer to the constructor which will be ultimately called.
1436 CXXConstructorDecl *Constructor;
1437
1438 SourceRange ParenOrBraceRange;
1439
1440 /// The number of arguments.
1441 unsigned NumArgs;
1442
1443 // We would like to stash the arguments of the constructor call after
1444 // CXXConstructExpr. However CXXConstructExpr is used as a base class of
1445 // CXXTemporaryObjectExpr which makes the use of llvm::TrailingObjects
1446 // impossible.
1447 //
1448 // Instead we manually stash the trailing object after the full object
1449 // containing CXXConstructExpr (that is either CXXConstructExpr or
1450 // CXXTemporaryObjectExpr).
1451 //
1452 // The trailing objects are:
1453 //
1454 // * An array of getNumArgs() "Stmt *" for the arguments of the
1455 // constructor call.
1456
1457 /// Return a pointer to the start of the trailing arguments.
1458 /// Defined just after CXXTemporaryObjectExpr.
1459 inline Stmt **getTrailingArgs();
1460 const Stmt *const *getTrailingArgs() const {
1461 return const_cast<CXXConstructExpr *>(this)->getTrailingArgs();
1462 }
1463
1464protected:
1465 /// Build a C++ construction expression.
1466 CXXConstructExpr(StmtClass SC, QualType Ty, SourceLocation Loc,
1467 CXXConstructorDecl *Ctor, bool Elidable,
1468 ArrayRef<Expr *> Args, bool HadMultipleCandidates,
1469 bool ListInitialization, bool StdInitListInitialization,
1470 bool ZeroInitialization, ConstructionKind ConstructKind,
1471 SourceRange ParenOrBraceRange);
1472
1473 /// Build an empty C++ construction expression.
1474 CXXConstructExpr(StmtClass SC, EmptyShell Empty, unsigned NumArgs);
1475
1476 /// Return the size in bytes of the trailing objects. Used by
1477 /// CXXTemporaryObjectExpr to allocate the right amount of storage.
1478 static unsigned sizeOfTrailingObjects(unsigned NumArgs) {
1479 return NumArgs * sizeof(Stmt *);
1480 }
1481
1482public:
1483 /// Create a C++ construction expression.
1484 static CXXConstructExpr *
1485 Create(const ASTContext &Ctx, QualType Ty, SourceLocation Loc,
1486 CXXConstructorDecl *Ctor, bool Elidable, ArrayRef<Expr *> Args,
1487 bool HadMultipleCandidates, bool ListInitialization,
1488 bool StdInitListInitialization, bool ZeroInitialization,
1489 ConstructionKind ConstructKind, SourceRange ParenOrBraceRange);
1490
1491 /// Create an empty C++ construction expression.
1492 static CXXConstructExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumArgs);
1493
1494 /// Get the constructor that this expression will (ultimately) call.
1495 CXXConstructorDecl *getConstructor() const { return Constructor; }
1496
1497 SourceLocation getLocation() const { return CXXConstructExprBits.Loc; }
1498 void setLocation(SourceLocation Loc) { CXXConstructExprBits.Loc = Loc; }
1499
1500 /// Whether this construction is elidable.
1501 bool isElidable() const { return CXXConstructExprBits.Elidable; }
1502 void setElidable(bool E) { CXXConstructExprBits.Elidable = E; }
1503
1504 /// Whether the referred constructor was resolved from
1505 /// an overloaded set having size greater than 1.
1506 bool hadMultipleCandidates() const {
1507 return CXXConstructExprBits.HadMultipleCandidates;
1508 }
1509 void setHadMultipleCandidates(bool V) {
1510 CXXConstructExprBits.HadMultipleCandidates = V;
1511 }
1512
1513 /// Whether this constructor call was written as list-initialization.
1514 bool isListInitialization() const {
1515 return CXXConstructExprBits.ListInitialization;
1516 }
1517 void setListInitialization(bool V) {
1518 CXXConstructExprBits.ListInitialization = V;
1519 }
1520
1521 /// Whether this constructor call was written as list-initialization,
1522 /// but was interpreted as forming a std::initializer_list<T> from the list
1523 /// and passing that as a single constructor argument.
1524 /// See C++11 [over.match.list]p1 bullet 1.
1525 bool isStdInitListInitialization() const {
1526 return CXXConstructExprBits.StdInitListInitialization;
1527 }
1528 void setStdInitListInitialization(bool V) {
1529 CXXConstructExprBits.StdInitListInitialization = V;
1530 }
1531
1532 /// Whether this construction first requires
1533 /// zero-initialization before the initializer is called.
1534 bool requiresZeroInitialization() const {
1535 return CXXConstructExprBits.ZeroInitialization;
1536 }
1537 void setRequiresZeroInitialization(bool ZeroInit) {
1538 CXXConstructExprBits.ZeroInitialization = ZeroInit;
1539 }
1540
1541 /// Determine whether this constructor is actually constructing
1542 /// a base class (rather than a complete object).
1543 ConstructionKind getConstructionKind() const {
1544 return static_cast<ConstructionKind>(CXXConstructExprBits.ConstructionKind);
1545 }
1546 void setConstructionKind(ConstructionKind CK) {
1547 CXXConstructExprBits.ConstructionKind = CK;
1548 }
1549
1550 using arg_iterator = ExprIterator;
1551 using const_arg_iterator = ConstExprIterator;
1552 using arg_range = llvm::iterator_range<arg_iterator>;
1553 using const_arg_range = llvm::iterator_range<const_arg_iterator>;
1554
1555 arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
1556 const_arg_range arguments() const {
1557 return const_arg_range(arg_begin(), arg_end());
1558 }
1559
1560 arg_iterator arg_begin() { return getTrailingArgs(); }
1561 arg_iterator arg_end() { return arg_begin() + getNumArgs(); }
1562 const_arg_iterator arg_begin() const { return getTrailingArgs(); }
1563 const_arg_iterator arg_end() const { return arg_begin() + getNumArgs(); }
1564
1565 Expr **getArgs() { return reinterpret_cast<Expr **>(getTrailingArgs()); }
1566 const Expr *const *getArgs() const {
1567 return reinterpret_cast<const Expr *const *>(getTrailingArgs());
1568 }
1569
1570 /// Return the number of arguments to the constructor call.
1571 unsigned getNumArgs() const { return NumArgs; }
1572
1573 /// Return the specified argument.
1574 Expr *getArg(unsigned Arg) {
1575 assert(Arg < getNumArgs() && "Arg access out of range!")((Arg < getNumArgs() && "Arg access out of range!"
) ? static_cast<void> (0) : __assert_fail ("Arg < getNumArgs() && \"Arg access out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 1575, __PRETTY_FUNCTION__))
;
1576 return getArgs()[Arg];
1577 }
1578 const Expr *getArg(unsigned Arg) const {
1579 assert(Arg < getNumArgs() && "Arg access out of range!")((Arg < getNumArgs() && "Arg access out of range!"
) ? static_cast<void> (0) : __assert_fail ("Arg < getNumArgs() && \"Arg access out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 1579, __PRETTY_FUNCTION__))
;
1580 return getArgs()[Arg];
1581 }
1582
1583 /// Set the specified argument.
1584 void setArg(unsigned Arg, Expr *ArgExpr) {
1585 assert(Arg < getNumArgs() && "Arg access out of range!")((Arg < getNumArgs() && "Arg access out of range!"
) ? static_cast<void> (0) : __assert_fail ("Arg < getNumArgs() && \"Arg access out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 1585, __PRETTY_FUNCTION__))
;
1586 getArgs()[Arg] = ArgExpr;
1587 }
1588
1589 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__));
1590 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__));
1591 SourceRange getParenOrBraceRange() const { return ParenOrBraceRange; }
1592 void setParenOrBraceRange(SourceRange Range) { ParenOrBraceRange = Range; }
1593
1594 static bool classof(const Stmt *T) {
1595 return T->getStmtClass() == CXXConstructExprClass ||
1596 T->getStmtClass() == CXXTemporaryObjectExprClass;
1597 }
1598
1599 // Iterators
1600 child_range children() {
1601 return child_range(getTrailingArgs(), getTrailingArgs() + getNumArgs());
1602 }
1603
1604 const_child_range children() const {
1605 auto Children = const_cast<CXXConstructExpr *>(this)->children();
1606 return const_child_range(Children.begin(), Children.end());
1607 }
1608};
1609
1610/// Represents a call to an inherited base class constructor from an
1611/// inheriting constructor. This call implicitly forwards the arguments from
1612/// the enclosing context (an inheriting constructor) to the specified inherited
1613/// base class constructor.
1614class CXXInheritedCtorInitExpr : public Expr {
1615private:
1616 CXXConstructorDecl *Constructor = nullptr;
1617
1618 /// The location of the using declaration.
1619 SourceLocation Loc;
1620
1621 /// Whether this is the construction of a virtual base.
1622 unsigned ConstructsVirtualBase : 1;
1623
1624 /// Whether the constructor is inherited from a virtual base class of the
1625 /// class that we construct.
1626 unsigned InheritedFromVirtualBase : 1;
1627
1628public:
1629 friend class ASTStmtReader;
1630
1631 /// Construct a C++ inheriting construction expression.
1632 CXXInheritedCtorInitExpr(SourceLocation Loc, QualType T,
1633 CXXConstructorDecl *Ctor, bool ConstructsVirtualBase,
1634 bool InheritedFromVirtualBase)
1635 : Expr(CXXInheritedCtorInitExprClass, T, VK_RValue, OK_Ordinary, false,
1636 false, false, false),
1637 Constructor(Ctor), Loc(Loc),
1638 ConstructsVirtualBase(ConstructsVirtualBase),
1639 InheritedFromVirtualBase(InheritedFromVirtualBase) {
1640 assert(!T->isDependentType())((!T->isDependentType()) ? static_cast<void> (0) : __assert_fail
("!T->isDependentType()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 1640, __PRETTY_FUNCTION__))
;
1641 }
1642
1643 /// Construct an empty C++ inheriting construction expression.
1644 explicit CXXInheritedCtorInitExpr(EmptyShell Empty)
1645 : Expr(CXXInheritedCtorInitExprClass, Empty),
1646 ConstructsVirtualBase(false), InheritedFromVirtualBase(false) {}
1647
1648 /// Get the constructor that this expression will call.
1649 CXXConstructorDecl *getConstructor() const { return Constructor; }
1650
1651 /// Determine whether this constructor is actually constructing
1652 /// a base class (rather than a complete object).
1653 bool constructsVBase() const { return ConstructsVirtualBase; }
1654 CXXConstructExpr::ConstructionKind getConstructionKind() const {
1655 return ConstructsVirtualBase ? CXXConstructExpr::CK_VirtualBase
1656 : CXXConstructExpr::CK_NonVirtualBase;
1657 }
1658
1659 /// Determine whether the inherited constructor is inherited from a
1660 /// virtual base of the object we construct. If so, we are not responsible
1661 /// for calling the inherited constructor (the complete object constructor
1662 /// does that), and so we don't need to pass any arguments.
1663 bool inheritedFromVBase() const { return InheritedFromVirtualBase; }
1664
1665 SourceLocation getLocation() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1666 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1667 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1668
1669 static bool classof(const Stmt *T) {
1670 return T->getStmtClass() == CXXInheritedCtorInitExprClass;
1671 }
1672
1673 child_range children() {
1674 return child_range(child_iterator(), child_iterator());
1675 }
1676
1677 const_child_range children() const {
1678 return const_child_range(const_child_iterator(), const_child_iterator());
1679 }
1680};
1681
1682/// Represents an explicit C++ type conversion that uses "functional"
1683/// notation (C++ [expr.type.conv]).
1684///
1685/// Example:
1686/// \code
1687/// x = int(0.5);
1688/// \endcode
1689class CXXFunctionalCastExpr final
1690 : public ExplicitCastExpr,
1691 private llvm::TrailingObjects<CXXFunctionalCastExpr, CXXBaseSpecifier *> {
1692 SourceLocation LParenLoc;
1693 SourceLocation RParenLoc;
1694
1695 CXXFunctionalCastExpr(QualType ty, ExprValueKind VK,
1696 TypeSourceInfo *writtenTy,
1697 CastKind kind, Expr *castExpr, unsigned pathSize,
1698 SourceLocation lParenLoc, SourceLocation rParenLoc)
1699 : ExplicitCastExpr(CXXFunctionalCastExprClass, ty, VK, kind,
1700 castExpr, pathSize, writtenTy),
1701 LParenLoc(lParenLoc), RParenLoc(rParenLoc) {}
1702
1703 explicit CXXFunctionalCastExpr(EmptyShell Shell, unsigned PathSize)
1704 : ExplicitCastExpr(CXXFunctionalCastExprClass, Shell, PathSize) {}
1705
1706public:
1707 friend class CastExpr;
1708 friend TrailingObjects;
1709
1710 static CXXFunctionalCastExpr *Create(const ASTContext &Context, QualType T,
1711 ExprValueKind VK,
1712 TypeSourceInfo *Written,
1713 CastKind Kind, Expr *Op,
1714 const CXXCastPath *Path,
1715 SourceLocation LPLoc,
1716 SourceLocation RPLoc);
1717 static CXXFunctionalCastExpr *CreateEmpty(const ASTContext &Context,
1718 unsigned PathSize);
1719
1720 SourceLocation getLParenLoc() const { return LParenLoc; }
1721 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
1722 SourceLocation getRParenLoc() const { return RParenLoc; }
1723 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
1724
1725 /// Determine whether this expression models list-initialization.
1726 bool isListInitialization() const { return LParenLoc.isInvalid(); }
1727
1728 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__));
1729 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__));
1730
1731 static bool classof(const Stmt *T) {
1732 return T->getStmtClass() == CXXFunctionalCastExprClass;
1733 }
1734};
1735
1736/// Represents a C++ functional cast expression that builds a
1737/// temporary object.
1738///
1739/// This expression type represents a C++ "functional" cast
1740/// (C++[expr.type.conv]) with N != 1 arguments that invokes a
1741/// constructor to build a temporary object. With N == 1 arguments the
1742/// functional cast expression will be represented by CXXFunctionalCastExpr.
1743/// Example:
1744/// \code
1745/// struct X { X(int, float); }
1746///
1747/// X create_X() {
1748/// return X(1, 3.14f); // creates a CXXTemporaryObjectExpr
1749/// };
1750/// \endcode
1751class CXXTemporaryObjectExpr final : public CXXConstructExpr {
1752 friend class ASTStmtReader;
1753
1754 // CXXTemporaryObjectExpr has some trailing objects belonging
1755 // to CXXConstructExpr. See the comment inside CXXConstructExpr
1756 // for more details.
1757
1758 TypeSourceInfo *TSI;
1759
1760 CXXTemporaryObjectExpr(CXXConstructorDecl *Cons, QualType Ty,
1761 TypeSourceInfo *TSI, ArrayRef<Expr *> Args,
1762 SourceRange ParenOrBraceRange,
1763 bool HadMultipleCandidates, bool ListInitialization,
1764 bool StdInitListInitialization,
1765 bool ZeroInitialization);
1766
1767 CXXTemporaryObjectExpr(EmptyShell Empty, unsigned NumArgs);
1768
1769public:
1770 static CXXTemporaryObjectExpr *
1771 Create(const ASTContext &Ctx, CXXConstructorDecl *Cons, QualType Ty,
1772 TypeSourceInfo *TSI, ArrayRef<Expr *> Args,
1773 SourceRange ParenOrBraceRange, bool HadMultipleCandidates,
1774 bool ListInitialization, bool StdInitListInitialization,
1775 bool ZeroInitialization);
1776
1777 static CXXTemporaryObjectExpr *CreateEmpty(const ASTContext &Ctx,
1778 unsigned NumArgs);
1779
1780 TypeSourceInfo *getTypeSourceInfo() const { return TSI; }
1781
1782 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__));
1783 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__));
1784
1785 static bool classof(const Stmt *T) {
1786 return T->getStmtClass() == CXXTemporaryObjectExprClass;
1787 }
1788};
1789
1790Stmt **CXXConstructExpr::getTrailingArgs() {
1791 if (auto *E = dyn_cast<CXXTemporaryObjectExpr>(this))
1792 return reinterpret_cast<Stmt **>(E + 1);
1793 assert((getStmtClass() == CXXConstructExprClass) &&(((getStmtClass() == CXXConstructExprClass) && "Unexpected class deriving from CXXConstructExpr!"
) ? static_cast<void> (0) : __assert_fail ("(getStmtClass() == CXXConstructExprClass) && \"Unexpected class deriving from CXXConstructExpr!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 1794, __PRETTY_FUNCTION__))
1794 "Unexpected class deriving from CXXConstructExpr!")(((getStmtClass() == CXXConstructExprClass) && "Unexpected class deriving from CXXConstructExpr!"
) ? static_cast<void> (0) : __assert_fail ("(getStmtClass() == CXXConstructExprClass) && \"Unexpected class deriving from CXXConstructExpr!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 1794, __PRETTY_FUNCTION__))
;
1795 return reinterpret_cast<Stmt **>(this + 1);
1796}
1797
1798/// A C++ lambda expression, which produces a function object
1799/// (of unspecified type) that can be invoked later.
1800///
1801/// Example:
1802/// \code
1803/// void low_pass_filter(std::vector<double> &values, double cutoff) {
1804/// values.erase(std::remove_if(values.begin(), values.end(),
1805/// [=](double value) { return value > cutoff; });
1806/// }
1807/// \endcode
1808///
1809/// C++11 lambda expressions can capture local variables, either by copying
1810/// the values of those local variables at the time the function
1811/// object is constructed (not when it is called!) or by holding a
1812/// reference to the local variable. These captures can occur either
1813/// implicitly or can be written explicitly between the square
1814/// brackets ([...]) that start the lambda expression.
1815///
1816/// C++1y introduces a new form of "capture" called an init-capture that
1817/// includes an initializing expression (rather than capturing a variable),
1818/// and which can never occur implicitly.
1819class LambdaExpr final : public Expr,
1820 private llvm::TrailingObjects<LambdaExpr, Stmt *> {
1821 /// The source range that covers the lambda introducer ([...]).
1822 SourceRange IntroducerRange;
1823
1824 /// The source location of this lambda's capture-default ('=' or '&').
1825 SourceLocation CaptureDefaultLoc;
1826
1827 /// The number of captures.
1828 unsigned NumCaptures : 16;
1829
1830 /// The default capture kind, which is a value of type
1831 /// LambdaCaptureDefault.
1832 unsigned CaptureDefault : 2;
1833
1834 /// Whether this lambda had an explicit parameter list vs. an
1835 /// implicit (and empty) parameter list.
1836 unsigned ExplicitParams : 1;
1837
1838 /// Whether this lambda had the result type explicitly specified.
1839 unsigned ExplicitResultType : 1;
1840
1841 /// The location of the closing brace ('}') that completes
1842 /// the lambda.
1843 ///
1844 /// The location of the brace is also available by looking up the
1845 /// function call operator in the lambda class. However, it is
1846 /// stored here to improve the performance of getSourceRange(), and
1847 /// to avoid having to deserialize the function call operator from a
1848 /// module file just to determine the source range.
1849 SourceLocation ClosingBrace;
1850
1851 /// Construct a lambda expression.
1852 LambdaExpr(QualType T, SourceRange IntroducerRange,
1853 LambdaCaptureDefault CaptureDefault,
1854 SourceLocation CaptureDefaultLoc, ArrayRef<LambdaCapture> Captures,
1855 bool ExplicitParams, bool ExplicitResultType,
1856 ArrayRef<Expr *> CaptureInits, SourceLocation ClosingBrace,
1857 bool ContainsUnexpandedParameterPack);
1858
1859 /// Construct an empty lambda expression.
1860 LambdaExpr(EmptyShell Empty, unsigned NumCaptures)
1861 : Expr(LambdaExprClass, Empty), NumCaptures(NumCaptures),
1862 CaptureDefault(LCD_None), ExplicitParams(false),
1863 ExplicitResultType(false) {
1864 getStoredStmts()[NumCaptures] = nullptr;
1865 }
1866
1867 Stmt **getStoredStmts() { return getTrailingObjects<Stmt *>(); }
1868
1869 Stmt *const *getStoredStmts() const { return getTrailingObjects<Stmt *>(); }
1870
1871public:
1872 friend class ASTStmtReader;
1873 friend class ASTStmtWriter;
1874 friend TrailingObjects;
1875
1876 /// Construct a new lambda expression.
1877 static LambdaExpr *
1878 Create(const ASTContext &C, CXXRecordDecl *Class, SourceRange IntroducerRange,
1879 LambdaCaptureDefault CaptureDefault, SourceLocation CaptureDefaultLoc,
1880 ArrayRef<LambdaCapture> Captures, bool ExplicitParams,
1881 bool ExplicitResultType, ArrayRef<Expr *> CaptureInits,
1882 SourceLocation ClosingBrace, bool ContainsUnexpandedParameterPack);
1883
1884 /// Construct a new lambda expression that will be deserialized from
1885 /// an external source.
1886 static LambdaExpr *CreateDeserialized(const ASTContext &C,
1887 unsigned NumCaptures);
1888
1889 /// Determine the default capture kind for this lambda.
1890 LambdaCaptureDefault getCaptureDefault() const {
1891 return static_cast<LambdaCaptureDefault>(CaptureDefault);
1892 }
1893
1894 /// Retrieve the location of this lambda's capture-default, if any.
1895 SourceLocation getCaptureDefaultLoc() const {
1896 return CaptureDefaultLoc;
1897 }
1898
1899 /// Determine whether one of this lambda's captures is an init-capture.
1900 bool isInitCapture(const LambdaCapture *Capture) const;
1901
1902 /// An iterator that walks over the captures of the lambda,
1903 /// both implicit and explicit.
1904 using capture_iterator = const LambdaCapture *;
1905
1906 /// An iterator over a range of lambda captures.
1907 using capture_range = llvm::iterator_range<capture_iterator>;
1908
1909 /// Retrieve this lambda's captures.
1910 capture_range captures() const;
1911
1912 /// Retrieve an iterator pointing to the first lambda capture.
1913 capture_iterator capture_begin() const;
1914
1915 /// Retrieve an iterator pointing past the end of the
1916 /// sequence of lambda captures.
1917 capture_iterator capture_end() const;
1918
1919 /// Determine the number of captures in this lambda.
1920 unsigned capture_size() const { return NumCaptures; }
1921
1922 /// Retrieve this lambda's explicit captures.
1923 capture_range explicit_captures() const;
1924
1925 /// Retrieve an iterator pointing to the first explicit
1926 /// lambda capture.
1927 capture_iterator explicit_capture_begin() const;
1928
1929 /// Retrieve an iterator pointing past the end of the sequence of
1930 /// explicit lambda captures.
1931 capture_iterator explicit_capture_end() const;
1932
1933 /// Retrieve this lambda's implicit captures.
1934 capture_range implicit_captures() const;
1935
1936 /// Retrieve an iterator pointing to the first implicit
1937 /// lambda capture.
1938 capture_iterator implicit_capture_begin() const;
1939
1940 /// Retrieve an iterator pointing past the end of the sequence of
1941 /// implicit lambda captures.
1942 capture_iterator implicit_capture_end() const;
1943
1944 /// Iterator that walks over the capture initialization
1945 /// arguments.
1946 using capture_init_iterator = Expr **;
1947
1948 /// Const iterator that walks over the capture initialization
1949 /// arguments.
1950 using const_capture_init_iterator = Expr *const *;
1951
1952 /// Retrieve the initialization expressions for this lambda's captures.
1953 llvm::iterator_range<capture_init_iterator> capture_inits() {
1954 return llvm::make_range(capture_init_begin(), capture_init_end());
1955 }
1956
1957 /// Retrieve the initialization expressions for this lambda's captures.
1958 llvm::iterator_range<const_capture_init_iterator> capture_inits() const {
1959 return llvm::make_range(capture_init_begin(), capture_init_end());
1960 }
1961
1962 /// Retrieve the first initialization argument for this
1963 /// lambda expression (which initializes the first capture field).
1964 capture_init_iterator capture_init_begin() {
1965 return reinterpret_cast<Expr **>(getStoredStmts());
1966 }
1967
1968 /// Retrieve the first initialization argument for this
1969 /// lambda expression (which initializes the first capture field).
1970 const_capture_init_iterator capture_init_begin() const {
1971 return reinterpret_cast<Expr *const *>(getStoredStmts());
1972 }
1973
1974 /// Retrieve the iterator pointing one past the last
1975 /// initialization argument for this lambda expression.
1976 capture_init_iterator capture_init_end() {
1977 return capture_init_begin() + NumCaptures;
1978 }
1979
1980 /// Retrieve the iterator pointing one past the last
1981 /// initialization argument for this lambda expression.
1982 const_capture_init_iterator capture_init_end() const {
1983 return capture_init_begin() + NumCaptures;
1984 }
1985
1986 /// Retrieve the source range covering the lambda introducer,
1987 /// which contains the explicit capture list surrounded by square
1988 /// brackets ([...]).
1989 SourceRange getIntroducerRange() const { return IntroducerRange; }
1990
1991 /// Retrieve the class that corresponds to the lambda.
1992 ///
1993 /// This is the "closure type" (C++1y [expr.prim.lambda]), and stores the
1994 /// captures in its fields and provides the various operations permitted
1995 /// on a lambda (copying, calling).
1996 CXXRecordDecl *getLambdaClass() const;
1997
1998 /// Retrieve the function call operator associated with this
1999 /// lambda expression.
2000 CXXMethodDecl *getCallOperator() const;
2001
2002 /// Retrieve the function template call operator associated with this
2003 /// lambda expression.
2004 FunctionTemplateDecl *getDependentCallOperator() const;
2005
2006 /// If this is a generic lambda expression, retrieve the template
2007 /// parameter list associated with it, or else return null.
2008 TemplateParameterList *getTemplateParameterList() const;
2009
2010 /// Get the template parameters were explicitly specified (as opposed to being
2011 /// invented by use of an auto parameter).
2012 ArrayRef<NamedDecl *> getExplicitTemplateParameters() const;
2013
2014 /// Whether this is a generic lambda.
2015 bool isGenericLambda() const { return getTemplateParameterList(); }
2016
2017 /// Retrieve the body of the lambda.
2018 CompoundStmt *getBody() const;
2019
2020 /// Determine whether the lambda is mutable, meaning that any
2021 /// captures values can be modified.
2022 bool isMutable() const;
2023
2024 /// Determine whether this lambda has an explicit parameter
2025 /// list vs. an implicit (empty) parameter list.
2026 bool hasExplicitParameters() const { return ExplicitParams; }
2027
2028 /// Whether this lambda had its result type explicitly specified.
2029 bool hasExplicitResultType() const { return ExplicitResultType; }
2030
2031 static bool classof(const Stmt *T) {
2032 return T->getStmtClass() == LambdaExprClass;
2033 }
2034
2035 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
2036 return IntroducerRange.getBegin();
2037 }
2038
2039 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return ClosingBrace; }
2040
2041 child_range children() {
2042 // Includes initialization exprs plus body stmt
2043 return child_range(getStoredStmts(), getStoredStmts() + NumCaptures + 1);
2044 }
2045
2046 const_child_range children() const {
2047 return const_child_range(getStoredStmts(),
2048 getStoredStmts() + NumCaptures + 1);
2049 }
2050};
2051
2052/// An expression "T()" which creates a value-initialized rvalue of type
2053/// T, which is a non-class type. See (C++98 [5.2.3p2]).
2054class CXXScalarValueInitExpr : public Expr {
2055 friend class ASTStmtReader;
2056
2057 TypeSourceInfo *TypeInfo;
2058
2059public:
2060 /// Create an explicitly-written scalar-value initialization
2061 /// expression.
2062 CXXScalarValueInitExpr(QualType Type, TypeSourceInfo *TypeInfo,
2063 SourceLocation RParenLoc)
2064 : Expr(CXXScalarValueInitExprClass, Type, VK_RValue, OK_Ordinary, false,
2065 false, Type->isInstantiationDependentType(),
2066 Type->containsUnexpandedParameterPack()),
2067 TypeInfo(TypeInfo) {
2068 CXXScalarValueInitExprBits.RParenLoc = RParenLoc;
2069 }
2070
2071 explicit CXXScalarValueInitExpr(EmptyShell Shell)
2072 : Expr(CXXScalarValueInitExprClass, Shell) {}
2073
2074 TypeSourceInfo *getTypeSourceInfo() const {
2075 return TypeInfo;
2076 }
2077
2078 SourceLocation getRParenLoc() const {
2079 return CXXScalarValueInitExprBits.RParenLoc;
2080 }
2081
2082 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__));
2083 SourceLocation getEndLoc() const { return getRParenLoc(); }
2084
2085 static bool classof(const Stmt *T) {
2086 return T->getStmtClass() == CXXScalarValueInitExprClass;
2087 }
2088
2089 // Iterators
2090 child_range children() {
2091 return child_range(child_iterator(), child_iterator());
2092 }
2093
2094 const_child_range children() const {
2095 return const_child_range(const_child_iterator(), const_child_iterator());
2096 }
2097};
2098
2099/// Represents a new-expression for memory allocation and constructor
2100/// calls, e.g: "new CXXNewExpr(foo)".
2101class CXXNewExpr final
2102 : public Expr,
2103 private llvm::TrailingObjects<CXXNewExpr, Stmt *, SourceRange> {
2104 friend class ASTStmtReader;
2105 friend class ASTStmtWriter;
2106 friend TrailingObjects;
2107
2108 /// Points to the allocation function used.
2109 FunctionDecl *OperatorNew;
2110
2111 /// Points to the deallocation function used in case of error. May be null.
2112 FunctionDecl *OperatorDelete;
2113
2114 /// The allocated type-source information, as written in the source.
2115 TypeSourceInfo *AllocatedTypeInfo;
2116
2117 /// Range of the entire new expression.
2118 SourceRange Range;
2119
2120 /// Source-range of a paren-delimited initializer.
2121 SourceRange DirectInitRange;
2122
2123 // CXXNewExpr is followed by several optional trailing objects.
2124 // They are in order:
2125 //
2126 // * An optional "Stmt *" for the array size expression.
2127 // Present if and ony if isArray().
2128 //
2129 // * An optional "Stmt *" for the init expression.
2130 // Present if and only if hasInitializer().
2131 //
2132 // * An array of getNumPlacementArgs() "Stmt *" for the placement new
2133 // arguments, if any.
2134 //
2135 // * An optional SourceRange for the range covering the parenthesized type-id
2136 // if the allocated type was expressed as a parenthesized type-id.
2137 // Present if and only if isParenTypeId().
2138 unsigned arraySizeOffset() const { return 0; }
2139 unsigned initExprOffset() const { return arraySizeOffset() + isArray(); }
2140 unsigned placementNewArgsOffset() const {
2141 return initExprOffset() + hasInitializer();
2142 }
2143
2144 unsigned numTrailingObjects(OverloadToken<Stmt *>) const {
2145 return isArray() + hasInitializer() + getNumPlacementArgs();
2146 }
2147
2148 unsigned numTrailingObjects(OverloadToken<SourceRange>) const {
2149 return isParenTypeId();
2150 }
2151
2152public:
2153 enum InitializationStyle {
2154 /// New-expression has no initializer as written.
2155 NoInit,
2156
2157 /// New-expression has a C++98 paren-delimited initializer.
2158 CallInit,
2159
2160 /// New-expression has a C++11 list-initializer.
2161 ListInit
2162 };
2163
2164private:
2165 /// Build a c++ new expression.
2166 CXXNewExpr(bool IsGlobalNew, FunctionDecl *OperatorNew,
2167 FunctionDecl *OperatorDelete, bool ShouldPassAlignment,
2168 bool UsualArrayDeleteWantsSize, ArrayRef<Expr *> PlacementArgs,
2169 SourceRange TypeIdParens, Optional<Expr *> ArraySize,
2170 InitializationStyle InitializationStyle, Expr *Initializer,
2171 QualType Ty, TypeSourceInfo *AllocatedTypeInfo, SourceRange Range,
2172 SourceRange DirectInitRange);
2173
2174 /// Build an empty c++ new expression.
2175 CXXNewExpr(EmptyShell Empty, bool IsArray, unsigned NumPlacementArgs,
2176 bool IsParenTypeId);
2177
2178public:
2179 /// Create a c++ new expression.
2180 static CXXNewExpr *
2181 Create(const ASTContext &Ctx, bool IsGlobalNew, FunctionDecl *OperatorNew,
2182 FunctionDecl *OperatorDelete, bool ShouldPassAlignment,
2183 bool UsualArrayDeleteWantsSize, ArrayRef<Expr *> PlacementArgs,
2184 SourceRange TypeIdParens, Optional<Expr *> ArraySize,
2185 InitializationStyle InitializationStyle, Expr *Initializer,
2186 QualType Ty, TypeSourceInfo *AllocatedTypeInfo, SourceRange Range,
2187 SourceRange DirectInitRange);
2188
2189 /// Create an empty c++ new expression.
2190 static CXXNewExpr *CreateEmpty(const ASTContext &Ctx, bool IsArray,
2191 bool HasInit, unsigned NumPlacementArgs,
2192 bool IsParenTypeId);
2193
2194 QualType getAllocatedType() const {
2195 return getType()->castAs<PointerType>()->getPointeeType();
2196 }
2197
2198 TypeSourceInfo *getAllocatedTypeSourceInfo() const {
2199 return AllocatedTypeInfo;
2200 }
2201
2202 /// True if the allocation result needs to be null-checked.
2203 ///
2204 /// C++11 [expr.new]p13:
2205 /// If the allocation function returns null, initialization shall
2206 /// not be done, the deallocation function shall not be called,
2207 /// and the value of the new-expression shall be null.
2208 ///
2209 /// C++ DR1748:
2210 /// If the allocation function is a reserved placement allocation
2211 /// function that returns null, the behavior is undefined.
2212 ///
2213 /// An allocation function is not allowed to return null unless it
2214 /// has a non-throwing exception-specification. The '03 rule is
2215 /// identical except that the definition of a non-throwing
2216 /// exception specification is just "is it throw()?".
2217 bool shouldNullCheckAllocation() const;
2218
2219 FunctionDecl *getOperatorNew() const { return OperatorNew; }
2220 void setOperatorNew(FunctionDecl *D) { OperatorNew = D; }
2221 FunctionDecl *getOperatorDelete() const { return OperatorDelete; }
2222 void setOperatorDelete(FunctionDecl *D) { OperatorDelete = D; }
2223
2224 bool isArray() const { return CXXNewExprBits.IsArray; }
2225
2226 Optional<Expr *> getArraySize() {
2227 if (!isArray())
2228 return None;
2229 return cast_or_null<Expr>(getTrailingObjects<Stmt *>()[arraySizeOffset()]);
2230 }
2231 Optional<const Expr *> getArraySize() const {
2232 if (!isArray())
2233 return None;
2234 return cast_or_null<Expr>(getTrailingObjects<Stmt *>()[arraySizeOffset()]);
2235 }
2236
2237 unsigned getNumPlacementArgs() const {
2238 return CXXNewExprBits.NumPlacementArgs;
2239 }
2240
2241 Expr **getPlacementArgs() {
2242 return reinterpret_cast<Expr **>(getTrailingObjects<Stmt *>() +
2243 placementNewArgsOffset());
2244 }
2245
2246 Expr *getPlacementArg(unsigned I) {
2247 assert((I < getNumPlacementArgs()) && "Index out of range!")(((I < getNumPlacementArgs()) && "Index out of range!"
) ? static_cast<void> (0) : __assert_fail ("(I < getNumPlacementArgs()) && \"Index out of range!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 2247, __PRETTY_FUNCTION__))
;
2248 return getPlacementArgs()[I];
2249 }
2250 const Expr *getPlacementArg(unsigned I) const {
2251 return const_cast<CXXNewExpr *>(this)->getPlacementArg(I);
2252 }
2253
2254 bool isParenTypeId() const { return CXXNewExprBits.IsParenTypeId; }
2255 SourceRange getTypeIdParens() const {
2256 return isParenTypeId() ? getTrailingObjects<SourceRange>()[0]
2257 : SourceRange();
2258 }
2259
2260 bool isGlobalNew() const { return CXXNewExprBits.IsGlobalNew; }
2261
2262 /// Whether this new-expression has any initializer at all.
2263 bool hasInitializer() const {
2264 return CXXNewExprBits.StoredInitializationStyle > 0;
26
Assuming field 'StoredInitializationStyle' is > 0
27
Returning the value 1, which participates in a condition later
2265 }
2266
2267 /// The kind of initializer this new-expression has.
2268 InitializationStyle getInitializationStyle() const {
2269 if (CXXNewExprBits.StoredInitializationStyle == 0)
2270 return NoInit;
2271 return static_cast<InitializationStyle>(
2272 CXXNewExprBits.StoredInitializationStyle - 1);
2273 }
2274
2275 /// The initializer of this new-expression.
2276 Expr *getInitializer() {
2277 return hasInitializer()
2278 ? cast<Expr>(getTrailingObjects<Stmt *>()[initExprOffset()])
2279 : nullptr;
2280 }
2281 const Expr *getInitializer() const {
2282 return hasInitializer()
2283 ? cast<Expr>(getTrailingObjects<Stmt *>()[initExprOffset()])
2284 : nullptr;
2285 }
2286
2287 /// Returns the CXXConstructExpr from this new-expression, or null.
2288 const CXXConstructExpr *getConstructExpr() const {
2289 return dyn_cast_or_null<CXXConstructExpr>(getInitializer());
2290 }
2291
2292 /// Indicates whether the required alignment should be implicitly passed to
2293 /// the allocation function.
2294 bool passAlignment() const { return CXXNewExprBits.ShouldPassAlignment; }
2295
2296 /// Answers whether the usual array deallocation function for the
2297 /// allocated type expects the size of the allocation as a
2298 /// parameter.
2299 bool doesUsualArrayDeleteWantSize() const {
2300 return CXXNewExprBits.UsualArrayDeleteWantsSize;
2301 }
2302
2303 using arg_iterator = ExprIterator;
2304 using const_arg_iterator = ConstExprIterator;
2305
2306 llvm::iterator_range<arg_iterator> placement_arguments() {
2307 return llvm::make_range(placement_arg_begin(), placement_arg_end());
2308 }
2309
2310 llvm::iterator_range<const_arg_iterator> placement_arguments() const {
2311 return llvm::make_range(placement_arg_begin(), placement_arg_end());
2312 }
2313
2314 arg_iterator placement_arg_begin() {
2315 return getTrailingObjects<Stmt *>() + placementNewArgsOffset();
2316 }
2317 arg_iterator placement_arg_end() {
2318 return placement_arg_begin() + getNumPlacementArgs();
2319 }
2320 const_arg_iterator placement_arg_begin() const {
2321 return getTrailingObjects<Stmt *>() + placementNewArgsOffset();
2322 }
2323 const_arg_iterator placement_arg_end() const {
2324 return placement_arg_begin() + getNumPlacementArgs();
2325 }
2326
2327 using raw_arg_iterator = Stmt **;
2328
2329 raw_arg_iterator raw_arg_begin() { return getTrailingObjects<Stmt *>(); }
2330 raw_arg_iterator raw_arg_end() {
2331 return raw_arg_begin() + numTrailingObjects(OverloadToken<Stmt *>());
2332 }
2333 const_arg_iterator raw_arg_begin() const {
2334 return getTrailingObjects<Stmt *>();
2335 }
2336 const_arg_iterator raw_arg_end() const {
2337 return raw_arg_begin() + numTrailingObjects(OverloadToken<Stmt *>());
2338 }
2339
2340 SourceLocation getBeginLoc() const { return Range.getBegin(); }
2341 SourceLocation getEndLoc() const { return Range.getEnd(); }
2342
2343 SourceRange getDirectInitRange() const { return DirectInitRange; }
2344 SourceRange getSourceRange() const { return Range; }
2345
2346 static bool classof(const Stmt *T) {
2347 return T->getStmtClass() == CXXNewExprClass;
2348 }
2349
2350 // Iterators
2351 child_range children() { return child_range(raw_arg_begin(), raw_arg_end()); }
2352
2353 const_child_range children() const {
2354 return const_child_range(const_cast<CXXNewExpr *>(this)->children());
2355 }
2356};
2357
2358/// Represents a \c delete expression for memory deallocation and
2359/// destructor calls, e.g. "delete[] pArray".
2360class CXXDeleteExpr : public Expr {
2361 friend class ASTStmtReader;
2362
2363 /// Points to the operator delete overload that is used. Could be a member.
2364 FunctionDecl *OperatorDelete = nullptr;
2365
2366 /// The pointer expression to be deleted.
2367 Stmt *Argument = nullptr;
2368
2369public:
2370 CXXDeleteExpr(QualType Ty, bool GlobalDelete, bool ArrayForm,
2371 bool ArrayFormAsWritten, bool UsualArrayDeleteWantsSize,
2372 FunctionDecl *OperatorDelete, Expr *Arg, SourceLocation Loc)
2373 : Expr(CXXDeleteExprClass, Ty, VK_RValue, OK_Ordinary, false,
2374 Arg->isValueDependent(), Arg->isInstantiationDependent(),
2375 Arg->containsUnexpandedParameterPack()),
2376 OperatorDelete(OperatorDelete), Argument(Arg) {
2377 CXXDeleteExprBits.GlobalDelete = GlobalDelete;
2378 CXXDeleteExprBits.ArrayForm = ArrayForm;
2379 CXXDeleteExprBits.ArrayFormAsWritten = ArrayFormAsWritten;
2380 CXXDeleteExprBits.UsualArrayDeleteWantsSize = UsualArrayDeleteWantsSize;
2381 CXXDeleteExprBits.Loc = Loc;
2382 }
2383
2384 explicit CXXDeleteExpr(EmptyShell Shell) : Expr(CXXDeleteExprClass, Shell) {}
2385
2386 bool isGlobalDelete() const { return CXXDeleteExprBits.GlobalDelete; }
2387 bool isArrayForm() const { return CXXDeleteExprBits.ArrayForm; }
2388 bool isArrayFormAsWritten() const {
2389 return CXXDeleteExprBits.ArrayFormAsWritten;
2390 }
2391
2392 /// Answers whether the usual array deallocation function for the
2393 /// allocated type expects the size of the allocation as a
2394 /// parameter. This can be true even if the actual deallocation
2395 /// function that we're using doesn't want a size.
2396 bool doesUsualArrayDeleteWantSize() const {
2397 return CXXDeleteExprBits.UsualArrayDeleteWantsSize;
2398 }
2399
2400 FunctionDecl *getOperatorDelete() const { return OperatorDelete; }
2401
2402 Expr *getArgument() { return cast<Expr>(Argument); }
2403 const Expr *getArgument() const { return cast<Expr>(Argument); }
2404
2405 /// Retrieve the type being destroyed.
2406 ///
2407 /// If the type being destroyed is a dependent type which may or may not
2408 /// be a pointer, return an invalid type.
2409 QualType getDestroyedType() const;
2410
2411 SourceLocation getBeginLoc() const { return CXXDeleteExprBits.Loc; }
2412 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
2413 return Argument->getEndLoc();
2414 }
2415
2416 static bool classof(const Stmt *T) {
2417 return T->getStmtClass() == CXXDeleteExprClass;
2418 }
2419
2420 // Iterators
2421 child_range children() { return child_range(&Argument, &Argument + 1); }
2422
2423 const_child_range children() const {
2424 return const_child_range(&Argument, &Argument + 1);
2425 }
2426};
2427
2428/// Stores the type being destroyed by a pseudo-destructor expression.
2429class PseudoDestructorTypeStorage {
2430 /// Either the type source information or the name of the type, if
2431 /// it couldn't be resolved due to type-dependence.
2432 llvm::PointerUnion<TypeSourceInfo *, IdentifierInfo *> Type;
2433
2434 /// The starting source location of the pseudo-destructor type.
2435 SourceLocation Location;
2436
2437public:
2438 PseudoDestructorTypeStorage() = default;
2439
2440 PseudoDestructorTypeStorage(IdentifierInfo *II, SourceLocation Loc)
2441 : Type(II), Location(Loc) {}
2442
2443 PseudoDestructorTypeStorage(TypeSourceInfo *Info);
2444
2445 TypeSourceInfo *getTypeSourceInfo() const {
2446 return Type.dyn_cast<TypeSourceInfo *>();
2447 }
2448
2449 IdentifierInfo *getIdentifier() const {
2450 return Type.dyn_cast<IdentifierInfo *>();
2451 }
2452
2453 SourceLocation getLocation() const { return Location; }
2454};
2455
2456/// Represents a C++ pseudo-destructor (C++ [expr.pseudo]).
2457///
2458/// A pseudo-destructor is an expression that looks like a member access to a
2459/// destructor of a scalar type, except that scalar types don't have
2460/// destructors. For example:
2461///
2462/// \code
2463/// typedef int T;
2464/// void f(int *p) {
2465/// p->T::~T();
2466/// }
2467/// \endcode
2468///
2469/// Pseudo-destructors typically occur when instantiating templates such as:
2470///
2471/// \code
2472/// template<typename T>
2473/// void destroy(T* ptr) {
2474/// ptr->T::~T();
2475/// }
2476/// \endcode
2477///
2478/// for scalar types. A pseudo-destructor expression has no run-time semantics
2479/// beyond evaluating the base expression.
2480class CXXPseudoDestructorExpr : public Expr {
2481 friend class ASTStmtReader;
2482
2483 /// The base expression (that is being destroyed).
2484 Stmt *Base = nullptr;
2485
2486 /// Whether the operator was an arrow ('->'); otherwise, it was a
2487 /// period ('.').
2488 bool IsArrow : 1;
2489
2490 /// The location of the '.' or '->' operator.
2491 SourceLocation OperatorLoc;
2492
2493 /// The nested-name-specifier that follows the operator, if present.
2494 NestedNameSpecifierLoc QualifierLoc;
2495
2496 /// The type that precedes the '::' in a qualified pseudo-destructor
2497 /// expression.
2498 TypeSourceInfo *ScopeType = nullptr;
2499
2500 /// The location of the '::' in a qualified pseudo-destructor
2501 /// expression.
2502 SourceLocation ColonColonLoc;
2503
2504 /// The location of the '~'.
2505 SourceLocation TildeLoc;
2506
2507 /// The type being destroyed, or its name if we were unable to
2508 /// resolve the name.
2509 PseudoDestructorTypeStorage DestroyedType;
2510
2511public:
2512 CXXPseudoDestructorExpr(const ASTContext &Context,
2513 Expr *Base, bool isArrow, SourceLocation OperatorLoc,
2514 NestedNameSpecifierLoc QualifierLoc,
2515 TypeSourceInfo *ScopeType,
2516 SourceLocation ColonColonLoc,
2517 SourceLocation TildeLoc,
2518 PseudoDestructorTypeStorage DestroyedType);
2519
2520 explicit CXXPseudoDestructorExpr(EmptyShell Shell)
2521 : Expr(CXXPseudoDestructorExprClass, Shell), IsArrow(false) {}
2522
2523 Expr *getBase() const { return cast<Expr>(Base); }
2524
2525 /// Determines whether this member expression actually had
2526 /// a C++ nested-name-specifier prior to the name of the member, e.g.,
2527 /// x->Base::foo.
2528 bool hasQualifier() const { return QualifierLoc.hasQualifier(); }
2529
2530 /// Retrieves the nested-name-specifier that qualifies the type name,
2531 /// with source-location information.
2532 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
2533
2534 /// If the member name was qualified, retrieves the
2535 /// nested-name-specifier that precedes the member name. Otherwise, returns
2536 /// null.
2537 NestedNameSpecifier *getQualifier() const {
2538 return QualifierLoc.getNestedNameSpecifier();
2539 }
2540
2541 /// Determine whether this pseudo-destructor expression was written
2542 /// using an '->' (otherwise, it used a '.').
2543 bool isArrow() const { return IsArrow; }
2544
2545 /// Retrieve the location of the '.' or '->' operator.
2546 SourceLocation getOperatorLoc() const { return OperatorLoc; }
2547
2548 /// Retrieve the scope type in a qualified pseudo-destructor
2549 /// expression.
2550 ///
2551 /// Pseudo-destructor expressions can have extra qualification within them
2552 /// that is not part of the nested-name-specifier, e.g., \c p->T::~T().
2553 /// Here, if the object type of the expression is (or may be) a scalar type,
2554 /// \p T may also be a scalar type and, therefore, cannot be part of a
2555 /// nested-name-specifier. It is stored as the "scope type" of the pseudo-
2556 /// destructor expression.
2557 TypeSourceInfo *getScopeTypeInfo() const { return ScopeType; }
2558
2559 /// Retrieve the location of the '::' in a qualified pseudo-destructor
2560 /// expression.
2561 SourceLocation getColonColonLoc() const { return ColonColonLoc; }
2562
2563 /// Retrieve the location of the '~'.
2564 SourceLocation getTildeLoc() const { return TildeLoc; }
2565
2566 /// Retrieve the source location information for the type
2567 /// being destroyed.
2568 ///
2569 /// This type-source information is available for non-dependent
2570 /// pseudo-destructor expressions and some dependent pseudo-destructor
2571 /// expressions. Returns null if we only have the identifier for a
2572 /// dependent pseudo-destructor expression.
2573 TypeSourceInfo *getDestroyedTypeInfo() const {
2574 return DestroyedType.getTypeSourceInfo();
2575 }
2576
2577 /// In a dependent pseudo-destructor expression for which we do not
2578 /// have full type information on the destroyed type, provides the name
2579 /// of the destroyed type.
2580 IdentifierInfo *getDestroyedTypeIdentifier() const {
2581 return DestroyedType.getIdentifier();
2582 }
2583
2584 /// Retrieve the type being destroyed.
2585 QualType getDestroyedType() const;
2586
2587 /// Retrieve the starting location of the type being destroyed.
2588 SourceLocation getDestroyedTypeLoc() const {
2589 return DestroyedType.getLocation();
2590 }
2591
2592 /// Set the name of destroyed type for a dependent pseudo-destructor
2593 /// expression.
2594 void setDestroyedType(IdentifierInfo *II, SourceLocation Loc) {
2595 DestroyedType = PseudoDestructorTypeStorage(II, Loc);
2596 }
2597
2598 /// Set the destroyed type.
2599 void setDestroyedType(TypeSourceInfo *Info) {
2600 DestroyedType = PseudoDestructorTypeStorage(Info);
2601 }
2602
2603 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
2604 return Base->getBeginLoc();
2605 }
2606 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__));
2607
2608 static bool classof(const Stmt *T) {
2609 return T->getStmtClass() == CXXPseudoDestructorExprClass;
2610 }
2611
2612 // Iterators
2613 child_range children() { return child_range(&Base, &Base + 1); }
2614
2615 const_child_range children() const {
2616 return const_child_range(&Base, &Base + 1);
2617 }
2618};
2619
2620/// A type trait used in the implementation of various C++11 and
2621/// Library TR1 trait templates.
2622///
2623/// \code
2624/// __is_pod(int) == true
2625/// __is_enum(std::string) == false
2626/// __is_trivially_constructible(vector<int>, int*, int*)
2627/// \endcode
2628class TypeTraitExpr final
2629 : public Expr,
2630 private llvm::TrailingObjects<TypeTraitExpr, TypeSourceInfo *> {
2631 /// The location of the type trait keyword.
2632 SourceLocation Loc;
2633
2634 /// The location of the closing parenthesis.
2635 SourceLocation RParenLoc;
2636
2637 // Note: The TypeSourceInfos for the arguments are allocated after the
2638 // TypeTraitExpr.
2639
2640 TypeTraitExpr(QualType T, SourceLocation Loc, TypeTrait Kind,
2641 ArrayRef<TypeSourceInfo *> Args,
2642 SourceLocation RParenLoc,
2643 bool Value);
2644
2645 TypeTraitExpr(EmptyShell Empty) : Expr(TypeTraitExprClass, Empty) {}
2646
2647 size_t numTrailingObjects(OverloadToken<TypeSourceInfo *>) const {
2648 return getNumArgs();
2649 }
2650
2651public:
2652 friend class ASTStmtReader;
2653 friend class ASTStmtWriter;
2654 friend TrailingObjects;
2655
2656 /// Create a new type trait expression.
2657 static TypeTraitExpr *Create(const ASTContext &C, QualType T,
2658 SourceLocation Loc, TypeTrait Kind,
2659 ArrayRef<TypeSourceInfo *> Args,
2660 SourceLocation RParenLoc,
2661 bool Value);
2662
2663 static TypeTraitExpr *CreateDeserialized(const ASTContext &C,
2664 unsigned NumArgs);
2665
2666 /// Determine which type trait this expression uses.
2667 TypeTrait getTrait() const {
2668 return static_cast<TypeTrait>(TypeTraitExprBits.Kind);
2669 }
2670
2671 bool getValue() const {
2672 assert(!isValueDependent())((!isValueDependent()) ? static_cast<void> (0) : __assert_fail
("!isValueDependent()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 2672, __PRETTY_FUNCTION__))
;
2673 return TypeTraitExprBits.Value;
2674 }
2675
2676 /// Determine the number of arguments to this type trait.
2677 unsigned getNumArgs() const { return TypeTraitExprBits.NumArgs; }
2678
2679 /// Retrieve the Ith argument.
2680 TypeSourceInfo *getArg(unsigned I) const {
2681 assert(I < getNumArgs() && "Argument out-of-range")((I < getNumArgs() && "Argument out-of-range") ? static_cast
<void> (0) : __assert_fail ("I < getNumArgs() && \"Argument out-of-range\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 2681, __PRETTY_FUNCTION__))
;
2682 return getArgs()[I];
2683 }
2684
2685 /// Retrieve the argument types.
2686 ArrayRef<TypeSourceInfo *> getArgs() const {
2687 return llvm::makeArrayRef(getTrailingObjects<TypeSourceInfo *>(),
2688 getNumArgs());
2689 }
2690
2691 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
2692 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; }
2693
2694 static bool classof(const Stmt *T) {
2695 return T->getStmtClass() == TypeTraitExprClass;
2696 }
2697
2698 // Iterators
2699 child_range children() {
2700 return child_range(child_iterator(), child_iterator());
2701 }
2702
2703 const_child_range children() const {
2704 return const_child_range(const_child_iterator(), const_child_iterator());
2705 }
2706};
2707
2708/// An Embarcadero array type trait, as used in the implementation of
2709/// __array_rank and __array_extent.
2710///
2711/// Example:
2712/// \code
2713/// __array_rank(int[10][20]) == 2
2714/// __array_extent(int, 1) == 20
2715/// \endcode
2716class ArrayTypeTraitExpr : public Expr {
2717 /// The trait. An ArrayTypeTrait enum in MSVC compat unsigned.
2718 unsigned ATT : 2;
2719
2720 /// The value of the type trait. Unspecified if dependent.
2721 uint64_t Value = 0;
2722
2723 /// The array dimension being queried, or -1 if not used.
2724 Expr *Dimension;
2725
2726 /// The location of the type trait keyword.
2727 SourceLocation Loc;
2728
2729 /// The location of the closing paren.
2730 SourceLocation RParen;
2731
2732 /// The type being queried.
2733 TypeSourceInfo *QueriedType = nullptr;
2734
2735public:
2736 friend class ASTStmtReader;
2737
2738 ArrayTypeTraitExpr(SourceLocation loc, ArrayTypeTrait att,
2739 TypeSourceInfo *queried, uint64_t value,
2740 Expr *dimension, SourceLocation rparen, QualType ty)
2741 : Expr(ArrayTypeTraitExprClass, ty, VK_RValue, OK_Ordinary,
2742 false, queried->getType()->isDependentType(),
2743 (queried->getType()->isInstantiationDependentType() ||
2744 (dimension && dimension->isInstantiationDependent())),
2745 queried->getType()->containsUnexpandedParameterPack()),
2746 ATT(att), Value(value), Dimension(dimension),
2747 Loc(loc), RParen(rparen), QueriedType(queried) {}
2748
2749 explicit ArrayTypeTraitExpr(EmptyShell Empty)
2750 : Expr(ArrayTypeTraitExprClass, Empty), ATT(0) {}
2751
2752 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
2753 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParen; }
2754
2755 ArrayTypeTrait getTrait() const { return static_cast<ArrayTypeTrait>(ATT); }
2756
2757 QualType getQueriedType() const { return QueriedType->getType(); }
2758
2759 TypeSourceInfo *getQueriedTypeSourceInfo() const { return QueriedType; }
2760
2761 uint64_t getValue() const { assert(!isTypeDependent())((!isTypeDependent()) ? static_cast<void> (0) : __assert_fail
("!isTypeDependent()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 2761, __PRETTY_FUNCTION__))
; return Value; }
2762
2763 Expr *getDimensionExpression() const { return Dimension; }
2764
2765 static bool classof(const Stmt *T) {
2766 return T->getStmtClass() == ArrayTypeTraitExprClass;
2767 }
2768
2769 // Iterators
2770 child_range children() {
2771 return child_range(child_iterator(), child_iterator());
2772 }
2773
2774 const_child_range children() const {
2775 return const_child_range(const_child_iterator(), const_child_iterator());
2776 }
2777};
2778
2779/// An expression trait intrinsic.
2780///
2781/// Example:
2782/// \code
2783/// __is_lvalue_expr(std::cout) == true
2784/// __is_lvalue_expr(1) == false
2785/// \endcode
2786class ExpressionTraitExpr : public Expr {
2787 /// The trait. A ExpressionTrait enum in MSVC compatible unsigned.
2788 unsigned ET : 31;
2789
2790 /// The value of the type trait. Unspecified if dependent.
2791 unsigned Value : 1;
2792
2793 /// The location of the type trait keyword.
2794 SourceLocation Loc;
2795
2796 /// The location of the closing paren.
2797 SourceLocation RParen;
2798
2799 /// The expression being queried.
2800 Expr* QueriedExpression = nullptr;
2801
2802public:
2803 friend class ASTStmtReader;
2804
2805 ExpressionTraitExpr(SourceLocation loc, ExpressionTrait et,
2806 Expr *queried, bool value,
2807 SourceLocation rparen, QualType resultType)
2808 : Expr(ExpressionTraitExprClass, resultType, VK_RValue, OK_Ordinary,
2809 false, // Not type-dependent
2810 // Value-dependent if the argument is type-dependent.
2811 queried->isTypeDependent(),
2812 queried->isInstantiationDependent(),
2813 queried->containsUnexpandedParameterPack()),
2814 ET(et), Value(value), Loc(loc), RParen(rparen),
2815 QueriedExpression(queried) {}
2816
2817 explicit ExpressionTraitExpr(EmptyShell Empty)
2818 : Expr(ExpressionTraitExprClass, Empty), ET(0), Value(false) {}
2819
2820 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
2821 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParen; }
2822
2823 ExpressionTrait getTrait() const { return static_cast<ExpressionTrait>(ET); }
2824
2825 Expr *getQueriedExpression() const { return QueriedExpression; }
2826
2827 bool getValue() const { return Value; }
2828
2829 static bool classof(const Stmt *T) {
2830 return T->getStmtClass() == ExpressionTraitExprClass;
2831 }
2832
2833 // Iterators
2834 child_range children() {
2835 return child_range(child_iterator(), child_iterator());
2836 }
2837
2838 const_child_range children() const {
2839 return const_child_range(const_child_iterator(), const_child_iterator());
2840 }
2841};
2842
2843/// A reference to an overloaded function set, either an
2844/// \c UnresolvedLookupExpr or an \c UnresolvedMemberExpr.
2845class OverloadExpr : public Expr {
2846 friend class ASTStmtReader;
2847 friend class ASTStmtWriter;
2848
2849 /// The common name of these declarations.
2850 DeclarationNameInfo NameInfo;
2851
2852 /// The nested-name-specifier that qualifies the name, if any.
2853 NestedNameSpecifierLoc QualifierLoc;
2854
2855protected:
2856 OverloadExpr(StmtClass SC, const ASTContext &Context,
2857 NestedNameSpecifierLoc QualifierLoc,
2858 SourceLocation TemplateKWLoc,
2859 const DeclarationNameInfo &NameInfo,
2860 const TemplateArgumentListInfo *TemplateArgs,
2861 UnresolvedSetIterator Begin, UnresolvedSetIterator End,
2862 bool KnownDependent, bool KnownInstantiationDependent,
2863 bool KnownContainsUnexpandedParameterPack);
2864
2865 OverloadExpr(StmtClass SC, EmptyShell Empty, unsigned NumResults,
2866 bool HasTemplateKWAndArgsInfo);
2867
2868 /// Return the results. Defined after UnresolvedMemberExpr.
2869 inline DeclAccessPair *getTrailingResults();
2870 const DeclAccessPair *getTrailingResults() const {
2871 return const_cast<OverloadExpr *>(this)->getTrailingResults();
2872 }
2873
2874 /// Return the optional template keyword and arguments info.
2875 /// Defined after UnresolvedMemberExpr.
2876 inline ASTTemplateKWAndArgsInfo *getTrailingASTTemplateKWAndArgsInfo();
2877 const ASTTemplateKWAndArgsInfo *getTrailingASTTemplateKWAndArgsInfo() const {
2878 return const_cast<OverloadExpr *>(this)
2879 ->getTrailingASTTemplateKWAndArgsInfo();
2880 }
2881
2882 /// Return the optional template arguments. Defined after
2883 /// UnresolvedMemberExpr.
2884 inline TemplateArgumentLoc *getTrailingTemplateArgumentLoc();
2885 const TemplateArgumentLoc *getTrailingTemplateArgumentLoc() const {
2886 return const_cast<OverloadExpr *>(this)->getTrailingTemplateArgumentLoc();
2887 }
2888
2889 bool hasTemplateKWAndArgsInfo() const {
2890 return OverloadExprBits.HasTemplateKWAndArgsInfo;
2891 }
2892
2893public:
2894 struct FindResult {
2895 OverloadExpr *Expression;
2896 bool IsAddressOfOperand;
2897 bool HasFormOfMemberPointer;
2898 };
2899
2900 /// Finds the overloaded expression in the given expression \p E of
2901 /// OverloadTy.
2902 ///
2903 /// \return the expression (which must be there) and true if it has
2904 /// the particular form of a member pointer expression
2905 static FindResult find(Expr *E) {
2906 assert(E->getType()->isSpecificBuiltinType(BuiltinType::Overload))((E->getType()->isSpecificBuiltinType(BuiltinType::Overload
)) ? static_cast<void> (0) : __assert_fail ("E->getType()->isSpecificBuiltinType(BuiltinType::Overload)"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 2906, __PRETTY_FUNCTION__))
;
2907
2908 FindResult Result;
2909
2910 E = E->IgnoreParens();
2911 if (isa<UnaryOperator>(E)) {
2912 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf)((cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) ?
static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 2912, __PRETTY_FUNCTION__))
;
2913 E = cast<UnaryOperator>(E)->getSubExpr();
2914 auto *Ovl = cast<OverloadExpr>(E->IgnoreParens());
2915
2916 Result.HasFormOfMemberPointer = (E == Ovl && Ovl->getQualifier());
2917 Result.IsAddressOfOperand = true;
2918 Result.Expression = Ovl;
2919 } else {
2920 Result.HasFormOfMemberPointer = false;
2921 Result.IsAddressOfOperand = false;
2922 Result.Expression = cast<OverloadExpr>(E);
2923 }
2924
2925 return Result;
2926 }
2927
2928 /// Gets the naming class of this lookup, if any.
2929 /// Defined after UnresolvedMemberExpr.
2930 inline CXXRecordDecl *getNamingClass();
2931 const CXXRecordDecl *getNamingClass() const {
2932 return const_cast<OverloadExpr *>(this)->getNamingClass();
2933 }
2934
2935 using decls_iterator = UnresolvedSetImpl::iterator;
2936
2937 decls_iterator decls_begin() const {
2938 return UnresolvedSetIterator(getTrailingResults());
2939 }
2940 decls_iterator decls_end() const {
2941 return UnresolvedSetIterator(getTrailingResults() + getNumDecls());
2942 }
2943 llvm::iterator_range<decls_iterator> decls() const {
2944 return llvm::make_range(decls_begin(), decls_end());
2945 }
2946
2947 /// Gets the number of declarations in the unresolved set.
2948 unsigned getNumDecls() const { return OverloadExprBits.NumResults; }
2949
2950 /// Gets the full name info.
2951 const DeclarationNameInfo &getNameInfo() const { return NameInfo; }
2952
2953 /// Gets the name looked up.
2954 DeclarationName getName() const { return NameInfo.getName(); }
2955
2956 /// Gets the location of the name.
2957 SourceLocation getNameLoc() const { return NameInfo.getLoc(); }
2958
2959 /// Fetches the nested-name qualifier, if one was given.
2960 NestedNameSpecifier *getQualifier() const {
2961 return QualifierLoc.getNestedNameSpecifier();
2962 }
2963
2964 /// Fetches the nested-name qualifier with source-location
2965 /// information, if one was given.
2966 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
2967
2968 /// Retrieve the location of the template keyword preceding
2969 /// this name, if any.
2970 SourceLocation getTemplateKeywordLoc() const {
2971 if (!hasTemplateKWAndArgsInfo())
2972 return SourceLocation();
2973 return getTrailingASTTemplateKWAndArgsInfo()->TemplateKWLoc;
2974 }
2975
2976 /// Retrieve the location of the left angle bracket starting the
2977 /// explicit template argument list following the name, if any.
2978 SourceLocation getLAngleLoc() const {
2979 if (!hasTemplateKWAndArgsInfo())
2980 return SourceLocation();
2981 return getTrailingASTTemplateKWAndArgsInfo()->LAngleLoc;
2982 }
2983
2984 /// Retrieve the location of the right angle bracket ending the
2985 /// explicit template argument list following the name, if any.
2986 SourceLocation getRAngleLoc() const {
2987 if (!hasTemplateKWAndArgsInfo())
2988 return SourceLocation();
2989 return getTrailingASTTemplateKWAndArgsInfo()->RAngleLoc;
2990 }
2991
2992 /// Determines whether the name was preceded by the template keyword.
2993 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
2994
2995 /// Determines whether this expression had explicit template arguments.
2996 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
2997
2998 TemplateArgumentLoc const *getTemplateArgs() const {
2999 if (!hasExplicitTemplateArgs())
3000 return nullptr;
3001 return const_cast<OverloadExpr *>(this)->getTrailingTemplateArgumentLoc();
3002 }
3003
3004 unsigned getNumTemplateArgs() const {
3005 if (!hasExplicitTemplateArgs())
3006 return 0;
3007
3008 return getTrailingASTTemplateKWAndArgsInfo()->NumTemplateArgs;
3009 }
3010
3011 ArrayRef<TemplateArgumentLoc> template_arguments() const {
3012 return {getTemplateArgs(), getNumTemplateArgs()};
3013 }
3014
3015 /// Copies the template arguments into the given structure.
3016 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
3017 if (hasExplicitTemplateArgs())
3018 getTrailingASTTemplateKWAndArgsInfo()->copyInto(getTemplateArgs(), List);
3019 }
3020
3021 static bool classof(const Stmt *T) {
3022 return T->getStmtClass() == UnresolvedLookupExprClass ||
3023 T->getStmtClass() == UnresolvedMemberExprClass;
3024 }
3025};
3026
3027/// A reference to a name which we were able to look up during
3028/// parsing but could not resolve to a specific declaration.
3029///
3030/// This arises in several ways:
3031/// * we might be waiting for argument-dependent lookup;
3032/// * the name might resolve to an overloaded function;
3033/// and eventually:
3034/// * the lookup might have included a function template.
3035///
3036/// These never include UnresolvedUsingValueDecls, which are always class
3037/// members and therefore appear only in UnresolvedMemberLookupExprs.
3038class UnresolvedLookupExpr final
3039 : public OverloadExpr,
3040 private llvm::TrailingObjects<UnresolvedLookupExpr, DeclAccessPair,
3041 ASTTemplateKWAndArgsInfo,
3042 TemplateArgumentLoc> {
3043 friend class ASTStmtReader;
3044 friend class OverloadExpr;
3045 friend TrailingObjects;
3046
3047 /// The naming class (C++ [class.access.base]p5) of the lookup, if
3048 /// any. This can generally be recalculated from the context chain,
3049 /// but that can be fairly expensive for unqualified lookups.
3050 CXXRecordDecl *NamingClass;
3051
3052 // UnresolvedLookupExpr is followed by several trailing objects.
3053 // They are in order:
3054 //
3055 // * An array of getNumResults() DeclAccessPair for the results. These are
3056 // undesugared, which is to say, they may include UsingShadowDecls.
3057 // Access is relative to the naming class.
3058 //
3059 // * An optional ASTTemplateKWAndArgsInfo for the explicitly specified
3060 // template keyword and arguments. Present if and only if
3061 // hasTemplateKWAndArgsInfo().
3062 //
3063 // * An array of getNumTemplateArgs() TemplateArgumentLoc containing
3064 // location information for the explicitly specified template arguments.
3065
3066 UnresolvedLookupExpr(const ASTContext &Context, CXXRecordDecl *NamingClass,
3067 NestedNameSpecifierLoc QualifierLoc,
3068 SourceLocation TemplateKWLoc,
3069 const DeclarationNameInfo &NameInfo, bool RequiresADL,
3070 bool Overloaded,
3071 const TemplateArgumentListInfo *TemplateArgs,
3072 UnresolvedSetIterator Begin, UnresolvedSetIterator End);
3073
3074 UnresolvedLookupExpr(EmptyShell Empty, unsigned NumResults,
3075 bool HasTemplateKWAndArgsInfo);
3076
3077 unsigned numTrailingObjects(OverloadToken<DeclAccessPair>) const {
3078 return getNumDecls();
3079 }
3080
3081 unsigned numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
3082 return hasTemplateKWAndArgsInfo();
3083 }
3084
3085public:
3086 static UnresolvedLookupExpr *
3087 Create(const ASTContext &Context, CXXRecordDecl *NamingClass,
3088 NestedNameSpecifierLoc QualifierLoc,
3089 const DeclarationNameInfo &NameInfo, bool RequiresADL, bool Overloaded,
3090 UnresolvedSetIterator Begin, UnresolvedSetIterator End);
3091
3092 static UnresolvedLookupExpr *
3093 Create(const ASTContext &Context, CXXRecordDecl *NamingClass,
3094 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
3095 const DeclarationNameInfo &NameInfo, bool RequiresADL,
3096 const TemplateArgumentListInfo *Args, UnresolvedSetIterator Begin,
3097 UnresolvedSetIterator End);
3098
3099 static UnresolvedLookupExpr *CreateEmpty(const ASTContext &Context,
3100 unsigned NumResults,
3101 bool HasTemplateKWAndArgsInfo,
3102 unsigned NumTemplateArgs);
3103
3104 /// True if this declaration should be extended by
3105 /// argument-dependent lookup.
3106 bool requiresADL() const { return UnresolvedLookupExprBits.RequiresADL; }
3107
3108 /// True if this lookup is overloaded.
3109 bool isOverloaded() const { return UnresolvedLookupExprBits.Overloaded; }
3110
3111 /// Gets the 'naming class' (in the sense of C++0x
3112 /// [class.access.base]p5) of the lookup. This is the scope
3113 /// that was looked in to find these results.
3114 CXXRecordDecl *getNamingClass() { return NamingClass; }
3115 const CXXRecordDecl *getNamingClass() const { return NamingClass; }
3116
3117 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
3118 if (NestedNameSpecifierLoc l = getQualifierLoc())
3119 return l.getBeginLoc();
3120 return getNameInfo().getBeginLoc();
3121 }
3122
3123 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
3124 if (hasExplicitTemplateArgs())
3125 return getRAngleLoc();
3126 return getNameInfo().getEndLoc();
3127 }
3128
3129 child_range children() {
3130 return child_range(child_iterator(), child_iterator());
3131 }
3132
3133 const_child_range children() const {
3134 return const_child_range(const_child_iterator(), const_child_iterator());
3135 }
3136
3137 static bool classof(const Stmt *T) {
3138 return T->getStmtClass() == UnresolvedLookupExprClass;
3139 }
3140};
3141
3142/// A qualified reference to a name whose declaration cannot
3143/// yet be resolved.
3144///
3145/// DependentScopeDeclRefExpr is similar to DeclRefExpr in that
3146/// it expresses a reference to a declaration such as
3147/// X<T>::value. The difference, however, is that an
3148/// DependentScopeDeclRefExpr node is used only within C++ templates when
3149/// the qualification (e.g., X<T>::) refers to a dependent type. In
3150/// this case, X<T>::value cannot resolve to a declaration because the
3151/// declaration will differ from one instantiation of X<T> to the
3152/// next. Therefore, DependentScopeDeclRefExpr keeps track of the
3153/// qualifier (X<T>::) and the name of the entity being referenced
3154/// ("value"). Such expressions will instantiate to a DeclRefExpr once the
3155/// declaration can be found.
3156class DependentScopeDeclRefExpr final
3157 : public Expr,
3158 private llvm::TrailingObjects<DependentScopeDeclRefExpr,
3159 ASTTemplateKWAndArgsInfo,
3160 TemplateArgumentLoc> {
3161 friend class ASTStmtReader;
3162 friend class ASTStmtWriter;
3163 friend TrailingObjects;
3164
3165 /// The nested-name-specifier that qualifies this unresolved
3166 /// declaration name.
3167 NestedNameSpecifierLoc QualifierLoc;
3168
3169 /// The name of the entity we will be referencing.
3170 DeclarationNameInfo NameInfo;
3171
3172 DependentScopeDeclRefExpr(QualType Ty, NestedNameSpecifierLoc QualifierLoc,
3173 SourceLocation TemplateKWLoc,
3174 const DeclarationNameInfo &NameInfo,
3175 const TemplateArgumentListInfo *Args);
3176
3177 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
3178 return hasTemplateKWAndArgsInfo();
3179 }
3180
3181 bool hasTemplateKWAndArgsInfo() const {
3182 return DependentScopeDeclRefExprBits.HasTemplateKWAndArgsInfo;
3183 }
3184
3185public:
3186 static DependentScopeDeclRefExpr *
3187 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
3188 SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo,
3189 const TemplateArgumentListInfo *TemplateArgs);
3190
3191 static DependentScopeDeclRefExpr *CreateEmpty(const ASTContext &Context,
3192 bool HasTemplateKWAndArgsInfo,
3193 unsigned NumTemplateArgs);
3194
3195 /// Retrieve the name that this expression refers to.
3196 const DeclarationNameInfo &getNameInfo() const { return NameInfo; }
3197
3198 /// Retrieve the name that this expression refers to.
3199 DeclarationName getDeclName() const { return NameInfo.getName(); }
3200
3201 /// Retrieve the location of the name within the expression.
3202 ///
3203 /// For example, in "X<T>::value" this is the location of "value".
3204 SourceLocation getLocation() const { return NameInfo.getLoc(); }
3205
3206 /// Retrieve the nested-name-specifier that qualifies the
3207 /// name, with source location information.
3208 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3209
3210 /// Retrieve the nested-name-specifier that qualifies this
3211 /// declaration.
3212 NestedNameSpecifier *getQualifier() const {
3213 return QualifierLoc.getNestedNameSpecifier();
3214 }
3215
3216 /// Retrieve the location of the template keyword preceding
3217 /// this name, if any.
3218 SourceLocation getTemplateKeywordLoc() const {
3219 if (!hasTemplateKWAndArgsInfo())
3220 return SourceLocation();
3221 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
3222 }
3223
3224 /// Retrieve the location of the left angle bracket starting the
3225 /// explicit template argument list following the name, if any.
3226 SourceLocation getLAngleLoc() const {
3227 if (!hasTemplateKWAndArgsInfo())
3228 return SourceLocation();
3229 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
3230 }
3231
3232 /// Retrieve the location of the right angle bracket ending the
3233 /// explicit template argument list following the name, if any.
3234 SourceLocation getRAngleLoc() const {
3235 if (!hasTemplateKWAndArgsInfo())
3236 return SourceLocation();
3237 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
3238 }
3239
3240 /// Determines whether the name was preceded by the template keyword.
3241 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
3242
3243 /// Determines whether this lookup had explicit template arguments.
3244 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
3245
3246 /// Copies the template arguments (if present) into the given
3247 /// structure.
3248 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
3249 if (hasExplicitTemplateArgs())
3250 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
3251 getTrailingObjects<TemplateArgumentLoc>(), List);
3252 }
3253
3254 TemplateArgumentLoc const *getTemplateArgs() const {
3255 if (!hasExplicitTemplateArgs())
3256 return nullptr;
3257
3258 return getTrailingObjects<TemplateArgumentLoc>();
3259 }
3260
3261 unsigned getNumTemplateArgs() const {
3262 if (!hasExplicitTemplateArgs())
3263 return 0;
3264
3265 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
3266 }
3267
3268 ArrayRef<TemplateArgumentLoc> template_arguments() const {
3269 return {getTemplateArgs(), getNumTemplateArgs()};
3270 }
3271
3272 /// Note: getBeginLoc() is the start of the whole DependentScopeDeclRefExpr,
3273 /// and differs from getLocation().getStart().
3274 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
3275 return QualifierLoc.getBeginLoc();
3276 }
3277
3278 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
3279 if (hasExplicitTemplateArgs())
3280 return getRAngleLoc();
3281 return getLocation();
3282 }
3283
3284 static bool classof(const Stmt *T) {
3285 return T->getStmtClass() == DependentScopeDeclRefExprClass;
3286 }
3287
3288 child_range children() {
3289 return child_range(child_iterator(), child_iterator());
3290 }
3291
3292 const_child_range children() const {
3293 return const_child_range(const_child_iterator(), const_child_iterator());
3294 }
3295};
3296
3297/// Represents an expression -- generally a full-expression -- that
3298/// introduces cleanups to be run at the end of the sub-expression's
3299/// evaluation. The most common source of expression-introduced
3300/// cleanups is temporary objects in C++, but several other kinds of
3301/// expressions can create cleanups, including basically every
3302/// call in ARC that returns an Objective-C pointer.
3303///
3304/// This expression also tracks whether the sub-expression contains a
3305/// potentially-evaluated block literal. The lifetime of a block
3306/// literal is the extent of the enclosing scope.
3307class ExprWithCleanups final
3308 : public FullExpr,
3309 private llvm::TrailingObjects<ExprWithCleanups, BlockDecl *> {
3310public:
3311 /// The type of objects that are kept in the cleanup.
3312 /// It's useful to remember the set of blocks; we could also
3313 /// remember the set of temporaries, but there's currently
3314 /// no need.
3315 using CleanupObject = BlockDecl *;
3316
3317private:
3318 friend class ASTStmtReader;
3319 friend TrailingObjects;
3320
3321 ExprWithCleanups(EmptyShell, unsigned NumObjects);
3322 ExprWithCleanups(Expr *SubExpr, bool CleanupsHaveSideEffects,
3323 ArrayRef<CleanupObject> Objects);
3324
3325public:
3326 static ExprWithCleanups *Create(const ASTContext &C, EmptyShell empty,
3327 unsigned numObjects);
3328
3329 static ExprWithCleanups *Create(const ASTContext &C, Expr *subexpr,
3330 bool CleanupsHaveSideEffects,
3331 ArrayRef<CleanupObject> objects);
3332
3333 ArrayRef<CleanupObject> getObjects() const {
3334 return llvm::makeArrayRef(getTrailingObjects<CleanupObject>(),
3335 getNumObjects());
3336 }
3337
3338 unsigned getNumObjects() const { return ExprWithCleanupsBits.NumObjects; }
3339
3340 CleanupObject getObject(unsigned i) const {
3341 assert(i < getNumObjects() && "Index out of range")((i < getNumObjects() && "Index out of range") ? static_cast
<void> (0) : __assert_fail ("i < getNumObjects() && \"Index out of range\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 3341, __PRETTY_FUNCTION__))
;
3342 return getObjects()[i];
3343 }
3344
3345 bool cleanupsHaveSideEffects() const {
3346 return ExprWithCleanupsBits.CleanupsHaveSideEffects;
3347 }
3348
3349 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
3350 return SubExpr->getBeginLoc();
3351 }
3352
3353 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
3354 return SubExpr->getEndLoc();
3355 }
3356
3357 // Implement isa/cast/dyncast/etc.
3358 static bool classof(const Stmt *T) {
3359 return T->getStmtClass() == ExprWithCleanupsClass;
3360 }
3361
3362 // Iterators
3363 child_range children() { return child_range(&SubExpr, &SubExpr + 1); }
3364
3365 const_child_range children() const {
3366 return const_child_range(&SubExpr, &SubExpr + 1);
3367 }
3368};
3369
3370/// Describes an explicit type conversion that uses functional
3371/// notion but could not be resolved because one or more arguments are
3372/// type-dependent.
3373///
3374/// The explicit type conversions expressed by
3375/// CXXUnresolvedConstructExpr have the form <tt>T(a1, a2, ..., aN)</tt>,
3376/// where \c T is some type and \c a1, \c a2, ..., \c aN are values, and
3377/// either \c T is a dependent type or one or more of the <tt>a</tt>'s is
3378/// type-dependent. For example, this would occur in a template such
3379/// as:
3380///
3381/// \code
3382/// template<typename T, typename A1>
3383/// inline T make_a(const A1& a1) {
3384/// return T(a1);
3385/// }
3386/// \endcode
3387///
3388/// When the returned expression is instantiated, it may resolve to a
3389/// constructor call, conversion function call, or some kind of type
3390/// conversion.
3391class CXXUnresolvedConstructExpr final
3392 : public Expr,
3393 private llvm::TrailingObjects<CXXUnresolvedConstructExpr, Expr *> {
3394 friend class ASTStmtReader;
3395 friend TrailingObjects;
3396
3397 /// The type being constructed.
3398 TypeSourceInfo *TSI;
3399
3400 /// The location of the left parentheses ('(').
3401 SourceLocation LParenLoc;
3402
3403 /// The location of the right parentheses (')').
3404 SourceLocation RParenLoc;
3405
3406 CXXUnresolvedConstructExpr(TypeSourceInfo *TSI, SourceLocation LParenLoc,
3407 ArrayRef<Expr *> Args, SourceLocation RParenLoc);
3408
3409 CXXUnresolvedConstructExpr(EmptyShell Empty, unsigned NumArgs)
3410 : Expr(CXXUnresolvedConstructExprClass, Empty) {
3411 CXXUnresolvedConstructExprBits.NumArgs = NumArgs;
3412 }
3413
3414public:
3415 static CXXUnresolvedConstructExpr *Create(const ASTContext &Context,
3416 TypeSourceInfo *Type,
3417 SourceLocation LParenLoc,
3418 ArrayRef<Expr *> Args,
3419 SourceLocation RParenLoc);
3420
3421 static CXXUnresolvedConstructExpr *CreateEmpty(const ASTContext &Context,
3422 unsigned NumArgs);
3423
3424 /// Retrieve the type that is being constructed, as specified
3425 /// in the source code.
3426 QualType getTypeAsWritten() const { return TSI->getType(); }
3427
3428 /// Retrieve the type source information for the type being
3429 /// constructed.
3430 TypeSourceInfo *getTypeSourceInfo() const { return TSI; }
3431
3432 /// Retrieve the location of the left parentheses ('(') that
3433 /// precedes the argument list.
3434 SourceLocation getLParenLoc() const { return LParenLoc; }
3435 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
3436
3437 /// Retrieve the location of the right parentheses (')') that
3438 /// follows the argument list.
3439 SourceLocation getRParenLoc() const { return RParenLoc; }
3440 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3441
3442 /// Determine whether this expression models list-initialization.
3443 /// If so, there will be exactly one subexpression, which will be
3444 /// an InitListExpr.
3445 bool isListInitialization() const { return LParenLoc.isInvalid(); }
3446
3447 /// Retrieve the number of arguments.
3448 unsigned arg_size() const { return CXXUnresolvedConstructExprBits.NumArgs; }
3449
3450 using arg_iterator = Expr **;
3451 using arg_range = llvm::iterator_range<arg_iterator>;
3452
3453 arg_iterator arg_begin() { return getTrailingObjects<Expr *>(); }
3454 arg_iterator arg_end() { return arg_begin() + arg_size(); }
3455 arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
3456
3457 using const_arg_iterator = const Expr* const *;
3458 using const_arg_range = llvm::iterator_range<const_arg_iterator>;
3459
3460 const_arg_iterator arg_begin() const { return getTrailingObjects<Expr *>(); }
3461 const_arg_iterator arg_end() const { return arg_begin() + arg_size(); }
3462 const_arg_range arguments() const {
3463 return const_arg_range(arg_begin(), arg_end());
3464 }
3465
3466 Expr *getArg(unsigned I) {
3467 assert(I < arg_size() && "Argument index out-of-range")((I < arg_size() && "Argument index out-of-range")
? static_cast<void> (0) : __assert_fail ("I < arg_size() && \"Argument index out-of-range\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 3467, __PRETTY_FUNCTION__))
;
3468 return arg_begin()[I];
3469 }
3470
3471 const Expr *getArg(unsigned I) const {
3472 assert(I < arg_size() && "Argument index out-of-range")((I < arg_size() && "Argument index out-of-range")
? static_cast<void> (0) : __assert_fail ("I < arg_size() && \"Argument index out-of-range\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 3472, __PRETTY_FUNCTION__))
;
3473 return arg_begin()[I];
3474 }
3475
3476 void setArg(unsigned I, Expr *E) {
3477 assert(I < arg_size() && "Argument index out-of-range")((I < arg_size() && "Argument index out-of-range")
? static_cast<void> (0) : __assert_fail ("I < arg_size() && \"Argument index out-of-range\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 3477, __PRETTY_FUNCTION__))
;
3478 arg_begin()[I] = E;
3479 }
3480
3481 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__));
3482 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
3483 if (!RParenLoc.isValid() && arg_size() > 0)
3484 return getArg(arg_size() - 1)->getEndLoc();
3485 return RParenLoc;
3486 }
3487
3488 static bool classof(const Stmt *T) {
3489 return T->getStmtClass() == CXXUnresolvedConstructExprClass;
3490 }
3491
3492 // Iterators
3493 child_range children() {
3494 auto **begin = reinterpret_cast<Stmt **>(arg_begin());
3495 return child_range(begin, begin + arg_size());
3496 }
3497
3498 const_child_range children() const {
3499 auto **begin = reinterpret_cast<Stmt **>(
3500 const_cast<CXXUnresolvedConstructExpr *>(this)->arg_begin());
3501 return const_child_range(begin, begin + arg_size());
3502 }
3503};
3504
3505/// Represents a C++ member access expression where the actual
3506/// member referenced could not be resolved because the base
3507/// expression or the member name was dependent.
3508///
3509/// Like UnresolvedMemberExprs, these can be either implicit or
3510/// explicit accesses. It is only possible to get one of these with
3511/// an implicit access if a qualifier is provided.
3512class CXXDependentScopeMemberExpr final
3513 : public Expr,
3514 private llvm::TrailingObjects<CXXDependentScopeMemberExpr,
3515 ASTTemplateKWAndArgsInfo,
3516 TemplateArgumentLoc, NamedDecl *> {
3517 friend class ASTStmtReader;
3518 friend class ASTStmtWriter;
3519 friend TrailingObjects;
3520
3521 /// The expression for the base pointer or class reference,
3522 /// e.g., the \c x in x.f. Can be null in implicit accesses.
3523 Stmt *Base;
3524
3525 /// The type of the base expression. Never null, even for
3526 /// implicit accesses.
3527 QualType BaseType;
3528
3529 /// The nested-name-specifier that precedes the member name, if any.
3530 /// FIXME: This could be in principle store as a trailing object.
3531 /// However the performance impact of doing so should be investigated first.
3532 NestedNameSpecifierLoc QualifierLoc;
3533
3534 /// The member to which this member expression refers, which
3535 /// can be name, overloaded operator, or destructor.
3536 ///
3537 /// FIXME: could also be a template-id
3538 DeclarationNameInfo MemberNameInfo;
3539
3540 // CXXDependentScopeMemberExpr is followed by several trailing objects,
3541 // some of which optional. They are in order:
3542 //
3543 // * An optional ASTTemplateKWAndArgsInfo for the explicitly specified
3544 // template keyword and arguments. Present if and only if
3545 // hasTemplateKWAndArgsInfo().
3546 //
3547 // * An array of getNumTemplateArgs() TemplateArgumentLoc containing location
3548 // information for the explicitly specified template arguments.
3549 //
3550 // * An optional NamedDecl *. In a qualified member access expression such
3551 // as t->Base::f, this member stores the resolves of name lookup in the
3552 // context of the member access expression, to be used at instantiation
3553 // time. Present if and only if hasFirstQualifierFoundInScope().
3554
3555 bool hasTemplateKWAndArgsInfo() const {
3556 return CXXDependentScopeMemberExprBits.HasTemplateKWAndArgsInfo;
3557 }
3558
3559 bool hasFirstQualifierFoundInScope() const {
3560 return CXXDependentScopeMemberExprBits.HasFirstQualifierFoundInScope;
3561 }
3562
3563 unsigned numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
3564 return hasTemplateKWAndArgsInfo();
3565 }
3566
3567 unsigned numTrailingObjects(OverloadToken<TemplateArgumentLoc>) const {
3568 return getNumTemplateArgs();
3569 }
3570
3571 unsigned numTrailingObjects(OverloadToken<NamedDecl *>) const {
3572 return hasFirstQualifierFoundInScope();
3573 }
3574
3575 CXXDependentScopeMemberExpr(const ASTContext &Ctx, Expr *Base,
3576 QualType BaseType, bool IsArrow,
3577 SourceLocation OperatorLoc,
3578 NestedNameSpecifierLoc QualifierLoc,
3579 SourceLocation TemplateKWLoc,
3580 NamedDecl *FirstQualifierFoundInScope,
3581 DeclarationNameInfo MemberNameInfo,
3582 const TemplateArgumentListInfo *TemplateArgs);
3583
3584 CXXDependentScopeMemberExpr(EmptyShell Empty, bool HasTemplateKWAndArgsInfo,
3585 bool HasFirstQualifierFoundInScope);
3586
3587public:
3588 static CXXDependentScopeMemberExpr *
3589 Create(const ASTContext &Ctx, Expr *Base, QualType BaseType, bool IsArrow,
3590 SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc,
3591 SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope,
3592 DeclarationNameInfo MemberNameInfo,
3593 const TemplateArgumentListInfo *TemplateArgs);
3594
3595 static CXXDependentScopeMemberExpr *
3596 CreateEmpty(const ASTContext &Ctx, bool HasTemplateKWAndArgsInfo,
3597 unsigned NumTemplateArgs, bool HasFirstQualifierFoundInScope);
3598
3599 /// True if this is an implicit access, i.e. one in which the
3600 /// member being accessed was not written in the source. The source
3601 /// location of the operator is invalid in this case.
3602 bool isImplicitAccess() const {
3603 if (!Base)
3604 return true;
3605 return cast<Expr>(Base)->isImplicitCXXThis();
3606 }
3607
3608 /// Retrieve the base object of this member expressions,
3609 /// e.g., the \c x in \c x.m.
3610 Expr *getBase() const {
3611 assert(!isImplicitAccess())((!isImplicitAccess()) ? static_cast<void> (0) : __assert_fail
("!isImplicitAccess()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 3611, __PRETTY_FUNCTION__))
;
3612 return cast<Expr>(Base);
3613 }
3614
3615 QualType getBaseType() const { return BaseType; }
3616
3617 /// Determine whether this member expression used the '->'
3618 /// operator; otherwise, it used the '.' operator.
3619 bool isArrow() const { return CXXDependentScopeMemberExprBits.IsArrow; }
3620
3621 /// Retrieve the location of the '->' or '.' operator.
3622 SourceLocation getOperatorLoc() const {
3623 return CXXDependentScopeMemberExprBits.OperatorLoc;
3624 }
3625
3626 /// Retrieve the nested-name-specifier that qualifies the member name.
3627 NestedNameSpecifier *getQualifier() const {
3628 return QualifierLoc.getNestedNameSpecifier();
3629 }
3630
3631 /// Retrieve the nested-name-specifier that qualifies the member
3632 /// name, with source location information.
3633 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3634
3635 /// Retrieve the first part of the nested-name-specifier that was
3636 /// found in the scope of the member access expression when the member access
3637 /// was initially parsed.
3638 ///
3639 /// This function only returns a useful result when member access expression
3640 /// uses a qualified member name, e.g., "x.Base::f". Here, the declaration
3641 /// returned by this function describes what was found by unqualified name
3642 /// lookup for the identifier "Base" within the scope of the member access
3643 /// expression itself. At template instantiation time, this information is
3644 /// combined with the results of name lookup into the type of the object
3645 /// expression itself (the class type of x).
3646 NamedDecl *getFirstQualifierFoundInScope() const {
3647 if (!hasFirstQualifierFoundInScope())
3648 return nullptr;
3649 return *getTrailingObjects<NamedDecl *>();
3650 }
3651
3652 /// Retrieve the name of the member that this expression refers to.
3653 const DeclarationNameInfo &getMemberNameInfo() const {
3654 return MemberNameInfo;
3655 }
3656
3657 /// Retrieve the name of the member that this expression refers to.
3658 DeclarationName getMember() const { return MemberNameInfo.getName(); }
3659
3660 // Retrieve the location of the name of the member that this
3661 // expression refers to.
3662 SourceLocation getMemberLoc() const { return MemberNameInfo.getLoc(); }
3663
3664 /// Retrieve the location of the template keyword preceding the
3665 /// member name, if any.
3666 SourceLocation getTemplateKeywordLoc() const {
3667 if (!hasTemplateKWAndArgsInfo())
3668 return SourceLocation();
3669 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
3670 }
3671
3672 /// Retrieve the location of the left angle bracket starting the
3673 /// explicit template argument list following the member name, if any.
3674 SourceLocation getLAngleLoc() const {
3675 if (!hasTemplateKWAndArgsInfo())
3676 return SourceLocation();
3677 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
3678 }
3679
3680 /// Retrieve the location of the right angle bracket ending the
3681 /// explicit template argument list following the member name, if any.
3682 SourceLocation getRAngleLoc() const {
3683 if (!hasTemplateKWAndArgsInfo())
3684 return SourceLocation();
3685 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
3686 }
3687
3688 /// Determines whether the member name was preceded by the template keyword.
3689 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
3690
3691 /// Determines whether this member expression actually had a C++
3692 /// template argument list explicitly specified, e.g., x.f<int>.
3693 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
3694
3695 /// Copies the template arguments (if present) into the given
3696 /// structure.
3697 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
3698 if (hasExplicitTemplateArgs())
3699 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
3700 getTrailingObjects<TemplateArgumentLoc>(), List);
3701 }
3702
3703 /// Retrieve the template arguments provided as part of this
3704 /// template-id.
3705 const TemplateArgumentLoc *getTemplateArgs() const {
3706 if (!hasExplicitTemplateArgs())
3707 return nullptr;
3708
3709 return getTrailingObjects<TemplateArgumentLoc>();
3710 }
3711
3712 /// Retrieve the number of template arguments provided as part of this
3713 /// template-id.
3714 unsigned getNumTemplateArgs() const {
3715 if (!hasExplicitTemplateArgs())
3716 return 0;
3717
3718 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
3719 }
3720
3721 ArrayRef<TemplateArgumentLoc> template_arguments() const {
3722 return {getTemplateArgs(), getNumTemplateArgs()};
3723 }
3724
3725 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
3726 if (!isImplicitAccess())
3727 return Base->getBeginLoc();
3728 if (getQualifier())
3729 return getQualifierLoc().getBeginLoc();
3730 return MemberNameInfo.getBeginLoc();
3731 }
3732
3733 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
3734 if (hasExplicitTemplateArgs())
3735 return getRAngleLoc();
3736 return MemberNameInfo.getEndLoc();
3737 }
3738
3739 static bool classof(const Stmt *T) {
3740 return T->getStmtClass() == CXXDependentScopeMemberExprClass;
3741 }
3742
3743 // Iterators
3744 child_range children() {
3745 if (isImplicitAccess())
3746 return child_range(child_iterator(), child_iterator());
3747 return child_range(&Base, &Base + 1);
3748 }
3749
3750 const_child_range children() const {
3751 if (isImplicitAccess())
3752 return const_child_range(const_child_iterator(), const_child_iterator());
3753 return const_child_range(&Base, &Base + 1);
3754 }
3755};
3756
3757/// Represents a C++ member access expression for which lookup
3758/// produced a set of overloaded functions.
3759///
3760/// The member access may be explicit or implicit:
3761/// \code
3762/// struct A {
3763/// int a, b;
3764/// int explicitAccess() { return this->a + this->A::b; }
3765/// int implicitAccess() { return a + A::b; }
3766/// };
3767/// \endcode
3768///
3769/// In the final AST, an explicit access always becomes a MemberExpr.
3770/// An implicit access may become either a MemberExpr or a
3771/// DeclRefExpr, depending on whether the member is static.
3772class UnresolvedMemberExpr final
3773 : public OverloadExpr,
3774 private llvm::TrailingObjects<UnresolvedMemberExpr, DeclAccessPair,
3775 ASTTemplateKWAndArgsInfo,
3776 TemplateArgumentLoc> {
3777 friend class ASTStmtReader;
3778 friend class OverloadExpr;
3779 friend TrailingObjects;
3780
3781 /// The expression for the base pointer or class reference,
3782 /// e.g., the \c x in x.f.
3783 ///
3784 /// This can be null if this is an 'unbased' member expression.
3785 Stmt *Base;
3786
3787 /// The type of the base expression; never null.
3788 QualType BaseType;
3789
3790 /// The location of the '->' or '.' operator.
3791 SourceLocation OperatorLoc;
3792
3793 // UnresolvedMemberExpr is followed by several trailing objects.
3794 // They are in order:
3795 //
3796 // * An array of getNumResults() DeclAccessPair for the results. These are
3797 // undesugared, which is to say, they may include UsingShadowDecls.
3798 // Access is relative to the naming class.
3799 //
3800 // * An optional ASTTemplateKWAndArgsInfo for the explicitly specified
3801 // template keyword and arguments. Present if and only if
3802 // hasTemplateKWAndArgsInfo().
3803 //
3804 // * An array of getNumTemplateArgs() TemplateArgumentLoc containing
3805 // location information for the explicitly specified template arguments.
3806
3807 UnresolvedMemberExpr(const ASTContext &Context, bool HasUnresolvedUsing,
3808 Expr *Base, QualType BaseType, bool IsArrow,
3809 SourceLocation OperatorLoc,
3810 NestedNameSpecifierLoc QualifierLoc,
3811 SourceLocation TemplateKWLoc,
3812 const DeclarationNameInfo &MemberNameInfo,
3813 const TemplateArgumentListInfo *TemplateArgs,
3814 UnresolvedSetIterator Begin, UnresolvedSetIterator End);
3815
3816 UnresolvedMemberExpr(EmptyShell Empty, unsigned NumResults,
3817 bool HasTemplateKWAndArgsInfo);
3818
3819 unsigned numTrailingObjects(OverloadToken<DeclAccessPair>) const {
3820 return getNumDecls();
3821 }
3822
3823 unsigned numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
3824 return hasTemplateKWAndArgsInfo();
3825 }
3826
3827public:
3828 static UnresolvedMemberExpr *
3829 Create(const ASTContext &Context, bool HasUnresolvedUsing, Expr *Base,
3830 QualType BaseType, bool IsArrow, SourceLocation OperatorLoc,
3831 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
3832 const DeclarationNameInfo &MemberNameInfo,
3833 const TemplateArgumentListInfo *TemplateArgs,
3834 UnresolvedSetIterator Begin, UnresolvedSetIterator End);
3835
3836 static UnresolvedMemberExpr *CreateEmpty(const ASTContext &Context,
3837 unsigned NumResults,
3838 bool HasTemplateKWAndArgsInfo,
3839 unsigned NumTemplateArgs);
3840
3841 /// True if this is an implicit access, i.e., one in which the
3842 /// member being accessed was not written in the source.
3843 ///
3844 /// The source location of the operator is invalid in this case.
3845 bool isImplicitAccess() const;
3846
3847 /// Retrieve the base object of this member expressions,
3848 /// e.g., the \c x in \c x.m.
3849 Expr *getBase() {
3850 assert(!isImplicitAccess())((!isImplicitAccess()) ? static_cast<void> (0) : __assert_fail
("!isImplicitAccess()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 3850, __PRETTY_FUNCTION__))
;
3851 return cast<Expr>(Base);
3852 }
3853 const Expr *getBase() const {
3854 assert(!isImplicitAccess())((!isImplicitAccess()) ? static_cast<void> (0) : __assert_fail
("!isImplicitAccess()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 3854, __PRETTY_FUNCTION__))
;
3855 return cast<Expr>(Base);
3856 }
3857
3858 QualType getBaseType() const { return BaseType; }
3859
3860 /// Determine whether the lookup results contain an unresolved using
3861 /// declaration.
3862 bool hasUnresolvedUsing() const {
3863 return UnresolvedMemberExprBits.HasUnresolvedUsing;
3864 }
3865
3866 /// Determine whether this member expression used the '->'
3867 /// operator; otherwise, it used the '.' operator.
3868 bool isArrow() const { return UnresolvedMemberExprBits.IsArrow; }
3869
3870 /// Retrieve the location of the '->' or '.' operator.
3871 SourceLocation getOperatorLoc() const { return OperatorLoc; }
3872
3873 /// Retrieve the naming class of this lookup.
3874 CXXRecordDecl *getNamingClass();
3875 const CXXRecordDecl *getNamingClass() const {
3876 return const_cast<UnresolvedMemberExpr *>(this)->getNamingClass();
3877 }
3878
3879 /// Retrieve the full name info for the member that this expression
3880 /// refers to.
3881 const DeclarationNameInfo &getMemberNameInfo() const { return getNameInfo(); }
3882
3883 /// Retrieve the name of the member that this expression refers to.
3884 DeclarationName getMemberName() const { return getName(); }
3885
3886 /// Retrieve the location of the name of the member that this
3887 /// expression refers to.
3888 SourceLocation getMemberLoc() const { return getNameLoc(); }
3889
3890 /// Return the preferred location (the member name) for the arrow when
3891 /// diagnosing a problem with this expression.
3892 SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__)) { return getMemberLoc(); }
3893
3894 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
3895 if (!isImplicitAccess())
3896 return Base->getBeginLoc();
3897 if (NestedNameSpecifierLoc l = getQualifierLoc())
3898 return l.getBeginLoc();
3899 return getMemberNameInfo().getBeginLoc();
3900 }
3901
3902 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
3903 if (hasExplicitTemplateArgs())
3904 return getRAngleLoc();
3905 return getMemberNameInfo().getEndLoc();
3906 }
3907
3908 static bool classof(const Stmt *T) {
3909 return T->getStmtClass() == UnresolvedMemberExprClass;
3910 }
3911
3912 // Iterators
3913 child_range children() {
3914 if (isImplicitAccess())
3915 return child_range(child_iterator(), child_iterator());
3916 return child_range(&Base, &Base + 1);
3917 }
3918
3919 const_child_range children() const {
3920 if (isImplicitAccess())
3921 return const_child_range(const_child_iterator(), const_child_iterator());
3922 return const_child_range(&Base, &Base + 1);
3923 }
3924};
3925
3926DeclAccessPair *OverloadExpr::getTrailingResults() {
3927 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(this))
3928 return ULE->getTrailingObjects<DeclAccessPair>();
3929 return cast<UnresolvedMemberExpr>(this)->getTrailingObjects<DeclAccessPair>();
3930}
3931
3932ASTTemplateKWAndArgsInfo *OverloadExpr::getTrailingASTTemplateKWAndArgsInfo() {
3933 if (!hasTemplateKWAndArgsInfo())
3934 return nullptr;
3935
3936 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(this))
3937 return ULE->getTrailingObjects<ASTTemplateKWAndArgsInfo>();
3938 return cast<UnresolvedMemberExpr>(this)
3939 ->getTrailingObjects<ASTTemplateKWAndArgsInfo>();
3940}
3941
3942TemplateArgumentLoc *OverloadExpr::getTrailingTemplateArgumentLoc() {
3943 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(this))
3944 return ULE->getTrailingObjects<TemplateArgumentLoc>();
3945 return cast<UnresolvedMemberExpr>(this)
3946 ->getTrailingObjects<TemplateArgumentLoc>();
3947}
3948
3949CXXRecordDecl *OverloadExpr::getNamingClass() {
3950 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(this))
3951 return ULE->getNamingClass();
3952 return cast<UnresolvedMemberExpr>(this)->getNamingClass();
3953}
3954
3955/// Represents a C++11 noexcept expression (C++ [expr.unary.noexcept]).
3956///
3957/// The noexcept expression tests whether a given expression might throw. Its
3958/// result is a boolean constant.
3959class CXXNoexceptExpr : public Expr {
3960 friend class ASTStmtReader;
3961
3962 Stmt *Operand;
3963 SourceRange Range;
3964
3965public:
3966 CXXNoexceptExpr(QualType Ty, Expr *Operand, CanThrowResult Val,
3967 SourceLocation Keyword, SourceLocation RParen)
3968 : Expr(CXXNoexceptExprClass, Ty, VK_RValue, OK_Ordinary,
3969 /*TypeDependent*/ false,
3970 /*ValueDependent*/ Val == CT_Dependent,
3971 Val == CT_Dependent || Operand->isInstantiationDependent(),
3972 Operand->containsUnexpandedParameterPack()),
3973 Operand(Operand), Range(Keyword, RParen) {
3974 CXXNoexceptExprBits.Value = Val == CT_Cannot;
3975 }
3976
3977 CXXNoexceptExpr(EmptyShell Empty) : Expr(CXXNoexceptExprClass, Empty) {}
3978
3979 Expr *getOperand() const { return static_cast<Expr *>(Operand); }
3980
3981 SourceLocation getBeginLoc() const { return Range.getBegin(); }
3982 SourceLocation getEndLoc() const { return Range.getEnd(); }
3983 SourceRange getSourceRange() const { return Range; }
3984
3985 bool getValue() const { return CXXNoexceptExprBits.Value; }
3986
3987 static bool classof(const Stmt *T) {
3988 return T->getStmtClass() == CXXNoexceptExprClass;
3989 }
3990
3991 // Iterators
3992 child_range children() { return child_range(&Operand, &Operand + 1); }
3993
3994 const_child_range children() const {
3995 return const_child_range(&Operand, &Operand + 1);
3996 }
3997};
3998
3999/// Represents a C++11 pack expansion that produces a sequence of
4000/// expressions.
4001///
4002/// A pack expansion expression contains a pattern (which itself is an
4003/// expression) followed by an ellipsis. For example:
4004///
4005/// \code
4006/// template<typename F, typename ...Types>
4007/// void forward(F f, Types &&...args) {
4008/// f(static_cast<Types&&>(args)...);
4009/// }
4010/// \endcode
4011///
4012/// Here, the argument to the function object \c f is a pack expansion whose
4013/// pattern is \c static_cast<Types&&>(args). When the \c forward function
4014/// template is instantiated, the pack expansion will instantiate to zero or
4015/// or more function arguments to the function object \c f.
4016class PackExpansionExpr : public Expr {
4017 friend class ASTStmtReader;
4018 friend class ASTStmtWriter;
4019
4020 SourceLocation EllipsisLoc;
4021
4022 /// The number of expansions that will be produced by this pack
4023 /// expansion expression, if known.
4024 ///
4025 /// When zero, the number of expansions is not known. Otherwise, this value
4026 /// is the number of expansions + 1.
4027 unsigned NumExpansions;
4028
4029 Stmt *Pattern;
4030
4031public:
4032 PackExpansionExpr(QualType T, Expr *Pattern, SourceLocation EllipsisLoc,
4033 Optional<unsigned> NumExpansions)
4034 : Expr(PackExpansionExprClass, T, Pattern->getValueKind(),
4035 Pattern->getObjectKind(), /*TypeDependent=*/true,
4036 /*ValueDependent=*/true, /*InstantiationDependent=*/true,
4037 /*ContainsUnexpandedParameterPack=*/false),
4038 EllipsisLoc(EllipsisLoc),
4039 NumExpansions(NumExpansions ? *NumExpansions + 1 : 0),
4040 Pattern(Pattern) {}
4041
4042 PackExpansionExpr(EmptyShell Empty) : Expr(PackExpansionExprClass, Empty) {}
4043
4044 /// Retrieve the pattern of the pack expansion.
4045 Expr *getPattern() { return reinterpret_cast<Expr *>(Pattern); }
4046
4047 /// Retrieve the pattern of the pack expansion.
4048 const Expr *getPattern() const { return reinterpret_cast<Expr *>(Pattern); }
4049
4050 /// Retrieve the location of the ellipsis that describes this pack
4051 /// expansion.
4052 SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
4053
4054 /// Determine the number of expansions that will be produced when
4055 /// this pack expansion is instantiated, if already known.
4056 Optional<unsigned> getNumExpansions() const {
4057 if (NumExpansions)
4058 return NumExpansions - 1;
4059
4060 return None;
4061 }
4062
4063 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
4064 return Pattern->getBeginLoc();
4065 }
4066
4067 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return EllipsisLoc; }
4068
4069 static bool classof(const Stmt *T) {
4070 return T->getStmtClass() == PackExpansionExprClass;
4071 }
4072
4073 // Iterators
4074 child_range children() {
4075 return child_range(&Pattern, &Pattern + 1);
4076 }
4077
4078 const_child_range children() const {
4079 return const_child_range(&Pattern, &Pattern + 1);
4080 }
4081};
4082
4083/// Represents an expression that computes the length of a parameter
4084/// pack.
4085///
4086/// \code
4087/// template<typename ...Types>
4088/// struct count {
4089/// static const unsigned value = sizeof...(Types);
4090/// };
4091/// \endcode
4092class SizeOfPackExpr final
4093 : public Expr,
4094 private llvm::TrailingObjects<SizeOfPackExpr, TemplateArgument> {
4095 friend class ASTStmtReader;
4096 friend class ASTStmtWriter;
4097 friend TrailingObjects;
4098
4099 /// The location of the \c sizeof keyword.
4100 SourceLocation OperatorLoc;
4101
4102 /// The location of the name of the parameter pack.
4103 SourceLocation PackLoc;
4104
4105 /// The location of the closing parenthesis.
4106 SourceLocation RParenLoc;
4107
4108 /// The length of the parameter pack, if known.
4109 ///
4110 /// When this expression is not value-dependent, this is the length of
4111 /// the pack. When the expression was parsed rather than instantiated
4112 /// (and thus is value-dependent), this is zero.
4113 ///
4114 /// After partial substitution into a sizeof...(X) expression (for instance,
4115 /// within an alias template or during function template argument deduction),
4116 /// we store a trailing array of partially-substituted TemplateArguments,
4117 /// and this is the length of that array.
4118 unsigned Length;
4119
4120 /// The parameter pack.
4121 NamedDecl *Pack = nullptr;
4122
4123 /// Create an expression that computes the length of
4124 /// the given parameter pack.
4125 SizeOfPackExpr(QualType SizeType, SourceLocation OperatorLoc, NamedDecl *Pack,
4126 SourceLocation PackLoc, SourceLocation RParenLoc,
4127 Optional<unsigned> Length, ArrayRef<TemplateArgument> PartialArgs)
4128 : Expr(SizeOfPackExprClass, SizeType, VK_RValue, OK_Ordinary,
4129 /*TypeDependent=*/false, /*ValueDependent=*/!Length,
4130 /*InstantiationDependent=*/!Length,
4131 /*ContainsUnexpandedParameterPack=*/false),
4132 OperatorLoc(OperatorLoc), PackLoc(PackLoc), RParenLoc(RParenLoc),
4133 Length(Length ? *Length : PartialArgs.size()), Pack(Pack) {
4134 assert((!Length || PartialArgs.empty()) &&(((!Length || PartialArgs.empty()) && "have partial args for non-dependent sizeof... expression"
) ? static_cast<void> (0) : __assert_fail ("(!Length || PartialArgs.empty()) && \"have partial args for non-dependent sizeof... expression\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 4135, __PRETTY_FUNCTION__))
4135 "have partial args for non-dependent sizeof... expression")(((!Length || PartialArgs.empty()) && "have partial args for non-dependent sizeof... expression"
) ? static_cast<void> (0) : __assert_fail ("(!Length || PartialArgs.empty()) && \"have partial args for non-dependent sizeof... expression\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 4135, __PRETTY_FUNCTION__))
;
4136 auto *Args = getTrailingObjects<TemplateArgument>();
4137 std::uninitialized_copy(PartialArgs.begin(), PartialArgs.end(), Args);
4138 }
4139
4140 /// Create an empty expression.
4141 SizeOfPackExpr(EmptyShell Empty, unsigned NumPartialArgs)
4142 : Expr(SizeOfPackExprClass, Empty), Length(NumPartialArgs) {}
4143
4144public:
4145 static SizeOfPackExpr *Create(ASTContext &Context, SourceLocation OperatorLoc,
4146 NamedDecl *Pack, SourceLocation PackLoc,
4147 SourceLocation RParenLoc,
4148 Optional<unsigned> Length = None,
4149 ArrayRef<TemplateArgument> PartialArgs = None);
4150 static SizeOfPackExpr *CreateDeserialized(ASTContext &Context,
4151 unsigned NumPartialArgs);
4152
4153 /// Determine the location of the 'sizeof' keyword.
4154 SourceLocation getOperatorLoc() const { return OperatorLoc; }
4155
4156 /// Determine the location of the parameter pack.
4157 SourceLocation getPackLoc() const { return PackLoc; }
4158
4159 /// Determine the location of the right parenthesis.
4160 SourceLocation getRParenLoc() const { return RParenLoc; }
4161
4162 /// Retrieve the parameter pack.
4163 NamedDecl *getPack() const { return Pack; }
4164
4165 /// Retrieve the length of the parameter pack.
4166 ///
4167 /// This routine may only be invoked when the expression is not
4168 /// value-dependent.
4169 unsigned getPackLength() const {
4170 assert(!isValueDependent() &&((!isValueDependent() && "Cannot get the length of a value-dependent pack size expression"
) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Cannot get the length of a value-dependent pack size expression\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 4171, __PRETTY_FUNCTION__))
4171 "Cannot get the length of a value-dependent pack size expression")((!isValueDependent() && "Cannot get the length of a value-dependent pack size expression"
) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"Cannot get the length of a value-dependent pack size expression\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 4171, __PRETTY_FUNCTION__))
;
4172 return Length;
4173 }
4174
4175 /// Determine whether this represents a partially-substituted sizeof...
4176 /// expression, such as is produced for:
4177 ///
4178 /// template<typename ...Ts> using X = int[sizeof...(Ts)];
4179 /// template<typename ...Us> void f(X<Us..., 1, 2, 3, Us...>);
4180 bool isPartiallySubstituted() const {
4181 return isValueDependent() && Length;
4182 }
4183
4184 /// Get
4185 ArrayRef<TemplateArgument> getPartialArguments() const {
4186 assert(isPartiallySubstituted())((isPartiallySubstituted()) ? static_cast<void> (0) : __assert_fail
("isPartiallySubstituted()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 4186, __PRETTY_FUNCTION__))
;
4187 const auto *Args = getTrailingObjects<TemplateArgument>();
4188 return llvm::makeArrayRef(Args, Args + Length);
4189 }
4190
4191 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return OperatorLoc; }
4192 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; }
4193
4194 static bool classof(const Stmt *T) {
4195 return T->getStmtClass() == SizeOfPackExprClass;
4196 }
4197
4198 // Iterators
4199 child_range children() {
4200 return child_range(child_iterator(), child_iterator());
4201 }
4202
4203 const_child_range children() const {
4204 return const_child_range(const_child_iterator(), const_child_iterator());
4205 }
4206};
4207
4208/// Represents a reference to a non-type template parameter
4209/// that has been substituted with a template argument.
4210class SubstNonTypeTemplateParmExpr : public Expr {
4211 friend class ASTReader;
4212 friend class ASTStmtReader;
4213
4214 /// The replaced parameter.
4215 NonTypeTemplateParmDecl *Param;
4216
4217 /// The replacement expression.
4218 Stmt *Replacement;
4219
4220 explicit SubstNonTypeTemplateParmExpr(EmptyShell Empty)
4221 : Expr(SubstNonTypeTemplateParmExprClass, Empty) {}
4222
4223public:
4224 SubstNonTypeTemplateParmExpr(QualType Ty, ExprValueKind ValueKind,
4225 SourceLocation Loc,
4226 NonTypeTemplateParmDecl *Param,
4227 Expr *Replacement)
4228 : Expr(SubstNonTypeTemplateParmExprClass, Ty, ValueKind, OK_Ordinary,
4229 Replacement->isTypeDependent(), Replacement->isValueDependent(),
4230 Replacement->isInstantiationDependent(),
4231 Replacement->containsUnexpandedParameterPack()),
4232 Param(Param), Replacement(Replacement) {
4233 SubstNonTypeTemplateParmExprBits.NameLoc = Loc;
4234 }
4235
4236 SourceLocation getNameLoc() const {
4237 return SubstNonTypeTemplateParmExprBits.NameLoc;
4238 }
4239 SourceLocation getBeginLoc() const { return getNameLoc(); }
4240 SourceLocation getEndLoc() const { return getNameLoc(); }
4241
4242 Expr *getReplacement() const { return cast<Expr>(Replacement); }
4243
4244 NonTypeTemplateParmDecl *getParameter() const { return Param; }
4245
4246 static bool classof(const Stmt *s) {
4247 return s->getStmtClass() == SubstNonTypeTemplateParmExprClass;
4248 }
4249
4250 // Iterators
4251 child_range children() { return child_range(&Replacement, &Replacement + 1); }
4252
4253 const_child_range children() const {
4254 return const_child_range(&Replacement, &Replacement + 1);
4255 }
4256};
4257
4258/// Represents a reference to a non-type template parameter pack that
4259/// has been substituted with a non-template argument pack.
4260///
4261/// When a pack expansion in the source code contains multiple parameter packs
4262/// and those parameter packs correspond to different levels of template
4263/// parameter lists, this node is used to represent a non-type template
4264/// parameter pack from an outer level, which has already had its argument pack
4265/// substituted but that still lives within a pack expansion that itself
4266/// could not be instantiated. When actually performing a substitution into
4267/// that pack expansion (e.g., when all template parameters have corresponding
4268/// arguments), this type will be replaced with the appropriate underlying
4269/// expression at the current pack substitution index.
4270class SubstNonTypeTemplateParmPackExpr : public Expr {
4271 friend class ASTReader;
4272 friend class ASTStmtReader;
4273
4274 /// The non-type template parameter pack itself.
4275 NonTypeTemplateParmDecl *Param;
4276
4277 /// A pointer to the set of template arguments that this
4278 /// parameter pack is instantiated with.
4279 const TemplateArgument *Arguments;
4280
4281 /// The number of template arguments in \c Arguments.
4282 unsigned NumArguments;
4283
4284 /// The location of the non-type template parameter pack reference.
4285 SourceLocation NameLoc;
4286
4287 explicit SubstNonTypeTemplateParmPackExpr(EmptyShell Empty)
4288 : Expr(SubstNonTypeTemplateParmPackExprClass, Empty) {}
4289
4290public:
4291 SubstNonTypeTemplateParmPackExpr(QualType T,
4292 ExprValueKind ValueKind,
4293 NonTypeTemplateParmDecl *Param,
4294 SourceLocation NameLoc,
4295 const TemplateArgument &ArgPack);
4296
4297 /// Retrieve the non-type template parameter pack being substituted.
4298 NonTypeTemplateParmDecl *getParameterPack() const { return Param; }
4299
4300 /// Retrieve the location of the parameter pack name.
4301 SourceLocation getParameterPackLocation() const { return NameLoc; }
4302
4303 /// Retrieve the template argument pack containing the substituted
4304 /// template arguments.
4305 TemplateArgument getArgumentPack() const;
4306
4307 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return NameLoc; }
4308 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return NameLoc; }
4309
4310 static bool classof(const Stmt *T) {
4311 return T->getStmtClass() == SubstNonTypeTemplateParmPackExprClass;
4312 }
4313
4314 // Iterators
4315 child_range children() {
4316 return child_range(child_iterator(), child_iterator());
4317 }
4318
4319 const_child_range children() const {
4320 return const_child_range(const_child_iterator(), const_child_iterator());
4321 }
4322};
4323
4324/// Represents a reference to a function parameter pack or init-capture pack
4325/// that has been substituted but not yet expanded.
4326///
4327/// When a pack expansion contains multiple parameter packs at different levels,
4328/// this node is used to represent a function parameter pack at an outer level
4329/// which we have already substituted to refer to expanded parameters, but where
4330/// the containing pack expansion cannot yet be expanded.
4331///
4332/// \code
4333/// template<typename...Ts> struct S {
4334/// template<typename...Us> auto f(Ts ...ts) -> decltype(g(Us(ts)...));
4335/// };
4336/// template struct S<int, int>;
4337/// \endcode
4338class FunctionParmPackExpr final
4339 : public Expr,
4340 private llvm::TrailingObjects<FunctionParmPackExpr, VarDecl *> {
4341 friend class ASTReader;
4342 friend class ASTStmtReader;
4343 friend TrailingObjects;
4344
4345 /// The function parameter pack which was referenced.
4346 VarDecl *ParamPack;
4347
4348 /// The location of the function parameter pack reference.
4349 SourceLocation NameLoc;
4350
4351 /// The number of expansions of this pack.
4352 unsigned NumParameters;
4353
4354 FunctionParmPackExpr(QualType T, VarDecl *ParamPack,
4355 SourceLocation NameLoc, unsigned NumParams,
4356 VarDecl *const *Params);
4357
4358public:
4359 static FunctionParmPackExpr *Create(const ASTContext &Context, QualType T,
4360 VarDecl *ParamPack,
4361 SourceLocation NameLoc,
4362 ArrayRef<VarDecl *> Params);
4363 static FunctionParmPackExpr *CreateEmpty(const ASTContext &Context,
4364 unsigned NumParams);
4365
4366 /// Get the parameter pack which this expression refers to.
4367 VarDecl *getParameterPack() const { return ParamPack; }
4368
4369 /// Get the location of the parameter pack.
4370 SourceLocation getParameterPackLocation() const { return NameLoc; }
4371
4372 /// Iterators over the parameters which the parameter pack expanded
4373 /// into.
4374 using iterator = VarDecl * const *;
4375 iterator begin() const { return getTrailingObjects<VarDecl *>(); }
4376 iterator end() const { return begin() + NumParameters; }
4377
4378 /// Get the number of parameters in this parameter pack.
4379 unsigned getNumExpansions() const { return NumParameters; }
4380
4381 /// Get an expansion of the parameter pack by index.
4382 VarDecl *getExpansion(unsigned I) const { return begin()[I]; }
4383
4384 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return NameLoc; }
4385 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return NameLoc; }
4386
4387 static bool classof(const Stmt *T) {
4388 return T->getStmtClass() == FunctionParmPackExprClass;
4389 }
4390
4391 child_range children() {
4392 return child_range(child_iterator(), child_iterator());
4393 }
4394
4395 const_child_range children() const {
4396 return const_child_range(const_child_iterator(), const_child_iterator());
4397 }
4398};
4399
4400/// Represents a prvalue temporary that is written into memory so that
4401/// a reference can bind to it.
4402///
4403/// Prvalue expressions are materialized when they need to have an address
4404/// in memory for a reference to bind to. This happens when binding a
4405/// reference to the result of a conversion, e.g.,
4406///
4407/// \code
4408/// const int &r = 1.0;
4409/// \endcode
4410///
4411/// Here, 1.0 is implicitly converted to an \c int. That resulting \c int is
4412/// then materialized via a \c MaterializeTemporaryExpr, and the reference
4413/// binds to the temporary. \c MaterializeTemporaryExprs are always glvalues
4414/// (either an lvalue or an xvalue, depending on the kind of reference binding
4415/// to it), maintaining the invariant that references always bind to glvalues.
4416///
4417/// Reference binding and copy-elision can both extend the lifetime of a
4418/// temporary. When either happens, the expression will also track the
4419/// declaration which is responsible for the lifetime extension.
4420class MaterializeTemporaryExpr : public Expr {
4421private:
4422 friend class ASTStmtReader;
4423 friend class ASTStmtWriter;
4424
4425 llvm::PointerUnion<Stmt *, LifetimeExtendedTemporaryDecl *> State;
4426
4427public:
4428 MaterializeTemporaryExpr(QualType T, Expr *Temporary,
4429 bool BoundToLvalueReference,
4430 LifetimeExtendedTemporaryDecl *MTD = nullptr);
4431
4432 MaterializeTemporaryExpr(EmptyShell Empty)
4433 : Expr(MaterializeTemporaryExprClass, Empty) {}
4434
4435 /// Retrieve the temporary-generating subexpression whose value will
4436 /// be materialized into a glvalue.
4437 Expr *getSubExpr() const {
4438 return cast<Expr>(
4439 State.is<Stmt *>()
4440 ? State.get<Stmt *>()
4441 : State.get<LifetimeExtendedTemporaryDecl *>()->getTemporaryExpr());
4442 }
4443
4444 /// Retrieve the storage duration for the materialized temporary.
4445 StorageDuration getStorageDuration() const {
4446 return State.is<Stmt *>() ? SD_FullExpression
4447 : State.get<LifetimeExtendedTemporaryDecl *>()
4448 ->getStorageDuration();
4449 }
4450
4451 /// Get the storage for the constant value of a materialized temporary
4452 /// of static storage duration.
4453 APValue *getOrCreateValue(bool MayCreate) const {
4454 assert(State.is<LifetimeExtendedTemporaryDecl *>() &&((State.is<LifetimeExtendedTemporaryDecl *>() &&
"the temporary has not been lifetime extended") ? static_cast
<void> (0) : __assert_fail ("State.is<LifetimeExtendedTemporaryDecl *>() && \"the temporary has not been lifetime extended\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 4455, __PRETTY_FUNCTION__))
4455 "the temporary has not been lifetime extended")((State.is<LifetimeExtendedTemporaryDecl *>() &&
"the temporary has not been lifetime extended") ? static_cast
<void> (0) : __assert_fail ("State.is<LifetimeExtendedTemporaryDecl *>() && \"the temporary has not been lifetime extended\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 4455, __PRETTY_FUNCTION__))
;
4456 return State.get<LifetimeExtendedTemporaryDecl *>()->getOrCreateValue(
4457 MayCreate);
4458 }
4459
4460 LifetimeExtendedTemporaryDecl *getLifetimeExtendedTemporaryDecl() {
4461 return State.dyn_cast<LifetimeExtendedTemporaryDecl *>();
4462 }
4463 const LifetimeExtendedTemporaryDecl *
4464 getLifetimeExtendedTemporaryDecl() const {
4465 return State.dyn_cast<LifetimeExtendedTemporaryDecl *>();
4466 }
4467
4468 /// Get the declaration which triggered the lifetime-extension of this
4469 /// temporary, if any.
4470 ValueDecl *getExtendingDecl() {
4471 return State.is<Stmt *>() ? nullptr
4472 : State.get<LifetimeExtendedTemporaryDecl *>()
4473 ->getExtendingDecl();
4474 }
4475 const ValueDecl *getExtendingDecl() const {
4476 return const_cast<MaterializeTemporaryExpr *>(this)->getExtendingDecl();
4477 }
4478
4479 void setExtendingDecl(ValueDecl *ExtendedBy, unsigned ManglingNumber);
4480
4481 unsigned getManglingNumber() const {
4482 return State.is<Stmt *>() ? 0
4483 : State.get<LifetimeExtendedTemporaryDecl *>()
4484 ->getManglingNumber();
4485 }
4486
4487 /// Determine whether this materialized temporary is bound to an
4488 /// lvalue reference; otherwise, it's bound to an rvalue reference.
4489 bool isBoundToLvalueReference() const {
4490 return getValueKind() == VK_LValue;
4491 }
4492
4493 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
4494 return getSubExpr()->getBeginLoc();
4495 }
4496
4497 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
4498 return getSubExpr()->getEndLoc();
4499 }
4500
4501 static bool classof(const Stmt *T) {
4502 return T->getStmtClass() == MaterializeTemporaryExprClass;
4503 }
4504
4505 // Iterators
4506 child_range children() {
4507 return State.is<Stmt *>()
4508 ? child_range(State.getAddrOfPtr1(), State.getAddrOfPtr1() + 1)
4509 : State.get<LifetimeExtendedTemporaryDecl *>()->childrenExpr();
4510 }
4511
4512 const_child_range children() const {
4513 return State.is<Stmt *>()
4514 ? const_child_range(State.getAddrOfPtr1(),
4515 State.getAddrOfPtr1() + 1)
4516 : const_cast<const LifetimeExtendedTemporaryDecl *>(
4517 State.get<LifetimeExtendedTemporaryDecl *>())
4518 ->childrenExpr();
4519 }
4520};
4521
4522/// Represents a folding of a pack over an operator.
4523///
4524/// This expression is always dependent and represents a pack expansion of the
4525/// forms:
4526///
4527/// ( expr op ... )
4528/// ( ... op expr )
4529/// ( expr op ... op expr )
4530class CXXFoldExpr : public Expr {
4531 friend class ASTStmtReader;
4532 friend class ASTStmtWriter;
4533
4534 SourceLocation LParenLoc;
4535 SourceLocation EllipsisLoc;
4536 SourceLocation RParenLoc;
4537 // When 0, the number of expansions is not known. Otherwise, this is one more
4538 // than the number of expansions.
4539 unsigned NumExpansions;
4540 Stmt *SubExprs[2];
4541 BinaryOperatorKind Opcode;
4542
4543public:
4544 CXXFoldExpr(QualType T, SourceLocation LParenLoc, Expr *LHS,
4545 BinaryOperatorKind Opcode, SourceLocation EllipsisLoc, Expr *RHS,
4546 SourceLocation RParenLoc, Optional<unsigned> NumExpansions)
4547 : Expr(CXXFoldExprClass, T, VK_RValue, OK_Ordinary,
4548 /*Dependent*/ true, true, true,
4549 /*ContainsUnexpandedParameterPack*/ false),
4550 LParenLoc(LParenLoc), EllipsisLoc(EllipsisLoc), RParenLoc(RParenLoc),
4551 NumExpansions(NumExpansions ? *NumExpansions + 1 : 0), Opcode(Opcode) {
4552 SubExprs[0] = LHS;
4553 SubExprs[1] = RHS;
4554 }
4555
4556 CXXFoldExpr(EmptyShell Empty) : Expr(CXXFoldExprClass, Empty) {}
4557
4558 Expr *getLHS() const { return static_cast<Expr*>(SubExprs[0]); }
4559 Expr *getRHS() const { return static_cast<Expr*>(SubExprs[1]); }
4560
4561 /// Does this produce a right-associated sequence of operators?
4562 bool isRightFold() const {
4563 return getLHS() && getLHS()->containsUnexpandedParameterPack();
4564 }
4565
4566 /// Does this produce a left-associated sequence of operators?
4567 bool isLeftFold() const { return !isRightFold(); }
4568
4569 /// Get the pattern, that is, the operand that contains an unexpanded pack.
4570 Expr *getPattern() const { return isLeftFold() ? getRHS() : getLHS(); }
4571
4572 /// Get the operand that doesn't contain a pack, for a binary fold.
4573 Expr *getInit() const { return isLeftFold() ? getLHS() : getRHS(); }
4574
4575 SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
4576 BinaryOperatorKind getOperator() const { return Opcode; }
4577
4578 Optional<unsigned> getNumExpansions() const {
4579 if (NumExpansions)
4580 return NumExpansions - 1;
4581 return None;
4582 }
4583
4584 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return LParenLoc; }
4585
4586 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; }
4587
4588 static bool classof(const Stmt *T) {
4589 return T->getStmtClass() == CXXFoldExprClass;
4590 }
4591
4592 // Iterators
4593 child_range children() { return child_range(SubExprs, SubExprs + 2); }
4594
4595 const_child_range children() const {
4596 return const_child_range(SubExprs, SubExprs + 2);
4597 }
4598};
4599
4600/// Represents an expression that might suspend coroutine execution;
4601/// either a co_await or co_yield expression.
4602///
4603/// Evaluation of this expression first evaluates its 'ready' expression. If
4604/// that returns 'false':
4605/// -- execution of the coroutine is suspended
4606/// -- the 'suspend' expression is evaluated
4607/// -- if the 'suspend' expression returns 'false', the coroutine is
4608/// resumed
4609/// -- otherwise, control passes back to the resumer.
4610/// If the coroutine is not suspended, or when it is resumed, the 'resume'
4611/// expression is evaluated, and its result is the result of the overall
4612/// expression.
4613class CoroutineSuspendExpr : public Expr {
4614 friend class ASTStmtReader;
4615
4616 SourceLocation KeywordLoc;
4617
4618 enum SubExpr { Common, Ready, Suspend, Resume, Count };
4619
4620 Stmt *SubExprs[SubExpr::Count];
4621 OpaqueValueExpr *OpaqueValue = nullptr;
4622
4623public:
4624 CoroutineSuspendExpr(StmtClass SC, SourceLocation KeywordLoc, Expr *Common,
4625 Expr *Ready, Expr *Suspend, Expr *Resume,
4626 OpaqueValueExpr *OpaqueValue)
4627 : Expr(SC, Resume->getType(), Resume->getValueKind(),
4628 Resume->getObjectKind(), Resume->isTypeDependent(),
4629 Resume->isValueDependent(), Common->isInstantiationDependent(),
4630 Common->containsUnexpandedParameterPack()),
4631 KeywordLoc(KeywordLoc), OpaqueValue(OpaqueValue) {
4632 SubExprs[SubExpr::Common] = Common;
4633 SubExprs[SubExpr::Ready] = Ready;
4634 SubExprs[SubExpr::Suspend] = Suspend;
4635 SubExprs[SubExpr::Resume] = Resume;
4636 }
4637
4638 CoroutineSuspendExpr(StmtClass SC, SourceLocation KeywordLoc, QualType Ty,
4639 Expr *Common)
4640 : Expr(SC, Ty, VK_RValue, OK_Ordinary, true, true, true,
4641 Common->containsUnexpandedParameterPack()),
4642 KeywordLoc(KeywordLoc) {
4643 assert(Common->isTypeDependent() && Ty->isDependentType() &&((Common->isTypeDependent() && Ty->isDependentType
() && "wrong constructor for non-dependent co_await/co_yield expression"
) ? static_cast<void> (0) : __assert_fail ("Common->isTypeDependent() && Ty->isDependentType() && \"wrong constructor for non-dependent co_await/co_yield expression\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 4644, __PRETTY_FUNCTION__))
4644 "wrong constructor for non-dependent co_await/co_yield expression")((Common->isTypeDependent() && Ty->isDependentType
() && "wrong constructor for non-dependent co_await/co_yield expression"
) ? static_cast<void> (0) : __assert_fail ("Common->isTypeDependent() && Ty->isDependentType() && \"wrong constructor for non-dependent co_await/co_yield expression\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 4644, __PRETTY_FUNCTION__))
;
4645 SubExprs[SubExpr::Common] = Common;
4646 SubExprs[SubExpr::Ready] = nullptr;
4647 SubExprs[SubExpr::Suspend] = nullptr;
4648 SubExprs[SubExpr::Resume] = nullptr;
4649 }
4650
4651 CoroutineSuspendExpr(StmtClass SC, EmptyShell Empty) : Expr(SC, Empty) {
4652 SubExprs[SubExpr::Common] = nullptr;
4653 SubExprs[SubExpr::Ready] = nullptr;
4654 SubExprs[SubExpr::Suspend] = nullptr;
4655 SubExprs[SubExpr::Resume] = nullptr;
4656 }
4657
4658 SourceLocation getKeywordLoc() const { return KeywordLoc; }
4659
4660 Expr *getCommonExpr() const {
4661 return static_cast<Expr*>(SubExprs[SubExpr::Common]);
4662 }
4663
4664 /// getOpaqueValue - Return the opaque value placeholder.
4665 OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; }
4666
4667 Expr *getReadyExpr() const {
4668 return static_cast<Expr*>(SubExprs[SubExpr::Ready]);
4669 }
4670
4671 Expr *getSuspendExpr() const {
4672 return static_cast<Expr*>(SubExprs[SubExpr::Suspend]);
4673 }
4674
4675 Expr *getResumeExpr() const {
4676 return static_cast<Expr*>(SubExprs[SubExpr::Resume]);
4677 }
4678
4679 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return KeywordLoc; }
4680
4681 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
4682 return getCommonExpr()->getEndLoc();
4683 }
4684
4685 child_range children() {
4686 return child_range(SubExprs, SubExprs + SubExpr::Count);
4687 }
4688
4689 const_child_range children() const {
4690 return const_child_range(SubExprs, SubExprs + SubExpr::Count);
4691 }
4692
4693 static bool classof(const Stmt *T) {
4694 return T->getStmtClass() == CoawaitExprClass ||
4695 T->getStmtClass() == CoyieldExprClass;
4696 }
4697};
4698
4699/// Represents a 'co_await' expression.
4700class CoawaitExpr : public CoroutineSuspendExpr {
4701 friend class ASTStmtReader;
4702
4703public:
4704 CoawaitExpr(SourceLocation CoawaitLoc, Expr *Operand, Expr *Ready,
4705 Expr *Suspend, Expr *Resume, OpaqueValueExpr *OpaqueValue,
4706 bool IsImplicit = false)
4707 : CoroutineSuspendExpr(CoawaitExprClass, CoawaitLoc, Operand, Ready,
4708 Suspend, Resume, OpaqueValue) {
4709 CoawaitBits.IsImplicit = IsImplicit;
4710 }
4711
4712 CoawaitExpr(SourceLocation CoawaitLoc, QualType Ty, Expr *Operand,
4713 bool IsImplicit = false)
4714 : CoroutineSuspendExpr(CoawaitExprClass, CoawaitLoc, Ty, Operand) {
4715 CoawaitBits.IsImplicit = IsImplicit;
4716 }
4717
4718 CoawaitExpr(EmptyShell Empty)
4719 : CoroutineSuspendExpr(CoawaitExprClass, Empty) {}
4720
4721 Expr *getOperand() const {
4722 // FIXME: Dig out the actual operand or store it.
4723 return getCommonExpr();
4724 }
4725
4726 bool isImplicit() const { return CoawaitBits.IsImplicit; }
4727 void setIsImplicit(bool value = true) { CoawaitBits.IsImplicit = value; }
4728
4729 static bool classof(const Stmt *T) {
4730 return T->getStmtClass() == CoawaitExprClass;
4731 }
4732};
4733
4734/// Represents a 'co_await' expression while the type of the promise
4735/// is dependent.
4736class DependentCoawaitExpr : public Expr {
4737 friend class ASTStmtReader;
4738
4739 SourceLocation KeywordLoc;
4740 Stmt *SubExprs[2];
4741
4742public:
4743 DependentCoawaitExpr(SourceLocation KeywordLoc, QualType Ty, Expr *Op,
4744 UnresolvedLookupExpr *OpCoawait)
4745 : Expr(DependentCoawaitExprClass, Ty, VK_RValue, OK_Ordinary,
4746 /*TypeDependent*/ true, /*ValueDependent*/ true,
4747 /*InstantiationDependent*/ true,
4748 Op->containsUnexpandedParameterPack()),
4749 KeywordLoc(KeywordLoc) {
4750 // NOTE: A co_await expression is dependent on the coroutines promise
4751 // type and may be dependent even when the `Op` expression is not.
4752 assert(Ty->isDependentType() &&((Ty->isDependentType() && "wrong constructor for non-dependent co_await/co_yield expression"
) ? static_cast<void> (0) : __assert_fail ("Ty->isDependentType() && \"wrong constructor for non-dependent co_await/co_yield expression\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 4753, __PRETTY_FUNCTION__))
4753 "wrong constructor for non-dependent co_await/co_yield expression")((Ty->isDependentType() && "wrong constructor for non-dependent co_await/co_yield expression"
) ? static_cast<void> (0) : __assert_fail ("Ty->isDependentType() && \"wrong constructor for non-dependent co_await/co_yield expression\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 4753, __PRETTY_FUNCTION__))
;
4754 SubExprs[0] = Op;
4755 SubExprs[1] = OpCoawait;
4756 }
4757
4758 DependentCoawaitExpr(EmptyShell Empty)
4759 : Expr(DependentCoawaitExprClass, Empty) {}
4760
4761 Expr *getOperand() const { return cast<Expr>(SubExprs[0]); }
4762
4763 UnresolvedLookupExpr *getOperatorCoawaitLookup() const {
4764 return cast<UnresolvedLookupExpr>(SubExprs[1]);
4765 }
4766
4767 SourceLocation getKeywordLoc() const { return KeywordLoc; }
4768
4769 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return KeywordLoc; }
4770
4771 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
4772 return getOperand()->getEndLoc();
4773 }
4774
4775 child_range children() { return child_range(SubExprs, SubExprs + 2); }
4776
4777 const_child_range children() const {
4778 return const_child_range(SubExprs, SubExprs + 2);
4779 }
4780
4781 static bool classof(const Stmt *T) {
4782 return T->getStmtClass() == DependentCoawaitExprClass;
4783 }
4784};
4785
4786/// Represents a 'co_yield' expression.
4787class CoyieldExpr : public CoroutineSuspendExpr {
4788 friend class ASTStmtReader;
4789
4790public:
4791 CoyieldExpr(SourceLocation CoyieldLoc, Expr *Operand, Expr *Ready,
4792 Expr *Suspend, Expr *Resume, OpaqueValueExpr *OpaqueValue)
4793 : CoroutineSuspendExpr(CoyieldExprClass, CoyieldLoc, Operand, Ready,
4794 Suspend, Resume, OpaqueValue) {}
4795 CoyieldExpr(SourceLocation CoyieldLoc, QualType Ty, Expr *Operand)
4796 : CoroutineSuspendExpr(CoyieldExprClass, CoyieldLoc, Ty, Operand) {}
4797 CoyieldExpr(EmptyShell Empty)
4798 : CoroutineSuspendExpr(CoyieldExprClass, Empty) {}
4799
4800 Expr *getOperand() const {
4801 // FIXME: Dig out the actual operand or store it.
4802 return getCommonExpr();
4803 }
4804
4805 static bool classof(const Stmt *T) {
4806 return T->getStmtClass() == CoyieldExprClass;
4807 }
4808};
4809
4810/// Represents a C++2a __builtin_bit_cast(T, v) expression. Used to implement
4811/// std::bit_cast. These can sometimes be evaluated as part of a constant
4812/// expression, but otherwise CodeGen to a simple memcpy in general.
4813class BuiltinBitCastExpr final
4814 : public ExplicitCastExpr,
4815 private llvm::TrailingObjects<BuiltinBitCastExpr, CXXBaseSpecifier *> {
4816 friend class ASTStmtReader;
4817 friend class CastExpr;
4818 friend class TrailingObjects;
4819
4820 SourceLocation KWLoc;
4821 SourceLocation RParenLoc;
4822
4823public:
4824 BuiltinBitCastExpr(QualType T, ExprValueKind VK, CastKind CK, Expr *SrcExpr,
4825 TypeSourceInfo *DstType, SourceLocation KWLoc,
4826 SourceLocation RParenLoc)
4827 : ExplicitCastExpr(BuiltinBitCastExprClass, T, VK, CK, SrcExpr, 0,
4828 DstType),
4829 KWLoc(KWLoc), RParenLoc(RParenLoc) {}
4830
4831 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return KWLoc; }
4832 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; }
4833
4834 static bool classof(const Stmt *T) {
4835 return T->getStmtClass() == BuiltinBitCastExprClass;
4836 }
4837};
4838
4839/// \brief Represents the specialization of a concept - evaluates to a prvalue
4840/// of type bool.
4841///
4842/// According to C++2a [expr.prim.id]p3 an id-expression that denotes the
4843/// specialization of a concept results in a prvalue of type bool.
4844class ConceptSpecializationExpr final : public Expr,
4845 private llvm::TrailingObjects<ConceptSpecializationExpr,
4846 TemplateArgument> {
4847 friend class ASTStmtReader;
4848 friend TrailingObjects;
4849public:
4850 using SubstitutionDiagnostic = std::pair<SourceLocation, std::string>;
4851
4852protected:
4853
4854 // \brief The optional nested name specifier used when naming the concept.
4855 NestedNameSpecifierLoc NestedNameSpec;
4856
4857 /// \brief The location of the template keyword, if specified when naming the
4858 /// concept.
4859 SourceLocation TemplateKWLoc;
4860
4861 /// \brief The location of the concept name in the expression.
4862 SourceLocation ConceptNameLoc;
4863
4864 /// \brief The declaration found by name lookup when the expression was
4865 /// created.
4866 /// Can differ from NamedConcept when, for example, the concept was found
4867 /// through a UsingShadowDecl.
4868 NamedDecl *FoundDecl;
4869
4870 /// \brief The concept named.
4871 ConceptDecl *NamedConcept;
4872
4873 /// \brief The template argument list source info used to specialize the
4874 /// concept.
4875 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
4876
4877 /// \brief The number of template arguments in the tail-allocated list of
4878 /// converted template arguments.
4879 unsigned NumTemplateArgs;
4880
4881 /// \brief Information about the satisfaction of the named concept with the
4882 /// given arguments. If this expression is value dependent, this is to be
4883 /// ignored.
4884 ASTConstraintSatisfaction *Satisfaction;
4885
4886 ConceptSpecializationExpr(ASTContext &C, NestedNameSpecifierLoc NNS,
4887 SourceLocation TemplateKWLoc,
4888 SourceLocation ConceptNameLoc, NamedDecl *FoundDecl,
4889 ConceptDecl *NamedConcept,
4890 const ASTTemplateArgumentListInfo *ArgsAsWritten,
4891 ArrayRef<TemplateArgument> ConvertedArgs,
4892 const ConstraintSatisfaction *Satisfaction);
4893
4894 ConceptSpecializationExpr(EmptyShell Empty, unsigned NumTemplateArgs);
4895
4896public:
4897
4898 static ConceptSpecializationExpr *
4899 Create(ASTContext &C, NestedNameSpecifierLoc NNS,
4900 SourceLocation TemplateKWLoc, SourceLocation ConceptNameLoc,
4901 NamedDecl *FoundDecl, ConceptDecl *NamedConcept,
4902 const ASTTemplateArgumentListInfo *ArgsAsWritten,
4903 ArrayRef<TemplateArgument> ConvertedArgs,
4904 const ConstraintSatisfaction *Satisfaction);
4905
4906 static ConceptSpecializationExpr *
4907 Create(ASTContext &C, EmptyShell Empty, unsigned NumTemplateArgs);
4908
4909 const NestedNameSpecifierLoc &getNestedNameSpecifierLoc() const {
4910 return NestedNameSpec;
4911 }
4912
4913 NamedDecl *getFoundDecl() const {
4914 return FoundDecl;
4915 }
4916
4917 ConceptDecl *getNamedConcept() const {
4918 return NamedConcept;
4919 }
4920
4921 ArrayRef<TemplateArgument> getTemplateArguments() const {
4922 return ArrayRef<TemplateArgument>(getTrailingObjects<TemplateArgument>(),
4923 NumTemplateArgs);
4924 }
4925
4926 const ASTTemplateArgumentListInfo *getTemplateArgsAsWritten() const {
4927 return ArgsAsWritten;
4928 }
4929
4930 /// \brief Set new template arguments for this concept specialization.
4931 void setTemplateArguments(const ASTTemplateArgumentListInfo *ArgsAsWritten,
4932 ArrayRef<TemplateArgument> Converted);
4933
4934 /// \brief Whether or not the concept with the given arguments was satisfied
4935 /// when the expression was created.
4936 /// The expression must not be dependent.
4937 bool isSatisfied() const {
4938 assert(!isValueDependent()((!isValueDependent() && "isSatisfied called on a dependent ConceptSpecializationExpr"
) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"isSatisfied called on a dependent ConceptSpecializationExpr\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 4939, __PRETTY_FUNCTION__))
4939 && "isSatisfied called on a dependent ConceptSpecializationExpr")((!isValueDependent() && "isSatisfied called on a dependent ConceptSpecializationExpr"
) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"isSatisfied called on a dependent ConceptSpecializationExpr\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 4939, __PRETTY_FUNCTION__))
;
4940 return Satisfaction->IsSatisfied;
4941 }
4942
4943 /// \brief Get elaborated satisfaction info about the template arguments'
4944 /// satisfaction of the named concept.
4945 /// The expression must not be dependent.
4946 const ASTConstraintSatisfaction &getSatisfaction() const {
4947 assert(!isValueDependent()((!isValueDependent() && "getSatisfaction called on dependent ConceptSpecializationExpr"
) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"getSatisfaction called on dependent ConceptSpecializationExpr\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 4948, __PRETTY_FUNCTION__))
4948 && "getSatisfaction called on dependent ConceptSpecializationExpr")((!isValueDependent() && "getSatisfaction called on dependent ConceptSpecializationExpr"
) ? static_cast<void> (0) : __assert_fail ("!isValueDependent() && \"getSatisfaction called on dependent ConceptSpecializationExpr\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/AST/ExprCXX.h"
, 4948, __PRETTY_FUNCTION__))
;
4949 return *Satisfaction;
4950 }
4951
4952 SourceLocation getConceptNameLoc() const { return ConceptNameLoc; }
4953
4954 SourceLocation getTemplateKWLoc() const { return TemplateKWLoc; }
4955
4956 static bool classof(const Stmt *T) {
4957 return T->getStmtClass() == ConceptSpecializationExprClass;
4958 }
4959
4960 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return ConceptNameLoc; }
4961 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
4962 return ArgsAsWritten->RAngleLoc;
4963 }
4964
4965 // Iterators
4966 child_range children() {
4967 return child_range(child_iterator(), child_iterator());
4968 }
4969 const_child_range children() const {
4970 return const_child_range(const_child_iterator(), const_child_iterator());
4971 }
4972};
4973
4974} // namespace clang
4975
4976#endif // LLVM_CLANG_AST_EXPRCXX_H