11569ce68SRoman Divacky //===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
24c8b2481SRoman Divacky //
322989816SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
422989816SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
522989816SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
64c8b2481SRoman Divacky //
74c8b2481SRoman Divacky //===----------------------------------------------------------------------===//
84c8b2481SRoman Divacky //
94c8b2481SRoman Divacky // This contains code dealing with code generation of C++ expressions
104c8b2481SRoman Divacky //
114c8b2481SRoman Divacky //===----------------------------------------------------------------------===//
124c8b2481SRoman Divacky
1336981b17SDimitry Andric #include "CGCUDARuntime.h"
143d1dcd9bSDimitry Andric #include "CGCXXABI.h"
15bca07a45SDimitry Andric #include "CGDebugInfo.h"
16809500fcSDimitry Andric #include "CGObjCRuntime.h"
1722989816SDimitry Andric #include "CodeGenFunction.h"
18461a67faSDimitry Andric #include "ConstantEmitter.h"
1922989816SDimitry Andric #include "TargetInfo.h"
20676fbe81SDimitry Andric #include "clang/Basic/CodeGenOptions.h"
21bfef3995SDimitry Andric #include "clang/CodeGen/CGFunctionInfo.h"
22809500fcSDimitry Andric #include "llvm/IR/Intrinsics.h"
2301af97d3SDimitry Andric
244c8b2481SRoman Divacky using namespace clang;
254c8b2481SRoman Divacky using namespace CodeGen;
264c8b2481SRoman Divacky
277442d6faSDimitry Andric namespace {
287442d6faSDimitry Andric struct MemberCallInfo {
297442d6faSDimitry Andric RequiredArgs ReqArgs;
307442d6faSDimitry Andric // Number of prefix arguments for the call. Ignores the `this` pointer.
317442d6faSDimitry Andric unsigned PrefixSize;
327442d6faSDimitry Andric };
337442d6faSDimitry Andric }
347442d6faSDimitry Andric
357442d6faSDimitry Andric static MemberCallInfo
commonEmitCXXMemberOrOperatorCall(CodeGenFunction & CGF,GlobalDecl GD,llvm::Value * This,llvm::Value * ImplicitParam,QualType ImplicitParamTy,const CallExpr * CE,CallArgList & Args,CallArgList * RtlArgs)367fa27ce4SDimitry Andric commonEmitCXXMemberOrOperatorCall(CodeGenFunction &CGF, GlobalDecl GD,
372b6b257fSDimitry Andric llvm::Value *This, llvm::Value *ImplicitParam,
382b6b257fSDimitry Andric QualType ImplicitParamTy, const CallExpr *CE,
39bab175ecSDimitry Andric CallArgList &Args, CallArgList *RtlArgs) {
407fa27ce4SDimitry Andric auto *MD = cast<CXXMethodDecl>(GD.getDecl());
417fa27ce4SDimitry Andric
4206d4ba38SDimitry Andric assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) ||
4306d4ba38SDimitry Andric isa<CXXOperatorCallExpr>(CE));
44b1c73532SDimitry Andric assert(MD->isImplicitObjectMemberFunction() &&
4506d4ba38SDimitry Andric "Trying to emit a member or operator call expr on a static method!");
46ee791ddeSRoman Divacky
47ee791ddeSRoman Divacky // Push the this ptr.
48bab175ecSDimitry Andric const CXXRecordDecl *RD =
497fa27ce4SDimitry Andric CGF.CGM.getCXXABI().getThisArgumentTypeForMethod(GD);
5022989816SDimitry Andric Args.add(RValue::get(This), CGF.getTypes().DeriveThisType(RD, MD));
51ee791ddeSRoman Divacky
52809500fcSDimitry Andric // If there is an implicit parameter (e.g. VTT), emit it.
53809500fcSDimitry Andric if (ImplicitParam) {
54809500fcSDimitry Andric Args.add(RValue::get(ImplicitParam), ImplicitParamTy);
55ee791ddeSRoman Divacky }
56ee791ddeSRoman Divacky
57dbe13110SDimitry Andric const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
5822989816SDimitry Andric RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size());
597442d6faSDimitry Andric unsigned PrefixSize = Args.size() - 1;
60dbe13110SDimitry Andric
61dbe13110SDimitry Andric // And the rest of the call args.
62bab175ecSDimitry Andric if (RtlArgs) {
63bab175ecSDimitry Andric // Special case: if the caller emitted the arguments right-to-left already
64bab175ecSDimitry Andric // (prior to emitting the *this argument), we're done. This happens for
65bab175ecSDimitry Andric // assignment operators.
66bab175ecSDimitry Andric Args.addFrom(*RtlArgs);
67bab175ecSDimitry Andric } else if (CE) {
6806d4ba38SDimitry Andric // Special case: skip first argument of CXXOperatorCall (it is "this").
69b1c73532SDimitry Andric unsigned ArgsToSkip = 0;
70b1c73532SDimitry Andric if (const auto *Op = dyn_cast<CXXOperatorCallExpr>(CE)) {
71b1c73532SDimitry Andric if (const auto *M = dyn_cast<CXXMethodDecl>(Op->getCalleeDecl()))
72b1c73532SDimitry Andric ArgsToSkip =
73b1c73532SDimitry Andric static_cast<unsigned>(!M->isExplicitObjectMemberFunction());
74b1c73532SDimitry Andric }
7545b53394SDimitry Andric CGF.EmitCallArgs(Args, FPT, drop_begin(CE->arguments(), ArgsToSkip),
7606d4ba38SDimitry Andric CE->getDirectCallee());
7706d4ba38SDimitry Andric } else {
7806d4ba38SDimitry Andric assert(
7906d4ba38SDimitry Andric FPT->getNumParams() == 0 &&
8006d4ba38SDimitry Andric "No CallExpr specified for function with non-zero number of arguments");
8106d4ba38SDimitry Andric }
827442d6faSDimitry Andric return {required, PrefixSize};
8306d4ba38SDimitry Andric }
84ee791ddeSRoman Divacky
EmitCXXMemberOrOperatorCall(const CXXMethodDecl * MD,const CGCallee & Callee,ReturnValueSlot ReturnValue,llvm::Value * This,llvm::Value * ImplicitParam,QualType ImplicitParamTy,const CallExpr * CE,CallArgList * RtlArgs)8506d4ba38SDimitry Andric RValue CodeGenFunction::EmitCXXMemberOrOperatorCall(
86bab175ecSDimitry Andric const CXXMethodDecl *MD, const CGCallee &Callee,
87bab175ecSDimitry Andric ReturnValueSlot ReturnValue,
8806d4ba38SDimitry Andric llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,
89bab175ecSDimitry Andric const CallExpr *CE, CallArgList *RtlArgs) {
9006d4ba38SDimitry Andric const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
9106d4ba38SDimitry Andric CallArgList Args;
927442d6faSDimitry Andric MemberCallInfo CallInfo = commonEmitCXXMemberOrOperatorCall(
93bab175ecSDimitry Andric *this, MD, This, ImplicitParam, ImplicitParamTy, CE, Args, RtlArgs);
947442d6faSDimitry Andric auto &FnInfo = CGM.getTypes().arrangeCXXMethodCall(
957442d6faSDimitry Andric Args, FPT, CallInfo.ReqArgs, CallInfo.PrefixSize);
966252156dSDimitry Andric return EmitCall(FnInfo, Callee, ReturnValue, Args, nullptr,
97344a3780SDimitry Andric CE && CE == MustTailCall,
986252156dSDimitry Andric CE ? CE->getExprLoc() : SourceLocation());
99ee791ddeSRoman Divacky }
100ee791ddeSRoman Divacky
EmitCXXDestructorCall(GlobalDecl Dtor,const CGCallee & Callee,llvm::Value * This,QualType ThisTy,llvm::Value * ImplicitParam,QualType ImplicitParamTy,const CallExpr * CE)1012b6b257fSDimitry Andric RValue CodeGenFunction::EmitCXXDestructorCall(
10222989816SDimitry Andric GlobalDecl Dtor, const CGCallee &Callee, llvm::Value *This, QualType ThisTy,
10322989816SDimitry Andric llvm::Value *ImplicitParam, QualType ImplicitParamTy, const CallExpr *CE) {
10422989816SDimitry Andric const CXXMethodDecl *DtorDecl = cast<CXXMethodDecl>(Dtor.getDecl());
10522989816SDimitry Andric
10622989816SDimitry Andric assert(!ThisTy.isNull());
10722989816SDimitry Andric assert(ThisTy->getAsCXXRecordDecl() == DtorDecl->getParent() &&
10822989816SDimitry Andric "Pointer/Object mixup");
10922989816SDimitry Andric
11022989816SDimitry Andric LangAS SrcAS = ThisTy.getAddressSpace();
11122989816SDimitry Andric LangAS DstAS = DtorDecl->getMethodQualifiers().getAddressSpace();
11222989816SDimitry Andric if (SrcAS != DstAS) {
11322989816SDimitry Andric QualType DstTy = DtorDecl->getThisType();
11422989816SDimitry Andric llvm::Type *NewType = CGM.getTypes().ConvertType(DstTy);
11522989816SDimitry Andric This = getTargetHooks().performAddrSpaceCast(*this, This, SrcAS, DstAS,
11622989816SDimitry Andric NewType);
11722989816SDimitry Andric }
11822989816SDimitry Andric
11906d4ba38SDimitry Andric CallArgList Args;
1207fa27ce4SDimitry Andric commonEmitCXXMemberOrOperatorCall(*this, Dtor, This, ImplicitParam,
121bab175ecSDimitry Andric ImplicitParamTy, CE, Args, nullptr);
12222989816SDimitry Andric return EmitCall(CGM.getTypes().arrangeCXXStructorDeclaration(Dtor), Callee,
123344a3780SDimitry Andric ReturnValueSlot(), Args, nullptr, CE && CE == MustTailCall,
124cfca06d7SDimitry Andric CE ? CE->getExprLoc() : SourceLocation{});
125bab175ecSDimitry Andric }
126bab175ecSDimitry Andric
EmitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr * E)127bab175ecSDimitry Andric RValue CodeGenFunction::EmitCXXPseudoDestructorExpr(
128bab175ecSDimitry Andric const CXXPseudoDestructorExpr *E) {
129bab175ecSDimitry Andric QualType DestroyedType = E->getDestroyedType();
130bab175ecSDimitry Andric if (DestroyedType.hasStrongOrWeakObjCLifetime()) {
131bab175ecSDimitry Andric // Automatic Reference Counting:
132bab175ecSDimitry Andric // If the pseudo-expression names a retainable object with weak or
133bab175ecSDimitry Andric // strong lifetime, the object shall be released.
134bab175ecSDimitry Andric Expr *BaseExpr = E->getBase();
135bab175ecSDimitry Andric Address BaseValue = Address::invalid();
136bab175ecSDimitry Andric Qualifiers BaseQuals;
137bab175ecSDimitry Andric
138bab175ecSDimitry Andric // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
139bab175ecSDimitry Andric if (E->isArrow()) {
140bab175ecSDimitry Andric BaseValue = EmitPointerWithAlignment(BaseExpr);
141706b4fc4SDimitry Andric const auto *PTy = BaseExpr->getType()->castAs<PointerType>();
142bab175ecSDimitry Andric BaseQuals = PTy->getPointeeType().getQualifiers();
143bab175ecSDimitry Andric } else {
144bab175ecSDimitry Andric LValue BaseLV = EmitLValue(BaseExpr);
145ac9a064cSDimitry Andric BaseValue = BaseLV.getAddress();
146bab175ecSDimitry Andric QualType BaseTy = BaseExpr->getType();
147bab175ecSDimitry Andric BaseQuals = BaseTy.getQualifiers();
148bab175ecSDimitry Andric }
149bab175ecSDimitry Andric
150bab175ecSDimitry Andric switch (DestroyedType.getObjCLifetime()) {
151bab175ecSDimitry Andric case Qualifiers::OCL_None:
152bab175ecSDimitry Andric case Qualifiers::OCL_ExplicitNone:
153bab175ecSDimitry Andric case Qualifiers::OCL_Autoreleasing:
154bab175ecSDimitry Andric break;
155bab175ecSDimitry Andric
156bab175ecSDimitry Andric case Qualifiers::OCL_Strong:
157bab175ecSDimitry Andric EmitARCRelease(Builder.CreateLoad(BaseValue,
158bab175ecSDimitry Andric DestroyedType.isVolatileQualified()),
159bab175ecSDimitry Andric ARCPreciseLifetime);
160bab175ecSDimitry Andric break;
161bab175ecSDimitry Andric
162bab175ecSDimitry Andric case Qualifiers::OCL_Weak:
163bab175ecSDimitry Andric EmitARCDestroyWeak(BaseValue);
164bab175ecSDimitry Andric break;
165bab175ecSDimitry Andric }
166bab175ecSDimitry Andric } else {
167bab175ecSDimitry Andric // C++ [expr.pseudo]p1:
168bab175ecSDimitry Andric // The result shall only be used as the operand for the function call
169bab175ecSDimitry Andric // operator (), and the result of such a call has type void. The only
170bab175ecSDimitry Andric // effect is the evaluation of the postfix-expression before the dot or
171bab175ecSDimitry Andric // arrow.
172bab175ecSDimitry Andric EmitIgnoredExpr(E->getBase());
173bab175ecSDimitry Andric }
174bab175ecSDimitry Andric
175bab175ecSDimitry Andric return RValue::get(nullptr);
17606d4ba38SDimitry Andric }
17706d4ba38SDimitry Andric
getCXXRecord(const Expr * E)17856d91b49SDimitry Andric static CXXRecordDecl *getCXXRecord(const Expr *E) {
17956d91b49SDimitry Andric QualType T = E->getType();
18056d91b49SDimitry Andric if (const PointerType *PTy = T->getAs<PointerType>())
18156d91b49SDimitry Andric T = PTy->getPointeeType();
18256d91b49SDimitry Andric const RecordType *Ty = T->castAs<RecordType>();
18356d91b49SDimitry Andric return cast<CXXRecordDecl>(Ty->getDecl());
18456d91b49SDimitry Andric }
18556d91b49SDimitry Andric
186bca07a45SDimitry Andric // Note: This function also emit constructor calls to support a MSVC
187bca07a45SDimitry Andric // extensions allowing explicit constructor function call.
EmitCXXMemberCallExpr(const CXXMemberCallExpr * CE,ReturnValueSlot ReturnValue)188ee791ddeSRoman Divacky RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
189ee791ddeSRoman Divacky ReturnValueSlot ReturnValue) {
19001af97d3SDimitry Andric const Expr *callee = CE->getCallee()->IgnoreParens();
19101af97d3SDimitry Andric
19201af97d3SDimitry Andric if (isa<BinaryOperator>(callee))
193ee791ddeSRoman Divacky return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
194ee791ddeSRoman Divacky
19501af97d3SDimitry Andric const MemberExpr *ME = cast<MemberExpr>(callee);
196ee791ddeSRoman Divacky const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
197ee791ddeSRoman Divacky
198ee791ddeSRoman Divacky if (MD->isStatic()) {
199ee791ddeSRoman Divacky // The method is static, emit it as we would a regular call.
200676fbe81SDimitry Andric CGCallee callee =
201676fbe81SDimitry Andric CGCallee::forDirect(CGM.GetAddrOfFunction(MD), GlobalDecl(MD));
202bab175ecSDimitry Andric return EmitCall(getContext().getPointerType(MD->getType()), callee, CE,
20306d4ba38SDimitry Andric ReturnValue);
204ee791ddeSRoman Divacky }
205ee791ddeSRoman Divacky
20606d4ba38SDimitry Andric bool HasQualifier = ME->hasQualifier();
20706d4ba38SDimitry Andric NestedNameSpecifier *Qualifier = HasQualifier ? ME->getQualifier() : nullptr;
20806d4ba38SDimitry Andric bool IsArrow = ME->isArrow();
20956d91b49SDimitry Andric const Expr *Base = ME->getBase();
21006d4ba38SDimitry Andric
21106d4ba38SDimitry Andric return EmitCXXMemberOrOperatorMemberCallExpr(
21206d4ba38SDimitry Andric CE, MD, ReturnValue, HasQualifier, Qualifier, IsArrow, Base);
21306d4ba38SDimitry Andric }
21406d4ba38SDimitry Andric
EmitCXXMemberOrOperatorMemberCallExpr(const CallExpr * CE,const CXXMethodDecl * MD,ReturnValueSlot ReturnValue,bool HasQualifier,NestedNameSpecifier * Qualifier,bool IsArrow,const Expr * Base)21506d4ba38SDimitry Andric RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr(
21606d4ba38SDimitry Andric const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue,
21706d4ba38SDimitry Andric bool HasQualifier, NestedNameSpecifier *Qualifier, bool IsArrow,
21806d4ba38SDimitry Andric const Expr *Base) {
21906d4ba38SDimitry Andric assert(isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE));
22006d4ba38SDimitry Andric
22106d4ba38SDimitry Andric // Compute the object pointer.
22206d4ba38SDimitry Andric bool CanUseVirtualCall = MD->isVirtual() && !HasQualifier;
22356d91b49SDimitry Andric
2249f4dbff6SDimitry Andric const CXXMethodDecl *DevirtualizedMethod = nullptr;
2258746d127SDimitry Andric if (CanUseVirtualCall &&
2268746d127SDimitry Andric MD->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) {
22756d91b49SDimitry Andric const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
22856d91b49SDimitry Andric DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
22956d91b49SDimitry Andric assert(DevirtualizedMethod);
23056d91b49SDimitry Andric const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
231b60736ecSDimitry Andric const Expr *Inner = Base->IgnoreParenBaseCasts();
23206d4ba38SDimitry Andric if (DevirtualizedMethod->getReturnType().getCanonicalType() !=
23306d4ba38SDimitry Andric MD->getReturnType().getCanonicalType())
23406d4ba38SDimitry Andric // If the return types are not the same, this might be a case where more
23506d4ba38SDimitry Andric // code needs to run to compensate for it. For example, the derived
23606d4ba38SDimitry Andric // method might return a type that inherits form from the return
23706d4ba38SDimitry Andric // type of MD and has a prefix.
23806d4ba38SDimitry Andric // For now we just avoid devirtualizing these covariant cases.
23906d4ba38SDimitry Andric DevirtualizedMethod = nullptr;
24006d4ba38SDimitry Andric else if (getCXXRecord(Inner) == DevirtualizedClass)
24156d91b49SDimitry Andric // If the class of the Inner expression is where the dynamic method
24256d91b49SDimitry Andric // is defined, build the this pointer from it.
24356d91b49SDimitry Andric Base = Inner;
24456d91b49SDimitry Andric else if (getCXXRecord(Base) != DevirtualizedClass) {
24556d91b49SDimitry Andric // If the method is defined in a class that is not the best dynamic
24656d91b49SDimitry Andric // one or the one of the full expression, we would have to build
24756d91b49SDimitry Andric // a derived-to-base cast to compute the correct this pointer, but
24856d91b49SDimitry Andric // we don't have support for that yet, so do a virtual call.
2499f4dbff6SDimitry Andric DevirtualizedMethod = nullptr;
25056d91b49SDimitry Andric }
25156d91b49SDimitry Andric }
25256d91b49SDimitry Andric
253706b4fc4SDimitry Andric bool TrivialForCodegen =
254706b4fc4SDimitry Andric MD->isTrivial() || (MD->isDefaulted() && MD->getParent()->isUnion());
255706b4fc4SDimitry Andric bool TrivialAssignment =
256706b4fc4SDimitry Andric TrivialForCodegen &&
257706b4fc4SDimitry Andric (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
258706b4fc4SDimitry Andric !MD->getParent()->mayInsertExtraPadding();
259706b4fc4SDimitry Andric
260bab175ecSDimitry Andric // C++17 demands that we evaluate the RHS of a (possibly-compound) assignment
261bab175ecSDimitry Andric // operator before the LHS.
262bab175ecSDimitry Andric CallArgList RtlArgStorage;
263bab175ecSDimitry Andric CallArgList *RtlArgs = nullptr;
264706b4fc4SDimitry Andric LValue TrivialAssignmentRHS;
265bab175ecSDimitry Andric if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
266bab175ecSDimitry Andric if (OCE->isAssignmentOp()) {
267706b4fc4SDimitry Andric if (TrivialAssignment) {
268706b4fc4SDimitry Andric TrivialAssignmentRHS = EmitLValue(CE->getArg(1));
269706b4fc4SDimitry Andric } else {
270bab175ecSDimitry Andric RtlArgs = &RtlArgStorage;
271bab175ecSDimitry Andric EmitCallArgs(*RtlArgs, MD->getType()->castAs<FunctionProtoType>(),
272bab175ecSDimitry Andric drop_begin(CE->arguments(), 1), CE->getDirectCallee(),
273bab175ecSDimitry Andric /*ParamsToSkip*/0, EvaluationOrder::ForceRightToLeft);
274bab175ecSDimitry Andric }
275bab175ecSDimitry Andric }
276706b4fc4SDimitry Andric }
277bab175ecSDimitry Andric
27848675466SDimitry Andric LValue This;
27948675466SDimitry Andric if (IsArrow) {
28048675466SDimitry Andric LValueBaseInfo BaseInfo;
28148675466SDimitry Andric TBAAAccessInfo TBAAInfo;
28248675466SDimitry Andric Address ThisValue = EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo);
283ac9a064cSDimitry Andric This = MakeAddrLValue(ThisValue, Base->getType()->getPointeeType(),
284ac9a064cSDimitry Andric BaseInfo, TBAAInfo);
28548675466SDimitry Andric } else {
28648675466SDimitry Andric This = EmitLValue(Base);
28748675466SDimitry Andric }
28856d91b49SDimitry Andric
28922989816SDimitry Andric if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
29022989816SDimitry Andric // This is the MSVC p->Ctor::Ctor(...) extension. We assume that's
29122989816SDimitry Andric // constructing a new complete object of type Ctor.
29222989816SDimitry Andric assert(!RtlArgs);
29322989816SDimitry Andric assert(ReturnValue.isNull() && "Constructor shouldn't have return value");
29422989816SDimitry Andric CallArgList Args;
29522989816SDimitry Andric commonEmitCXXMemberOrOperatorCall(
2967fa27ce4SDimitry Andric *this, {Ctor, Ctor_Complete}, This.getPointer(*this),
2977fa27ce4SDimitry Andric /*ImplicitParam=*/nullptr,
29822989816SDimitry Andric /*ImplicitParamTy=*/QualType(), CE, Args, nullptr);
29922989816SDimitry Andric
30022989816SDimitry Andric EmitCXXConstructorCall(Ctor, Ctor_Complete, /*ForVirtualBase=*/false,
301ac9a064cSDimitry Andric /*Delegating=*/false, This.getAddress(), Args,
30222989816SDimitry Andric AggValueSlot::DoesNotOverlap, CE->getExprLoc(),
30322989816SDimitry Andric /*NewPointerIsChecked=*/false);
30422989816SDimitry Andric return RValue::get(nullptr);
30522989816SDimitry Andric }
306ee791ddeSRoman Divacky
307706b4fc4SDimitry Andric if (TrivialForCodegen) {
308706b4fc4SDimitry Andric if (isa<CXXDestructorDecl>(MD))
309706b4fc4SDimitry Andric return RValue::get(nullptr);
310706b4fc4SDimitry Andric
311706b4fc4SDimitry Andric if (TrivialAssignment) {
31236981b17SDimitry Andric // We don't like to generate the trivial copy/move assignment operator
31336981b17SDimitry Andric // when it isn't necessary; just produce the proper effect here.
314706b4fc4SDimitry Andric // It's important that we use the result of EmitLValue here rather than
315706b4fc4SDimitry Andric // emitting call arguments, in order to preserve TBAA information from
316706b4fc4SDimitry Andric // the RHS.
317bab175ecSDimitry Andric LValue RHS = isa<CXXOperatorCallExpr>(CE)
318706b4fc4SDimitry Andric ? TrivialAssignmentRHS
319bab175ecSDimitry Andric : EmitLValue(*CE->arg_begin());
32048675466SDimitry Andric EmitAggregateAssign(This, RHS, CE->getType());
321706b4fc4SDimitry Andric return RValue::get(This.getPointer(*this));
322ee791ddeSRoman Divacky }
323706b4fc4SDimitry Andric
324706b4fc4SDimitry Andric assert(MD->getParent()->mayInsertExtraPadding() &&
325706b4fc4SDimitry Andric "unknown trivial member function");
32606d4ba38SDimitry Andric }
327bca07a45SDimitry Andric
3283d1dcd9bSDimitry Andric // Compute the function type we're calling.
32906d4ba38SDimitry Andric const CXXMethodDecl *CalleeDecl =
33006d4ba38SDimitry Andric DevirtualizedMethod ? DevirtualizedMethod : MD;
3319f4dbff6SDimitry Andric const CGFunctionInfo *FInfo = nullptr;
33206d4ba38SDimitry Andric if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
33306d4ba38SDimitry Andric FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
33422989816SDimitry Andric GlobalDecl(Dtor, Dtor_Complete));
335bca07a45SDimitry Andric else
33613cc256eSDimitry Andric FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
3373d1dcd9bSDimitry Andric
338bfef3995SDimitry Andric llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
3393d1dcd9bSDimitry Andric
340bab175ecSDimitry Andric // C++11 [class.mfct.non-static]p2:
341bab175ecSDimitry Andric // If a non-static member function of a class X is called for an object that
342bab175ecSDimitry Andric // is not of type X, or of a type derived from X, the behavior is undefined.
343bab175ecSDimitry Andric SourceLocation CallLoc;
344bab175ecSDimitry Andric ASTContext &C = getContext();
345bab175ecSDimitry Andric if (CE)
346bab175ecSDimitry Andric CallLoc = CE->getExprLoc();
347bab175ecSDimitry Andric
3487442d6faSDimitry Andric SanitizerSet SkippedChecks;
3497442d6faSDimitry Andric if (const auto *CMCE = dyn_cast<CXXMemberCallExpr>(CE)) {
3507442d6faSDimitry Andric auto *IOA = CMCE->getImplicitObjectArgument();
3517442d6faSDimitry Andric bool IsImplicitObjectCXXThis = IsWrappedCXXThis(IOA);
3527442d6faSDimitry Andric if (IsImplicitObjectCXXThis)
3537442d6faSDimitry Andric SkippedChecks.set(SanitizerKind::Alignment, true);
3547442d6faSDimitry Andric if (IsImplicitObjectCXXThis || isa<DeclRefExpr>(IOA))
3557442d6faSDimitry Andric SkippedChecks.set(SanitizerKind::Null, true);
3567442d6faSDimitry Andric }
357ac9a064cSDimitry Andric
358ac9a064cSDimitry Andric if (sanitizePerformTypeCheck())
359706b4fc4SDimitry Andric EmitTypeCheck(CodeGenFunction::TCK_MemberCall, CallLoc,
360ac9a064cSDimitry Andric This.emitRawPointer(*this),
36122989816SDimitry Andric C.getRecordType(CalleeDecl->getParent()),
3627442d6faSDimitry Andric /*Alignment=*/CharUnits::Zero(), SkippedChecks);
363bab175ecSDimitry Andric
364ee791ddeSRoman Divacky // C++ [class.virtual]p12:
365ee791ddeSRoman Divacky // Explicit qualification with the scope operator (5.1) suppresses the
366ee791ddeSRoman Divacky // virtual call mechanism.
367ee791ddeSRoman Divacky //
368ee791ddeSRoman Divacky // We also don't emit a virtual call if the base expression has a record type
369ee791ddeSRoman Divacky // because then we know what the type is.
37056d91b49SDimitry Andric bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
371bfef3995SDimitry Andric
37222989816SDimitry Andric if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl)) {
373809500fcSDimitry Andric assert(CE->arg_begin() == CE->arg_end() &&
374bfef3995SDimitry Andric "Destructor shouldn't have explicit parameters");
375bfef3995SDimitry Andric assert(ReturnValue.isNull() && "Destructor shouldn't have return value");
376bfef3995SDimitry Andric if (UseVirtualCall) {
377706b4fc4SDimitry Andric CGM.getCXXABI().EmitVirtualDestructorCall(*this, Dtor, Dtor_Complete,
378ac9a064cSDimitry Andric This.getAddress(),
37948675466SDimitry Andric cast<CXXMemberCallExpr>(CE));
380ee791ddeSRoman Divacky } else {
38122989816SDimitry Andric GlobalDecl GD(Dtor, Dtor_Complete);
382bab175ecSDimitry Andric CGCallee Callee;
38322989816SDimitry Andric if (getLangOpts().AppleKext && Dtor->isVirtual() && HasQualifier)
38422989816SDimitry Andric Callee = BuildAppleKextVirtualCall(Dtor, Qualifier, Ty);
38556d91b49SDimitry Andric else if (!DevirtualizedMethod)
38622989816SDimitry Andric Callee =
38722989816SDimitry Andric CGCallee::forDirect(CGM.getAddrOfCXXStructor(GD, FInfo, Ty), GD);
38856d91b49SDimitry Andric else {
38922989816SDimitry Andric Callee = CGCallee::forDirect(CGM.GetAddrOfFunction(GD, Ty), GD);
39056d91b49SDimitry Andric }
39122989816SDimitry Andric
39222989816SDimitry Andric QualType ThisTy =
39322989816SDimitry Andric IsArrow ? Base->getType()->getPointeeType() : Base->getType();
394706b4fc4SDimitry Andric EmitCXXDestructorCall(GD, Callee, This.getPointer(*this), ThisTy,
39522989816SDimitry Andric /*ImplicitParam=*/nullptr,
396cfca06d7SDimitry Andric /*ImplicitParamTy=*/QualType(), CE);
397ee791ddeSRoman Divacky }
3989f4dbff6SDimitry Andric return RValue::get(nullptr);
399bfef3995SDimitry Andric }
400bfef3995SDimitry Andric
40122989816SDimitry Andric // FIXME: Uses of 'MD' past this point need to be audited. We may need to use
40222989816SDimitry Andric // 'CalleeDecl' instead.
40322989816SDimitry Andric
404bab175ecSDimitry Andric CGCallee Callee;
40522989816SDimitry Andric if (UseVirtualCall) {
406ac9a064cSDimitry Andric Callee = CGCallee::forVirtual(CE, MD, This.getAddress(), Ty);
407ee791ddeSRoman Divacky } else {
4085e20cdd8SDimitry Andric if (SanOpts.has(SanitizerKind::CFINVCall) &&
4095e20cdd8SDimitry Andric MD->getParent()->isDynamicClass()) {
410461a67faSDimitry Andric llvm::Value *VTable;
411461a67faSDimitry Andric const CXXRecordDecl *RD;
412706b4fc4SDimitry Andric std::tie(VTable, RD) = CGM.getCXXABI().LoadVTablePtr(
413ac9a064cSDimitry Andric *this, This.getAddress(), CalleeDecl->getParent());
414676fbe81SDimitry Andric EmitVTablePtrCheckForCall(RD, VTable, CFITCK_NVCall, CE->getBeginLoc());
4155e20cdd8SDimitry Andric }
4165e20cdd8SDimitry Andric
41706d4ba38SDimitry Andric if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
41806d4ba38SDimitry Andric Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
41956d91b49SDimitry Andric else if (!DevirtualizedMethod)
420676fbe81SDimitry Andric Callee =
421676fbe81SDimitry Andric CGCallee::forDirect(CGM.GetAddrOfFunction(MD, Ty), GlobalDecl(MD));
42256d91b49SDimitry Andric else {
423676fbe81SDimitry Andric Callee =
424676fbe81SDimitry Andric CGCallee::forDirect(CGM.GetAddrOfFunction(DevirtualizedMethod, Ty),
425676fbe81SDimitry Andric GlobalDecl(DevirtualizedMethod));
42656d91b49SDimitry Andric }
427ee791ddeSRoman Divacky }
428ee791ddeSRoman Divacky
4299f4dbff6SDimitry Andric if (MD->isVirtual()) {
43048675466SDimitry Andric Address NewThisAddr =
43148675466SDimitry Andric CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
432ac9a064cSDimitry Andric *this, CalleeDecl, This.getAddress(), UseVirtualCall);
43348675466SDimitry Andric This.setAddress(NewThisAddr);
4349f4dbff6SDimitry Andric }
435bfef3995SDimitry Andric
436bab175ecSDimitry Andric return EmitCXXMemberOrOperatorCall(
437706b4fc4SDimitry Andric CalleeDecl, Callee, ReturnValue, This.getPointer(*this),
438bab175ecSDimitry Andric /*ImplicitParam=*/nullptr, QualType(), CE, RtlArgs);
439ee791ddeSRoman Divacky }
440ee791ddeSRoman Divacky
441ee791ddeSRoman Divacky RValue
EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr * E,ReturnValueSlot ReturnValue)442ee791ddeSRoman Divacky CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
443ee791ddeSRoman Divacky ReturnValueSlot ReturnValue) {
444ee791ddeSRoman Divacky const BinaryOperator *BO =
445ee791ddeSRoman Divacky cast<BinaryOperator>(E->getCallee()->IgnoreParens());
446ee791ddeSRoman Divacky const Expr *BaseExpr = BO->getLHS();
447ee791ddeSRoman Divacky const Expr *MemFnExpr = BO->getRHS();
448ee791ddeSRoman Divacky
449519fc96cSDimitry Andric const auto *MPT = MemFnExpr->getType()->castAs<MemberPointerType>();
450519fc96cSDimitry Andric const auto *FPT = MPT->getPointeeType()->castAs<FunctionProtoType>();
451519fc96cSDimitry Andric const auto *RD =
452519fc96cSDimitry Andric cast<CXXRecordDecl>(MPT->getClass()->castAs<RecordType>()->getDecl());
453ee791ddeSRoman Divacky
454ee791ddeSRoman Divacky // Emit the 'this' pointer.
45545b53394SDimitry Andric Address This = Address::invalid();
4563d1dcd9bSDimitry Andric if (BO->getOpcode() == BO_PtrMemI)
4577fa27ce4SDimitry Andric This = EmitPointerWithAlignment(BaseExpr, nullptr, nullptr, KnownNonNull);
458ee791ddeSRoman Divacky else
459ac9a064cSDimitry Andric This = EmitLValue(BaseExpr, KnownNonNull).getAddress();
460ee791ddeSRoman Divacky
461ac9a064cSDimitry Andric EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This.emitRawPointer(*this),
46213cc256eSDimitry Andric QualType(MPT->getClass(), 0));
46313cc256eSDimitry Andric
464bab175ecSDimitry Andric // Get the member function pointer.
465bab175ecSDimitry Andric llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
466bab175ecSDimitry Andric
4673d1dcd9bSDimitry Andric // Ask the ABI to load the callee. Note that This is modified.
46845b53394SDimitry Andric llvm::Value *ThisPtrForCall = nullptr;
469bab175ecSDimitry Andric CGCallee Callee =
47045b53394SDimitry Andric CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This,
47145b53394SDimitry Andric ThisPtrForCall, MemFnPtr, MPT);
472ee791ddeSRoman Divacky
473ee791ddeSRoman Divacky CallArgList Args;
474ee791ddeSRoman Divacky
475ee791ddeSRoman Divacky QualType ThisType =
476ee791ddeSRoman Divacky getContext().getPointerType(getContext().getTagDeclType(RD));
477ee791ddeSRoman Divacky
478ee791ddeSRoman Divacky // Push the this ptr.
47945b53394SDimitry Andric Args.add(RValue::get(ThisPtrForCall), ThisType);
480ee791ddeSRoman Divacky
48122989816SDimitry Andric RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1);
48256d91b49SDimitry Andric
483ee791ddeSRoman Divacky // And the rest of the call args
4842b6b257fSDimitry Andric EmitCallArgs(Args, FPT, E->arguments());
4857442d6faSDimitry Andric return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required,
4867442d6faSDimitry Andric /*PrefixSize=*/0),
487344a3780SDimitry Andric Callee, ReturnValue, Args, nullptr, E == MustTailCall,
488344a3780SDimitry Andric E->getExprLoc());
489ee791ddeSRoman Divacky }
490ee791ddeSRoman Divacky
491ee791ddeSRoman Divacky RValue
EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr * E,const CXXMethodDecl * MD,ReturnValueSlot ReturnValue)492ee791ddeSRoman Divacky CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
493ee791ddeSRoman Divacky const CXXMethodDecl *MD,
494ee791ddeSRoman Divacky ReturnValueSlot ReturnValue) {
495b1c73532SDimitry Andric assert(MD->isImplicitObjectMemberFunction() &&
496ee791ddeSRoman Divacky "Trying to emit a member call expr on a static method!");
49706d4ba38SDimitry Andric return EmitCXXMemberOrOperatorMemberCallExpr(
49806d4ba38SDimitry Andric E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr,
49906d4ba38SDimitry Andric /*IsArrow=*/false, E->getArg(0));
500ee791ddeSRoman Divacky }
501ee791ddeSRoman Divacky
EmitCUDAKernelCallExpr(const CUDAKernelCallExpr * E,ReturnValueSlot ReturnValue)50236981b17SDimitry Andric RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
50336981b17SDimitry Andric ReturnValueSlot ReturnValue) {
50436981b17SDimitry Andric return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
50536981b17SDimitry Andric }
50636981b17SDimitry Andric
EmitNullBaseClassInitialization(CodeGenFunction & CGF,Address DestPtr,const CXXRecordDecl * Base)50736981b17SDimitry Andric static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
50845b53394SDimitry Andric Address DestPtr,
50936981b17SDimitry Andric const CXXRecordDecl *Base) {
51036981b17SDimitry Andric if (Base->isEmpty())
51136981b17SDimitry Andric return;
51236981b17SDimitry Andric
5137fa27ce4SDimitry Andric DestPtr = DestPtr.withElementType(CGF.Int8Ty);
51436981b17SDimitry Andric
51536981b17SDimitry Andric const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
51645b53394SDimitry Andric CharUnits NVSize = Layout.getNonVirtualSize();
51736981b17SDimitry Andric
51845b53394SDimitry Andric // We cannot simply zero-initialize the entire base sub-object if vbptrs are
51945b53394SDimitry Andric // present, they are initialized by the most derived class before calling the
52045b53394SDimitry Andric // constructor.
52145b53394SDimitry Andric SmallVector<std::pair<CharUnits, CharUnits>, 1> Stores;
52245b53394SDimitry Andric Stores.emplace_back(CharUnits::Zero(), NVSize);
52345b53394SDimitry Andric
52445b53394SDimitry Andric // Each store is split by the existence of a vbptr.
52545b53394SDimitry Andric CharUnits VBPtrWidth = CGF.getPointerSize();
52645b53394SDimitry Andric std::vector<CharUnits> VBPtrOffsets =
52745b53394SDimitry Andric CGF.CGM.getCXXABI().getVBPtrOffsets(Base);
52845b53394SDimitry Andric for (CharUnits VBPtrOffset : VBPtrOffsets) {
5292b6b257fSDimitry Andric // Stop before we hit any virtual base pointers located in virtual bases.
5302b6b257fSDimitry Andric if (VBPtrOffset >= NVSize)
5312b6b257fSDimitry Andric break;
53245b53394SDimitry Andric std::pair<CharUnits, CharUnits> LastStore = Stores.pop_back_val();
53345b53394SDimitry Andric CharUnits LastStoreOffset = LastStore.first;
53445b53394SDimitry Andric CharUnits LastStoreSize = LastStore.second;
53545b53394SDimitry Andric
53645b53394SDimitry Andric CharUnits SplitBeforeOffset = LastStoreOffset;
53745b53394SDimitry Andric CharUnits SplitBeforeSize = VBPtrOffset - SplitBeforeOffset;
53845b53394SDimitry Andric assert(!SplitBeforeSize.isNegative() && "negative store size!");
53945b53394SDimitry Andric if (!SplitBeforeSize.isZero())
54045b53394SDimitry Andric Stores.emplace_back(SplitBeforeOffset, SplitBeforeSize);
54145b53394SDimitry Andric
54245b53394SDimitry Andric CharUnits SplitAfterOffset = VBPtrOffset + VBPtrWidth;
54345b53394SDimitry Andric CharUnits SplitAfterSize = LastStoreSize - SplitAfterOffset;
54445b53394SDimitry Andric assert(!SplitAfterSize.isNegative() && "negative store size!");
54545b53394SDimitry Andric if (!SplitAfterSize.isZero())
54645b53394SDimitry Andric Stores.emplace_back(SplitAfterOffset, SplitAfterSize);
54745b53394SDimitry Andric }
54836981b17SDimitry Andric
54936981b17SDimitry Andric // If the type contains a pointer to data member we can't memset it to zero.
55036981b17SDimitry Andric // Instead, create a null constant and copy it to the destination.
55136981b17SDimitry Andric // TODO: there are other patterns besides zero that we can usefully memset,
55236981b17SDimitry Andric // like -1, which happens to be the pattern used by member-pointers.
55336981b17SDimitry Andric // TODO: isZeroInitializable can be over-conservative in the case where a
55436981b17SDimitry Andric // virtual base contains a member pointer.
55545b53394SDimitry Andric llvm::Constant *NullConstantForBase = CGF.CGM.EmitNullConstantForBase(Base);
55645b53394SDimitry Andric if (!NullConstantForBase->isNullValue()) {
55745b53394SDimitry Andric llvm::GlobalVariable *NullVariable = new llvm::GlobalVariable(
55845b53394SDimitry Andric CGF.CGM.getModule(), NullConstantForBase->getType(),
55945b53394SDimitry Andric /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage,
56045b53394SDimitry Andric NullConstantForBase, Twine());
56136981b17SDimitry Andric
562145449b1SDimitry Andric CharUnits Align =
563145449b1SDimitry Andric std::max(Layout.getNonVirtualAlignment(), DestPtr.getAlignment());
564519fc96cSDimitry Andric NullVariable->setAlignment(Align.getAsAlign());
56545b53394SDimitry Andric
5667fa27ce4SDimitry Andric Address SrcPtr(NullVariable, CGF.Int8Ty, Align);
56736981b17SDimitry Andric
56836981b17SDimitry Andric // Get and call the appropriate llvm.memcpy overload.
56945b53394SDimitry Andric for (std::pair<CharUnits, CharUnits> Store : Stores) {
57045b53394SDimitry Andric CharUnits StoreOffset = Store.first;
57145b53394SDimitry Andric CharUnits StoreSize = Store.second;
57245b53394SDimitry Andric llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
57345b53394SDimitry Andric CGF.Builder.CreateMemCpy(
57445b53394SDimitry Andric CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
57545b53394SDimitry Andric CGF.Builder.CreateConstInBoundsByteGEP(SrcPtr, StoreOffset),
57645b53394SDimitry Andric StoreSizeVal);
57736981b17SDimitry Andric }
57836981b17SDimitry Andric
57936981b17SDimitry Andric // Otherwise, just memset the whole thing to zero. This is legal
58036981b17SDimitry Andric // because in LLVM, all default initializers (other than the ones we just
58136981b17SDimitry Andric // handled above) are guaranteed to have a bit pattern of all zeros.
58245b53394SDimitry Andric } else {
58345b53394SDimitry Andric for (std::pair<CharUnits, CharUnits> Store : Stores) {
58445b53394SDimitry Andric CharUnits StoreOffset = Store.first;
58545b53394SDimitry Andric CharUnits StoreSize = Store.second;
58645b53394SDimitry Andric llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
58745b53394SDimitry Andric CGF.Builder.CreateMemSet(
58845b53394SDimitry Andric CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
58945b53394SDimitry Andric CGF.Builder.getInt8(0), StoreSizeVal);
59045b53394SDimitry Andric }
59145b53394SDimitry Andric }
59236981b17SDimitry Andric }
59336981b17SDimitry Andric
594ee791ddeSRoman Divacky void
EmitCXXConstructExpr(const CXXConstructExpr * E,AggValueSlot Dest)595bca07a45SDimitry Andric CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
596bca07a45SDimitry Andric AggValueSlot Dest) {
597bca07a45SDimitry Andric assert(!Dest.isIgnored() && "Must have a destination!");
598ee791ddeSRoman Divacky const CXXConstructorDecl *CD = E->getConstructor();
5993d1dcd9bSDimitry Andric
6003d1dcd9bSDimitry Andric // If we require zero initialization before (or instead of) calling the
6013d1dcd9bSDimitry Andric // constructor, as can be the case with a non-user-provided default
60201af97d3SDimitry Andric // constructor, emit the zero initialization now, unless destination is
60301af97d3SDimitry Andric // already zeroed.
60436981b17SDimitry Andric if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
60536981b17SDimitry Andric switch (E->getConstructionKind()) {
606b1c73532SDimitry Andric case CXXConstructionKind::Delegating:
607b1c73532SDimitry Andric case CXXConstructionKind::Complete:
60845b53394SDimitry Andric EmitNullInitialization(Dest.getAddress(), E->getType());
60936981b17SDimitry Andric break;
610b1c73532SDimitry Andric case CXXConstructionKind::VirtualBase:
611b1c73532SDimitry Andric case CXXConstructionKind::NonVirtualBase:
61245b53394SDimitry Andric EmitNullBaseClassInitialization(*this, Dest.getAddress(),
61345b53394SDimitry Andric CD->getParent());
61436981b17SDimitry Andric break;
61536981b17SDimitry Andric }
61636981b17SDimitry Andric }
6173d1dcd9bSDimitry Andric
6183d1dcd9bSDimitry Andric // If this is a call to a trivial default constructor, do nothing.
6193d1dcd9bSDimitry Andric if (CD->isTrivial() && CD->isDefaultConstructor())
620ee791ddeSRoman Divacky return;
6213d1dcd9bSDimitry Andric
622bca07a45SDimitry Andric // Elide the constructor if we're constructing from a temporary.
62313cc256eSDimitry Andric if (getLangOpts().ElideConstructors && E->isElidable()) {
624c0981da4SDimitry Andric // FIXME: This only handles the simplest case, where the source object
625c0981da4SDimitry Andric // is passed directly as the first argument to the constructor.
626c0981da4SDimitry Andric // This should also handle stepping though implicit casts and
627c0981da4SDimitry Andric // conversion sequences which involve two steps, with a
628c0981da4SDimitry Andric // conversion operator followed by a converting constructor.
629c0981da4SDimitry Andric const Expr *SrcObj = E->getArg(0);
630c0981da4SDimitry Andric assert(SrcObj->isTemporaryObject(getContext(), CD->getParent()));
631c0981da4SDimitry Andric assert(
632c0981da4SDimitry Andric getContext().hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
633c0981da4SDimitry Andric EmitAggExpr(SrcObj, Dest);
634ee791ddeSRoman Divacky return;
635ee791ddeSRoman Divacky }
6363d1dcd9bSDimitry Andric
6372b6b257fSDimitry Andric if (const ArrayType *arrayType
6382b6b257fSDimitry Andric = getContext().getAsArrayType(E->getType())) {
639c7e70c43SDimitry Andric EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddress(), E,
640c7e70c43SDimitry Andric Dest.isSanitizerChecked());
641180abc3dSDimitry Andric } else {
64229cafa66SDimitry Andric CXXCtorType Type = Ctor_Complete;
64329cafa66SDimitry Andric bool ForVirtualBase = false;
644809500fcSDimitry Andric bool Delegating = false;
64529cafa66SDimitry Andric
64629cafa66SDimitry Andric switch (E->getConstructionKind()) {
647b1c73532SDimitry Andric case CXXConstructionKind::Delegating:
64801af97d3SDimitry Andric // We should be emitting a constructor; GlobalDecl will assert this
64901af97d3SDimitry Andric Type = CurGD.getCtorType();
650809500fcSDimitry Andric Delegating = true;
65129cafa66SDimitry Andric break;
65201af97d3SDimitry Andric
653b1c73532SDimitry Andric case CXXConstructionKind::Complete:
65429cafa66SDimitry Andric Type = Ctor_Complete;
65529cafa66SDimitry Andric break;
65629cafa66SDimitry Andric
657b1c73532SDimitry Andric case CXXConstructionKind::VirtualBase:
65829cafa66SDimitry Andric ForVirtualBase = true;
659e3b55780SDimitry Andric [[fallthrough]];
66029cafa66SDimitry Andric
661b1c73532SDimitry Andric case CXXConstructionKind::NonVirtualBase:
66229cafa66SDimitry Andric Type = Ctor_Base;
66329cafa66SDimitry Andric }
6640883ccd9SRoman Divacky
665ee791ddeSRoman Divacky // Call the constructor.
66622989816SDimitry Andric EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating, Dest, E);
667ee791ddeSRoman Divacky }
6680883ccd9SRoman Divacky }
669ee791ddeSRoman Divacky
EmitSynthesizedCXXCopyCtor(Address Dest,Address Src,const Expr * Exp)67045b53394SDimitry Andric void CodeGenFunction::EmitSynthesizedCXXCopyCtor(Address Dest, Address Src,
671bca07a45SDimitry Andric const Expr *Exp) {
672bca07a45SDimitry Andric if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
673bca07a45SDimitry Andric Exp = E->getSubExpr();
674bca07a45SDimitry Andric assert(isa<CXXConstructExpr>(Exp) &&
675bca07a45SDimitry Andric "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
676bca07a45SDimitry Andric const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
677bca07a45SDimitry Andric const CXXConstructorDecl *CD = E->getConstructor();
678bca07a45SDimitry Andric RunCleanupsScope Scope(*this);
679bca07a45SDimitry Andric
680bca07a45SDimitry Andric // If we require zero initialization before (or instead of) calling the
681bca07a45SDimitry Andric // constructor, as can be the case with a non-user-provided default
682bca07a45SDimitry Andric // constructor, emit the zero initialization now.
683bca07a45SDimitry Andric // FIXME. Do I still need this for a copy ctor synthesis?
684bca07a45SDimitry Andric if (E->requiresZeroInitialization())
685bca07a45SDimitry Andric EmitNullInitialization(Dest, E->getType());
686bca07a45SDimitry Andric
687bca07a45SDimitry Andric assert(!getContext().getAsConstantArrayType(E->getType())
688bca07a45SDimitry Andric && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
68906d4ba38SDimitry Andric EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E);
690bca07a45SDimitry Andric }
691bca07a45SDimitry Andric
CalculateCookiePadding(CodeGenFunction & CGF,const CXXNewExpr * E)6923d1dcd9bSDimitry Andric static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
6933d1dcd9bSDimitry Andric const CXXNewExpr *E) {
69434d02d0bSRoman Divacky if (!E->isArray())
695ecb7e5c8SRoman Divacky return CharUnits::Zero();
69634d02d0bSRoman Divacky
69729cafa66SDimitry Andric // No cookie is required if the operator new[] being used is the
69829cafa66SDimitry Andric // reserved placement operator new[].
69929cafa66SDimitry Andric if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
700ecb7e5c8SRoman Divacky return CharUnits::Zero();
70134d02d0bSRoman Divacky
702bca07a45SDimitry Andric return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
7034c8b2481SRoman Divacky }
7044c8b2481SRoman Divacky
EmitCXXNewAllocSize(CodeGenFunction & CGF,const CXXNewExpr * e,unsigned minElements,llvm::Value * & numElements,llvm::Value * & sizeWithoutCookie)70529cafa66SDimitry Andric static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
70629cafa66SDimitry Andric const CXXNewExpr *e,
707dbe13110SDimitry Andric unsigned minElements,
70829cafa66SDimitry Andric llvm::Value *&numElements,
70929cafa66SDimitry Andric llvm::Value *&sizeWithoutCookie) {
71029cafa66SDimitry Andric QualType type = e->getAllocatedType();
7114c8b2481SRoman Divacky
71229cafa66SDimitry Andric if (!e->isArray()) {
71329cafa66SDimitry Andric CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
71429cafa66SDimitry Andric sizeWithoutCookie
71529cafa66SDimitry Andric = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
71629cafa66SDimitry Andric return sizeWithoutCookie;
71711d2b2d2SRoman Divacky }
7184c8b2481SRoman Divacky
71929cafa66SDimitry Andric // The width of size_t.
72029cafa66SDimitry Andric unsigned sizeWidth = CGF.SizeTy->getBitWidth();
72129cafa66SDimitry Andric
7223d1dcd9bSDimitry Andric // Figure out the cookie size.
72329cafa66SDimitry Andric llvm::APInt cookieSize(sizeWidth,
72429cafa66SDimitry Andric CalculateCookiePadding(CGF, e).getQuantity());
7254c8b2481SRoman Divacky
7264c8b2481SRoman Divacky // Emit the array size expression.
7273d1dcd9bSDimitry Andric // We multiply the size of all dimensions for NumElements.
7283d1dcd9bSDimitry Andric // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
729461a67faSDimitry Andric numElements =
73022989816SDimitry Andric ConstantEmitter(CGF).tryEmitAbstract(*e->getArraySize(), e->getType());
7317442d6faSDimitry Andric if (!numElements)
73222989816SDimitry Andric numElements = CGF.EmitScalarExpr(*e->getArraySize());
73329cafa66SDimitry Andric assert(isa<llvm::IntegerType>(numElements->getType()));
7344c8b2481SRoman Divacky
73529cafa66SDimitry Andric // The number of elements can be have an arbitrary integer type;
73629cafa66SDimitry Andric // essentially, we need to multiply it by a constant factor, add a
73729cafa66SDimitry Andric // cookie size, and verify that the result is representable as a
73829cafa66SDimitry Andric // size_t. That's just a gloss, though, and it's wrong in one
73929cafa66SDimitry Andric // important way: if the count is negative, it's an error even if
74029cafa66SDimitry Andric // the cookie size would bring the total size >= 0.
74129cafa66SDimitry Andric bool isSigned
74222989816SDimitry Andric = (*e->getArraySize())->getType()->isSignedIntegerOrEnumerationType();
74336981b17SDimitry Andric llvm::IntegerType *numElementsType
74429cafa66SDimitry Andric = cast<llvm::IntegerType>(numElements->getType());
74529cafa66SDimitry Andric unsigned numElementsWidth = numElementsType->getBitWidth();
74629cafa66SDimitry Andric
74729cafa66SDimitry Andric // Compute the constant factor.
74829cafa66SDimitry Andric llvm::APInt arraySizeMultiplier(sizeWidth, 1);
7493d1dcd9bSDimitry Andric while (const ConstantArrayType *CAT
75029cafa66SDimitry Andric = CGF.getContext().getAsConstantArrayType(type)) {
75129cafa66SDimitry Andric type = CAT->getElementType();
75229cafa66SDimitry Andric arraySizeMultiplier *= CAT->getSize();
75311d2b2d2SRoman Divacky }
75411d2b2d2SRoman Divacky
75529cafa66SDimitry Andric CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
75629cafa66SDimitry Andric llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
75729cafa66SDimitry Andric typeSizeMultiplier *= arraySizeMultiplier;
75829cafa66SDimitry Andric
75929cafa66SDimitry Andric // This will be a size_t.
76029cafa66SDimitry Andric llvm::Value *size;
7614c8b2481SRoman Divacky
7623d1dcd9bSDimitry Andric // If someone is doing 'new int[42]' there is no need to do a dynamic check.
7633d1dcd9bSDimitry Andric // Don't bloat the -O0 code.
76429cafa66SDimitry Andric if (llvm::ConstantInt *numElementsC =
76529cafa66SDimitry Andric dyn_cast<llvm::ConstantInt>(numElements)) {
76629cafa66SDimitry Andric const llvm::APInt &count = numElementsC->getValue();
7673d1dcd9bSDimitry Andric
76829cafa66SDimitry Andric bool hasAnyOverflow = false;
7693d1dcd9bSDimitry Andric
77029cafa66SDimitry Andric // If 'count' was a negative number, it's an overflow.
77129cafa66SDimitry Andric if (isSigned && count.isNegative())
77229cafa66SDimitry Andric hasAnyOverflow = true;
7733d1dcd9bSDimitry Andric
77429cafa66SDimitry Andric // We want to do all this arithmetic in size_t. If numElements is
77529cafa66SDimitry Andric // wider than that, check whether it's already too big, and if so,
77629cafa66SDimitry Andric // overflow.
77729cafa66SDimitry Andric else if (numElementsWidth > sizeWidth &&
7787fa27ce4SDimitry Andric numElementsWidth - sizeWidth > count.countl_zero())
77929cafa66SDimitry Andric hasAnyOverflow = true;
78029cafa66SDimitry Andric
78129cafa66SDimitry Andric // Okay, compute a count at the right width.
78229cafa66SDimitry Andric llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
78329cafa66SDimitry Andric
784dbe13110SDimitry Andric // If there is a brace-initializer, we cannot allocate fewer elements than
785dbe13110SDimitry Andric // there are initializers. If we do, that's treated like an overflow.
786dbe13110SDimitry Andric if (adjustedCount.ult(minElements))
787dbe13110SDimitry Andric hasAnyOverflow = true;
788dbe13110SDimitry Andric
78929cafa66SDimitry Andric // Scale numElements by that. This might overflow, but we don't
79029cafa66SDimitry Andric // care because it only overflows if allocationSize does, too, and
79129cafa66SDimitry Andric // if that overflows then we shouldn't use this.
79229cafa66SDimitry Andric numElements = llvm::ConstantInt::get(CGF.SizeTy,
79329cafa66SDimitry Andric adjustedCount * arraySizeMultiplier);
79429cafa66SDimitry Andric
79529cafa66SDimitry Andric // Compute the size before cookie, and track whether it overflowed.
79629cafa66SDimitry Andric bool overflow;
79729cafa66SDimitry Andric llvm::APInt allocationSize
79829cafa66SDimitry Andric = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
79929cafa66SDimitry Andric hasAnyOverflow |= overflow;
80029cafa66SDimitry Andric
80129cafa66SDimitry Andric // Add in the cookie, and check whether it's overflowed.
80229cafa66SDimitry Andric if (cookieSize != 0) {
80329cafa66SDimitry Andric // Save the current size without a cookie. This shouldn't be
80429cafa66SDimitry Andric // used if there was overflow.
80529cafa66SDimitry Andric sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
80629cafa66SDimitry Andric
80729cafa66SDimitry Andric allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
80829cafa66SDimitry Andric hasAnyOverflow |= overflow;
8093d1dcd9bSDimitry Andric }
8103d1dcd9bSDimitry Andric
81129cafa66SDimitry Andric // On overflow, produce a -1 so operator new will fail.
81229cafa66SDimitry Andric if (hasAnyOverflow) {
81329cafa66SDimitry Andric size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
8143d1dcd9bSDimitry Andric } else {
81529cafa66SDimitry Andric size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
8163d1dcd9bSDimitry Andric }
8173d1dcd9bSDimitry Andric
81829cafa66SDimitry Andric // Otherwise, we might need to use the overflow intrinsics.
8193d1dcd9bSDimitry Andric } else {
820dbe13110SDimitry Andric // There are up to five conditions we need to test for:
82129cafa66SDimitry Andric // 1) if isSigned, we need to check whether numElements is negative;
82229cafa66SDimitry Andric // 2) if numElementsWidth > sizeWidth, we need to check whether
82329cafa66SDimitry Andric // numElements is larger than something representable in size_t;
824dbe13110SDimitry Andric // 3) if minElements > 0, we need to check whether numElements is smaller
825dbe13110SDimitry Andric // than that.
826dbe13110SDimitry Andric // 4) we need to compute
82729cafa66SDimitry Andric // sizeWithoutCookie := numElements * typeSizeMultiplier
82829cafa66SDimitry Andric // and check whether it overflows; and
829dbe13110SDimitry Andric // 5) if we need a cookie, we need to compute
83029cafa66SDimitry Andric // size := sizeWithoutCookie + cookieSize
83129cafa66SDimitry Andric // and check whether it overflows.
8323d1dcd9bSDimitry Andric
8339f4dbff6SDimitry Andric llvm::Value *hasOverflow = nullptr;
8343d1dcd9bSDimitry Andric
83529cafa66SDimitry Andric // If numElementsWidth > sizeWidth, then one way or another, we're
83629cafa66SDimitry Andric // going to have to do a comparison for (2), and this happens to
83729cafa66SDimitry Andric // take care of (1), too.
83829cafa66SDimitry Andric if (numElementsWidth > sizeWidth) {
8397fa27ce4SDimitry Andric llvm::APInt threshold =
8407fa27ce4SDimitry Andric llvm::APInt::getOneBitSet(numElementsWidth, sizeWidth);
8413d1dcd9bSDimitry Andric
84229cafa66SDimitry Andric llvm::Value *thresholdV
84329cafa66SDimitry Andric = llvm::ConstantInt::get(numElementsType, threshold);
84429cafa66SDimitry Andric
84529cafa66SDimitry Andric hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
84629cafa66SDimitry Andric numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
84729cafa66SDimitry Andric
84829cafa66SDimitry Andric // Otherwise, if we're signed, we want to sext up to size_t.
84929cafa66SDimitry Andric } else if (isSigned) {
85029cafa66SDimitry Andric if (numElementsWidth < sizeWidth)
85129cafa66SDimitry Andric numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
85229cafa66SDimitry Andric
85329cafa66SDimitry Andric // If there's a non-1 type size multiplier, then we can do the
85429cafa66SDimitry Andric // signedness check at the same time as we do the multiply
85529cafa66SDimitry Andric // because a negative number times anything will cause an
856dbe13110SDimitry Andric // unsigned overflow. Otherwise, we have to do it here. But at least
857dbe13110SDimitry Andric // in this case, we can subsume the >= minElements check.
85829cafa66SDimitry Andric if (typeSizeMultiplier == 1)
85929cafa66SDimitry Andric hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
860dbe13110SDimitry Andric llvm::ConstantInt::get(CGF.SizeTy, minElements));
86129cafa66SDimitry Andric
86229cafa66SDimitry Andric // Otherwise, zext up to size_t if necessary.
86329cafa66SDimitry Andric } else if (numElementsWidth < sizeWidth) {
86429cafa66SDimitry Andric numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
86529cafa66SDimitry Andric }
86629cafa66SDimitry Andric
86729cafa66SDimitry Andric assert(numElements->getType() == CGF.SizeTy);
86829cafa66SDimitry Andric
869dbe13110SDimitry Andric if (minElements) {
870dbe13110SDimitry Andric // Don't allow allocation of fewer elements than we have initializers.
871dbe13110SDimitry Andric if (!hasOverflow) {
872dbe13110SDimitry Andric hasOverflow = CGF.Builder.CreateICmpULT(numElements,
873dbe13110SDimitry Andric llvm::ConstantInt::get(CGF.SizeTy, minElements));
874dbe13110SDimitry Andric } else if (numElementsWidth > sizeWidth) {
875dbe13110SDimitry Andric // The other existing overflow subsumes this check.
876dbe13110SDimitry Andric // We do an unsigned comparison, since any signed value < -1 is
877dbe13110SDimitry Andric // taken care of either above or below.
878dbe13110SDimitry Andric hasOverflow = CGF.Builder.CreateOr(hasOverflow,
879dbe13110SDimitry Andric CGF.Builder.CreateICmpULT(numElements,
880dbe13110SDimitry Andric llvm::ConstantInt::get(CGF.SizeTy, minElements)));
881dbe13110SDimitry Andric }
882dbe13110SDimitry Andric }
883dbe13110SDimitry Andric
88429cafa66SDimitry Andric size = numElements;
88529cafa66SDimitry Andric
88629cafa66SDimitry Andric // Multiply by the type size if necessary. This multiplier
88729cafa66SDimitry Andric // includes all the factors for nested arrays.
8883d1dcd9bSDimitry Andric //
88929cafa66SDimitry Andric // This step also causes numElements to be scaled up by the
89029cafa66SDimitry Andric // nested-array factor if necessary. Overflow on this computation
89129cafa66SDimitry Andric // can be ignored because the result shouldn't be used if
89229cafa66SDimitry Andric // allocation fails.
89329cafa66SDimitry Andric if (typeSizeMultiplier != 1) {
89422989816SDimitry Andric llvm::Function *umul_with_overflow
895180abc3dSDimitry Andric = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
8963d1dcd9bSDimitry Andric
89729cafa66SDimitry Andric llvm::Value *tsmV =
89829cafa66SDimitry Andric llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
89929cafa66SDimitry Andric llvm::Value *result =
9005e20cdd8SDimitry Andric CGF.Builder.CreateCall(umul_with_overflow, {size, tsmV});
9013d1dcd9bSDimitry Andric
90229cafa66SDimitry Andric llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
90329cafa66SDimitry Andric if (hasOverflow)
90429cafa66SDimitry Andric hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
9053d1dcd9bSDimitry Andric else
90629cafa66SDimitry Andric hasOverflow = overflowed;
9073d1dcd9bSDimitry Andric
90829cafa66SDimitry Andric size = CGF.Builder.CreateExtractValue(result, 0);
90929cafa66SDimitry Andric
91029cafa66SDimitry Andric // Also scale up numElements by the array size multiplier.
91129cafa66SDimitry Andric if (arraySizeMultiplier != 1) {
91229cafa66SDimitry Andric // If the base element type size is 1, then we can re-use the
91329cafa66SDimitry Andric // multiply we just did.
91429cafa66SDimitry Andric if (typeSize.isOne()) {
91529cafa66SDimitry Andric assert(arraySizeMultiplier == typeSizeMultiplier);
91629cafa66SDimitry Andric numElements = size;
91729cafa66SDimitry Andric
91829cafa66SDimitry Andric // Otherwise we need a separate multiply.
91929cafa66SDimitry Andric } else {
92029cafa66SDimitry Andric llvm::Value *asmV =
92129cafa66SDimitry Andric llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
92229cafa66SDimitry Andric numElements = CGF.Builder.CreateMul(numElements, asmV);
92329cafa66SDimitry Andric }
92429cafa66SDimitry Andric }
92529cafa66SDimitry Andric } else {
92629cafa66SDimitry Andric // numElements doesn't need to be scaled.
92729cafa66SDimitry Andric assert(arraySizeMultiplier == 1);
92829cafa66SDimitry Andric }
92929cafa66SDimitry Andric
93029cafa66SDimitry Andric // Add in the cookie size if necessary.
93129cafa66SDimitry Andric if (cookieSize != 0) {
93229cafa66SDimitry Andric sizeWithoutCookie = size;
93329cafa66SDimitry Andric
93422989816SDimitry Andric llvm::Function *uadd_with_overflow
935180abc3dSDimitry Andric = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
93629cafa66SDimitry Andric
93729cafa66SDimitry Andric llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
93829cafa66SDimitry Andric llvm::Value *result =
9395e20cdd8SDimitry Andric CGF.Builder.CreateCall(uadd_with_overflow, {size, cookieSizeV});
94029cafa66SDimitry Andric
94129cafa66SDimitry Andric llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
94229cafa66SDimitry Andric if (hasOverflow)
94329cafa66SDimitry Andric hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
94429cafa66SDimitry Andric else
94529cafa66SDimitry Andric hasOverflow = overflowed;
94629cafa66SDimitry Andric
94729cafa66SDimitry Andric size = CGF.Builder.CreateExtractValue(result, 0);
94829cafa66SDimitry Andric }
94929cafa66SDimitry Andric
95029cafa66SDimitry Andric // If we had any possibility of dynamic overflow, make a select to
95129cafa66SDimitry Andric // overwrite 'size' with an all-ones value, which should cause
95229cafa66SDimitry Andric // operator new to throw.
95329cafa66SDimitry Andric if (hasOverflow)
95429cafa66SDimitry Andric size = CGF.Builder.CreateSelect(hasOverflow,
95529cafa66SDimitry Andric llvm::Constant::getAllOnesValue(CGF.SizeTy),
95629cafa66SDimitry Andric size);
95729cafa66SDimitry Andric }
95829cafa66SDimitry Andric
95929cafa66SDimitry Andric if (cookieSize == 0)
96029cafa66SDimitry Andric sizeWithoutCookie = size;
96129cafa66SDimitry Andric else
96229cafa66SDimitry Andric assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
96329cafa66SDimitry Andric
96429cafa66SDimitry Andric return size;
9654c8b2481SRoman Divacky }
9664c8b2481SRoman Divacky
StoreAnyExprIntoOneUnit(CodeGenFunction & CGF,const Expr * Init,QualType AllocType,Address NewPtr,AggValueSlot::Overlap_t MayOverlap)967dbe13110SDimitry Andric static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
96848675466SDimitry Andric QualType AllocType, Address NewPtr,
96948675466SDimitry Andric AggValueSlot::Overlap_t MayOverlap) {
970bfef3995SDimitry Andric // FIXME: Refactor with EmitExprAsInit.
971809500fcSDimitry Andric switch (CGF.getEvaluationKind(AllocType)) {
972809500fcSDimitry Andric case TEK_Scalar:
97306d4ba38SDimitry Andric CGF.EmitScalarInit(Init, nullptr,
97445b53394SDimitry Andric CGF.MakeAddrLValue(NewPtr, AllocType), false);
975809500fcSDimitry Andric return;
976809500fcSDimitry Andric case TEK_Complex:
97745b53394SDimitry Andric CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType),
978809500fcSDimitry Andric /*isInit*/ true);
979809500fcSDimitry Andric return;
980809500fcSDimitry Andric case TEK_Aggregate: {
981bca07a45SDimitry Andric AggValueSlot Slot
98245b53394SDimitry Andric = AggValueSlot::forAddr(NewPtr, AllocType.getQualifiers(),
98336981b17SDimitry Andric AggValueSlot::IsDestructed,
98436981b17SDimitry Andric AggValueSlot::DoesNotNeedGCBarriers,
98548675466SDimitry Andric AggValueSlot::IsNotAliased,
986c7e70c43SDimitry Andric MayOverlap, AggValueSlot::IsNotZeroed,
987c7e70c43SDimitry Andric AggValueSlot::IsSanitizerChecked);
988bca07a45SDimitry Andric CGF.EmitAggExpr(Init, Slot);
989809500fcSDimitry Andric return;
990bca07a45SDimitry Andric }
9914ba67500SRoman Divacky }
992809500fcSDimitry Andric llvm_unreachable("bad evaluation kind");
993809500fcSDimitry Andric }
9944ba67500SRoman Divacky
EmitNewArrayInitializer(const CXXNewExpr * E,QualType ElementType,llvm::Type * ElementTy,Address BeginPtr,llvm::Value * NumElements,llvm::Value * AllocSizeWithoutCookie)9955e20cdd8SDimitry Andric void CodeGenFunction::EmitNewArrayInitializer(
9965e20cdd8SDimitry Andric const CXXNewExpr *E, QualType ElementType, llvm::Type *ElementTy,
99745b53394SDimitry Andric Address BeginPtr, llvm::Value *NumElements,
9989f4dbff6SDimitry Andric llvm::Value *AllocSizeWithoutCookie) {
9999f4dbff6SDimitry Andric // If we have a type with trivial initialization and no initializer,
10009f4dbff6SDimitry Andric // there's nothing to do.
1001dbe13110SDimitry Andric if (!E->hasInitializer())
10029f4dbff6SDimitry Andric return;
10034ba67500SRoman Divacky
100445b53394SDimitry Andric Address CurPtr = BeginPtr;
10054ba67500SRoman Divacky
10069f4dbff6SDimitry Andric unsigned InitListElements = 0;
1007dbe13110SDimitry Andric
1008dbe13110SDimitry Andric const Expr *Init = E->getInitializer();
100945b53394SDimitry Andric Address EndOfInit = Address::invalid();
10109f4dbff6SDimitry Andric QualType::DestructionKind DtorKind = ElementType.isDestructedType();
1011ac9a064cSDimitry Andric CleanupDeactivationScope deactivation(*this);
1012ac9a064cSDimitry Andric bool pushedCleanup = false;
1013bfef3995SDimitry Andric
101445b53394SDimitry Andric CharUnits ElementSize = getContext().getTypeSizeInChars(ElementType);
101545b53394SDimitry Andric CharUnits ElementAlign =
101645b53394SDimitry Andric BeginPtr.getAlignment().alignmentOfArrayElement(ElementSize);
101745b53394SDimitry Andric
1018bab175ecSDimitry Andric // Attempt to perform zero-initialization using memset.
1019bab175ecSDimitry Andric auto TryMemsetInitialization = [&]() -> bool {
1020bab175ecSDimitry Andric // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
1021bab175ecSDimitry Andric // we can initialize with a memset to -1.
1022bab175ecSDimitry Andric if (!CGM.getTypes().isZeroInitializable(ElementType))
1023bab175ecSDimitry Andric return false;
1024bab175ecSDimitry Andric
1025bab175ecSDimitry Andric // Optimization: since zero initialization will just set the memory
1026bab175ecSDimitry Andric // to all zeroes, generate a single memset to do it in one shot.
1027bab175ecSDimitry Andric
1028bab175ecSDimitry Andric // Subtract out the size of any elements we've already initialized.
1029bab175ecSDimitry Andric auto *RemainingSize = AllocSizeWithoutCookie;
1030bab175ecSDimitry Andric if (InitListElements) {
1031bab175ecSDimitry Andric // We know this can't overflow; we check this when doing the allocation.
1032bab175ecSDimitry Andric auto *InitializedSize = llvm::ConstantInt::get(
1033bab175ecSDimitry Andric RemainingSize->getType(),
1034bab175ecSDimitry Andric getContext().getTypeSizeInChars(ElementType).getQuantity() *
1035bab175ecSDimitry Andric InitListElements);
1036bab175ecSDimitry Andric RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
1037bab175ecSDimitry Andric }
1038bab175ecSDimitry Andric
1039bab175ecSDimitry Andric // Create the memset.
1040bab175ecSDimitry Andric Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize, false);
1041bab175ecSDimitry Andric return true;
1042bab175ecSDimitry Andric };
1043bab175ecSDimitry Andric
10444df029ccSDimitry Andric const InitListExpr *ILE = dyn_cast<InitListExpr>(Init);
10454df029ccSDimitry Andric const CXXParenListInitExpr *CPLIE = nullptr;
10464df029ccSDimitry Andric const StringLiteral *SL = nullptr;
10474df029ccSDimitry Andric const ObjCEncodeExpr *OCEE = nullptr;
10484df029ccSDimitry Andric const Expr *IgnoreParen = nullptr;
10494df029ccSDimitry Andric if (!ILE) {
10504df029ccSDimitry Andric IgnoreParen = Init->IgnoreParenImpCasts();
10514df029ccSDimitry Andric CPLIE = dyn_cast<CXXParenListInitExpr>(IgnoreParen);
10524df029ccSDimitry Andric SL = dyn_cast<StringLiteral>(IgnoreParen);
10534df029ccSDimitry Andric OCEE = dyn_cast<ObjCEncodeExpr>(IgnoreParen);
10544df029ccSDimitry Andric }
10554df029ccSDimitry Andric
1056dbe13110SDimitry Andric // If the initializer is an initializer list, first do the explicit elements.
10574df029ccSDimitry Andric if (ILE || CPLIE || SL || OCEE) {
1058bab175ecSDimitry Andric // Initializing from a (braced) string literal is a special case; the init
1059bab175ecSDimitry Andric // list element does not initialize a (single) array element.
10604df029ccSDimitry Andric if ((ILE && ILE->isStringLiteralInit()) || SL || OCEE) {
10614df029ccSDimitry Andric if (!ILE)
10624df029ccSDimitry Andric Init = IgnoreParen;
1063bab175ecSDimitry Andric // Initialize the initial portion of length equal to that of the string
1064bab175ecSDimitry Andric // literal. The allocation must be for at least this much; we emitted a
1065bab175ecSDimitry Andric // check for that earlier.
1066bab175ecSDimitry Andric AggValueSlot Slot =
1067bab175ecSDimitry Andric AggValueSlot::forAddr(CurPtr, ElementType.getQualifiers(),
1068bab175ecSDimitry Andric AggValueSlot::IsDestructed,
1069bab175ecSDimitry Andric AggValueSlot::DoesNotNeedGCBarriers,
107048675466SDimitry Andric AggValueSlot::IsNotAliased,
1071c7e70c43SDimitry Andric AggValueSlot::DoesNotOverlap,
1072c7e70c43SDimitry Andric AggValueSlot::IsNotZeroed,
1073c7e70c43SDimitry Andric AggValueSlot::IsSanitizerChecked);
10744df029ccSDimitry Andric EmitAggExpr(ILE ? ILE->getInit(0) : Init, Slot);
1075bab175ecSDimitry Andric
1076bab175ecSDimitry Andric // Move past these elements.
1077bab175ecSDimitry Andric InitListElements =
10784df029ccSDimitry Andric cast<ConstantArrayType>(Init->getType()->getAsArrayTypeUnsafe())
1079ac9a064cSDimitry Andric ->getZExtSize();
108077fc4c14SDimitry Andric CurPtr = Builder.CreateConstInBoundsGEP(
108177fc4c14SDimitry Andric CurPtr, InitListElements, "string.init.end");
1082bab175ecSDimitry Andric
1083bab175ecSDimitry Andric // Zero out the rest, if any remain.
1084bab175ecSDimitry Andric llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
1085bab175ecSDimitry Andric if (!ConstNum || !ConstNum->equalsInt(InitListElements)) {
1086bab175ecSDimitry Andric bool OK = TryMemsetInitialization();
1087bab175ecSDimitry Andric (void)OK;
1088bab175ecSDimitry Andric assert(OK && "couldn't memset character type?");
1089bab175ecSDimitry Andric }
1090bab175ecSDimitry Andric return;
1091bab175ecSDimitry Andric }
1092bab175ecSDimitry Andric
10934df029ccSDimitry Andric ArrayRef<const Expr *> InitExprs =
10944df029ccSDimitry Andric ILE ? ILE->inits() : CPLIE->getInitExprs();
10954df029ccSDimitry Andric InitListElements = InitExprs.size();
1096dbe13110SDimitry Andric
1097bfef3995SDimitry Andric // If this is a multi-dimensional array new, we will initialize multiple
1098bfef3995SDimitry Andric // elements with each init list element.
1099bfef3995SDimitry Andric QualType AllocType = E->getAllocatedType();
1100bfef3995SDimitry Andric if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
1101bfef3995SDimitry Andric AllocType->getAsArrayTypeUnsafe())) {
11025e20cdd8SDimitry Andric ElementTy = ConvertTypeForMem(AllocType);
11037fa27ce4SDimitry Andric CurPtr = CurPtr.withElementType(ElementTy);
11049f4dbff6SDimitry Andric InitListElements *= getContext().getConstantArrayElementCount(CAT);
1105bfef3995SDimitry Andric }
1106bfef3995SDimitry Andric
11079f4dbff6SDimitry Andric // Enter a partial-destruction Cleanup if necessary.
1108ac9a064cSDimitry Andric if (DtorKind) {
1109ac9a064cSDimitry Andric AllocaTrackerRAII AllocaTracker(*this);
11109f4dbff6SDimitry Andric // In principle we could tell the Cleanup where we are more
1111dbe13110SDimitry Andric // directly, but the control flow can get so varied here that it
1112dbe13110SDimitry Andric // would actually be quite complex. Therefore we go through an
1113dbe13110SDimitry Andric // alloca.
1114ac9a064cSDimitry Andric llvm::Instruction *DominatingIP =
1115ac9a064cSDimitry Andric Builder.CreateFlagLoad(llvm::ConstantInt::getNullValue(Int8PtrTy));
111645b53394SDimitry Andric EndOfInit = CreateTempAlloca(BeginPtr.getType(), getPointerAlign(),
111745b53394SDimitry Andric "array.init.end");
1118ac9a064cSDimitry Andric pushIrregularPartialArrayCleanup(BeginPtr.emitRawPointer(*this),
1119ac9a064cSDimitry Andric EndOfInit, ElementType, ElementAlign,
11209f4dbff6SDimitry Andric getDestroyer(DtorKind));
1121ac9a064cSDimitry Andric cast<EHCleanupScope>(*EHStack.find(EHStack.stable_begin()))
1122ac9a064cSDimitry Andric .AddAuxAllocas(AllocaTracker.Take());
1123ac9a064cSDimitry Andric DeferredDeactivationCleanupStack.push_back(
1124ac9a064cSDimitry Andric {EHStack.stable_begin(), DominatingIP});
1125ac9a064cSDimitry Andric pushedCleanup = true;
1126dbe13110SDimitry Andric }
1127dbe13110SDimitry Andric
112845b53394SDimitry Andric CharUnits StartAlign = CurPtr.getAlignment();
11294df029ccSDimitry Andric unsigned i = 0;
11304df029ccSDimitry Andric for (const Expr *IE : InitExprs) {
1131dbe13110SDimitry Andric // Tell the cleanup that it needs to destroy up to this
1132dbe13110SDimitry Andric // element. TODO: some of these stores can be trivially
1133dbe13110SDimitry Andric // observed to be unnecessary.
113445b53394SDimitry Andric if (EndOfInit.isValid()) {
1135ac9a064cSDimitry Andric Builder.CreateStore(CurPtr.emitRawPointer(*this), EndOfInit);
113645b53394SDimitry Andric }
11379f4dbff6SDimitry Andric // FIXME: If the last initializer is an incomplete initializer list for
11389f4dbff6SDimitry Andric // an array, and we have an array filler, we can fold together the two
11399f4dbff6SDimitry Andric // initialization loops.
11404df029ccSDimitry Andric StoreAnyExprIntoOneUnit(*this, IE, IE->getType(), CurPtr,
114148675466SDimitry Andric AggValueSlot::DoesNotOverlap);
1142ac9a064cSDimitry Andric CurPtr = Address(Builder.CreateInBoundsGEP(CurPtr.getElementType(),
1143ac9a064cSDimitry Andric CurPtr.emitRawPointer(*this),
1144ac9a064cSDimitry Andric Builder.getSize(1),
1145ac9a064cSDimitry Andric "array.exp.next"),
1146ecbca9f5SDimitry Andric CurPtr.getElementType(),
11474df029ccSDimitry Andric StartAlign.alignmentAtOffset((++i) * ElementSize));
1148dbe13110SDimitry Andric }
1149dbe13110SDimitry Andric
1150dbe13110SDimitry Andric // The remaining elements are filled with the array filler expression.
11514df029ccSDimitry Andric Init = ILE ? ILE->getArrayFiller() : CPLIE->getArrayFiller();
1152bfef3995SDimitry Andric
11539f4dbff6SDimitry Andric // Extract the initializer for the individual array elements by pulling
11549f4dbff6SDimitry Andric // out the array filler from all the nested initializer lists. This avoids
11559f4dbff6SDimitry Andric // generating a nested loop for the initialization.
11569f4dbff6SDimitry Andric while (Init && Init->getType()->isConstantArrayType()) {
11579f4dbff6SDimitry Andric auto *SubILE = dyn_cast<InitListExpr>(Init);
11589f4dbff6SDimitry Andric if (!SubILE)
11599f4dbff6SDimitry Andric break;
11609f4dbff6SDimitry Andric assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
11619f4dbff6SDimitry Andric Init = SubILE->getArrayFiller();
1162dbe13110SDimitry Andric }
1163dbe13110SDimitry Andric
11649f4dbff6SDimitry Andric // Switch back to initializing one base element at a time.
11657fa27ce4SDimitry Andric CurPtr = CurPtr.withElementType(BeginPtr.getElementType());
11669f4dbff6SDimitry Andric }
11674ba67500SRoman Divacky
11689f4dbff6SDimitry Andric // If all elements have already been initialized, skip any further
11699f4dbff6SDimitry Andric // initialization.
11709f4dbff6SDimitry Andric llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
11719f4dbff6SDimitry Andric if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
1172dbe13110SDimitry Andric return;
1173dbe13110SDimitry Andric }
11744ba67500SRoman Divacky
11759f4dbff6SDimitry Andric assert(Init && "have trailing elements to initialize but no initializer");
11764ba67500SRoman Divacky
11779f4dbff6SDimitry Andric // If this is a constructor call, try to optimize it out, and failing that
11789f4dbff6SDimitry Andric // emit a single loop to initialize all remaining elements.
11799f4dbff6SDimitry Andric if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
1180dbe13110SDimitry Andric CXXConstructorDecl *Ctor = CCE->getConstructor();
1181dbe13110SDimitry Andric if (Ctor->isTrivial()) {
11823d1dcd9bSDimitry Andric // If new expression did not specify value-initialization, then there
11833d1dcd9bSDimitry Andric // is no initialization.
1184dbe13110SDimitry Andric if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
11853d1dcd9bSDimitry Andric return;
11863d1dcd9bSDimitry Andric
11879f4dbff6SDimitry Andric if (TryMemsetInitialization())
11881569ce68SRoman Divacky return;
11891569ce68SRoman Divacky }
11903d1dcd9bSDimitry Andric
11919f4dbff6SDimitry Andric // Store the new Cleanup position for irregular Cleanups.
11929f4dbff6SDimitry Andric //
11939f4dbff6SDimitry Andric // FIXME: Share this cleanup with the constructor call emission rather than
11949f4dbff6SDimitry Andric // having it create a cleanup of its own.
119545b53394SDimitry Andric if (EndOfInit.isValid())
1196ac9a064cSDimitry Andric Builder.CreateStore(CurPtr.emitRawPointer(*this), EndOfInit);
11979f4dbff6SDimitry Andric
11989f4dbff6SDimitry Andric // Emit a constructor call loop to initialize the remaining elements.
11999f4dbff6SDimitry Andric if (InitListElements)
12009f4dbff6SDimitry Andric NumElements = Builder.CreateSub(
12019f4dbff6SDimitry Andric NumElements,
12029f4dbff6SDimitry Andric llvm::ConstantInt::get(NumElements->getType(), InitListElements));
120306d4ba38SDimitry Andric EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,
1204c7e70c43SDimitry Andric /*NewPointerIsChecked*/true,
120513cc256eSDimitry Andric CCE->requiresZeroInitialization());
12063d1dcd9bSDimitry Andric return;
12074ba67500SRoman Divacky }
12081569ce68SRoman Divacky
12099f4dbff6SDimitry Andric // If this is value-initialization, we can usually use memset.
12109f4dbff6SDimitry Andric ImplicitValueInitExpr IVIE(ElementType);
12119f4dbff6SDimitry Andric if (isa<ImplicitValueInitExpr>(Init)) {
12129f4dbff6SDimitry Andric if (TryMemsetInitialization())
12134c8b2481SRoman Divacky return;
12144c8b2481SRoman Divacky
12159f4dbff6SDimitry Andric // Switch to an ImplicitValueInitExpr for the element type. This handles
12169f4dbff6SDimitry Andric // only one case: multidimensional array new of pointers to members. In
12179f4dbff6SDimitry Andric // all other cases, we already have an initializer for the array element.
12189f4dbff6SDimitry Andric Init = &IVIE;
12199f4dbff6SDimitry Andric }
12209f4dbff6SDimitry Andric
12219f4dbff6SDimitry Andric // At this point we should have found an initializer for the individual
12229f4dbff6SDimitry Andric // elements of the array.
12239f4dbff6SDimitry Andric assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&
12249f4dbff6SDimitry Andric "got wrong type of element to initialize");
12259f4dbff6SDimitry Andric
12269f4dbff6SDimitry Andric // If we have an empty initializer list, we can usually use memset.
12279f4dbff6SDimitry Andric if (auto *ILE = dyn_cast<InitListExpr>(Init))
12289f4dbff6SDimitry Andric if (ILE->getNumInits() == 0 && TryMemsetInitialization())
12299f4dbff6SDimitry Andric return;
12309f4dbff6SDimitry Andric
12312e645aa5SDimitry Andric // If we have a struct whose every field is value-initialized, we can
12322e645aa5SDimitry Andric // usually use memset.
12332e645aa5SDimitry Andric if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
12342e645aa5SDimitry Andric if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
12352e645aa5SDimitry Andric if (RType->getDecl()->isStruct()) {
12362b6b257fSDimitry Andric unsigned NumElements = 0;
12372b6b257fSDimitry Andric if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RType->getDecl()))
12382b6b257fSDimitry Andric NumElements = CXXRD->getNumBases();
12392e645aa5SDimitry Andric for (auto *Field : RType->getDecl()->fields())
1240ac9a064cSDimitry Andric if (!Field->isUnnamedBitField())
12412b6b257fSDimitry Andric ++NumElements;
12422b6b257fSDimitry Andric // FIXME: Recurse into nested InitListExprs.
12432b6b257fSDimitry Andric if (ILE->getNumInits() == NumElements)
12442e645aa5SDimitry Andric for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
12452e645aa5SDimitry Andric if (!isa<ImplicitValueInitExpr>(ILE->getInit(i)))
12462b6b257fSDimitry Andric --NumElements;
12472b6b257fSDimitry Andric if (ILE->getNumInits() == NumElements && TryMemsetInitialization())
12482e645aa5SDimitry Andric return;
12492e645aa5SDimitry Andric }
12502e645aa5SDimitry Andric }
12512e645aa5SDimitry Andric }
12522e645aa5SDimitry Andric
12539f4dbff6SDimitry Andric // Create the loop blocks.
12549f4dbff6SDimitry Andric llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
12559f4dbff6SDimitry Andric llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
12569f4dbff6SDimitry Andric llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
12579f4dbff6SDimitry Andric
12589f4dbff6SDimitry Andric // Find the end of the array, hoisted out of the loop.
1259ac9a064cSDimitry Andric llvm::Value *EndPtr = Builder.CreateInBoundsGEP(
1260ac9a064cSDimitry Andric BeginPtr.getElementType(), BeginPtr.emitRawPointer(*this), NumElements,
1261ac9a064cSDimitry Andric "array.end");
12629f4dbff6SDimitry Andric
12639f4dbff6SDimitry Andric // If the number of elements isn't constant, we have to now check if there is
12649f4dbff6SDimitry Andric // anything left to initialize.
12659f4dbff6SDimitry Andric if (!ConstNum) {
1266ac9a064cSDimitry Andric llvm::Value *IsEmpty = Builder.CreateICmpEQ(CurPtr.emitRawPointer(*this),
1267ac9a064cSDimitry Andric EndPtr, "array.isempty");
12689f4dbff6SDimitry Andric Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
12699f4dbff6SDimitry Andric }
12709f4dbff6SDimitry Andric
12719f4dbff6SDimitry Andric // Enter the loop.
12729f4dbff6SDimitry Andric EmitBlock(LoopBB);
12739f4dbff6SDimitry Andric
12749f4dbff6SDimitry Andric // Set up the current-element phi.
12759f4dbff6SDimitry Andric llvm::PHINode *CurPtrPhi =
127645b53394SDimitry Andric Builder.CreatePHI(CurPtr.getType(), 2, "array.cur");
1277ac9a064cSDimitry Andric CurPtrPhi->addIncoming(CurPtr.emitRawPointer(*this), EntryBB);
127845b53394SDimitry Andric
1279145449b1SDimitry Andric CurPtr = Address(CurPtrPhi, CurPtr.getElementType(), ElementAlign);
12809f4dbff6SDimitry Andric
12819f4dbff6SDimitry Andric // Store the new Cleanup position for irregular Cleanups.
128245b53394SDimitry Andric if (EndOfInit.isValid())
1283ac9a064cSDimitry Andric Builder.CreateStore(CurPtr.emitRawPointer(*this), EndOfInit);
12849f4dbff6SDimitry Andric
12859f4dbff6SDimitry Andric // Enter a partial-destruction Cleanup if necessary.
1286ac9a064cSDimitry Andric if (!pushedCleanup && needsEHCleanup(DtorKind)) {
1287ac9a064cSDimitry Andric llvm::Instruction *DominatingIP =
1288ac9a064cSDimitry Andric Builder.CreateFlagLoad(llvm::ConstantInt::getNullValue(Int8PtrTy));
1289ac9a064cSDimitry Andric pushRegularPartialArrayCleanup(BeginPtr.emitRawPointer(*this),
1290ac9a064cSDimitry Andric CurPtr.emitRawPointer(*this), ElementType,
1291ac9a064cSDimitry Andric ElementAlign, getDestroyer(DtorKind));
1292ac9a064cSDimitry Andric DeferredDeactivationCleanupStack.push_back(
1293ac9a064cSDimitry Andric {EHStack.stable_begin(), DominatingIP});
12949f4dbff6SDimitry Andric }
12959f4dbff6SDimitry Andric
12969f4dbff6SDimitry Andric // Emit the initializer into this element.
129748675466SDimitry Andric StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr,
129848675466SDimitry Andric AggValueSlot::DoesNotOverlap);
12999f4dbff6SDimitry Andric
13009f4dbff6SDimitry Andric // Leave the Cleanup if we entered one.
1301ac9a064cSDimitry Andric deactivation.ForceDeactivate();
13029f4dbff6SDimitry Andric
13039f4dbff6SDimitry Andric // Advance to the next element by adjusting the pointer type as necessary.
1304ac9a064cSDimitry Andric llvm::Value *NextPtr = Builder.CreateConstInBoundsGEP1_32(
1305ac9a064cSDimitry Andric ElementTy, CurPtr.emitRawPointer(*this), 1, "array.next");
13069f4dbff6SDimitry Andric
13079f4dbff6SDimitry Andric // Check whether we've gotten to the end of the array and, if so,
13089f4dbff6SDimitry Andric // exit the loop.
13099f4dbff6SDimitry Andric llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
13109f4dbff6SDimitry Andric Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
13119f4dbff6SDimitry Andric CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
13129f4dbff6SDimitry Andric
13139f4dbff6SDimitry Andric EmitBlock(ContBB);
13149f4dbff6SDimitry Andric }
13159f4dbff6SDimitry Andric
EmitNewInitializer(CodeGenFunction & CGF,const CXXNewExpr * E,QualType ElementType,llvm::Type * ElementTy,Address NewPtr,llvm::Value * NumElements,llvm::Value * AllocSizeWithoutCookie)13169f4dbff6SDimitry Andric static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
13175e20cdd8SDimitry Andric QualType ElementType, llvm::Type *ElementTy,
131845b53394SDimitry Andric Address NewPtr, llvm::Value *NumElements,
13199f4dbff6SDimitry Andric llvm::Value *AllocSizeWithoutCookie) {
13205e20cdd8SDimitry Andric ApplyDebugLocation DL(CGF, E);
13219f4dbff6SDimitry Andric if (E->isArray())
13225e20cdd8SDimitry Andric CGF.EmitNewArrayInitializer(E, ElementType, ElementTy, NewPtr, NumElements,
13239f4dbff6SDimitry Andric AllocSizeWithoutCookie);
13249f4dbff6SDimitry Andric else if (const Expr *Init = E->getInitializer())
132548675466SDimitry Andric StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr,
132648675466SDimitry Andric AggValueSlot::DoesNotOverlap);
13274c8b2481SRoman Divacky }
13284c8b2481SRoman Divacky
1329bfef3995SDimitry Andric /// Emit a call to an operator new or operator delete function, as implicitly
1330bfef3995SDimitry Andric /// created by new-expressions and delete-expressions.
EmitNewDeleteCall(CodeGenFunction & CGF,const FunctionDecl * CalleeDecl,const FunctionProtoType * CalleeType,const CallArgList & Args)1331bfef3995SDimitry Andric static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
1332bab175ecSDimitry Andric const FunctionDecl *CalleeDecl,
1333bfef3995SDimitry Andric const FunctionProtoType *CalleeType,
1334bfef3995SDimitry Andric const CallArgList &Args) {
133522989816SDimitry Andric llvm::CallBase *CallOrInvoke;
1336bab175ecSDimitry Andric llvm::Constant *CalleePtr = CGF.CGM.GetAddrOfFunction(CalleeDecl);
1337676fbe81SDimitry Andric CGCallee Callee = CGCallee::forDirect(CalleePtr, GlobalDecl(CalleeDecl));
1338bfef3995SDimitry Andric RValue RV =
133906d4ba38SDimitry Andric CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(
134022989816SDimitry Andric Args, CalleeType, /*ChainCall=*/false),
1341bab175ecSDimitry Andric Callee, ReturnValueSlot(), Args, &CallOrInvoke);
1342bfef3995SDimitry Andric
1343bfef3995SDimitry Andric /// C++1y [expr.new]p10:
1344bfef3995SDimitry Andric /// [In a new-expression,] an implementation is allowed to omit a call
1345bfef3995SDimitry Andric /// to a replaceable global allocation function.
1346bfef3995SDimitry Andric ///
1347bfef3995SDimitry Andric /// We model such elidable calls with the 'builtin' attribute.
1348bab175ecSDimitry Andric llvm::Function *Fn = dyn_cast<llvm::Function>(CalleePtr);
1349bab175ecSDimitry Andric if (CalleeDecl->isReplaceableGlobalAllocationFunction() &&
1350bfef3995SDimitry Andric Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
1351c0981da4SDimitry Andric CallOrInvoke->addFnAttr(llvm::Attribute::Builtin);
1352bfef3995SDimitry Andric }
1353bfef3995SDimitry Andric
1354bfef3995SDimitry Andric return RV;
1355bfef3995SDimitry Andric }
1356bfef3995SDimitry Andric
EmitBuiltinNewDeleteCall(const FunctionProtoType * Type,const CallExpr * TheCall,bool IsDelete)13579f4dbff6SDimitry Andric RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
135848675466SDimitry Andric const CallExpr *TheCall,
13599f4dbff6SDimitry Andric bool IsDelete) {
13609f4dbff6SDimitry Andric CallArgList Args;
1361b60736ecSDimitry Andric EmitCallArgs(Args, Type, TheCall->arguments());
13629f4dbff6SDimitry Andric // Find the allocation or deallocation function that we're calling.
13639f4dbff6SDimitry Andric ASTContext &Ctx = getContext();
13649f4dbff6SDimitry Andric DeclarationName Name = Ctx.DeclarationNames
13659f4dbff6SDimitry Andric .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
136648675466SDimitry Andric
13679f4dbff6SDimitry Andric for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
13689f4dbff6SDimitry Andric if (auto *FD = dyn_cast<FunctionDecl>(Decl))
13699f4dbff6SDimitry Andric if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
137048675466SDimitry Andric return EmitNewDeleteCall(*this, FD, Type, Args);
13719f4dbff6SDimitry Andric llvm_unreachable("predeclared global operator new/delete is missing");
13729f4dbff6SDimitry Andric }
13739f4dbff6SDimitry Andric
1374461a67faSDimitry Andric namespace {
1375461a67faSDimitry Andric /// The parameters to pass to a usual operator delete.
1376461a67faSDimitry Andric struct UsualDeleteParams {
1377461a67faSDimitry Andric bool DestroyingDelete = false;
1378461a67faSDimitry Andric bool Size = false;
1379461a67faSDimitry Andric bool Alignment = false;
1380461a67faSDimitry Andric };
1381461a67faSDimitry Andric }
1382461a67faSDimitry Andric
getUsualDeleteParams(const FunctionDecl * FD)1383461a67faSDimitry Andric static UsualDeleteParams getUsualDeleteParams(const FunctionDecl *FD) {
1384461a67faSDimitry Andric UsualDeleteParams Params;
1385461a67faSDimitry Andric
1386461a67faSDimitry Andric const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
1387bab175ecSDimitry Andric auto AI = FPT->param_type_begin(), AE = FPT->param_type_end();
1388bca07a45SDimitry Andric
1389bab175ecSDimitry Andric // The first argument is always a void*.
1390bab175ecSDimitry Andric ++AI;
1391bab175ecSDimitry Andric
1392461a67faSDimitry Andric // The next parameter may be a std::destroying_delete_t.
1393461a67faSDimitry Andric if (FD->isDestroyingOperatorDelete()) {
1394461a67faSDimitry Andric Params.DestroyingDelete = true;
1395461a67faSDimitry Andric assert(AI != AE);
1396461a67faSDimitry Andric ++AI;
1397461a67faSDimitry Andric }
1398bab175ecSDimitry Andric
1399461a67faSDimitry Andric // Figure out what other parameters we should be implicitly passing.
1400bab175ecSDimitry Andric if (AI != AE && (*AI)->isIntegerType()) {
1401461a67faSDimitry Andric Params.Size = true;
1402bab175ecSDimitry Andric ++AI;
1403bab175ecSDimitry Andric }
1404bab175ecSDimitry Andric
1405bab175ecSDimitry Andric if (AI != AE && (*AI)->isAlignValT()) {
1406461a67faSDimitry Andric Params.Alignment = true;
1407bab175ecSDimitry Andric ++AI;
1408bab175ecSDimitry Andric }
1409bab175ecSDimitry Andric
1410bab175ecSDimitry Andric assert(AI == AE && "unexpected usual deallocation function parameter");
1411461a67faSDimitry Andric return Params;
1412bab175ecSDimitry Andric }
1413bab175ecSDimitry Andric
1414bab175ecSDimitry Andric namespace {
1415bab175ecSDimitry Andric /// A cleanup to call the given 'operator delete' function upon abnormal
1416bab175ecSDimitry Andric /// exit from a new expression. Templated on a traits type that deals with
1417bab175ecSDimitry Andric /// ensuring that the arguments dominate the cleanup if necessary.
1418bab175ecSDimitry Andric template<typename Traits>
1419bab175ecSDimitry Andric class CallDeleteDuringNew final : public EHScopeStack::Cleanup {
1420bab175ecSDimitry Andric /// Type used to hold llvm::Value*s.
1421bab175ecSDimitry Andric typedef typename Traits::ValueTy ValueTy;
1422bab175ecSDimitry Andric /// Type used to hold RValues.
1423bab175ecSDimitry Andric typedef typename Traits::RValueTy RValueTy;
1424bab175ecSDimitry Andric struct PlacementArg {
1425bab175ecSDimitry Andric RValueTy ArgValue;
1426bab175ecSDimitry Andric QualType ArgType;
1427bab175ecSDimitry Andric };
1428bab175ecSDimitry Andric
1429bab175ecSDimitry Andric unsigned NumPlacementArgs : 31;
1430ac9a064cSDimitry Andric LLVM_PREFERRED_TYPE(bool)
1431bab175ecSDimitry Andric unsigned PassAlignmentToPlacementDelete : 1;
1432bab175ecSDimitry Andric const FunctionDecl *OperatorDelete;
1433bab175ecSDimitry Andric ValueTy Ptr;
1434bab175ecSDimitry Andric ValueTy AllocSize;
1435bab175ecSDimitry Andric CharUnits AllocAlign;
1436bab175ecSDimitry Andric
getPlacementArgs()1437bab175ecSDimitry Andric PlacementArg *getPlacementArgs() {
1438bab175ecSDimitry Andric return reinterpret_cast<PlacementArg *>(this + 1);
1439bab175ecSDimitry Andric }
1440bca07a45SDimitry Andric
1441bca07a45SDimitry Andric public:
getExtraSize(size_t NumPlacementArgs)1442bca07a45SDimitry Andric static size_t getExtraSize(size_t NumPlacementArgs) {
1443bab175ecSDimitry Andric return NumPlacementArgs * sizeof(PlacementArg);
1444bca07a45SDimitry Andric }
1445bca07a45SDimitry Andric
CallDeleteDuringNew(size_t NumPlacementArgs,const FunctionDecl * OperatorDelete,ValueTy Ptr,ValueTy AllocSize,bool PassAlignmentToPlacementDelete,CharUnits AllocAlign)1446bca07a45SDimitry Andric CallDeleteDuringNew(size_t NumPlacementArgs,
1447bab175ecSDimitry Andric const FunctionDecl *OperatorDelete, ValueTy Ptr,
1448bab175ecSDimitry Andric ValueTy AllocSize, bool PassAlignmentToPlacementDelete,
1449bab175ecSDimitry Andric CharUnits AllocAlign)
1450bab175ecSDimitry Andric : NumPlacementArgs(NumPlacementArgs),
1451bab175ecSDimitry Andric PassAlignmentToPlacementDelete(PassAlignmentToPlacementDelete),
1452bab175ecSDimitry Andric OperatorDelete(OperatorDelete), Ptr(Ptr), AllocSize(AllocSize),
1453bab175ecSDimitry Andric AllocAlign(AllocAlign) {}
1454bca07a45SDimitry Andric
setPlacementArg(unsigned I,RValueTy Arg,QualType Type)1455bab175ecSDimitry Andric void setPlacementArg(unsigned I, RValueTy Arg, QualType Type) {
1456bca07a45SDimitry Andric assert(I < NumPlacementArgs && "index out of range");
1457bab175ecSDimitry Andric getPlacementArgs()[I] = {Arg, Type};
1458bca07a45SDimitry Andric }
1459bca07a45SDimitry Andric
Emit(CodeGenFunction & CGF,Flags flags)14609f4dbff6SDimitry Andric void Emit(CodeGenFunction &CGF, Flags flags) override {
1461706b4fc4SDimitry Andric const auto *FPT = OperatorDelete->getType()->castAs<FunctionProtoType>();
1462bca07a45SDimitry Andric CallArgList DeleteArgs;
1463bca07a45SDimitry Andric
1464461a67faSDimitry Andric // The first argument is always a void* (or C* for a destroying operator
1465461a67faSDimitry Andric // delete for class type C).
1466bab175ecSDimitry Andric DeleteArgs.add(Traits::get(CGF, Ptr), FPT->getParamType(0));
1467bca07a45SDimitry Andric
1468bab175ecSDimitry Andric // Figure out what other parameters we should be implicitly passing.
1469461a67faSDimitry Andric UsualDeleteParams Params;
1470bab175ecSDimitry Andric if (NumPlacementArgs) {
1471bab175ecSDimitry Andric // A placement deallocation function is implicitly passed an alignment
1472bab175ecSDimitry Andric // if the placement allocation function was, but is never passed a size.
1473461a67faSDimitry Andric Params.Alignment = PassAlignmentToPlacementDelete;
1474bab175ecSDimitry Andric } else {
1475bab175ecSDimitry Andric // For a non-placement new-expression, 'operator delete' can take a
1476bab175ecSDimitry Andric // size and/or an alignment if it has the right parameters.
1477461a67faSDimitry Andric Params = getUsualDeleteParams(OperatorDelete);
1478bca07a45SDimitry Andric }
1479bca07a45SDimitry Andric
1480461a67faSDimitry Andric assert(!Params.DestroyingDelete &&
1481461a67faSDimitry Andric "should not call destroying delete in a new-expression");
1482461a67faSDimitry Andric
1483bab175ecSDimitry Andric // The second argument can be a std::size_t (for non-placement delete).
1484461a67faSDimitry Andric if (Params.Size)
1485bab175ecSDimitry Andric DeleteArgs.add(Traits::get(CGF, AllocSize),
1486bab175ecSDimitry Andric CGF.getContext().getSizeType());
1487bca07a45SDimitry Andric
1488bab175ecSDimitry Andric // The next (second or third) argument can be a std::align_val_t, which
1489bab175ecSDimitry Andric // is an enum whose underlying type is std::size_t.
1490bab175ecSDimitry Andric // FIXME: Use the right type as the parameter type. Note that in a call
1491bab175ecSDimitry Andric // to operator delete(size_t, ...), we may not have it available.
1492461a67faSDimitry Andric if (Params.Alignment)
1493bab175ecSDimitry Andric DeleteArgs.add(RValue::get(llvm::ConstantInt::get(
1494bab175ecSDimitry Andric CGF.SizeTy, AllocAlign.getQuantity())),
1495bab175ecSDimitry Andric CGF.getContext().getSizeType());
1496bca07a45SDimitry Andric
1497bca07a45SDimitry Andric // Pass the rest of the arguments, which must match exactly.
1498bca07a45SDimitry Andric for (unsigned I = 0; I != NumPlacementArgs; ++I) {
1499bab175ecSDimitry Andric auto Arg = getPlacementArgs()[I];
1500bab175ecSDimitry Andric DeleteArgs.add(Traits::get(CGF, Arg.ArgValue), Arg.ArgType);
1501bca07a45SDimitry Andric }
1502bca07a45SDimitry Andric
1503bca07a45SDimitry Andric // Call 'operator delete'.
1504bfef3995SDimitry Andric EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
1505bca07a45SDimitry Andric }
1506bca07a45SDimitry Andric };
1507bca07a45SDimitry Andric }
1508bca07a45SDimitry Andric
1509bca07a45SDimitry Andric /// Enter a cleanup to call 'operator delete' if the initializer in a
1510bca07a45SDimitry Andric /// new-expression throws.
EnterNewDeleteCleanup(CodeGenFunction & CGF,const CXXNewExpr * E,Address NewPtr,llvm::Value * AllocSize,CharUnits AllocAlign,const CallArgList & NewArgs)1511bca07a45SDimitry Andric static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1512bca07a45SDimitry Andric const CXXNewExpr *E,
151345b53394SDimitry Andric Address NewPtr,
1514bca07a45SDimitry Andric llvm::Value *AllocSize,
1515bab175ecSDimitry Andric CharUnits AllocAlign,
1516bca07a45SDimitry Andric const CallArgList &NewArgs) {
1517bab175ecSDimitry Andric unsigned NumNonPlacementArgs = E->passAlignment() ? 2 : 1;
1518bab175ecSDimitry Andric
1519bca07a45SDimitry Andric // If we're not inside a conditional branch, then the cleanup will
1520bca07a45SDimitry Andric // dominate and we can do the easier (and more efficient) thing.
1521bca07a45SDimitry Andric if (!CGF.isInConditionalBranch()) {
1522bab175ecSDimitry Andric struct DirectCleanupTraits {
1523bab175ecSDimitry Andric typedef llvm::Value *ValueTy;
1524bab175ecSDimitry Andric typedef RValue RValueTy;
1525bab175ecSDimitry Andric static RValue get(CodeGenFunction &, ValueTy V) { return RValue::get(V); }
1526bab175ecSDimitry Andric static RValue get(CodeGenFunction &, RValueTy V) { return V; }
1527bab175ecSDimitry Andric };
1528bab175ecSDimitry Andric
1529bab175ecSDimitry Andric typedef CallDeleteDuringNew<DirectCleanupTraits> DirectCleanup;
1530bab175ecSDimitry Andric
1531ac9a064cSDimitry Andric DirectCleanup *Cleanup = CGF.EHStack.pushCleanupWithExtra<DirectCleanup>(
1532ac9a064cSDimitry Andric EHCleanup, E->getNumPlacementArgs(), E->getOperatorDelete(),
1533ac9a064cSDimitry Andric NewPtr.emitRawPointer(CGF), AllocSize, E->passAlignment(), AllocAlign);
1534bab175ecSDimitry Andric for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
1535bab175ecSDimitry Andric auto &Arg = NewArgs[I + NumNonPlacementArgs];
153648675466SDimitry Andric Cleanup->setPlacementArg(I, Arg.getRValue(CGF), Arg.Ty);
1537bab175ecSDimitry Andric }
1538bca07a45SDimitry Andric
1539bca07a45SDimitry Andric return;
1540bca07a45SDimitry Andric }
1541bca07a45SDimitry Andric
1542bca07a45SDimitry Andric // Otherwise, we need to save all this stuff.
1543bca07a45SDimitry Andric DominatingValue<RValue>::saved_type SavedNewPtr =
1544ac9a064cSDimitry Andric DominatingValue<RValue>::save(CGF, RValue::get(NewPtr, CGF));
1545bca07a45SDimitry Andric DominatingValue<RValue>::saved_type SavedAllocSize =
1546bca07a45SDimitry Andric DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
1547bca07a45SDimitry Andric
1548bab175ecSDimitry Andric struct ConditionalCleanupTraits {
1549bab175ecSDimitry Andric typedef DominatingValue<RValue>::saved_type ValueTy;
1550bab175ecSDimitry Andric typedef DominatingValue<RValue>::saved_type RValueTy;
1551bab175ecSDimitry Andric static RValue get(CodeGenFunction &CGF, ValueTy V) {
1552bab175ecSDimitry Andric return V.restore(CGF);
1553bab175ecSDimitry Andric }
1554bab175ecSDimitry Andric };
1555bab175ecSDimitry Andric typedef CallDeleteDuringNew<ConditionalCleanupTraits> ConditionalCleanup;
1556bab175ecSDimitry Andric
1557bab175ecSDimitry Andric ConditionalCleanup *Cleanup = CGF.EHStack
1558bab175ecSDimitry Andric .pushCleanupWithExtra<ConditionalCleanup>(EHCleanup,
1559bca07a45SDimitry Andric E->getNumPlacementArgs(),
1560bca07a45SDimitry Andric E->getOperatorDelete(),
1561bca07a45SDimitry Andric SavedNewPtr,
1562bab175ecSDimitry Andric SavedAllocSize,
1563bab175ecSDimitry Andric E->passAlignment(),
1564bab175ecSDimitry Andric AllocAlign);
1565bab175ecSDimitry Andric for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
1566bab175ecSDimitry Andric auto &Arg = NewArgs[I + NumNonPlacementArgs];
156748675466SDimitry Andric Cleanup->setPlacementArg(
156848675466SDimitry Andric I, DominatingValue<RValue>::save(CGF, Arg.getRValue(CGF)), Arg.Ty);
1569bab175ecSDimitry Andric }
1570bca07a45SDimitry Andric
1571dbe13110SDimitry Andric CGF.initFullExprCleanup();
1572bca07a45SDimitry Andric }
1573bca07a45SDimitry Andric
EmitCXXNewExpr(const CXXNewExpr * E)15744c8b2481SRoman Divacky llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
157501af97d3SDimitry Andric // The element type being allocated.
157601af97d3SDimitry Andric QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
15773d1dcd9bSDimitry Andric
157801af97d3SDimitry Andric // 1. Build a call to the allocation function.
157901af97d3SDimitry Andric FunctionDecl *allocator = E->getOperatorNew();
15804c8b2481SRoman Divacky
15814df029ccSDimitry Andric // If there is a brace-initializer or C++20 parenthesized initializer, cannot
15824df029ccSDimitry Andric // allocate fewer elements than inits.
1583dbe13110SDimitry Andric unsigned minElements = 0;
1584dbe13110SDimitry Andric if (E->isArray() && E->hasInitializer()) {
15854df029ccSDimitry Andric const Expr *Init = E->getInitializer();
15864df029ccSDimitry Andric const InitListExpr *ILE = dyn_cast<InitListExpr>(Init);
15874df029ccSDimitry Andric const CXXParenListInitExpr *CPLIE = dyn_cast<CXXParenListInitExpr>(Init);
15884df029ccSDimitry Andric const Expr *IgnoreParen = Init->IgnoreParenImpCasts();
15894df029ccSDimitry Andric if ((ILE && ILE->isStringLiteralInit()) ||
15904df029ccSDimitry Andric isa<StringLiteral>(IgnoreParen) || isa<ObjCEncodeExpr>(IgnoreParen)) {
1591bab175ecSDimitry Andric minElements =
15924df029ccSDimitry Andric cast<ConstantArrayType>(Init->getType()->getAsArrayTypeUnsafe())
1593ac9a064cSDimitry Andric ->getZExtSize();
15944df029ccSDimitry Andric } else if (ILE || CPLIE) {
15954df029ccSDimitry Andric minElements = ILE ? ILE->getNumInits() : CPLIE->getInitExprs().size();
15964df029ccSDimitry Andric }
1597dbe13110SDimitry Andric }
1598dbe13110SDimitry Andric
15999f4dbff6SDimitry Andric llvm::Value *numElements = nullptr;
16009f4dbff6SDimitry Andric llvm::Value *allocSizeWithoutCookie = nullptr;
160101af97d3SDimitry Andric llvm::Value *allocSize =
1602dbe13110SDimitry Andric EmitCXXNewAllocSize(*this, E, minElements, numElements,
1603dbe13110SDimitry Andric allocSizeWithoutCookie);
1604145449b1SDimitry Andric CharUnits allocAlign = getContext().getTypeAlignInChars(allocType);
16054c8b2481SRoman Divacky
160645b53394SDimitry Andric // Emit the allocation call. If the allocator is a global placement
160745b53394SDimitry Andric // operator, just "inline" it directly.
160845b53394SDimitry Andric Address allocation = Address::invalid();
160945b53394SDimitry Andric CallArgList allocatorArgs;
161045b53394SDimitry Andric if (allocator->isReservedGlobalPlacementOperator()) {
161145b53394SDimitry Andric assert(E->getNumPlacementArgs() == 1);
161245b53394SDimitry Andric const Expr *arg = *E->placement_arguments().begin();
161345b53394SDimitry Andric
1614aa803409SDimitry Andric LValueBaseInfo BaseInfo;
1615aa803409SDimitry Andric allocation = EmitPointerWithAlignment(arg, &BaseInfo);
161645b53394SDimitry Andric
161745b53394SDimitry Andric // The pointer expression will, in many cases, be an opaque void*.
161845b53394SDimitry Andric // In these cases, discard the computed alignment and use the
161945b53394SDimitry Andric // formal alignment of the allocated type.
1620aa803409SDimitry Andric if (BaseInfo.getAlignmentSource() != AlignmentSource::Decl)
1621ac9a064cSDimitry Andric allocation.setAlignment(allocAlign);
162245b53394SDimitry Andric
162345b53394SDimitry Andric // Set up allocatorArgs for the call to operator delete if it's not
162445b53394SDimitry Andric // the reserved global operator.
162545b53394SDimitry Andric if (E->getOperatorDelete() &&
162645b53394SDimitry Andric !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
162745b53394SDimitry Andric allocatorArgs.add(RValue::get(allocSize), getContext().getSizeType());
1628ac9a064cSDimitry Andric allocatorArgs.add(RValue::get(allocation, *this), arg->getType());
162945b53394SDimitry Andric }
163045b53394SDimitry Andric
163145b53394SDimitry Andric } else {
163245b53394SDimitry Andric const FunctionProtoType *allocatorType =
163345b53394SDimitry Andric allocator->getType()->castAs<FunctionProtoType>();
1634bab175ecSDimitry Andric unsigned ParamsToSkip = 0;
163545b53394SDimitry Andric
163645b53394SDimitry Andric // The allocation size is the first argument.
163745b53394SDimitry Andric QualType sizeType = getContext().getSizeType();
163801af97d3SDimitry Andric allocatorArgs.add(RValue::get(allocSize), sizeType);
1639bab175ecSDimitry Andric ++ParamsToSkip;
16404c8b2481SRoman Divacky
1641bab175ecSDimitry Andric if (allocSize != allocSizeWithoutCookie) {
1642bab175ecSDimitry Andric CharUnits cookieAlign = getSizeAlign(); // FIXME: Ask the ABI.
1643bab175ecSDimitry Andric allocAlign = std::max(allocAlign, cookieAlign);
1644bab175ecSDimitry Andric }
1645bab175ecSDimitry Andric
1646bab175ecSDimitry Andric // The allocation alignment may be passed as the second argument.
1647bab175ecSDimitry Andric if (E->passAlignment()) {
1648bab175ecSDimitry Andric QualType AlignValT = sizeType;
1649bab175ecSDimitry Andric if (allocatorType->getNumParams() > 1) {
1650bab175ecSDimitry Andric AlignValT = allocatorType->getParamType(1);
1651bab175ecSDimitry Andric assert(getContext().hasSameUnqualifiedType(
1652bab175ecSDimitry Andric AlignValT->castAs<EnumType>()->getDecl()->getIntegerType(),
1653bab175ecSDimitry Andric sizeType) &&
1654bab175ecSDimitry Andric "wrong type for alignment parameter");
1655bab175ecSDimitry Andric ++ParamsToSkip;
1656bab175ecSDimitry Andric } else {
1657bab175ecSDimitry Andric // Corner case, passing alignment to 'operator new(size_t, ...)'.
1658bab175ecSDimitry Andric assert(allocator->isVariadic() && "can't pass alignment to allocator");
1659bab175ecSDimitry Andric }
1660bab175ecSDimitry Andric allocatorArgs.add(
1661bab175ecSDimitry Andric RValue::get(llvm::ConstantInt::get(SizeTy, allocAlign.getQuantity())),
1662bab175ecSDimitry Andric AlignValT);
1663bab175ecSDimitry Andric }
1664bab175ecSDimitry Andric
1665bab175ecSDimitry Andric // FIXME: Why do we not pass a CalleeDecl here?
166645b53394SDimitry Andric EmitCallArgs(allocatorArgs, allocatorType, E->placement_arguments(),
16677442d6faSDimitry Andric /*AC*/AbstractCallee(), /*ParamsToSkip*/ParamsToSkip);
16684c8b2481SRoman Divacky
166945b53394SDimitry Andric RValue RV =
167045b53394SDimitry Andric EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
167145b53394SDimitry Andric
1672cfca06d7SDimitry Andric // Set !heapallocsite metadata on the call to operator new.
1673cfca06d7SDimitry Andric if (getDebugInfo())
1674cfca06d7SDimitry Andric if (auto *newCall = dyn_cast<llvm::CallBase>(RV.getScalarVal()))
1675cfca06d7SDimitry Andric getDebugInfo()->addHeapAllocSiteMetadata(newCall, allocType,
1676cfca06d7SDimitry Andric E->getExprLoc());
1677cfca06d7SDimitry Andric
1678bab175ecSDimitry Andric // If this was a call to a global replaceable allocation function that does
1679bab175ecSDimitry Andric // not take an alignment argument, the allocator is known to produce
1680bab175ecSDimitry Andric // storage that's suitably aligned for any object that fits, up to a known
1681bab175ecSDimitry Andric // threshold. Otherwise assume it's suitably aligned for the allocated type.
1682bab175ecSDimitry Andric CharUnits allocationAlign = allocAlign;
1683bab175ecSDimitry Andric if (!E->passAlignment() &&
1684bab175ecSDimitry Andric allocator->isReplaceableGlobalAllocationFunction()) {
16857fa27ce4SDimitry Andric unsigned AllocatorAlign = llvm::bit_floor(std::min<uint64_t>(
1686bab175ecSDimitry Andric Target.getNewAlign(), getContext().getTypeSize(allocType)));
1687bab175ecSDimitry Andric allocationAlign = std::max(
1688bab175ecSDimitry Andric allocationAlign, getContext().toCharUnitsFromBits(AllocatorAlign));
168945b53394SDimitry Andric }
169045b53394SDimitry Andric
169177fc4c14SDimitry Andric allocation = Address(RV.getScalarVal(), Int8Ty, allocationAlign);
169229cafa66SDimitry Andric }
16934c8b2481SRoman Divacky
169401af97d3SDimitry Andric // Emit a null check on the allocation result if the allocation
169501af97d3SDimitry Andric // function is allowed to return null (because it has a non-throwing
16965e20cdd8SDimitry Andric // exception spec or is the reserved placement new) and we have an
1697676fbe81SDimitry Andric // interesting initializer will be running sanitizers on the initialization.
1698676fbe81SDimitry Andric bool nullCheck = E->shouldNullCheckAllocation() &&
1699676fbe81SDimitry Andric (!allocType.isPODType(getContext()) || E->hasInitializer() ||
1700676fbe81SDimitry Andric sanitizePerformTypeCheck());
17014c8b2481SRoman Divacky
17029f4dbff6SDimitry Andric llvm::BasicBlock *nullCheckBB = nullptr;
17039f4dbff6SDimitry Andric llvm::BasicBlock *contBB = nullptr;
17044c8b2481SRoman Divacky
170501af97d3SDimitry Andric // The null-check means that the initializer is conditionally
170601af97d3SDimitry Andric // evaluated.
170701af97d3SDimitry Andric ConditionalEvaluation conditional(*this);
17084c8b2481SRoman Divacky
170901af97d3SDimitry Andric if (nullCheck) {
171001af97d3SDimitry Andric conditional.begin(*this);
171101af97d3SDimitry Andric
171201af97d3SDimitry Andric nullCheckBB = Builder.GetInsertBlock();
171301af97d3SDimitry Andric llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
171401af97d3SDimitry Andric contBB = createBasicBlock("new.cont");
171501af97d3SDimitry Andric
1716ac9a064cSDimitry Andric llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
171701af97d3SDimitry Andric Builder.CreateCondBr(isNull, contBB, notNullBB);
171801af97d3SDimitry Andric EmitBlock(notNullBB);
17194c8b2481SRoman Divacky }
17204c8b2481SRoman Divacky
1721bca07a45SDimitry Andric // If there's an operator delete, enter a cleanup to call it if an
1722bca07a45SDimitry Andric // exception is thrown.
172301af97d3SDimitry Andric EHScopeStack::stable_iterator operatorDeleteCleanup;
17249f4dbff6SDimitry Andric llvm::Instruction *cleanupDominator = nullptr;
172529cafa66SDimitry Andric if (E->getOperatorDelete() &&
172629cafa66SDimitry Andric !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
1727bab175ecSDimitry Andric EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocAlign,
1728bab175ecSDimitry Andric allocatorArgs);
172901af97d3SDimitry Andric operatorDeleteCleanup = EHStack.stable_begin();
1730dbe13110SDimitry Andric cleanupDominator = Builder.CreateUnreachable();
17314c8b2481SRoman Divacky }
17324c8b2481SRoman Divacky
173336981b17SDimitry Andric assert((allocSize == allocSizeWithoutCookie) ==
173436981b17SDimitry Andric CalculateCookiePadding(*this, E).isZero());
173536981b17SDimitry Andric if (allocSize != allocSizeWithoutCookie) {
173636981b17SDimitry Andric assert(E->isArray());
173736981b17SDimitry Andric allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
173836981b17SDimitry Andric numElements,
173936981b17SDimitry Andric E, allocType);
174036981b17SDimitry Andric }
174136981b17SDimitry Andric
17425e20cdd8SDimitry Andric llvm::Type *elementTy = ConvertTypeForMem(allocType);
17437fa27ce4SDimitry Andric Address result = allocation.withElementType(elementTy);
174445b53394SDimitry Andric
174548675466SDimitry Andric // Passing pointer through launder.invariant.group to avoid propagation of
174645b53394SDimitry Andric // vptrs information which may be included in previous type.
1747aa803409SDimitry Andric // To not break LTO with different optimizations levels, we do it regardless
1748aa803409SDimitry Andric // of optimization level.
174945b53394SDimitry Andric if (CGM.getCodeGenOpts().StrictVTablePointers &&
175045b53394SDimitry Andric allocator->isReservedGlobalPlacementOperator())
175177fc4c14SDimitry Andric result = Builder.CreateLaunderInvariantGroup(result);
1752bca07a45SDimitry Andric
1753c7e70c43SDimitry Andric // Emit sanitizer checks for pointer value now, so that in the case of an
175422989816SDimitry Andric // array it was checked only once and not at each constructor call. We may
175522989816SDimitry Andric // have already checked that the pointer is non-null.
175622989816SDimitry Andric // FIXME: If we have an array cookie and a potentially-throwing allocator,
175722989816SDimitry Andric // we'll null check the wrong pointer here.
175822989816SDimitry Andric SanitizerSet SkippedChecks;
175922989816SDimitry Andric SkippedChecks.set(SanitizerKind::Null, nullCheck);
1760c7e70c43SDimitry Andric EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall,
1761c7e70c43SDimitry Andric E->getAllocatedTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1762ac9a064cSDimitry Andric result, allocType, result.getAlignment(), SkippedChecks,
1763ac9a064cSDimitry Andric numElements);
1764c7e70c43SDimitry Andric
17655e20cdd8SDimitry Andric EmitNewInitializer(*this, E, allocType, elementTy, result, numElements,
176636981b17SDimitry Andric allocSizeWithoutCookie);
1767ac9a064cSDimitry Andric llvm::Value *resultPtr = result.emitRawPointer(*this);
17683d1dcd9bSDimitry Andric if (E->isArray()) {
17693d1dcd9bSDimitry Andric // NewPtr is a pointer to the base element type. If we're
17703d1dcd9bSDimitry Andric // allocating an array of arrays, we'll need to cast back to the
17713d1dcd9bSDimitry Andric // array pointer type.
177236981b17SDimitry Andric llvm::Type *resultType = ConvertTypeForMem(E->getType());
1773145449b1SDimitry Andric if (resultPtr->getType() != resultType)
1774145449b1SDimitry Andric resultPtr = Builder.CreateBitCast(resultPtr, resultType);
177511d2b2d2SRoman Divacky }
17764c8b2481SRoman Divacky
1777bca07a45SDimitry Andric // Deactivate the 'operator delete' cleanup if we finished
1778bca07a45SDimitry Andric // initialization.
1779dbe13110SDimitry Andric if (operatorDeleteCleanup.isValid()) {
1780dbe13110SDimitry Andric DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1781dbe13110SDimitry Andric cleanupDominator->eraseFromParent();
1782dbe13110SDimitry Andric }
1783bca07a45SDimitry Andric
178401af97d3SDimitry Andric if (nullCheck) {
178501af97d3SDimitry Andric conditional.end(*this);
17864c8b2481SRoman Divacky
178701af97d3SDimitry Andric llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
178801af97d3SDimitry Andric EmitBlock(contBB);
17894c8b2481SRoman Divacky
179045b53394SDimitry Andric llvm::PHINode *PHI = Builder.CreatePHI(resultPtr->getType(), 2);
179145b53394SDimitry Andric PHI->addIncoming(resultPtr, notNullBB);
179245b53394SDimitry Andric PHI->addIncoming(llvm::Constant::getNullValue(resultPtr->getType()),
179301af97d3SDimitry Andric nullCheckBB);
179401af97d3SDimitry Andric
179545b53394SDimitry Andric resultPtr = PHI;
17964c8b2481SRoman Divacky }
17974c8b2481SRoman Divacky
179845b53394SDimitry Andric return resultPtr;
17994c8b2481SRoman Divacky }
18004c8b2481SRoman Divacky
EmitDeleteCall(const FunctionDecl * DeleteFD,llvm::Value * Ptr,QualType DeleteTy,llvm::Value * NumElements,CharUnits CookieSize)1801b3d5a323SRoman Divacky void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1802bab175ecSDimitry Andric llvm::Value *Ptr, QualType DeleteTy,
1803bab175ecSDimitry Andric llvm::Value *NumElements,
1804bab175ecSDimitry Andric CharUnits CookieSize) {
1805bab175ecSDimitry Andric assert((!NumElements && CookieSize.isZero()) ||
1806bab175ecSDimitry Andric DeleteFD->getOverloadedOperator() == OO_Array_Delete);
18073d1dcd9bSDimitry Andric
1808706b4fc4SDimitry Andric const auto *DeleteFTy = DeleteFD->getType()->castAs<FunctionProtoType>();
1809b3d5a323SRoman Divacky CallArgList DeleteArgs;
1810b3d5a323SRoman Divacky
1811461a67faSDimitry Andric auto Params = getUsualDeleteParams(DeleteFD);
1812bab175ecSDimitry Andric auto ParamTypeIt = DeleteFTy->param_type_begin();
1813bab175ecSDimitry Andric
1814bab175ecSDimitry Andric // Pass the pointer itself.
1815bab175ecSDimitry Andric QualType ArgTy = *ParamTypeIt++;
1816b3d5a323SRoman Divacky llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
181701af97d3SDimitry Andric DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
1818b3d5a323SRoman Divacky
1819461a67faSDimitry Andric // Pass the std::destroying_delete tag if present.
1820b60736ecSDimitry Andric llvm::AllocaInst *DestroyingDeleteTag = nullptr;
1821461a67faSDimitry Andric if (Params.DestroyingDelete) {
1822461a67faSDimitry Andric QualType DDTag = *ParamTypeIt++;
1823b60736ecSDimitry Andric llvm::Type *Ty = getTypes().ConvertType(DDTag);
1824b60736ecSDimitry Andric CharUnits Align = CGM.getNaturalTypeAlignment(DDTag);
1825b60736ecSDimitry Andric DestroyingDeleteTag = CreateTempAlloca(Ty, "destroying.delete.tag");
1826b60736ecSDimitry Andric DestroyingDeleteTag->setAlignment(Align.getAsAlign());
1827145449b1SDimitry Andric DeleteArgs.add(
1828145449b1SDimitry Andric RValue::getAggregate(Address(DestroyingDeleteTag, Ty, Align)), DDTag);
1829461a67faSDimitry Andric }
1830461a67faSDimitry Andric
1831bab175ecSDimitry Andric // Pass the size if the delete function has a size_t parameter.
1832461a67faSDimitry Andric if (Params.Size) {
1833bab175ecSDimitry Andric QualType SizeType = *ParamTypeIt++;
1834bab175ecSDimitry Andric CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1835bab175ecSDimitry Andric llvm::Value *Size = llvm::ConstantInt::get(ConvertType(SizeType),
1836bab175ecSDimitry Andric DeleteTypeSize.getQuantity());
1837bab175ecSDimitry Andric
1838bab175ecSDimitry Andric // For array new, multiply by the number of elements.
1839bab175ecSDimitry Andric if (NumElements)
1840bab175ecSDimitry Andric Size = Builder.CreateMul(Size, NumElements);
1841bab175ecSDimitry Andric
1842bab175ecSDimitry Andric // If there is a cookie, add the cookie size.
1843bab175ecSDimitry Andric if (!CookieSize.isZero())
1844bab175ecSDimitry Andric Size = Builder.CreateAdd(
1845bab175ecSDimitry Andric Size, llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity()));
1846bab175ecSDimitry Andric
1847bab175ecSDimitry Andric DeleteArgs.add(RValue::get(Size), SizeType);
1848bab175ecSDimitry Andric }
1849bab175ecSDimitry Andric
1850bab175ecSDimitry Andric // Pass the alignment if the delete function has an align_val_t parameter.
1851461a67faSDimitry Andric if (Params.Alignment) {
1852bab175ecSDimitry Andric QualType AlignValType = *ParamTypeIt++;
1853b60736ecSDimitry Andric CharUnits DeleteTypeAlign =
1854b60736ecSDimitry Andric getContext().toCharUnitsFromBits(getContext().getTypeAlignIfKnown(
1855b60736ecSDimitry Andric DeleteTy, true /* NeedsPreferredAlignment */));
1856bab175ecSDimitry Andric llvm::Value *Align = llvm::ConstantInt::get(ConvertType(AlignValType),
1857bab175ecSDimitry Andric DeleteTypeAlign.getQuantity());
1858bab175ecSDimitry Andric DeleteArgs.add(RValue::get(Align), AlignValType);
1859bab175ecSDimitry Andric }
1860bab175ecSDimitry Andric
1861bab175ecSDimitry Andric assert(ParamTypeIt == DeleteFTy->param_type_end() &&
1862bab175ecSDimitry Andric "unknown parameter to usual delete function");
1863b3d5a323SRoman Divacky
1864b3d5a323SRoman Divacky // Emit the call to delete.
1865bfef3995SDimitry Andric EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
1866b60736ecSDimitry Andric
1867b60736ecSDimitry Andric // If call argument lowering didn't use the destroying_delete_t alloca,
1868b60736ecSDimitry Andric // remove it again.
1869b60736ecSDimitry Andric if (DestroyingDeleteTag && DestroyingDeleteTag->use_empty())
1870b60736ecSDimitry Andric DestroyingDeleteTag->eraseFromParent();
1871b3d5a323SRoman Divacky }
1872b3d5a323SRoman Divacky
18733d1dcd9bSDimitry Andric namespace {
18743d1dcd9bSDimitry Andric /// Calls the given 'operator delete' on a single object.
187545b53394SDimitry Andric struct CallObjectDelete final : EHScopeStack::Cleanup {
18763d1dcd9bSDimitry Andric llvm::Value *Ptr;
18773d1dcd9bSDimitry Andric const FunctionDecl *OperatorDelete;
18783d1dcd9bSDimitry Andric QualType ElementType;
18793d1dcd9bSDimitry Andric
CallObjectDelete__anond0bfbf4f0511::CallObjectDelete18803d1dcd9bSDimitry Andric CallObjectDelete(llvm::Value *Ptr,
18813d1dcd9bSDimitry Andric const FunctionDecl *OperatorDelete,
18823d1dcd9bSDimitry Andric QualType ElementType)
18833d1dcd9bSDimitry Andric : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
18843d1dcd9bSDimitry Andric
Emit__anond0bfbf4f0511::CallObjectDelete18859f4dbff6SDimitry Andric void Emit(CodeGenFunction &CGF, Flags flags) override {
18863d1dcd9bSDimitry Andric CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
18873d1dcd9bSDimitry Andric }
18883d1dcd9bSDimitry Andric };
18893d1dcd9bSDimitry Andric }
18903d1dcd9bSDimitry Andric
189106d4ba38SDimitry Andric void
pushCallObjectDeleteCleanup(const FunctionDecl * OperatorDelete,llvm::Value * CompletePtr,QualType ElementType)189206d4ba38SDimitry Andric CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
189306d4ba38SDimitry Andric llvm::Value *CompletePtr,
189406d4ba38SDimitry Andric QualType ElementType) {
189506d4ba38SDimitry Andric EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr,
189606d4ba38SDimitry Andric OperatorDelete, ElementType);
189706d4ba38SDimitry Andric }
189806d4ba38SDimitry Andric
1899461a67faSDimitry Andric /// Emit the code for deleting a single object with a destroying operator
1900461a67faSDimitry Andric /// delete. If the element type has a non-virtual destructor, Ptr has already
1901461a67faSDimitry Andric /// been converted to the type of the parameter of 'operator delete'. Otherwise
1902461a67faSDimitry Andric /// Ptr points to an object of the static type.
EmitDestroyingObjectDelete(CodeGenFunction & CGF,const CXXDeleteExpr * DE,Address Ptr,QualType ElementType)1903461a67faSDimitry Andric static void EmitDestroyingObjectDelete(CodeGenFunction &CGF,
1904461a67faSDimitry Andric const CXXDeleteExpr *DE, Address Ptr,
1905461a67faSDimitry Andric QualType ElementType) {
1906461a67faSDimitry Andric auto *Dtor = ElementType->getAsCXXRecordDecl()->getDestructor();
1907461a67faSDimitry Andric if (Dtor && Dtor->isVirtual())
1908461a67faSDimitry Andric CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
1909461a67faSDimitry Andric Dtor);
1910461a67faSDimitry Andric else
1911ac9a064cSDimitry Andric CGF.EmitDeleteCall(DE->getOperatorDelete(), Ptr.emitRawPointer(CGF),
1912ac9a064cSDimitry Andric ElementType);
1913461a67faSDimitry Andric }
1914461a67faSDimitry Andric
19153d1dcd9bSDimitry Andric /// Emit the code for deleting a single object.
1916cfca06d7SDimitry Andric /// \return \c true if we started emitting UnconditionalDeleteBlock, \c false
1917cfca06d7SDimitry Andric /// if not.
EmitObjectDelete(CodeGenFunction & CGF,const CXXDeleteExpr * DE,Address Ptr,QualType ElementType,llvm::BasicBlock * UnconditionalDeleteBlock)1918cfca06d7SDimitry Andric static bool EmitObjectDelete(CodeGenFunction &CGF,
191906d4ba38SDimitry Andric const CXXDeleteExpr *DE,
192045b53394SDimitry Andric Address Ptr,
1921cfca06d7SDimitry Andric QualType ElementType,
1922cfca06d7SDimitry Andric llvm::BasicBlock *UnconditionalDeleteBlock) {
1923bab175ecSDimitry Andric // C++11 [expr.delete]p3:
1924bab175ecSDimitry Andric // If the static type of the object to be deleted is different from its
1925bab175ecSDimitry Andric // dynamic type, the static type shall be a base class of the dynamic type
1926bab175ecSDimitry Andric // of the object to be deleted and the static type shall have a virtual
1927bab175ecSDimitry Andric // destructor or the behavior is undefined.
1928ac9a064cSDimitry Andric CGF.EmitTypeCheck(CodeGenFunction::TCK_MemberCall, DE->getExprLoc(), Ptr,
1929bab175ecSDimitry Andric ElementType);
1930bab175ecSDimitry Andric
1931461a67faSDimitry Andric const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
1932461a67faSDimitry Andric assert(!OperatorDelete->isDestroyingOperatorDelete());
1933461a67faSDimitry Andric
19343d1dcd9bSDimitry Andric // Find the destructor for the type, if applicable. If the
19353d1dcd9bSDimitry Andric // destructor is virtual, we'll just emit the vcall and return.
19369f4dbff6SDimitry Andric const CXXDestructorDecl *Dtor = nullptr;
19373d1dcd9bSDimitry Andric if (const RecordType *RT = ElementType->getAs<RecordType>()) {
19383d1dcd9bSDimitry Andric CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
193936981b17SDimitry Andric if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
19403d1dcd9bSDimitry Andric Dtor = RD->getDestructor();
19413d1dcd9bSDimitry Andric
19423d1dcd9bSDimitry Andric if (Dtor->isVirtual()) {
1943519fc96cSDimitry Andric bool UseVirtualCall = true;
1944519fc96cSDimitry Andric const Expr *Base = DE->getArgument();
1945519fc96cSDimitry Andric if (auto *DevirtualizedDtor =
1946519fc96cSDimitry Andric dyn_cast_or_null<const CXXDestructorDecl>(
1947519fc96cSDimitry Andric Dtor->getDevirtualizedMethod(
1948519fc96cSDimitry Andric Base, CGF.CGM.getLangOpts().AppleKext))) {
1949519fc96cSDimitry Andric UseVirtualCall = false;
1950519fc96cSDimitry Andric const CXXRecordDecl *DevirtualizedClass =
1951519fc96cSDimitry Andric DevirtualizedDtor->getParent();
1952519fc96cSDimitry Andric if (declaresSameEntity(getCXXRecord(Base), DevirtualizedClass)) {
1953519fc96cSDimitry Andric // Devirtualized to the class of the base type (the type of the
1954519fc96cSDimitry Andric // whole expression).
1955519fc96cSDimitry Andric Dtor = DevirtualizedDtor;
1956519fc96cSDimitry Andric } else {
1957519fc96cSDimitry Andric // Devirtualized to some other type. Would need to cast the this
1958519fc96cSDimitry Andric // pointer to that type but we don't have support for that yet, so
1959519fc96cSDimitry Andric // do a virtual call. FIXME: handle the case where it is
1960519fc96cSDimitry Andric // devirtualized to the derived type (the type of the inner
1961519fc96cSDimitry Andric // expression) as in EmitCXXMemberOrOperatorMemberCallExpr.
1962519fc96cSDimitry Andric UseVirtualCall = true;
1963519fc96cSDimitry Andric }
1964519fc96cSDimitry Andric }
1965519fc96cSDimitry Andric if (UseVirtualCall) {
196606d4ba38SDimitry Andric CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
196706d4ba38SDimitry Andric Dtor);
1968cfca06d7SDimitry Andric return false;
19693d1dcd9bSDimitry Andric }
19703d1dcd9bSDimitry Andric }
19713d1dcd9bSDimitry Andric }
1972519fc96cSDimitry Andric }
19733d1dcd9bSDimitry Andric
19743d1dcd9bSDimitry Andric // Make sure that we call delete even if the dtor throws.
1975bca07a45SDimitry Andric // This doesn't have to a conditional cleanup because we're going
1976bca07a45SDimitry Andric // to pop it off in a second.
1977ac9a064cSDimitry Andric CGF.EHStack.pushCleanup<CallObjectDelete>(
1978ac9a064cSDimitry Andric NormalAndEHCleanup, Ptr.emitRawPointer(CGF), OperatorDelete, ElementType);
19793d1dcd9bSDimitry Andric
19803d1dcd9bSDimitry Andric if (Dtor)
19813d1dcd9bSDimitry Andric CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1982809500fcSDimitry Andric /*ForVirtualBase=*/false,
1983809500fcSDimitry Andric /*Delegating=*/false,
198422989816SDimitry Andric Ptr, ElementType);
198545b53394SDimitry Andric else if (auto Lifetime = ElementType.getObjCLifetime()) {
198645b53394SDimitry Andric switch (Lifetime) {
1987180abc3dSDimitry Andric case Qualifiers::OCL_None:
1988180abc3dSDimitry Andric case Qualifiers::OCL_ExplicitNone:
1989180abc3dSDimitry Andric case Qualifiers::OCL_Autoreleasing:
1990180abc3dSDimitry Andric break;
1991180abc3dSDimitry Andric
199245b53394SDimitry Andric case Qualifiers::OCL_Strong:
199345b53394SDimitry Andric CGF.EmitARCDestroyStrong(Ptr, ARCPreciseLifetime);
1994180abc3dSDimitry Andric break;
1995180abc3dSDimitry Andric
1996180abc3dSDimitry Andric case Qualifiers::OCL_Weak:
1997180abc3dSDimitry Andric CGF.EmitARCDestroyWeak(Ptr);
1998180abc3dSDimitry Andric break;
1999180abc3dSDimitry Andric }
2000180abc3dSDimitry Andric }
20013d1dcd9bSDimitry Andric
2002cfca06d7SDimitry Andric // When optimizing for size, call 'operator delete' unconditionally.
2003cfca06d7SDimitry Andric if (CGF.CGM.getCodeGenOpts().OptimizeSize > 1) {
2004cfca06d7SDimitry Andric CGF.EmitBlock(UnconditionalDeleteBlock);
20053d1dcd9bSDimitry Andric CGF.PopCleanupBlock();
2006cfca06d7SDimitry Andric return true;
2007cfca06d7SDimitry Andric }
2008cfca06d7SDimitry Andric
2009cfca06d7SDimitry Andric CGF.PopCleanupBlock();
2010cfca06d7SDimitry Andric return false;
20113d1dcd9bSDimitry Andric }
20123d1dcd9bSDimitry Andric
20133d1dcd9bSDimitry Andric namespace {
20143d1dcd9bSDimitry Andric /// Calls the given 'operator delete' on an array of objects.
201545b53394SDimitry Andric struct CallArrayDelete final : EHScopeStack::Cleanup {
20163d1dcd9bSDimitry Andric llvm::Value *Ptr;
20173d1dcd9bSDimitry Andric const FunctionDecl *OperatorDelete;
20183d1dcd9bSDimitry Andric llvm::Value *NumElements;
20193d1dcd9bSDimitry Andric QualType ElementType;
20203d1dcd9bSDimitry Andric CharUnits CookieSize;
20213d1dcd9bSDimitry Andric
CallArrayDelete__anond0bfbf4f0611::CallArrayDelete20223d1dcd9bSDimitry Andric CallArrayDelete(llvm::Value *Ptr,
20233d1dcd9bSDimitry Andric const FunctionDecl *OperatorDelete,
20243d1dcd9bSDimitry Andric llvm::Value *NumElements,
20253d1dcd9bSDimitry Andric QualType ElementType,
20263d1dcd9bSDimitry Andric CharUnits CookieSize)
20273d1dcd9bSDimitry Andric : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
20283d1dcd9bSDimitry Andric ElementType(ElementType), CookieSize(CookieSize) {}
20293d1dcd9bSDimitry Andric
Emit__anond0bfbf4f0611::CallArrayDelete20309f4dbff6SDimitry Andric void Emit(CodeGenFunction &CGF, Flags flags) override {
2031bab175ecSDimitry Andric CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType, NumElements,
2032bab175ecSDimitry Andric CookieSize);
20333d1dcd9bSDimitry Andric }
20343d1dcd9bSDimitry Andric };
20353d1dcd9bSDimitry Andric }
20363d1dcd9bSDimitry Andric
20373d1dcd9bSDimitry Andric /// Emit the code for deleting an array of objects.
EmitArrayDelete(CodeGenFunction & CGF,const CXXDeleteExpr * E,Address deletedPtr,QualType elementType)20383d1dcd9bSDimitry Andric static void EmitArrayDelete(CodeGenFunction &CGF,
2039bca07a45SDimitry Andric const CXXDeleteExpr *E,
204045b53394SDimitry Andric Address deletedPtr,
2041180abc3dSDimitry Andric QualType elementType) {
20429f4dbff6SDimitry Andric llvm::Value *numElements = nullptr;
20439f4dbff6SDimitry Andric llvm::Value *allocatedPtr = nullptr;
2044180abc3dSDimitry Andric CharUnits cookieSize;
2045180abc3dSDimitry Andric CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
2046180abc3dSDimitry Andric numElements, allocatedPtr, cookieSize);
20473d1dcd9bSDimitry Andric
2048180abc3dSDimitry Andric assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
20493d1dcd9bSDimitry Andric
20503d1dcd9bSDimitry Andric // Make sure that we call delete even if one of the dtors throws.
2051180abc3dSDimitry Andric const FunctionDecl *operatorDelete = E->getOperatorDelete();
20523d1dcd9bSDimitry Andric CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
2053180abc3dSDimitry Andric allocatedPtr, operatorDelete,
2054180abc3dSDimitry Andric numElements, elementType,
2055180abc3dSDimitry Andric cookieSize);
20563d1dcd9bSDimitry Andric
2057180abc3dSDimitry Andric // Destroy the elements.
2058180abc3dSDimitry Andric if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
2059180abc3dSDimitry Andric assert(numElements && "no element count for a type with a destructor!");
2060180abc3dSDimitry Andric
206145b53394SDimitry Andric CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
206245b53394SDimitry Andric CharUnits elementAlign =
206345b53394SDimitry Andric deletedPtr.getAlignment().alignmentOfArrayElement(elementSize);
206445b53394SDimitry Andric
2065ac9a064cSDimitry Andric llvm::Value *arrayBegin = deletedPtr.emitRawPointer(CGF);
2066344a3780SDimitry Andric llvm::Value *arrayEnd = CGF.Builder.CreateInBoundsGEP(
2067344a3780SDimitry Andric deletedPtr.getElementType(), arrayBegin, numElements, "delete.end");
2068180abc3dSDimitry Andric
2069180abc3dSDimitry Andric // Note that it is legal to allocate a zero-length array, and we
2070180abc3dSDimitry Andric // can never fold the check away because the length should always
2071180abc3dSDimitry Andric // come from a cookie.
207245b53394SDimitry Andric CGF.emitArrayDestroy(arrayBegin, arrayEnd, elementType, elementAlign,
2073180abc3dSDimitry Andric CGF.getDestroyer(dtorKind),
2074180abc3dSDimitry Andric /*checkZeroLength*/ true,
2075180abc3dSDimitry Andric CGF.needsEHCleanup(dtorKind));
20763d1dcd9bSDimitry Andric }
20773d1dcd9bSDimitry Andric
2078180abc3dSDimitry Andric // Pop the cleanup block.
20793d1dcd9bSDimitry Andric CGF.PopCleanupBlock();
20803d1dcd9bSDimitry Andric }
20813d1dcd9bSDimitry Andric
EmitCXXDeleteExpr(const CXXDeleteExpr * E)20824c8b2481SRoman Divacky void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
20834c8b2481SRoman Divacky const Expr *Arg = E->getArgument();
208445b53394SDimitry Andric Address Ptr = EmitPointerWithAlignment(Arg);
20854c8b2481SRoman Divacky
20864c8b2481SRoman Divacky // Null check the pointer.
2087cfca06d7SDimitry Andric //
2088cfca06d7SDimitry Andric // We could avoid this null check if we can determine that the object
2089cfca06d7SDimitry Andric // destruction is trivial and doesn't require an array cookie; we can
2090cfca06d7SDimitry Andric // unconditionally perform the operator delete call in that case. For now, we
2091cfca06d7SDimitry Andric // assume that deleted pointers are null rarely enough that it's better to
2092cfca06d7SDimitry Andric // keep the branch. This might be worth revisiting for a -O0 code size win.
20934c8b2481SRoman Divacky llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
20944c8b2481SRoman Divacky llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
20954c8b2481SRoman Divacky
2096ac9a064cSDimitry Andric llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
20974c8b2481SRoman Divacky
20984c8b2481SRoman Divacky Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
20994c8b2481SRoman Divacky EmitBlock(DeleteNotNull);
21007fa27ce4SDimitry Andric Ptr.setKnownNonNull();
21014c8b2481SRoman Divacky
2102461a67faSDimitry Andric QualType DeleteTy = E->getDestroyedType();
2103461a67faSDimitry Andric
2104461a67faSDimitry Andric // A destroying operator delete overrides the entire operation of the
2105461a67faSDimitry Andric // delete expression.
2106461a67faSDimitry Andric if (E->getOperatorDelete()->isDestroyingOperatorDelete()) {
2107461a67faSDimitry Andric EmitDestroyingObjectDelete(*this, E, Ptr, DeleteTy);
2108461a67faSDimitry Andric EmitBlock(DeleteEnd);
2109461a67faSDimitry Andric return;
2110461a67faSDimitry Andric }
2111461a67faSDimitry Andric
21123d1dcd9bSDimitry Andric // We might be deleting a pointer to array. If so, GEP down to the
21133d1dcd9bSDimitry Andric // first non-array element.
21143d1dcd9bSDimitry Andric // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
21153d1dcd9bSDimitry Andric if (DeleteTy->isConstantArrayType()) {
21163d1dcd9bSDimitry Andric llvm::Value *Zero = Builder.getInt32(0);
211736981b17SDimitry Andric SmallVector<llvm::Value*,8> GEP;
2118b3d5a323SRoman Divacky
21193d1dcd9bSDimitry Andric GEP.push_back(Zero); // point at the outermost array
21203d1dcd9bSDimitry Andric
21213d1dcd9bSDimitry Andric // For each layer of array type we're pointing at:
21223d1dcd9bSDimitry Andric while (const ConstantArrayType *Arr
21233d1dcd9bSDimitry Andric = getContext().getAsConstantArrayType(DeleteTy)) {
21243d1dcd9bSDimitry Andric // 1. Unpeel the array type.
21253d1dcd9bSDimitry Andric DeleteTy = Arr->getElementType();
21263d1dcd9bSDimitry Andric
21273d1dcd9bSDimitry Andric // 2. GEP to the first element of the array.
21283d1dcd9bSDimitry Andric GEP.push_back(Zero);
21293d1dcd9bSDimitry Andric }
21303d1dcd9bSDimitry Andric
2131ac9a064cSDimitry Andric Ptr = Builder.CreateInBoundsGEP(Ptr, GEP, ConvertTypeForMem(DeleteTy),
2132ac9a064cSDimitry Andric Ptr.getAlignment(), "del.first");
21333d1dcd9bSDimitry Andric }
21343d1dcd9bSDimitry Andric
213545b53394SDimitry Andric assert(ConvertTypeForMem(DeleteTy) == Ptr.getElementType());
21363d1dcd9bSDimitry Andric
2137b3d5a323SRoman Divacky if (E->isArrayForm()) {
2138bca07a45SDimitry Andric EmitArrayDelete(*this, E, Ptr, DeleteTy);
21394c8b2481SRoman Divacky EmitBlock(DeleteEnd);
2140cfca06d7SDimitry Andric } else {
2141cfca06d7SDimitry Andric if (!EmitObjectDelete(*this, E, Ptr, DeleteTy, DeleteEnd))
2142cfca06d7SDimitry Andric EmitBlock(DeleteEnd);
2143cfca06d7SDimitry Andric }
21444c8b2481SRoman Divacky }
2145b3d5a323SRoman Divacky
EmitTypeidFromVTable(CodeGenFunction & CGF,const Expr * E,llvm::Type * StdTypeInfoPtrTy,bool HasNullCheck)21469f4dbff6SDimitry Andric static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
2147ac9a064cSDimitry Andric llvm::Type *StdTypeInfoPtrTy,
2148ac9a064cSDimitry Andric bool HasNullCheck) {
214901af97d3SDimitry Andric // Get the vtable pointer.
2150ac9a064cSDimitry Andric Address ThisPtr = CGF.EmitLValue(E).getAddress();
215101af97d3SDimitry Andric
215255e6d896SDimitry Andric QualType SrcRecordTy = E->getType();
215355e6d896SDimitry Andric
215455e6d896SDimitry Andric // C++ [class.cdtor]p4:
215555e6d896SDimitry Andric // If the operand of typeid refers to the object under construction or
215655e6d896SDimitry Andric // destruction and the static type of the operand is neither the constructor
215755e6d896SDimitry Andric // or destructor’s class nor one of its bases, the behavior is undefined.
215855e6d896SDimitry Andric CGF.EmitTypeCheck(CodeGenFunction::TCK_DynamicOperation, E->getExprLoc(),
2159ac9a064cSDimitry Andric ThisPtr, SrcRecordTy);
216055e6d896SDimitry Andric
2161ac9a064cSDimitry Andric // Whether we need an explicit null pointer check. For example, with the
2162ac9a064cSDimitry Andric // Microsoft ABI, if this is a call to __RTtypeid, the null pointer check and
2163ac9a064cSDimitry Andric // exception throw is inside the __RTtypeid(nullptr) call
2164ac9a064cSDimitry Andric if (HasNullCheck &&
2165ac9a064cSDimitry Andric CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(SrcRecordTy)) {
216601af97d3SDimitry Andric llvm::BasicBlock *BadTypeidBlock =
216701af97d3SDimitry Andric CGF.createBasicBlock("typeid.bad_typeid");
21689f4dbff6SDimitry Andric llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
216901af97d3SDimitry Andric
2170ac9a064cSDimitry Andric llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
217101af97d3SDimitry Andric CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
217201af97d3SDimitry Andric
217301af97d3SDimitry Andric CGF.EmitBlock(BadTypeidBlock);
21749f4dbff6SDimitry Andric CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
217501af97d3SDimitry Andric CGF.EmitBlock(EndBlock);
217601af97d3SDimitry Andric }
217701af97d3SDimitry Andric
21789f4dbff6SDimitry Andric return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
21799f4dbff6SDimitry Andric StdTypeInfoPtrTy);
218001af97d3SDimitry Andric }
218101af97d3SDimitry Andric
EmitCXXTypeidExpr(const CXXTypeidExpr * E)2182b3d5a323SRoman Divacky llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
2183ac9a064cSDimitry Andric // Ideally, we would like to use GlobalsInt8PtrTy here, however, we cannot,
2184ac9a064cSDimitry Andric // primarily because the result of applying typeid is a value of type
2185ac9a064cSDimitry Andric // type_info, which is declared & defined by the standard library
2186ac9a064cSDimitry Andric // implementation and expects to operate on the generic (default) AS.
2187ac9a064cSDimitry Andric // https://reviews.llvm.org/D157452 has more context, and a possible solution.
2188ac9a064cSDimitry Andric llvm::Type *PtrTy = Int8PtrTy;
2189b1c73532SDimitry Andric LangAS GlobAS = CGM.GetGlobalVarAddressSpace(nullptr);
2190b1c73532SDimitry Andric
2191b1c73532SDimitry Andric auto MaybeASCast = [=](auto &&TypeInfo) {
2192b1c73532SDimitry Andric if (GlobAS == LangAS::Default)
2193b1c73532SDimitry Andric return TypeInfo;
2194b1c73532SDimitry Andric return getTargetHooks().performAddrSpaceCast(CGM,TypeInfo, GlobAS,
2195b1c73532SDimitry Andric LangAS::Default, PtrTy);
2196b1c73532SDimitry Andric };
219734d02d0bSRoman Divacky
2198abe15e55SRoman Divacky if (E->isTypeOperand()) {
2199abe15e55SRoman Divacky llvm::Constant *TypeInfo =
2200bfef3995SDimitry Andric CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
2201b1c73532SDimitry Andric return MaybeASCast(TypeInfo);
2202abe15e55SRoman Divacky }
220334d02d0bSRoman Divacky
220401af97d3SDimitry Andric // C++ [expr.typeid]p2:
220501af97d3SDimitry Andric // When typeid is applied to a glvalue expression whose type is a
220601af97d3SDimitry Andric // polymorphic class type, the result refers to a std::type_info object
220701af97d3SDimitry Andric // representing the type of the most derived object (that is, the dynamic
220801af97d3SDimitry Andric // type) to which the glvalue refers.
2209b60736ecSDimitry Andric // If the operand is already most derived object, no need to look up vtable.
2210b60736ecSDimitry Andric if (E->isPotentiallyEvaluated() && !E->isMostDerived(getContext()))
2211ac9a064cSDimitry Andric return EmitTypeidFromVTable(*this, E->getExprOperand(), PtrTy,
2212ac9a064cSDimitry Andric E->hasNullCheck());
2213b3d5a323SRoman Divacky
221401af97d3SDimitry Andric QualType OperandTy = E->getExprOperand()->getType();
2215b1c73532SDimitry Andric return MaybeASCast(CGM.GetAddrOfRTTIDescriptor(OperandTy));
221601af97d3SDimitry Andric }
221701af97d3SDimitry Andric
EmitDynamicCastToNull(CodeGenFunction & CGF,QualType DestTy)221801af97d3SDimitry Andric static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
221901af97d3SDimitry Andric QualType DestTy) {
222036981b17SDimitry Andric llvm::Type *DestLTy = CGF.ConvertType(DestTy);
222101af97d3SDimitry Andric if (DestTy->isPointerType())
222201af97d3SDimitry Andric return llvm::Constant::getNullValue(DestLTy);
222301af97d3SDimitry Andric
222401af97d3SDimitry Andric /// C++ [expr.dynamic.cast]p9:
222501af97d3SDimitry Andric /// A failed cast to reference type throws std::bad_cast
22269f4dbff6SDimitry Andric if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
22279f4dbff6SDimitry Andric return nullptr;
222801af97d3SDimitry Andric
22297fa27ce4SDimitry Andric CGF.Builder.ClearInsertionPoint();
22307fa27ce4SDimitry Andric return llvm::PoisonValue::get(DestLTy);
223101af97d3SDimitry Andric }
223201af97d3SDimitry Andric
EmitDynamicCast(Address ThisAddr,const CXXDynamicCastExpr * DCE)223345b53394SDimitry Andric llvm::Value *CodeGenFunction::EmitDynamicCast(Address ThisAddr,
2234b3d5a323SRoman Divacky const CXXDynamicCastExpr *DCE) {
223545b53394SDimitry Andric CGM.EmitExplicitCastExprType(DCE, this);
2236abe15e55SRoman Divacky QualType DestTy = DCE->getTypeAsWritten();
2237abe15e55SRoman Divacky
223801af97d3SDimitry Andric QualType SrcTy = DCE->getSubExpr()->getType();
2239d7279c4cSRoman Divacky
22409f4dbff6SDimitry Andric // C++ [expr.dynamic.cast]p7:
22419f4dbff6SDimitry Andric // If T is "pointer to cv void," then the result is a pointer to the most
22429f4dbff6SDimitry Andric // derived object pointed to by v.
22437fa27ce4SDimitry Andric bool IsDynamicCastToVoid = DestTy->isVoidPointerType();
22449f4dbff6SDimitry Andric QualType SrcRecordTy;
22459f4dbff6SDimitry Andric QualType DestRecordTy;
22467fa27ce4SDimitry Andric if (IsDynamicCastToVoid) {
22477fa27ce4SDimitry Andric SrcRecordTy = SrcTy->getPointeeType();
22487fa27ce4SDimitry Andric // No DestRecordTy.
22497fa27ce4SDimitry Andric } else if (const PointerType *DestPTy = DestTy->getAs<PointerType>()) {
22509f4dbff6SDimitry Andric SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
22519f4dbff6SDimitry Andric DestRecordTy = DestPTy->getPointeeType();
22529f4dbff6SDimitry Andric } else {
22539f4dbff6SDimitry Andric SrcRecordTy = SrcTy;
22549f4dbff6SDimitry Andric DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
22559f4dbff6SDimitry Andric }
22569f4dbff6SDimitry Andric
225755e6d896SDimitry Andric // C++ [class.cdtor]p5:
225855e6d896SDimitry Andric // If the operand of the dynamic_cast refers to the object under
225955e6d896SDimitry Andric // construction or destruction and the static type of the operand is not a
226055e6d896SDimitry Andric // pointer to or object of the constructor or destructor’s own class or one
226155e6d896SDimitry Andric // of its bases, the dynamic_cast results in undefined behavior.
2262ac9a064cSDimitry Andric EmitTypeCheck(TCK_DynamicOperation, DCE->getExprLoc(), ThisAddr, SrcRecordTy);
226355e6d896SDimitry Andric
22647fa27ce4SDimitry Andric if (DCE->isAlwaysNull()) {
22657fa27ce4SDimitry Andric if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy)) {
22667fa27ce4SDimitry Andric // Expression emission is expected to retain a valid insertion point.
22677fa27ce4SDimitry Andric if (!Builder.GetInsertBlock())
22687fa27ce4SDimitry Andric EmitBlock(createBasicBlock("dynamic_cast.unreachable"));
226955e6d896SDimitry Andric return T;
22707fa27ce4SDimitry Andric }
22717fa27ce4SDimitry Andric }
227255e6d896SDimitry Andric
22739f4dbff6SDimitry Andric assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
22749f4dbff6SDimitry Andric
22757fa27ce4SDimitry Andric // If the destination is effectively final, the cast succeeds if and only
22767fa27ce4SDimitry Andric // if the dynamic type of the pointer is exactly the destination type.
22777fa27ce4SDimitry Andric bool IsExact = !IsDynamicCastToVoid &&
22787fa27ce4SDimitry Andric CGM.getCodeGenOpts().OptimizationLevel > 0 &&
22797fa27ce4SDimitry Andric DestRecordTy->getAsCXXRecordDecl()->isEffectivelyFinal() &&
22807fa27ce4SDimitry Andric CGM.getCXXABI().shouldEmitExactDynamicCast(DestRecordTy);
22817fa27ce4SDimitry Andric
228201af97d3SDimitry Andric // C++ [expr.dynamic.cast]p4:
228301af97d3SDimitry Andric // If the value of v is a null pointer value in the pointer case, the result
228401af97d3SDimitry Andric // is the null pointer value of type T.
22859f4dbff6SDimitry Andric bool ShouldNullCheckSrcValue =
22867fa27ce4SDimitry Andric IsExact || CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(
22877fa27ce4SDimitry Andric SrcTy->isPointerType(), SrcRecordTy);
228801af97d3SDimitry Andric
22899f4dbff6SDimitry Andric llvm::BasicBlock *CastNull = nullptr;
22909f4dbff6SDimitry Andric llvm::BasicBlock *CastNotNull = nullptr;
229101af97d3SDimitry Andric llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
229201af97d3SDimitry Andric
229301af97d3SDimitry Andric if (ShouldNullCheckSrcValue) {
229401af97d3SDimitry Andric CastNull = createBasicBlock("dynamic_cast.null");
229501af97d3SDimitry Andric CastNotNull = createBasicBlock("dynamic_cast.notnull");
229601af97d3SDimitry Andric
2297ac9a064cSDimitry Andric llvm::Value *IsNull = Builder.CreateIsNull(ThisAddr);
229801af97d3SDimitry Andric Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
229901af97d3SDimitry Andric EmitBlock(CastNotNull);
2300b3d5a323SRoman Divacky }
2301b3d5a323SRoman Divacky
230245b53394SDimitry Andric llvm::Value *Value;
23037fa27ce4SDimitry Andric if (IsDynamicCastToVoid) {
23047fa27ce4SDimitry Andric Value = CGM.getCXXABI().emitDynamicCastToVoid(*this, ThisAddr, SrcRecordTy);
23057fa27ce4SDimitry Andric } else if (IsExact) {
23067fa27ce4SDimitry Andric // If the destination type is effectively final, this pointer points to the
23077fa27ce4SDimitry Andric // right type if and only if its vptr has the right value.
23087fa27ce4SDimitry Andric Value = CGM.getCXXABI().emitExactDynamicCast(
23097fa27ce4SDimitry Andric *this, ThisAddr, SrcRecordTy, DestTy, DestRecordTy, CastEnd, CastNull);
23109f4dbff6SDimitry Andric } else {
23119f4dbff6SDimitry Andric assert(DestRecordTy->isRecordType() &&
23129f4dbff6SDimitry Andric "destination type must be a record type!");
23137fa27ce4SDimitry Andric Value = CGM.getCXXABI().emitDynamicCastCall(*this, ThisAddr, SrcRecordTy,
23149f4dbff6SDimitry Andric DestTy, DestRecordTy, CastEnd);
23159f4dbff6SDimitry Andric }
23167fa27ce4SDimitry Andric CastNotNull = Builder.GetInsertBlock();
2317abe15e55SRoman Divacky
23187fa27ce4SDimitry Andric llvm::Value *NullValue = nullptr;
231901af97d3SDimitry Andric if (ShouldNullCheckSrcValue) {
232001af97d3SDimitry Andric EmitBranch(CastEnd);
2321b3d5a323SRoman Divacky
232201af97d3SDimitry Andric EmitBlock(CastNull);
23237fa27ce4SDimitry Andric NullValue = EmitDynamicCastToNull(*this, DestTy);
23247fa27ce4SDimitry Andric CastNull = Builder.GetInsertBlock();
23257fa27ce4SDimitry Andric
232601af97d3SDimitry Andric EmitBranch(CastEnd);
2327b3d5a323SRoman Divacky }
2328b3d5a323SRoman Divacky
232901af97d3SDimitry Andric EmitBlock(CastEnd);
2330b3d5a323SRoman Divacky
23317fa27ce4SDimitry Andric if (CastNull) {
233201af97d3SDimitry Andric llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
233301af97d3SDimitry Andric PHI->addIncoming(Value, CastNotNull);
23347fa27ce4SDimitry Andric PHI->addIncoming(NullValue, CastNull);
2335b3d5a323SRoman Divacky
233601af97d3SDimitry Andric Value = PHI;
2337b3d5a323SRoman Divacky }
2338b3d5a323SRoman Divacky
233901af97d3SDimitry Andric return Value;
2340b3d5a323SRoman Divacky }
2341