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