10b57cec5SDimitry Andric //===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This contains code dealing with code generation of C++ expressions
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric
130b57cec5SDimitry Andric #include "CGCUDARuntime.h"
140b57cec5SDimitry Andric #include "CGCXXABI.h"
150b57cec5SDimitry Andric #include "CGDebugInfo.h"
160b57cec5SDimitry Andric #include "CGObjCRuntime.h"
170b57cec5SDimitry Andric #include "CodeGenFunction.h"
180b57cec5SDimitry Andric #include "ConstantEmitter.h"
190b57cec5SDimitry Andric #include "TargetInfo.h"
200b57cec5SDimitry Andric #include "clang/Basic/CodeGenOptions.h"
210b57cec5SDimitry Andric #include "clang/CodeGen/CGFunctionInfo.h"
220b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
230b57cec5SDimitry Andric
240b57cec5SDimitry Andric using namespace clang;
250b57cec5SDimitry Andric using namespace CodeGen;
260b57cec5SDimitry Andric
270b57cec5SDimitry Andric namespace {
280b57cec5SDimitry Andric struct MemberCallInfo {
290b57cec5SDimitry Andric RequiredArgs ReqArgs;
300b57cec5SDimitry Andric // Number of prefix arguments for the call. Ignores the `this` pointer.
310b57cec5SDimitry Andric unsigned PrefixSize;
320b57cec5SDimitry Andric };
330b57cec5SDimitry Andric }
340b57cec5SDimitry Andric
350b57cec5SDimitry Andric static MemberCallInfo
commonEmitCXXMemberOrOperatorCall(CodeGenFunction & CGF,GlobalDecl GD,llvm::Value * This,llvm::Value * ImplicitParam,QualType ImplicitParamTy,const CallExpr * CE,CallArgList & Args,CallArgList * RtlArgs)361ac55f4cSDimitry Andric commonEmitCXXMemberOrOperatorCall(CodeGenFunction &CGF, GlobalDecl GD,
370b57cec5SDimitry Andric llvm::Value *This, llvm::Value *ImplicitParam,
380b57cec5SDimitry Andric QualType ImplicitParamTy, const CallExpr *CE,
390b57cec5SDimitry Andric CallArgList &Args, CallArgList *RtlArgs) {
401ac55f4cSDimitry Andric auto *MD = cast<CXXMethodDecl>(GD.getDecl());
411ac55f4cSDimitry Andric
420b57cec5SDimitry Andric assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) ||
430b57cec5SDimitry Andric isa<CXXOperatorCallExpr>(CE));
44c9157d92SDimitry Andric assert(MD->isImplicitObjectMemberFunction() &&
450b57cec5SDimitry Andric "Trying to emit a member or operator call expr on a static method!");
460b57cec5SDimitry Andric
470b57cec5SDimitry Andric // Push the this ptr.
480b57cec5SDimitry Andric const CXXRecordDecl *RD =
491ac55f4cSDimitry Andric CGF.CGM.getCXXABI().getThisArgumentTypeForMethod(GD);
500b57cec5SDimitry Andric Args.add(RValue::get(This), CGF.getTypes().DeriveThisType(RD, MD));
510b57cec5SDimitry Andric
520b57cec5SDimitry Andric // If there is an implicit parameter (e.g. VTT), emit it.
530b57cec5SDimitry Andric if (ImplicitParam) {
540b57cec5SDimitry Andric Args.add(RValue::get(ImplicitParam), ImplicitParamTy);
550b57cec5SDimitry Andric }
560b57cec5SDimitry Andric
570b57cec5SDimitry Andric const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
580b57cec5SDimitry Andric RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size());
590b57cec5SDimitry Andric unsigned PrefixSize = Args.size() - 1;
600b57cec5SDimitry Andric
610b57cec5SDimitry Andric // And the rest of the call args.
620b57cec5SDimitry Andric if (RtlArgs) {
630b57cec5SDimitry Andric // Special case: if the caller emitted the arguments right-to-left already
640b57cec5SDimitry Andric // (prior to emitting the *this argument), we're done. This happens for
650b57cec5SDimitry Andric // assignment operators.
660b57cec5SDimitry Andric Args.addFrom(*RtlArgs);
670b57cec5SDimitry Andric } else if (CE) {
680b57cec5SDimitry Andric // Special case: skip first argument of CXXOperatorCall (it is "this").
69c9157d92SDimitry Andric unsigned ArgsToSkip = 0;
70c9157d92SDimitry Andric if (const auto *Op = dyn_cast<CXXOperatorCallExpr>(CE)) {
71c9157d92SDimitry Andric if (const auto *M = dyn_cast<CXXMethodDecl>(Op->getCalleeDecl()))
72c9157d92SDimitry Andric ArgsToSkip =
73c9157d92SDimitry Andric static_cast<unsigned>(!M->isExplicitObjectMemberFunction());
74c9157d92SDimitry Andric }
750b57cec5SDimitry Andric CGF.EmitCallArgs(Args, FPT, drop_begin(CE->arguments(), ArgsToSkip),
760b57cec5SDimitry Andric CE->getDirectCallee());
770b57cec5SDimitry Andric } else {
780b57cec5SDimitry Andric assert(
790b57cec5SDimitry Andric FPT->getNumParams() == 0 &&
800b57cec5SDimitry Andric "No CallExpr specified for function with non-zero number of arguments");
810b57cec5SDimitry Andric }
820b57cec5SDimitry Andric return {required, PrefixSize};
830b57cec5SDimitry Andric }
840b57cec5SDimitry Andric
EmitCXXMemberOrOperatorCall(const CXXMethodDecl * MD,const CGCallee & Callee,ReturnValueSlot ReturnValue,llvm::Value * This,llvm::Value * ImplicitParam,QualType ImplicitParamTy,const CallExpr * CE,CallArgList * RtlArgs)850b57cec5SDimitry Andric RValue CodeGenFunction::EmitCXXMemberOrOperatorCall(
860b57cec5SDimitry Andric const CXXMethodDecl *MD, const CGCallee &Callee,
870b57cec5SDimitry Andric ReturnValueSlot ReturnValue,
880b57cec5SDimitry Andric llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,
890b57cec5SDimitry Andric const CallExpr *CE, CallArgList *RtlArgs) {
900b57cec5SDimitry Andric const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
910b57cec5SDimitry Andric CallArgList Args;
920b57cec5SDimitry Andric MemberCallInfo CallInfo = commonEmitCXXMemberOrOperatorCall(
930b57cec5SDimitry Andric *this, MD, This, ImplicitParam, ImplicitParamTy, CE, Args, RtlArgs);
940b57cec5SDimitry Andric auto &FnInfo = CGM.getTypes().arrangeCXXMethodCall(
950b57cec5SDimitry Andric Args, FPT, CallInfo.ReqArgs, CallInfo.PrefixSize);
960b57cec5SDimitry Andric return EmitCall(FnInfo, Callee, ReturnValue, Args, nullptr,
97fe6060f1SDimitry Andric CE && CE == MustTailCall,
980b57cec5SDimitry Andric CE ? CE->getExprLoc() : SourceLocation());
990b57cec5SDimitry Andric }
1000b57cec5SDimitry Andric
EmitCXXDestructorCall(GlobalDecl Dtor,const CGCallee & Callee,llvm::Value * This,QualType ThisTy,llvm::Value * ImplicitParam,QualType ImplicitParamTy,const CallExpr * CE)1010b57cec5SDimitry Andric RValue CodeGenFunction::EmitCXXDestructorCall(
1020b57cec5SDimitry Andric GlobalDecl Dtor, const CGCallee &Callee, llvm::Value *This, QualType ThisTy,
1030b57cec5SDimitry Andric llvm::Value *ImplicitParam, QualType ImplicitParamTy, const CallExpr *CE) {
1040b57cec5SDimitry Andric const CXXMethodDecl *DtorDecl = cast<CXXMethodDecl>(Dtor.getDecl());
1050b57cec5SDimitry Andric
1060b57cec5SDimitry Andric assert(!ThisTy.isNull());
1070b57cec5SDimitry Andric assert(ThisTy->getAsCXXRecordDecl() == DtorDecl->getParent() &&
1080b57cec5SDimitry Andric "Pointer/Object mixup");
1090b57cec5SDimitry Andric
1100b57cec5SDimitry Andric LangAS SrcAS = ThisTy.getAddressSpace();
1110b57cec5SDimitry Andric LangAS DstAS = DtorDecl->getMethodQualifiers().getAddressSpace();
1120b57cec5SDimitry Andric if (SrcAS != DstAS) {
1130b57cec5SDimitry Andric QualType DstTy = DtorDecl->getThisType();
1140b57cec5SDimitry Andric llvm::Type *NewType = CGM.getTypes().ConvertType(DstTy);
1150b57cec5SDimitry Andric This = getTargetHooks().performAddrSpaceCast(*this, This, SrcAS, DstAS,
1160b57cec5SDimitry Andric NewType);
1170b57cec5SDimitry Andric }
1180b57cec5SDimitry Andric
1190b57cec5SDimitry Andric CallArgList Args;
1201ac55f4cSDimitry Andric commonEmitCXXMemberOrOperatorCall(*this, Dtor, This, ImplicitParam,
1210b57cec5SDimitry Andric ImplicitParamTy, CE, Args, nullptr);
1220b57cec5SDimitry Andric return EmitCall(CGM.getTypes().arrangeCXXStructorDeclaration(Dtor), Callee,
123fe6060f1SDimitry Andric ReturnValueSlot(), Args, nullptr, CE && CE == MustTailCall,
124c3ca3130SDimitry Andric CE ? CE->getExprLoc() : SourceLocation{});
1250b57cec5SDimitry Andric }
1260b57cec5SDimitry Andric
EmitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr * E)1270b57cec5SDimitry Andric RValue CodeGenFunction::EmitCXXPseudoDestructorExpr(
1280b57cec5SDimitry Andric const CXXPseudoDestructorExpr *E) {
1290b57cec5SDimitry Andric QualType DestroyedType = E->getDestroyedType();
1300b57cec5SDimitry Andric if (DestroyedType.hasStrongOrWeakObjCLifetime()) {
1310b57cec5SDimitry Andric // Automatic Reference Counting:
1320b57cec5SDimitry Andric // If the pseudo-expression names a retainable object with weak or
1330b57cec5SDimitry Andric // strong lifetime, the object shall be released.
1340b57cec5SDimitry Andric Expr *BaseExpr = E->getBase();
1350b57cec5SDimitry Andric Address BaseValue = Address::invalid();
1360b57cec5SDimitry Andric Qualifiers BaseQuals;
1370b57cec5SDimitry Andric
1380b57cec5SDimitry Andric // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
1390b57cec5SDimitry Andric if (E->isArrow()) {
1400b57cec5SDimitry Andric BaseValue = EmitPointerWithAlignment(BaseExpr);
141480093f4SDimitry Andric const auto *PTy = BaseExpr->getType()->castAs<PointerType>();
1420b57cec5SDimitry Andric BaseQuals = PTy->getPointeeType().getQualifiers();
1430b57cec5SDimitry Andric } else {
1440b57cec5SDimitry Andric LValue BaseLV = EmitLValue(BaseExpr);
145480093f4SDimitry Andric BaseValue = BaseLV.getAddress(*this);
1460b57cec5SDimitry Andric QualType BaseTy = BaseExpr->getType();
1470b57cec5SDimitry Andric BaseQuals = BaseTy.getQualifiers();
1480b57cec5SDimitry Andric }
1490b57cec5SDimitry Andric
1500b57cec5SDimitry Andric switch (DestroyedType.getObjCLifetime()) {
1510b57cec5SDimitry Andric case Qualifiers::OCL_None:
1520b57cec5SDimitry Andric case Qualifiers::OCL_ExplicitNone:
1530b57cec5SDimitry Andric case Qualifiers::OCL_Autoreleasing:
1540b57cec5SDimitry Andric break;
1550b57cec5SDimitry Andric
1560b57cec5SDimitry Andric case Qualifiers::OCL_Strong:
1570b57cec5SDimitry Andric EmitARCRelease(Builder.CreateLoad(BaseValue,
1580b57cec5SDimitry Andric DestroyedType.isVolatileQualified()),
1590b57cec5SDimitry Andric ARCPreciseLifetime);
1600b57cec5SDimitry Andric break;
1610b57cec5SDimitry Andric
1620b57cec5SDimitry Andric case Qualifiers::OCL_Weak:
1630b57cec5SDimitry Andric EmitARCDestroyWeak(BaseValue);
1640b57cec5SDimitry Andric break;
1650b57cec5SDimitry Andric }
1660b57cec5SDimitry Andric } else {
1670b57cec5SDimitry Andric // C++ [expr.pseudo]p1:
1680b57cec5SDimitry Andric // The result shall only be used as the operand for the function call
1690b57cec5SDimitry Andric // operator (), and the result of such a call has type void. The only
1700b57cec5SDimitry Andric // effect is the evaluation of the postfix-expression before the dot or
1710b57cec5SDimitry Andric // arrow.
1720b57cec5SDimitry Andric EmitIgnoredExpr(E->getBase());
1730b57cec5SDimitry Andric }
1740b57cec5SDimitry Andric
1750b57cec5SDimitry Andric return RValue::get(nullptr);
1760b57cec5SDimitry Andric }
1770b57cec5SDimitry Andric
getCXXRecord(const Expr * E)1780b57cec5SDimitry Andric static CXXRecordDecl *getCXXRecord(const Expr *E) {
1790b57cec5SDimitry Andric QualType T = E->getType();
1800b57cec5SDimitry Andric if (const PointerType *PTy = T->getAs<PointerType>())
1810b57cec5SDimitry Andric T = PTy->getPointeeType();
1820b57cec5SDimitry Andric const RecordType *Ty = T->castAs<RecordType>();
1830b57cec5SDimitry Andric return cast<CXXRecordDecl>(Ty->getDecl());
1840b57cec5SDimitry Andric }
1850b57cec5SDimitry Andric
1860b57cec5SDimitry Andric // Note: This function also emit constructor calls to support a MSVC
1870b57cec5SDimitry Andric // extensions allowing explicit constructor function call.
EmitCXXMemberCallExpr(const CXXMemberCallExpr * CE,ReturnValueSlot ReturnValue)1880b57cec5SDimitry Andric RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
1890b57cec5SDimitry Andric ReturnValueSlot ReturnValue) {
1900b57cec5SDimitry Andric const Expr *callee = CE->getCallee()->IgnoreParens();
1910b57cec5SDimitry Andric
1920b57cec5SDimitry Andric if (isa<BinaryOperator>(callee))
1930b57cec5SDimitry Andric return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
1940b57cec5SDimitry Andric
1950b57cec5SDimitry Andric const MemberExpr *ME = cast<MemberExpr>(callee);
1960b57cec5SDimitry Andric const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
1970b57cec5SDimitry Andric
1980b57cec5SDimitry Andric if (MD->isStatic()) {
1990b57cec5SDimitry Andric // The method is static, emit it as we would a regular call.
2000b57cec5SDimitry Andric CGCallee callee =
2010b57cec5SDimitry Andric CGCallee::forDirect(CGM.GetAddrOfFunction(MD), GlobalDecl(MD));
2020b57cec5SDimitry Andric return EmitCall(getContext().getPointerType(MD->getType()), callee, CE,
2030b57cec5SDimitry Andric ReturnValue);
2040b57cec5SDimitry Andric }
2050b57cec5SDimitry Andric
2060b57cec5SDimitry Andric bool HasQualifier = ME->hasQualifier();
2070b57cec5SDimitry Andric NestedNameSpecifier *Qualifier = HasQualifier ? ME->getQualifier() : nullptr;
2080b57cec5SDimitry Andric bool IsArrow = ME->isArrow();
2090b57cec5SDimitry Andric const Expr *Base = ME->getBase();
2100b57cec5SDimitry Andric
2110b57cec5SDimitry Andric return EmitCXXMemberOrOperatorMemberCallExpr(
2120b57cec5SDimitry Andric CE, MD, ReturnValue, HasQualifier, Qualifier, IsArrow, Base);
2130b57cec5SDimitry Andric }
2140b57cec5SDimitry Andric
EmitCXXMemberOrOperatorMemberCallExpr(const CallExpr * CE,const CXXMethodDecl * MD,ReturnValueSlot ReturnValue,bool HasQualifier,NestedNameSpecifier * Qualifier,bool IsArrow,const Expr * Base)2150b57cec5SDimitry Andric RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr(
2160b57cec5SDimitry Andric const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue,
2170b57cec5SDimitry Andric bool HasQualifier, NestedNameSpecifier *Qualifier, bool IsArrow,
2180b57cec5SDimitry Andric const Expr *Base) {
2190b57cec5SDimitry Andric assert(isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE));
2200b57cec5SDimitry Andric
2210b57cec5SDimitry Andric // Compute the object pointer.
2220b57cec5SDimitry Andric bool CanUseVirtualCall = MD->isVirtual() && !HasQualifier;
2230b57cec5SDimitry Andric
2240b57cec5SDimitry Andric const CXXMethodDecl *DevirtualizedMethod = nullptr;
2250b57cec5SDimitry Andric if (CanUseVirtualCall &&
2260b57cec5SDimitry Andric MD->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) {
2270b57cec5SDimitry Andric const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
2280b57cec5SDimitry Andric DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
2290b57cec5SDimitry Andric assert(DevirtualizedMethod);
2300b57cec5SDimitry Andric const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
231e8d8bef9SDimitry Andric const Expr *Inner = Base->IgnoreParenBaseCasts();
2320b57cec5SDimitry Andric if (DevirtualizedMethod->getReturnType().getCanonicalType() !=
2330b57cec5SDimitry Andric MD->getReturnType().getCanonicalType())
2340b57cec5SDimitry Andric // If the return types are not the same, this might be a case where more
2350b57cec5SDimitry Andric // code needs to run to compensate for it. For example, the derived
2360b57cec5SDimitry Andric // method might return a type that inherits form from the return
2370b57cec5SDimitry Andric // type of MD and has a prefix.
2380b57cec5SDimitry Andric // For now we just avoid devirtualizing these covariant cases.
2390b57cec5SDimitry Andric DevirtualizedMethod = nullptr;
2400b57cec5SDimitry Andric else if (getCXXRecord(Inner) == DevirtualizedClass)
2410b57cec5SDimitry Andric // If the class of the Inner expression is where the dynamic method
2420b57cec5SDimitry Andric // is defined, build the this pointer from it.
2430b57cec5SDimitry Andric Base = Inner;
2440b57cec5SDimitry Andric else if (getCXXRecord(Base) != DevirtualizedClass) {
2450b57cec5SDimitry Andric // If the method is defined in a class that is not the best dynamic
2460b57cec5SDimitry Andric // one or the one of the full expression, we would have to build
2470b57cec5SDimitry Andric // a derived-to-base cast to compute the correct this pointer, but
2480b57cec5SDimitry Andric // we don't have support for that yet, so do a virtual call.
2490b57cec5SDimitry Andric DevirtualizedMethod = nullptr;
2500b57cec5SDimitry Andric }
2510b57cec5SDimitry Andric }
2520b57cec5SDimitry Andric
253480093f4SDimitry Andric bool TrivialForCodegen =
254480093f4SDimitry Andric MD->isTrivial() || (MD->isDefaulted() && MD->getParent()->isUnion());
255480093f4SDimitry Andric bool TrivialAssignment =
256480093f4SDimitry Andric TrivialForCodegen &&
257480093f4SDimitry Andric (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
258480093f4SDimitry Andric !MD->getParent()->mayInsertExtraPadding();
259480093f4SDimitry Andric
2600b57cec5SDimitry Andric // C++17 demands that we evaluate the RHS of a (possibly-compound) assignment
2610b57cec5SDimitry Andric // operator before the LHS.
2620b57cec5SDimitry Andric CallArgList RtlArgStorage;
2630b57cec5SDimitry Andric CallArgList *RtlArgs = nullptr;
264480093f4SDimitry Andric LValue TrivialAssignmentRHS;
2650b57cec5SDimitry Andric if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
2660b57cec5SDimitry Andric if (OCE->isAssignmentOp()) {
267480093f4SDimitry Andric if (TrivialAssignment) {
268480093f4SDimitry Andric TrivialAssignmentRHS = EmitLValue(CE->getArg(1));
269480093f4SDimitry Andric } else {
2700b57cec5SDimitry Andric RtlArgs = &RtlArgStorage;
2710b57cec5SDimitry Andric EmitCallArgs(*RtlArgs, MD->getType()->castAs<FunctionProtoType>(),
2720b57cec5SDimitry Andric drop_begin(CE->arguments(), 1), CE->getDirectCallee(),
2730b57cec5SDimitry Andric /*ParamsToSkip*/0, EvaluationOrder::ForceRightToLeft);
2740b57cec5SDimitry Andric }
2750b57cec5SDimitry Andric }
276480093f4SDimitry Andric }
2770b57cec5SDimitry Andric
2780b57cec5SDimitry Andric LValue This;
2790b57cec5SDimitry Andric if (IsArrow) {
2800b57cec5SDimitry Andric LValueBaseInfo BaseInfo;
2810b57cec5SDimitry Andric TBAAAccessInfo TBAAInfo;
2820b57cec5SDimitry Andric Address ThisValue = EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo);
2830b57cec5SDimitry Andric This = MakeAddrLValue(ThisValue, Base->getType(), BaseInfo, TBAAInfo);
2840b57cec5SDimitry Andric } else {
2850b57cec5SDimitry Andric This = EmitLValue(Base);
2860b57cec5SDimitry Andric }
2870b57cec5SDimitry Andric
2880b57cec5SDimitry Andric if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2890b57cec5SDimitry Andric // This is the MSVC p->Ctor::Ctor(...) extension. We assume that's
2900b57cec5SDimitry Andric // constructing a new complete object of type Ctor.
2910b57cec5SDimitry Andric assert(!RtlArgs);
2920b57cec5SDimitry Andric assert(ReturnValue.isNull() && "Constructor shouldn't have return value");
2930b57cec5SDimitry Andric CallArgList Args;
2940b57cec5SDimitry Andric commonEmitCXXMemberOrOperatorCall(
2951ac55f4cSDimitry Andric *this, {Ctor, Ctor_Complete}, This.getPointer(*this),
2961ac55f4cSDimitry Andric /*ImplicitParam=*/nullptr,
2970b57cec5SDimitry Andric /*ImplicitParamTy=*/QualType(), CE, Args, nullptr);
2980b57cec5SDimitry Andric
2990b57cec5SDimitry Andric EmitCXXConstructorCall(Ctor, Ctor_Complete, /*ForVirtualBase=*/false,
300480093f4SDimitry Andric /*Delegating=*/false, This.getAddress(*this), Args,
3010b57cec5SDimitry Andric AggValueSlot::DoesNotOverlap, CE->getExprLoc(),
3020b57cec5SDimitry Andric /*NewPointerIsChecked=*/false);
3030b57cec5SDimitry Andric return RValue::get(nullptr);
3040b57cec5SDimitry Andric }
3050b57cec5SDimitry Andric
306480093f4SDimitry Andric if (TrivialForCodegen) {
307480093f4SDimitry Andric if (isa<CXXDestructorDecl>(MD))
308480093f4SDimitry Andric return RValue::get(nullptr);
309480093f4SDimitry Andric
310480093f4SDimitry Andric if (TrivialAssignment) {
3110b57cec5SDimitry Andric // We don't like to generate the trivial copy/move assignment operator
3120b57cec5SDimitry Andric // when it isn't necessary; just produce the proper effect here.
313480093f4SDimitry Andric // It's important that we use the result of EmitLValue here rather than
314480093f4SDimitry Andric // emitting call arguments, in order to preserve TBAA information from
315480093f4SDimitry Andric // the RHS.
3160b57cec5SDimitry Andric LValue RHS = isa<CXXOperatorCallExpr>(CE)
317480093f4SDimitry Andric ? TrivialAssignmentRHS
3180b57cec5SDimitry Andric : EmitLValue(*CE->arg_begin());
3190b57cec5SDimitry Andric EmitAggregateAssign(This, RHS, CE->getType());
320480093f4SDimitry Andric return RValue::get(This.getPointer(*this));
3210b57cec5SDimitry Andric }
322480093f4SDimitry Andric
323480093f4SDimitry Andric assert(MD->getParent()->mayInsertExtraPadding() &&
324480093f4SDimitry Andric "unknown trivial member function");
3250b57cec5SDimitry Andric }
3260b57cec5SDimitry Andric
3270b57cec5SDimitry Andric // Compute the function type we're calling.
3280b57cec5SDimitry Andric const CXXMethodDecl *CalleeDecl =
3290b57cec5SDimitry Andric DevirtualizedMethod ? DevirtualizedMethod : MD;
3300b57cec5SDimitry Andric const CGFunctionInfo *FInfo = nullptr;
3310b57cec5SDimitry Andric if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
3320b57cec5SDimitry Andric FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
3330b57cec5SDimitry Andric GlobalDecl(Dtor, Dtor_Complete));
3340b57cec5SDimitry Andric else
3350b57cec5SDimitry Andric FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
3360b57cec5SDimitry Andric
3370b57cec5SDimitry Andric llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
3380b57cec5SDimitry Andric
3390b57cec5SDimitry Andric // C++11 [class.mfct.non-static]p2:
3400b57cec5SDimitry Andric // If a non-static member function of a class X is called for an object that
3410b57cec5SDimitry Andric // is not of type X, or of a type derived from X, the behavior is undefined.
3420b57cec5SDimitry Andric SourceLocation CallLoc;
3430b57cec5SDimitry Andric ASTContext &C = getContext();
3440b57cec5SDimitry Andric if (CE)
3450b57cec5SDimitry Andric CallLoc = CE->getExprLoc();
3460b57cec5SDimitry Andric
3470b57cec5SDimitry Andric SanitizerSet SkippedChecks;
3480b57cec5SDimitry Andric if (const auto *CMCE = dyn_cast<CXXMemberCallExpr>(CE)) {
3490b57cec5SDimitry Andric auto *IOA = CMCE->getImplicitObjectArgument();
3500b57cec5SDimitry Andric bool IsImplicitObjectCXXThis = IsWrappedCXXThis(IOA);
3510b57cec5SDimitry Andric if (IsImplicitObjectCXXThis)
3520b57cec5SDimitry Andric SkippedChecks.set(SanitizerKind::Alignment, true);
3530b57cec5SDimitry Andric if (IsImplicitObjectCXXThis || isa<DeclRefExpr>(IOA))
3540b57cec5SDimitry Andric SkippedChecks.set(SanitizerKind::Null, true);
3550b57cec5SDimitry Andric }
356480093f4SDimitry Andric EmitTypeCheck(CodeGenFunction::TCK_MemberCall, CallLoc,
357480093f4SDimitry Andric This.getPointer(*this),
3580b57cec5SDimitry Andric C.getRecordType(CalleeDecl->getParent()),
3590b57cec5SDimitry Andric /*Alignment=*/CharUnits::Zero(), SkippedChecks);
3600b57cec5SDimitry Andric
3610b57cec5SDimitry Andric // C++ [class.virtual]p12:
3620b57cec5SDimitry Andric // Explicit qualification with the scope operator (5.1) suppresses the
3630b57cec5SDimitry Andric // virtual call mechanism.
3640b57cec5SDimitry Andric //
3650b57cec5SDimitry Andric // We also don't emit a virtual call if the base expression has a record type
3660b57cec5SDimitry Andric // because then we know what the type is.
3670b57cec5SDimitry Andric bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
3680b57cec5SDimitry Andric
3690b57cec5SDimitry Andric if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl)) {
3700b57cec5SDimitry Andric assert(CE->arg_begin() == CE->arg_end() &&
3710b57cec5SDimitry Andric "Destructor shouldn't have explicit parameters");
3720b57cec5SDimitry Andric assert(ReturnValue.isNull() && "Destructor shouldn't have return value");
3730b57cec5SDimitry Andric if (UseVirtualCall) {
374480093f4SDimitry Andric CGM.getCXXABI().EmitVirtualDestructorCall(*this, Dtor, Dtor_Complete,
375480093f4SDimitry Andric This.getAddress(*this),
3760b57cec5SDimitry Andric cast<CXXMemberCallExpr>(CE));
3770b57cec5SDimitry Andric } else {
3780b57cec5SDimitry Andric GlobalDecl GD(Dtor, Dtor_Complete);
3790b57cec5SDimitry Andric CGCallee Callee;
3800b57cec5SDimitry Andric if (getLangOpts().AppleKext && Dtor->isVirtual() && HasQualifier)
3810b57cec5SDimitry Andric Callee = BuildAppleKextVirtualCall(Dtor, Qualifier, Ty);
3820b57cec5SDimitry Andric else if (!DevirtualizedMethod)
3830b57cec5SDimitry Andric Callee =
3840b57cec5SDimitry Andric CGCallee::forDirect(CGM.getAddrOfCXXStructor(GD, FInfo, Ty), GD);
3850b57cec5SDimitry Andric else {
3860b57cec5SDimitry Andric Callee = CGCallee::forDirect(CGM.GetAddrOfFunction(GD, Ty), GD);
3870b57cec5SDimitry Andric }
3880b57cec5SDimitry Andric
3890b57cec5SDimitry Andric QualType ThisTy =
3900b57cec5SDimitry Andric IsArrow ? Base->getType()->getPointeeType() : Base->getType();
391480093f4SDimitry Andric EmitCXXDestructorCall(GD, Callee, This.getPointer(*this), ThisTy,
3920b57cec5SDimitry Andric /*ImplicitParam=*/nullptr,
393c3ca3130SDimitry Andric /*ImplicitParamTy=*/QualType(), CE);
3940b57cec5SDimitry Andric }
3950b57cec5SDimitry Andric return RValue::get(nullptr);
3960b57cec5SDimitry Andric }
3970b57cec5SDimitry Andric
3980b57cec5SDimitry Andric // FIXME: Uses of 'MD' past this point need to be audited. We may need to use
3990b57cec5SDimitry Andric // 'CalleeDecl' instead.
4000b57cec5SDimitry Andric
4010b57cec5SDimitry Andric CGCallee Callee;
4020b57cec5SDimitry Andric if (UseVirtualCall) {
403480093f4SDimitry Andric Callee = CGCallee::forVirtual(CE, MD, This.getAddress(*this), Ty);
4040b57cec5SDimitry Andric } else {
4050b57cec5SDimitry Andric if (SanOpts.has(SanitizerKind::CFINVCall) &&
4060b57cec5SDimitry Andric MD->getParent()->isDynamicClass()) {
4070b57cec5SDimitry Andric llvm::Value *VTable;
4080b57cec5SDimitry Andric const CXXRecordDecl *RD;
409480093f4SDimitry Andric std::tie(VTable, RD) = CGM.getCXXABI().LoadVTablePtr(
410480093f4SDimitry Andric *this, This.getAddress(*this), CalleeDecl->getParent());
4110b57cec5SDimitry Andric EmitVTablePtrCheckForCall(RD, VTable, CFITCK_NVCall, CE->getBeginLoc());
4120b57cec5SDimitry Andric }
4130b57cec5SDimitry Andric
4140b57cec5SDimitry Andric if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
4150b57cec5SDimitry Andric Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
4160b57cec5SDimitry Andric else if (!DevirtualizedMethod)
4170b57cec5SDimitry Andric Callee =
4180b57cec5SDimitry Andric CGCallee::forDirect(CGM.GetAddrOfFunction(MD, Ty), GlobalDecl(MD));
4190b57cec5SDimitry Andric else {
4200b57cec5SDimitry Andric Callee =
4210b57cec5SDimitry Andric CGCallee::forDirect(CGM.GetAddrOfFunction(DevirtualizedMethod, Ty),
4220b57cec5SDimitry Andric GlobalDecl(DevirtualizedMethod));
4230b57cec5SDimitry Andric }
4240b57cec5SDimitry Andric }
4250b57cec5SDimitry Andric
4260b57cec5SDimitry Andric if (MD->isVirtual()) {
4270b57cec5SDimitry Andric Address NewThisAddr =
4280b57cec5SDimitry Andric CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
429480093f4SDimitry Andric *this, CalleeDecl, This.getAddress(*this), UseVirtualCall);
4300b57cec5SDimitry Andric This.setAddress(NewThisAddr);
4310b57cec5SDimitry Andric }
4320b57cec5SDimitry Andric
4330b57cec5SDimitry Andric return EmitCXXMemberOrOperatorCall(
434480093f4SDimitry Andric CalleeDecl, Callee, ReturnValue, This.getPointer(*this),
4350b57cec5SDimitry Andric /*ImplicitParam=*/nullptr, QualType(), CE, RtlArgs);
4360b57cec5SDimitry Andric }
4370b57cec5SDimitry Andric
4380b57cec5SDimitry Andric RValue
EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr * E,ReturnValueSlot ReturnValue)4390b57cec5SDimitry Andric CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
4400b57cec5SDimitry Andric ReturnValueSlot ReturnValue) {
4410b57cec5SDimitry Andric const BinaryOperator *BO =
4420b57cec5SDimitry Andric cast<BinaryOperator>(E->getCallee()->IgnoreParens());
4430b57cec5SDimitry Andric const Expr *BaseExpr = BO->getLHS();
4440b57cec5SDimitry Andric const Expr *MemFnExpr = BO->getRHS();
4450b57cec5SDimitry Andric
446a7dea167SDimitry Andric const auto *MPT = MemFnExpr->getType()->castAs<MemberPointerType>();
447a7dea167SDimitry Andric const auto *FPT = MPT->getPointeeType()->castAs<FunctionProtoType>();
448a7dea167SDimitry Andric const auto *RD =
449a7dea167SDimitry Andric cast<CXXRecordDecl>(MPT->getClass()->castAs<RecordType>()->getDecl());
4500b57cec5SDimitry Andric
4510b57cec5SDimitry Andric // Emit the 'this' pointer.
4520b57cec5SDimitry Andric Address This = Address::invalid();
4530b57cec5SDimitry Andric if (BO->getOpcode() == BO_PtrMemI)
454fe013be4SDimitry Andric This = EmitPointerWithAlignment(BaseExpr, nullptr, nullptr, KnownNonNull);
4550b57cec5SDimitry Andric else
456fe013be4SDimitry Andric This = EmitLValue(BaseExpr, KnownNonNull).getAddress(*this);
4570b57cec5SDimitry Andric
4580b57cec5SDimitry Andric EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This.getPointer(),
4590b57cec5SDimitry Andric QualType(MPT->getClass(), 0));
4600b57cec5SDimitry Andric
4610b57cec5SDimitry Andric // Get the member function pointer.
4620b57cec5SDimitry Andric llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
4630b57cec5SDimitry Andric
4640b57cec5SDimitry Andric // Ask the ABI to load the callee. Note that This is modified.
4650b57cec5SDimitry Andric llvm::Value *ThisPtrForCall = nullptr;
4660b57cec5SDimitry Andric CGCallee Callee =
4670b57cec5SDimitry Andric CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This,
4680b57cec5SDimitry Andric ThisPtrForCall, MemFnPtr, MPT);
4690b57cec5SDimitry Andric
4700b57cec5SDimitry Andric CallArgList Args;
4710b57cec5SDimitry Andric
4720b57cec5SDimitry Andric QualType ThisType =
4730b57cec5SDimitry Andric getContext().getPointerType(getContext().getTagDeclType(RD));
4740b57cec5SDimitry Andric
4750b57cec5SDimitry Andric // Push the this ptr.
4760b57cec5SDimitry Andric Args.add(RValue::get(ThisPtrForCall), ThisType);
4770b57cec5SDimitry Andric
4780b57cec5SDimitry Andric RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1);
4790b57cec5SDimitry Andric
4800b57cec5SDimitry Andric // And the rest of the call args
4810b57cec5SDimitry Andric EmitCallArgs(Args, FPT, E->arguments());
4820b57cec5SDimitry Andric return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required,
4830b57cec5SDimitry Andric /*PrefixSize=*/0),
484fe6060f1SDimitry Andric Callee, ReturnValue, Args, nullptr, E == MustTailCall,
485fe6060f1SDimitry Andric E->getExprLoc());
4860b57cec5SDimitry Andric }
4870b57cec5SDimitry Andric
4880b57cec5SDimitry Andric RValue
EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr * E,const CXXMethodDecl * MD,ReturnValueSlot ReturnValue)4890b57cec5SDimitry Andric CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
4900b57cec5SDimitry Andric const CXXMethodDecl *MD,
4910b57cec5SDimitry Andric ReturnValueSlot ReturnValue) {
492c9157d92SDimitry Andric assert(MD->isImplicitObjectMemberFunction() &&
4930b57cec5SDimitry Andric "Trying to emit a member call expr on a static method!");
4940b57cec5SDimitry Andric return EmitCXXMemberOrOperatorMemberCallExpr(
4950b57cec5SDimitry Andric E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr,
4960b57cec5SDimitry Andric /*IsArrow=*/false, E->getArg(0));
4970b57cec5SDimitry Andric }
4980b57cec5SDimitry Andric
EmitCUDAKernelCallExpr(const CUDAKernelCallExpr * E,ReturnValueSlot ReturnValue)4990b57cec5SDimitry Andric RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
5000b57cec5SDimitry Andric ReturnValueSlot ReturnValue) {
5010b57cec5SDimitry Andric return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
5020b57cec5SDimitry Andric }
5030b57cec5SDimitry Andric
EmitNullBaseClassInitialization(CodeGenFunction & CGF,Address DestPtr,const CXXRecordDecl * Base)5040b57cec5SDimitry Andric static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
5050b57cec5SDimitry Andric Address DestPtr,
5060b57cec5SDimitry Andric const CXXRecordDecl *Base) {
5070b57cec5SDimitry Andric if (Base->isEmpty())
5080b57cec5SDimitry Andric return;
5090b57cec5SDimitry Andric
510fe013be4SDimitry Andric DestPtr = DestPtr.withElementType(CGF.Int8Ty);
5110b57cec5SDimitry Andric
5120b57cec5SDimitry Andric const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
5130b57cec5SDimitry Andric CharUnits NVSize = Layout.getNonVirtualSize();
5140b57cec5SDimitry Andric
5150b57cec5SDimitry Andric // We cannot simply zero-initialize the entire base sub-object if vbptrs are
5160b57cec5SDimitry Andric // present, they are initialized by the most derived class before calling the
5170b57cec5SDimitry Andric // constructor.
5180b57cec5SDimitry Andric SmallVector<std::pair<CharUnits, CharUnits>, 1> Stores;
5190b57cec5SDimitry Andric Stores.emplace_back(CharUnits::Zero(), NVSize);
5200b57cec5SDimitry Andric
5210b57cec5SDimitry Andric // Each store is split by the existence of a vbptr.
5220b57cec5SDimitry Andric CharUnits VBPtrWidth = CGF.getPointerSize();
5230b57cec5SDimitry Andric std::vector<CharUnits> VBPtrOffsets =
5240b57cec5SDimitry Andric CGF.CGM.getCXXABI().getVBPtrOffsets(Base);
5250b57cec5SDimitry Andric for (CharUnits VBPtrOffset : VBPtrOffsets) {
5260b57cec5SDimitry Andric // Stop before we hit any virtual base pointers located in virtual bases.
5270b57cec5SDimitry Andric if (VBPtrOffset >= NVSize)
5280b57cec5SDimitry Andric break;
5290b57cec5SDimitry Andric std::pair<CharUnits, CharUnits> LastStore = Stores.pop_back_val();
5300b57cec5SDimitry Andric CharUnits LastStoreOffset = LastStore.first;
5310b57cec5SDimitry Andric CharUnits LastStoreSize = LastStore.second;
5320b57cec5SDimitry Andric
5330b57cec5SDimitry Andric CharUnits SplitBeforeOffset = LastStoreOffset;
5340b57cec5SDimitry Andric CharUnits SplitBeforeSize = VBPtrOffset - SplitBeforeOffset;
5350b57cec5SDimitry Andric assert(!SplitBeforeSize.isNegative() && "negative store size!");
5360b57cec5SDimitry Andric if (!SplitBeforeSize.isZero())
5370b57cec5SDimitry Andric Stores.emplace_back(SplitBeforeOffset, SplitBeforeSize);
5380b57cec5SDimitry Andric
5390b57cec5SDimitry Andric CharUnits SplitAfterOffset = VBPtrOffset + VBPtrWidth;
5400b57cec5SDimitry Andric CharUnits SplitAfterSize = LastStoreSize - SplitAfterOffset;
5410b57cec5SDimitry Andric assert(!SplitAfterSize.isNegative() && "negative store size!");
5420b57cec5SDimitry Andric if (!SplitAfterSize.isZero())
5430b57cec5SDimitry Andric Stores.emplace_back(SplitAfterOffset, SplitAfterSize);
5440b57cec5SDimitry Andric }
5450b57cec5SDimitry Andric
5460b57cec5SDimitry Andric // If the type contains a pointer to data member we can't memset it to zero.
5470b57cec5SDimitry Andric // Instead, create a null constant and copy it to the destination.
5480b57cec5SDimitry Andric // TODO: there are other patterns besides zero that we can usefully memset,
5490b57cec5SDimitry Andric // like -1, which happens to be the pattern used by member-pointers.
5500b57cec5SDimitry Andric // TODO: isZeroInitializable can be over-conservative in the case where a
5510b57cec5SDimitry Andric // virtual base contains a member pointer.
5520b57cec5SDimitry Andric llvm::Constant *NullConstantForBase = CGF.CGM.EmitNullConstantForBase(Base);
5530b57cec5SDimitry Andric if (!NullConstantForBase->isNullValue()) {
5540b57cec5SDimitry Andric llvm::GlobalVariable *NullVariable = new llvm::GlobalVariable(
5550b57cec5SDimitry Andric CGF.CGM.getModule(), NullConstantForBase->getType(),
5560b57cec5SDimitry Andric /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage,
5570b57cec5SDimitry Andric NullConstantForBase, Twine());
5580b57cec5SDimitry Andric
55981ad6265SDimitry Andric CharUnits Align =
56081ad6265SDimitry Andric std::max(Layout.getNonVirtualAlignment(), DestPtr.getAlignment());
561a7dea167SDimitry Andric NullVariable->setAlignment(Align.getAsAlign());
5620b57cec5SDimitry Andric
563fe013be4SDimitry Andric Address SrcPtr(NullVariable, CGF.Int8Ty, Align);
5640b57cec5SDimitry Andric
5650b57cec5SDimitry Andric // Get and call the appropriate llvm.memcpy overload.
5660b57cec5SDimitry Andric for (std::pair<CharUnits, CharUnits> Store : Stores) {
5670b57cec5SDimitry Andric CharUnits StoreOffset = Store.first;
5680b57cec5SDimitry Andric CharUnits StoreSize = Store.second;
5690b57cec5SDimitry Andric llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
5700b57cec5SDimitry Andric CGF.Builder.CreateMemCpy(
5710b57cec5SDimitry Andric CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
5720b57cec5SDimitry Andric CGF.Builder.CreateConstInBoundsByteGEP(SrcPtr, StoreOffset),
5730b57cec5SDimitry Andric StoreSizeVal);
5740b57cec5SDimitry Andric }
5750b57cec5SDimitry Andric
5760b57cec5SDimitry Andric // Otherwise, just memset the whole thing to zero. This is legal
5770b57cec5SDimitry Andric // because in LLVM, all default initializers (other than the ones we just
5780b57cec5SDimitry Andric // handled above) are guaranteed to have a bit pattern of all zeros.
5790b57cec5SDimitry Andric } else {
5800b57cec5SDimitry Andric for (std::pair<CharUnits, CharUnits> Store : Stores) {
5810b57cec5SDimitry Andric CharUnits StoreOffset = Store.first;
5820b57cec5SDimitry Andric CharUnits StoreSize = Store.second;
5830b57cec5SDimitry Andric llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
5840b57cec5SDimitry Andric CGF.Builder.CreateMemSet(
5850b57cec5SDimitry Andric CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
5860b57cec5SDimitry Andric CGF.Builder.getInt8(0), StoreSizeVal);
5870b57cec5SDimitry Andric }
5880b57cec5SDimitry Andric }
5890b57cec5SDimitry Andric }
5900b57cec5SDimitry Andric
5910b57cec5SDimitry Andric void
EmitCXXConstructExpr(const CXXConstructExpr * E,AggValueSlot Dest)5920b57cec5SDimitry Andric CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
5930b57cec5SDimitry Andric AggValueSlot Dest) {
5940b57cec5SDimitry Andric assert(!Dest.isIgnored() && "Must have a destination!");
5950b57cec5SDimitry Andric const CXXConstructorDecl *CD = E->getConstructor();
5960b57cec5SDimitry Andric
5970b57cec5SDimitry Andric // If we require zero initialization before (or instead of) calling the
5980b57cec5SDimitry Andric // constructor, as can be the case with a non-user-provided default
5990b57cec5SDimitry Andric // constructor, emit the zero initialization now, unless destination is
6000b57cec5SDimitry Andric // already zeroed.
6010b57cec5SDimitry Andric if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
6020b57cec5SDimitry Andric switch (E->getConstructionKind()) {
603c9157d92SDimitry Andric case CXXConstructionKind::Delegating:
604c9157d92SDimitry Andric case CXXConstructionKind::Complete:
6050b57cec5SDimitry Andric EmitNullInitialization(Dest.getAddress(), E->getType());
6060b57cec5SDimitry Andric break;
607c9157d92SDimitry Andric case CXXConstructionKind::VirtualBase:
608c9157d92SDimitry Andric case CXXConstructionKind::NonVirtualBase:
6090b57cec5SDimitry Andric EmitNullBaseClassInitialization(*this, Dest.getAddress(),
6100b57cec5SDimitry Andric CD->getParent());
6110b57cec5SDimitry Andric break;
6120b57cec5SDimitry Andric }
6130b57cec5SDimitry Andric }
6140b57cec5SDimitry Andric
6150b57cec5SDimitry Andric // If this is a call to a trivial default constructor, do nothing.
6160b57cec5SDimitry Andric if (CD->isTrivial() && CD->isDefaultConstructor())
6170b57cec5SDimitry Andric return;
6180b57cec5SDimitry Andric
6190b57cec5SDimitry Andric // Elide the constructor if we're constructing from a temporary.
6200b57cec5SDimitry Andric if (getLangOpts().ElideConstructors && E->isElidable()) {
62128a41182SDimitry Andric // FIXME: This only handles the simplest case, where the source object
62228a41182SDimitry Andric // is passed directly as the first argument to the constructor.
62328a41182SDimitry Andric // This should also handle stepping though implicit casts and
62428a41182SDimitry Andric // conversion sequences which involve two steps, with a
62528a41182SDimitry Andric // conversion operator followed by a converting constructor.
62628a41182SDimitry Andric const Expr *SrcObj = E->getArg(0);
62728a41182SDimitry Andric assert(SrcObj->isTemporaryObject(getContext(), CD->getParent()));
62828a41182SDimitry Andric assert(
62928a41182SDimitry Andric getContext().hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
63028a41182SDimitry Andric EmitAggExpr(SrcObj, Dest);
6310b57cec5SDimitry Andric return;
6320b57cec5SDimitry Andric }
6330b57cec5SDimitry Andric
6340b57cec5SDimitry Andric if (const ArrayType *arrayType
6350b57cec5SDimitry Andric = getContext().getAsArrayType(E->getType())) {
6360b57cec5SDimitry Andric EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddress(), E,
6370b57cec5SDimitry Andric Dest.isSanitizerChecked());
6380b57cec5SDimitry Andric } else {
6390b57cec5SDimitry Andric CXXCtorType Type = Ctor_Complete;
6400b57cec5SDimitry Andric bool ForVirtualBase = false;
6410b57cec5SDimitry Andric bool Delegating = false;
6420b57cec5SDimitry Andric
6430b57cec5SDimitry Andric switch (E->getConstructionKind()) {
644c9157d92SDimitry Andric case CXXConstructionKind::Delegating:
6450b57cec5SDimitry Andric // We should be emitting a constructor; GlobalDecl will assert this
6460b57cec5SDimitry Andric Type = CurGD.getCtorType();
6470b57cec5SDimitry Andric Delegating = true;
6480b57cec5SDimitry Andric break;
6490b57cec5SDimitry Andric
650c9157d92SDimitry Andric case CXXConstructionKind::Complete:
6510b57cec5SDimitry Andric Type = Ctor_Complete;
6520b57cec5SDimitry Andric break;
6530b57cec5SDimitry Andric
654c9157d92SDimitry Andric case CXXConstructionKind::VirtualBase:
6550b57cec5SDimitry Andric ForVirtualBase = true;
656bdd1243dSDimitry Andric [[fallthrough]];
6570b57cec5SDimitry Andric
658c9157d92SDimitry Andric case CXXConstructionKind::NonVirtualBase:
6590b57cec5SDimitry Andric Type = Ctor_Base;
6600b57cec5SDimitry Andric }
6610b57cec5SDimitry Andric
6620b57cec5SDimitry Andric // Call the constructor.
6630b57cec5SDimitry Andric EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating, Dest, E);
6640b57cec5SDimitry Andric }
6650b57cec5SDimitry Andric }
6660b57cec5SDimitry Andric
EmitSynthesizedCXXCopyCtor(Address Dest,Address Src,const Expr * Exp)6670b57cec5SDimitry Andric void CodeGenFunction::EmitSynthesizedCXXCopyCtor(Address Dest, Address Src,
6680b57cec5SDimitry Andric const Expr *Exp) {
6690b57cec5SDimitry Andric if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
6700b57cec5SDimitry Andric Exp = E->getSubExpr();
6710b57cec5SDimitry Andric assert(isa<CXXConstructExpr>(Exp) &&
6720b57cec5SDimitry Andric "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
6730b57cec5SDimitry Andric const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
6740b57cec5SDimitry Andric const CXXConstructorDecl *CD = E->getConstructor();
6750b57cec5SDimitry Andric RunCleanupsScope Scope(*this);
6760b57cec5SDimitry Andric
6770b57cec5SDimitry Andric // If we require zero initialization before (or instead of) calling the
6780b57cec5SDimitry Andric // constructor, as can be the case with a non-user-provided default
6790b57cec5SDimitry Andric // constructor, emit the zero initialization now.
6800b57cec5SDimitry Andric // FIXME. Do I still need this for a copy ctor synthesis?
6810b57cec5SDimitry Andric if (E->requiresZeroInitialization())
6820b57cec5SDimitry Andric EmitNullInitialization(Dest, E->getType());
6830b57cec5SDimitry Andric
6840b57cec5SDimitry Andric assert(!getContext().getAsConstantArrayType(E->getType())
6850b57cec5SDimitry Andric && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
6860b57cec5SDimitry Andric EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E);
6870b57cec5SDimitry Andric }
6880b57cec5SDimitry Andric
CalculateCookiePadding(CodeGenFunction & CGF,const CXXNewExpr * E)6890b57cec5SDimitry Andric static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
6900b57cec5SDimitry Andric const CXXNewExpr *E) {
6910b57cec5SDimitry Andric if (!E->isArray())
6920b57cec5SDimitry Andric return CharUnits::Zero();
6930b57cec5SDimitry Andric
6940b57cec5SDimitry Andric // No cookie is required if the operator new[] being used is the
6950b57cec5SDimitry Andric // reserved placement operator new[].
6960b57cec5SDimitry Andric if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
6970b57cec5SDimitry Andric return CharUnits::Zero();
6980b57cec5SDimitry Andric
6990b57cec5SDimitry Andric return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
7000b57cec5SDimitry Andric }
7010b57cec5SDimitry Andric
EmitCXXNewAllocSize(CodeGenFunction & CGF,const CXXNewExpr * e,unsigned minElements,llvm::Value * & numElements,llvm::Value * & sizeWithoutCookie)7020b57cec5SDimitry Andric static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
7030b57cec5SDimitry Andric const CXXNewExpr *e,
7040b57cec5SDimitry Andric unsigned minElements,
7050b57cec5SDimitry Andric llvm::Value *&numElements,
7060b57cec5SDimitry Andric llvm::Value *&sizeWithoutCookie) {
7070b57cec5SDimitry Andric QualType type = e->getAllocatedType();
7080b57cec5SDimitry Andric
7090b57cec5SDimitry Andric if (!e->isArray()) {
7100b57cec5SDimitry Andric CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
7110b57cec5SDimitry Andric sizeWithoutCookie
7120b57cec5SDimitry Andric = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
7130b57cec5SDimitry Andric return sizeWithoutCookie;
7140b57cec5SDimitry Andric }
7150b57cec5SDimitry Andric
7160b57cec5SDimitry Andric // The width of size_t.
7170b57cec5SDimitry Andric unsigned sizeWidth = CGF.SizeTy->getBitWidth();
7180b57cec5SDimitry Andric
7190b57cec5SDimitry Andric // Figure out the cookie size.
7200b57cec5SDimitry Andric llvm::APInt cookieSize(sizeWidth,
7210b57cec5SDimitry Andric CalculateCookiePadding(CGF, e).getQuantity());
7220b57cec5SDimitry Andric
7230b57cec5SDimitry Andric // Emit the array size expression.
7240b57cec5SDimitry Andric // We multiply the size of all dimensions for NumElements.
7250b57cec5SDimitry Andric // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
7260b57cec5SDimitry Andric numElements =
7270b57cec5SDimitry Andric ConstantEmitter(CGF).tryEmitAbstract(*e->getArraySize(), e->getType());
7280b57cec5SDimitry Andric if (!numElements)
7290b57cec5SDimitry Andric numElements = CGF.EmitScalarExpr(*e->getArraySize());
7300b57cec5SDimitry Andric assert(isa<llvm::IntegerType>(numElements->getType()));
7310b57cec5SDimitry Andric
7320b57cec5SDimitry Andric // The number of elements can be have an arbitrary integer type;
7330b57cec5SDimitry Andric // essentially, we need to multiply it by a constant factor, add a
7340b57cec5SDimitry Andric // cookie size, and verify that the result is representable as a
7350b57cec5SDimitry Andric // size_t. That's just a gloss, though, and it's wrong in one
7360b57cec5SDimitry Andric // important way: if the count is negative, it's an error even if
7370b57cec5SDimitry Andric // the cookie size would bring the total size >= 0.
7380b57cec5SDimitry Andric bool isSigned
7390b57cec5SDimitry Andric = (*e->getArraySize())->getType()->isSignedIntegerOrEnumerationType();
7400b57cec5SDimitry Andric llvm::IntegerType *numElementsType
7410b57cec5SDimitry Andric = cast<llvm::IntegerType>(numElements->getType());
7420b57cec5SDimitry Andric unsigned numElementsWidth = numElementsType->getBitWidth();
7430b57cec5SDimitry Andric
7440b57cec5SDimitry Andric // Compute the constant factor.
7450b57cec5SDimitry Andric llvm::APInt arraySizeMultiplier(sizeWidth, 1);
7460b57cec5SDimitry Andric while (const ConstantArrayType *CAT
7470b57cec5SDimitry Andric = CGF.getContext().getAsConstantArrayType(type)) {
7480b57cec5SDimitry Andric type = CAT->getElementType();
7490b57cec5SDimitry Andric arraySizeMultiplier *= CAT->getSize();
7500b57cec5SDimitry Andric }
7510b57cec5SDimitry Andric
7520b57cec5SDimitry Andric CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
7530b57cec5SDimitry Andric llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
7540b57cec5SDimitry Andric typeSizeMultiplier *= arraySizeMultiplier;
7550b57cec5SDimitry Andric
7560b57cec5SDimitry Andric // This will be a size_t.
7570b57cec5SDimitry Andric llvm::Value *size;
7580b57cec5SDimitry Andric
7590b57cec5SDimitry Andric // If someone is doing 'new int[42]' there is no need to do a dynamic check.
7600b57cec5SDimitry Andric // Don't bloat the -O0 code.
7610b57cec5SDimitry Andric if (llvm::ConstantInt *numElementsC =
7620b57cec5SDimitry Andric dyn_cast<llvm::ConstantInt>(numElements)) {
7630b57cec5SDimitry Andric const llvm::APInt &count = numElementsC->getValue();
7640b57cec5SDimitry Andric
7650b57cec5SDimitry Andric bool hasAnyOverflow = false;
7660b57cec5SDimitry Andric
7670b57cec5SDimitry Andric // If 'count' was a negative number, it's an overflow.
7680b57cec5SDimitry Andric if (isSigned && count.isNegative())
7690b57cec5SDimitry Andric hasAnyOverflow = true;
7700b57cec5SDimitry Andric
7710b57cec5SDimitry Andric // We want to do all this arithmetic in size_t. If numElements is
7720b57cec5SDimitry Andric // wider than that, check whether it's already too big, and if so,
7730b57cec5SDimitry Andric // overflow.
7740b57cec5SDimitry Andric else if (numElementsWidth > sizeWidth &&
775fe013be4SDimitry Andric numElementsWidth - sizeWidth > count.countl_zero())
7760b57cec5SDimitry Andric hasAnyOverflow = true;
7770b57cec5SDimitry Andric
7780b57cec5SDimitry Andric // Okay, compute a count at the right width.
7790b57cec5SDimitry Andric llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
7800b57cec5SDimitry Andric
7810b57cec5SDimitry Andric // If there is a brace-initializer, we cannot allocate fewer elements than
7820b57cec5SDimitry Andric // there are initializers. If we do, that's treated like an overflow.
7830b57cec5SDimitry Andric if (adjustedCount.ult(minElements))
7840b57cec5SDimitry Andric hasAnyOverflow = true;
7850b57cec5SDimitry Andric
7860b57cec5SDimitry Andric // Scale numElements by that. This might overflow, but we don't
7870b57cec5SDimitry Andric // care because it only overflows if allocationSize does, too, and
7880b57cec5SDimitry Andric // if that overflows then we shouldn't use this.
7890b57cec5SDimitry Andric numElements = llvm::ConstantInt::get(CGF.SizeTy,
7900b57cec5SDimitry Andric adjustedCount * arraySizeMultiplier);
7910b57cec5SDimitry Andric
7920b57cec5SDimitry Andric // Compute the size before cookie, and track whether it overflowed.
7930b57cec5SDimitry Andric bool overflow;
7940b57cec5SDimitry Andric llvm::APInt allocationSize
7950b57cec5SDimitry Andric = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
7960b57cec5SDimitry Andric hasAnyOverflow |= overflow;
7970b57cec5SDimitry Andric
7980b57cec5SDimitry Andric // Add in the cookie, and check whether it's overflowed.
7990b57cec5SDimitry Andric if (cookieSize != 0) {
8000b57cec5SDimitry Andric // Save the current size without a cookie. This shouldn't be
8010b57cec5SDimitry Andric // used if there was overflow.
8020b57cec5SDimitry Andric sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
8030b57cec5SDimitry Andric
8040b57cec5SDimitry Andric allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
8050b57cec5SDimitry Andric hasAnyOverflow |= overflow;
8060b57cec5SDimitry Andric }
8070b57cec5SDimitry Andric
8080b57cec5SDimitry Andric // On overflow, produce a -1 so operator new will fail.
8090b57cec5SDimitry Andric if (hasAnyOverflow) {
8100b57cec5SDimitry Andric size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
8110b57cec5SDimitry Andric } else {
8120b57cec5SDimitry Andric size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
8130b57cec5SDimitry Andric }
8140b57cec5SDimitry Andric
8150b57cec5SDimitry Andric // Otherwise, we might need to use the overflow intrinsics.
8160b57cec5SDimitry Andric } else {
8170b57cec5SDimitry Andric // There are up to five conditions we need to test for:
8180b57cec5SDimitry Andric // 1) if isSigned, we need to check whether numElements is negative;
8190b57cec5SDimitry Andric // 2) if numElementsWidth > sizeWidth, we need to check whether
8200b57cec5SDimitry Andric // numElements is larger than something representable in size_t;
8210b57cec5SDimitry Andric // 3) if minElements > 0, we need to check whether numElements is smaller
8220b57cec5SDimitry Andric // than that.
8230b57cec5SDimitry Andric // 4) we need to compute
8240b57cec5SDimitry Andric // sizeWithoutCookie := numElements * typeSizeMultiplier
8250b57cec5SDimitry Andric // and check whether it overflows; and
8260b57cec5SDimitry Andric // 5) if we need a cookie, we need to compute
8270b57cec5SDimitry Andric // size := sizeWithoutCookie + cookieSize
8280b57cec5SDimitry Andric // and check whether it overflows.
8290b57cec5SDimitry Andric
8300b57cec5SDimitry Andric llvm::Value *hasOverflow = nullptr;
8310b57cec5SDimitry Andric
8320b57cec5SDimitry Andric // If numElementsWidth > sizeWidth, then one way or another, we're
8330b57cec5SDimitry Andric // going to have to do a comparison for (2), and this happens to
8340b57cec5SDimitry Andric // take care of (1), too.
8350b57cec5SDimitry Andric if (numElementsWidth > sizeWidth) {
836fe013be4SDimitry Andric llvm::APInt threshold =
837fe013be4SDimitry Andric llvm::APInt::getOneBitSet(numElementsWidth, sizeWidth);
8380b57cec5SDimitry Andric
8390b57cec5SDimitry Andric llvm::Value *thresholdV
8400b57cec5SDimitry Andric = llvm::ConstantInt::get(numElementsType, threshold);
8410b57cec5SDimitry Andric
8420b57cec5SDimitry Andric hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
8430b57cec5SDimitry Andric numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
8440b57cec5SDimitry Andric
8450b57cec5SDimitry Andric // Otherwise, if we're signed, we want to sext up to size_t.
8460b57cec5SDimitry Andric } else if (isSigned) {
8470b57cec5SDimitry Andric if (numElementsWidth < sizeWidth)
8480b57cec5SDimitry Andric numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
8490b57cec5SDimitry Andric
8500b57cec5SDimitry Andric // If there's a non-1 type size multiplier, then we can do the
8510b57cec5SDimitry Andric // signedness check at the same time as we do the multiply
8520b57cec5SDimitry Andric // because a negative number times anything will cause an
8530b57cec5SDimitry Andric // unsigned overflow. Otherwise, we have to do it here. But at least
8540b57cec5SDimitry Andric // in this case, we can subsume the >= minElements check.
8550b57cec5SDimitry Andric if (typeSizeMultiplier == 1)
8560b57cec5SDimitry Andric hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
8570b57cec5SDimitry Andric llvm::ConstantInt::get(CGF.SizeTy, minElements));
8580b57cec5SDimitry Andric
8590b57cec5SDimitry Andric // Otherwise, zext up to size_t if necessary.
8600b57cec5SDimitry Andric } else if (numElementsWidth < sizeWidth) {
8610b57cec5SDimitry Andric numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
8620b57cec5SDimitry Andric }
8630b57cec5SDimitry Andric
8640b57cec5SDimitry Andric assert(numElements->getType() == CGF.SizeTy);
8650b57cec5SDimitry Andric
8660b57cec5SDimitry Andric if (minElements) {
8670b57cec5SDimitry Andric // Don't allow allocation of fewer elements than we have initializers.
8680b57cec5SDimitry Andric if (!hasOverflow) {
8690b57cec5SDimitry Andric hasOverflow = CGF.Builder.CreateICmpULT(numElements,
8700b57cec5SDimitry Andric llvm::ConstantInt::get(CGF.SizeTy, minElements));
8710b57cec5SDimitry Andric } else if (numElementsWidth > sizeWidth) {
8720b57cec5SDimitry Andric // The other existing overflow subsumes this check.
8730b57cec5SDimitry Andric // We do an unsigned comparison, since any signed value < -1 is
8740b57cec5SDimitry Andric // taken care of either above or below.
8750b57cec5SDimitry Andric hasOverflow = CGF.Builder.CreateOr(hasOverflow,
8760b57cec5SDimitry Andric CGF.Builder.CreateICmpULT(numElements,
8770b57cec5SDimitry Andric llvm::ConstantInt::get(CGF.SizeTy, minElements)));
8780b57cec5SDimitry Andric }
8790b57cec5SDimitry Andric }
8800b57cec5SDimitry Andric
8810b57cec5SDimitry Andric size = numElements;
8820b57cec5SDimitry Andric
8830b57cec5SDimitry Andric // Multiply by the type size if necessary. This multiplier
8840b57cec5SDimitry Andric // includes all the factors for nested arrays.
8850b57cec5SDimitry Andric //
8860b57cec5SDimitry Andric // This step also causes numElements to be scaled up by the
8870b57cec5SDimitry Andric // nested-array factor if necessary. Overflow on this computation
8880b57cec5SDimitry Andric // can be ignored because the result shouldn't be used if
8890b57cec5SDimitry Andric // allocation fails.
8900b57cec5SDimitry Andric if (typeSizeMultiplier != 1) {
8910b57cec5SDimitry Andric llvm::Function *umul_with_overflow
8920b57cec5SDimitry Andric = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
8930b57cec5SDimitry Andric
8940b57cec5SDimitry Andric llvm::Value *tsmV =
8950b57cec5SDimitry Andric llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
8960b57cec5SDimitry Andric llvm::Value *result =
8970b57cec5SDimitry Andric CGF.Builder.CreateCall(umul_with_overflow, {size, tsmV});
8980b57cec5SDimitry Andric
8990b57cec5SDimitry Andric llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
9000b57cec5SDimitry Andric if (hasOverflow)
9010b57cec5SDimitry Andric hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
9020b57cec5SDimitry Andric else
9030b57cec5SDimitry Andric hasOverflow = overflowed;
9040b57cec5SDimitry Andric
9050b57cec5SDimitry Andric size = CGF.Builder.CreateExtractValue(result, 0);
9060b57cec5SDimitry Andric
9070b57cec5SDimitry Andric // Also scale up numElements by the array size multiplier.
9080b57cec5SDimitry Andric if (arraySizeMultiplier != 1) {
9090b57cec5SDimitry Andric // If the base element type size is 1, then we can re-use the
9100b57cec5SDimitry Andric // multiply we just did.
9110b57cec5SDimitry Andric if (typeSize.isOne()) {
9120b57cec5SDimitry Andric assert(arraySizeMultiplier == typeSizeMultiplier);
9130b57cec5SDimitry Andric numElements = size;
9140b57cec5SDimitry Andric
9150b57cec5SDimitry Andric // Otherwise we need a separate multiply.
9160b57cec5SDimitry Andric } else {
9170b57cec5SDimitry Andric llvm::Value *asmV =
9180b57cec5SDimitry Andric llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
9190b57cec5SDimitry Andric numElements = CGF.Builder.CreateMul(numElements, asmV);
9200b57cec5SDimitry Andric }
9210b57cec5SDimitry Andric }
9220b57cec5SDimitry Andric } else {
9230b57cec5SDimitry Andric // numElements doesn't need to be scaled.
9240b57cec5SDimitry Andric assert(arraySizeMultiplier == 1);
9250b57cec5SDimitry Andric }
9260b57cec5SDimitry Andric
9270b57cec5SDimitry Andric // Add in the cookie size if necessary.
9280b57cec5SDimitry Andric if (cookieSize != 0) {
9290b57cec5SDimitry Andric sizeWithoutCookie = size;
9300b57cec5SDimitry Andric
9310b57cec5SDimitry Andric llvm::Function *uadd_with_overflow
9320b57cec5SDimitry Andric = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
9330b57cec5SDimitry Andric
9340b57cec5SDimitry Andric llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
9350b57cec5SDimitry Andric llvm::Value *result =
9360b57cec5SDimitry Andric CGF.Builder.CreateCall(uadd_with_overflow, {size, cookieSizeV});
9370b57cec5SDimitry Andric
9380b57cec5SDimitry Andric llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
9390b57cec5SDimitry Andric if (hasOverflow)
9400b57cec5SDimitry Andric hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
9410b57cec5SDimitry Andric else
9420b57cec5SDimitry Andric hasOverflow = overflowed;
9430b57cec5SDimitry Andric
9440b57cec5SDimitry Andric size = CGF.Builder.CreateExtractValue(result, 0);
9450b57cec5SDimitry Andric }
9460b57cec5SDimitry Andric
9470b57cec5SDimitry Andric // If we had any possibility of dynamic overflow, make a select to
9480b57cec5SDimitry Andric // overwrite 'size' with an all-ones value, which should cause
9490b57cec5SDimitry Andric // operator new to throw.
9500b57cec5SDimitry Andric if (hasOverflow)
9510b57cec5SDimitry Andric size = CGF.Builder.CreateSelect(hasOverflow,
9520b57cec5SDimitry Andric llvm::Constant::getAllOnesValue(CGF.SizeTy),
9530b57cec5SDimitry Andric size);
9540b57cec5SDimitry Andric }
9550b57cec5SDimitry Andric
9560b57cec5SDimitry Andric if (cookieSize == 0)
9570b57cec5SDimitry Andric sizeWithoutCookie = size;
9580b57cec5SDimitry Andric else
9590b57cec5SDimitry Andric assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
9600b57cec5SDimitry Andric
9610b57cec5SDimitry Andric return size;
9620b57cec5SDimitry Andric }
9630b57cec5SDimitry Andric
StoreAnyExprIntoOneUnit(CodeGenFunction & CGF,const Expr * Init,QualType AllocType,Address NewPtr,AggValueSlot::Overlap_t MayOverlap)9640b57cec5SDimitry Andric static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
9650b57cec5SDimitry Andric QualType AllocType, Address NewPtr,
9660b57cec5SDimitry Andric AggValueSlot::Overlap_t MayOverlap) {
9670b57cec5SDimitry Andric // FIXME: Refactor with EmitExprAsInit.
9680b57cec5SDimitry Andric switch (CGF.getEvaluationKind(AllocType)) {
9690b57cec5SDimitry Andric case TEK_Scalar:
9700b57cec5SDimitry Andric CGF.EmitScalarInit(Init, nullptr,
9710b57cec5SDimitry Andric CGF.MakeAddrLValue(NewPtr, AllocType), false);
9720b57cec5SDimitry Andric return;
9730b57cec5SDimitry Andric case TEK_Complex:
9740b57cec5SDimitry Andric CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType),
9750b57cec5SDimitry Andric /*isInit*/ true);
9760b57cec5SDimitry Andric return;
9770b57cec5SDimitry Andric case TEK_Aggregate: {
9780b57cec5SDimitry Andric AggValueSlot Slot
9790b57cec5SDimitry Andric = AggValueSlot::forAddr(NewPtr, AllocType.getQualifiers(),
9800b57cec5SDimitry Andric AggValueSlot::IsDestructed,
9810b57cec5SDimitry Andric AggValueSlot::DoesNotNeedGCBarriers,
9820b57cec5SDimitry Andric AggValueSlot::IsNotAliased,
9830b57cec5SDimitry Andric MayOverlap, AggValueSlot::IsNotZeroed,
9840b57cec5SDimitry Andric AggValueSlot::IsSanitizerChecked);
9850b57cec5SDimitry Andric CGF.EmitAggExpr(Init, Slot);
9860b57cec5SDimitry Andric return;
9870b57cec5SDimitry Andric }
9880b57cec5SDimitry Andric }
9890b57cec5SDimitry Andric llvm_unreachable("bad evaluation kind");
9900b57cec5SDimitry Andric }
9910b57cec5SDimitry Andric
EmitNewArrayInitializer(const CXXNewExpr * E,QualType ElementType,llvm::Type * ElementTy,Address BeginPtr,llvm::Value * NumElements,llvm::Value * AllocSizeWithoutCookie)9920b57cec5SDimitry Andric void CodeGenFunction::EmitNewArrayInitializer(
9930b57cec5SDimitry Andric const CXXNewExpr *E, QualType ElementType, llvm::Type *ElementTy,
9940b57cec5SDimitry Andric Address BeginPtr, llvm::Value *NumElements,
9950b57cec5SDimitry Andric llvm::Value *AllocSizeWithoutCookie) {
9960b57cec5SDimitry Andric // If we have a type with trivial initialization and no initializer,
9970b57cec5SDimitry Andric // there's nothing to do.
9980b57cec5SDimitry Andric if (!E->hasInitializer())
9990b57cec5SDimitry Andric return;
10000b57cec5SDimitry Andric
10010b57cec5SDimitry Andric Address CurPtr = BeginPtr;
10020b57cec5SDimitry Andric
10030b57cec5SDimitry Andric unsigned InitListElements = 0;
10040b57cec5SDimitry Andric
10050b57cec5SDimitry Andric const Expr *Init = E->getInitializer();
10060b57cec5SDimitry Andric Address EndOfInit = Address::invalid();
10070b57cec5SDimitry Andric QualType::DestructionKind DtorKind = ElementType.isDestructedType();
10080b57cec5SDimitry Andric EHScopeStack::stable_iterator Cleanup;
10090b57cec5SDimitry Andric llvm::Instruction *CleanupDominator = nullptr;
10100b57cec5SDimitry Andric
10110b57cec5SDimitry Andric CharUnits ElementSize = getContext().getTypeSizeInChars(ElementType);
10120b57cec5SDimitry Andric CharUnits ElementAlign =
10130b57cec5SDimitry Andric BeginPtr.getAlignment().alignmentOfArrayElement(ElementSize);
10140b57cec5SDimitry Andric
10150b57cec5SDimitry Andric // Attempt to perform zero-initialization using memset.
10160b57cec5SDimitry Andric auto TryMemsetInitialization = [&]() -> bool {
10170b57cec5SDimitry Andric // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
10180b57cec5SDimitry Andric // we can initialize with a memset to -1.
10190b57cec5SDimitry Andric if (!CGM.getTypes().isZeroInitializable(ElementType))
10200b57cec5SDimitry Andric return false;
10210b57cec5SDimitry Andric
10220b57cec5SDimitry Andric // Optimization: since zero initialization will just set the memory
10230b57cec5SDimitry Andric // to all zeroes, generate a single memset to do it in one shot.
10240b57cec5SDimitry Andric
10250b57cec5SDimitry Andric // Subtract out the size of any elements we've already initialized.
10260b57cec5SDimitry Andric auto *RemainingSize = AllocSizeWithoutCookie;
10270b57cec5SDimitry Andric if (InitListElements) {
10280b57cec5SDimitry Andric // We know this can't overflow; we check this when doing the allocation.
10290b57cec5SDimitry Andric auto *InitializedSize = llvm::ConstantInt::get(
10300b57cec5SDimitry Andric RemainingSize->getType(),
10310b57cec5SDimitry Andric getContext().getTypeSizeInChars(ElementType).getQuantity() *
10320b57cec5SDimitry Andric InitListElements);
10330b57cec5SDimitry Andric RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
10340b57cec5SDimitry Andric }
10350b57cec5SDimitry Andric
10360b57cec5SDimitry Andric // Create the memset.
10370b57cec5SDimitry Andric Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize, false);
10380b57cec5SDimitry Andric return true;
10390b57cec5SDimitry Andric };
10400b57cec5SDimitry Andric
1041*a58f00eaSDimitry Andric const InitListExpr *ILE = dyn_cast<InitListExpr>(Init);
1042*a58f00eaSDimitry Andric const CXXParenListInitExpr *CPLIE = nullptr;
1043*a58f00eaSDimitry Andric const StringLiteral *SL = nullptr;
1044*a58f00eaSDimitry Andric const ObjCEncodeExpr *OCEE = nullptr;
1045*a58f00eaSDimitry Andric const Expr *IgnoreParen = nullptr;
1046*a58f00eaSDimitry Andric if (!ILE) {
1047*a58f00eaSDimitry Andric IgnoreParen = Init->IgnoreParenImpCasts();
1048*a58f00eaSDimitry Andric CPLIE = dyn_cast<CXXParenListInitExpr>(IgnoreParen);
1049*a58f00eaSDimitry Andric SL = dyn_cast<StringLiteral>(IgnoreParen);
1050*a58f00eaSDimitry Andric OCEE = dyn_cast<ObjCEncodeExpr>(IgnoreParen);
1051*a58f00eaSDimitry Andric }
1052*a58f00eaSDimitry Andric
10530b57cec5SDimitry Andric // If the initializer is an initializer list, first do the explicit elements.
1054*a58f00eaSDimitry Andric if (ILE || CPLIE || SL || OCEE) {
10550b57cec5SDimitry Andric // Initializing from a (braced) string literal is a special case; the init
10560b57cec5SDimitry Andric // list element does not initialize a (single) array element.
1057*a58f00eaSDimitry Andric if ((ILE && ILE->isStringLiteralInit()) || SL || OCEE) {
1058*a58f00eaSDimitry Andric if (!ILE)
1059*a58f00eaSDimitry Andric Init = IgnoreParen;
10600b57cec5SDimitry Andric // Initialize the initial portion of length equal to that of the string
10610b57cec5SDimitry Andric // literal. The allocation must be for at least this much; we emitted a
10620b57cec5SDimitry Andric // check for that earlier.
10630b57cec5SDimitry Andric AggValueSlot Slot =
10640b57cec5SDimitry Andric AggValueSlot::forAddr(CurPtr, ElementType.getQualifiers(),
10650b57cec5SDimitry Andric AggValueSlot::IsDestructed,
10660b57cec5SDimitry Andric AggValueSlot::DoesNotNeedGCBarriers,
10670b57cec5SDimitry Andric AggValueSlot::IsNotAliased,
10680b57cec5SDimitry Andric AggValueSlot::DoesNotOverlap,
10690b57cec5SDimitry Andric AggValueSlot::IsNotZeroed,
10700b57cec5SDimitry Andric AggValueSlot::IsSanitizerChecked);
1071*a58f00eaSDimitry Andric EmitAggExpr(ILE ? ILE->getInit(0) : Init, Slot);
10720b57cec5SDimitry Andric
10730b57cec5SDimitry Andric // Move past these elements.
10740b57cec5SDimitry Andric InitListElements =
1075*a58f00eaSDimitry Andric cast<ConstantArrayType>(Init->getType()->getAsArrayTypeUnsafe())
1076*a58f00eaSDimitry Andric ->getSize()
1077*a58f00eaSDimitry Andric .getZExtValue();
10780eae32dcSDimitry Andric CurPtr = Builder.CreateConstInBoundsGEP(
10790eae32dcSDimitry Andric CurPtr, InitListElements, "string.init.end");
10800b57cec5SDimitry Andric
10810b57cec5SDimitry Andric // Zero out the rest, if any remain.
10820b57cec5SDimitry Andric llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
10830b57cec5SDimitry Andric if (!ConstNum || !ConstNum->equalsInt(InitListElements)) {
10840b57cec5SDimitry Andric bool OK = TryMemsetInitialization();
10850b57cec5SDimitry Andric (void)OK;
10860b57cec5SDimitry Andric assert(OK && "couldn't memset character type?");
10870b57cec5SDimitry Andric }
10880b57cec5SDimitry Andric return;
10890b57cec5SDimitry Andric }
10900b57cec5SDimitry Andric
1091*a58f00eaSDimitry Andric ArrayRef<const Expr *> InitExprs =
1092*a58f00eaSDimitry Andric ILE ? ILE->inits() : CPLIE->getInitExprs();
1093*a58f00eaSDimitry Andric InitListElements = InitExprs.size();
10940b57cec5SDimitry Andric
10950b57cec5SDimitry Andric // If this is a multi-dimensional array new, we will initialize multiple
10960b57cec5SDimitry Andric // elements with each init list element.
10970b57cec5SDimitry Andric QualType AllocType = E->getAllocatedType();
10980b57cec5SDimitry Andric if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
10990b57cec5SDimitry Andric AllocType->getAsArrayTypeUnsafe())) {
11000b57cec5SDimitry Andric ElementTy = ConvertTypeForMem(AllocType);
1101fe013be4SDimitry Andric CurPtr = CurPtr.withElementType(ElementTy);
11020b57cec5SDimitry Andric InitListElements *= getContext().getConstantArrayElementCount(CAT);
11030b57cec5SDimitry Andric }
11040b57cec5SDimitry Andric
11050b57cec5SDimitry Andric // Enter a partial-destruction Cleanup if necessary.
11060b57cec5SDimitry Andric if (needsEHCleanup(DtorKind)) {
11070b57cec5SDimitry Andric // In principle we could tell the Cleanup where we are more
11080b57cec5SDimitry Andric // directly, but the control flow can get so varied here that it
11090b57cec5SDimitry Andric // would actually be quite complex. Therefore we go through an
11100b57cec5SDimitry Andric // alloca.
11110b57cec5SDimitry Andric EndOfInit = CreateTempAlloca(BeginPtr.getType(), getPointerAlign(),
11120b57cec5SDimitry Andric "array.init.end");
11130b57cec5SDimitry Andric CleanupDominator = Builder.CreateStore(BeginPtr.getPointer(), EndOfInit);
11140b57cec5SDimitry Andric pushIrregularPartialArrayCleanup(BeginPtr.getPointer(), EndOfInit,
11150b57cec5SDimitry Andric ElementType, ElementAlign,
11160b57cec5SDimitry Andric getDestroyer(DtorKind));
11170b57cec5SDimitry Andric Cleanup = EHStack.stable_begin();
11180b57cec5SDimitry Andric }
11190b57cec5SDimitry Andric
11200b57cec5SDimitry Andric CharUnits StartAlign = CurPtr.getAlignment();
1121*a58f00eaSDimitry Andric unsigned i = 0;
1122*a58f00eaSDimitry Andric for (const Expr *IE : InitExprs) {
11230b57cec5SDimitry Andric // Tell the cleanup that it needs to destroy up to this
11240b57cec5SDimitry Andric // element. TODO: some of these stores can be trivially
11250b57cec5SDimitry Andric // observed to be unnecessary.
11260b57cec5SDimitry Andric if (EndOfInit.isValid()) {
1127c9157d92SDimitry Andric Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
11280b57cec5SDimitry Andric }
11290b57cec5SDimitry Andric // FIXME: If the last initializer is an incomplete initializer list for
11300b57cec5SDimitry Andric // an array, and we have an array filler, we can fold together the two
11310b57cec5SDimitry Andric // initialization loops.
1132*a58f00eaSDimitry Andric StoreAnyExprIntoOneUnit(*this, IE, IE->getType(), CurPtr,
11330b57cec5SDimitry Andric AggValueSlot::DoesNotOverlap);
11341fd87a68SDimitry Andric CurPtr = Address(Builder.CreateInBoundsGEP(
11351fd87a68SDimitry Andric CurPtr.getElementType(), CurPtr.getPointer(),
11361fd87a68SDimitry Andric Builder.getSize(1), "array.exp.next"),
11371fd87a68SDimitry Andric CurPtr.getElementType(),
1138*a58f00eaSDimitry Andric StartAlign.alignmentAtOffset((++i) * ElementSize));
11390b57cec5SDimitry Andric }
11400b57cec5SDimitry Andric
11410b57cec5SDimitry Andric // The remaining elements are filled with the array filler expression.
1142*a58f00eaSDimitry Andric Init = ILE ? ILE->getArrayFiller() : CPLIE->getArrayFiller();
11430b57cec5SDimitry Andric
11440b57cec5SDimitry Andric // Extract the initializer for the individual array elements by pulling
11450b57cec5SDimitry Andric // out the array filler from all the nested initializer lists. This avoids
11460b57cec5SDimitry Andric // generating a nested loop for the initialization.
11470b57cec5SDimitry Andric while (Init && Init->getType()->isConstantArrayType()) {
11480b57cec5SDimitry Andric auto *SubILE = dyn_cast<InitListExpr>(Init);
11490b57cec5SDimitry Andric if (!SubILE)
11500b57cec5SDimitry Andric break;
11510b57cec5SDimitry Andric assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
11520b57cec5SDimitry Andric Init = SubILE->getArrayFiller();
11530b57cec5SDimitry Andric }
11540b57cec5SDimitry Andric
11550b57cec5SDimitry Andric // Switch back to initializing one base element at a time.
1156fe013be4SDimitry Andric CurPtr = CurPtr.withElementType(BeginPtr.getElementType());
11570b57cec5SDimitry Andric }
11580b57cec5SDimitry Andric
11590b57cec5SDimitry Andric // If all elements have already been initialized, skip any further
11600b57cec5SDimitry Andric // initialization.
11610b57cec5SDimitry Andric llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
11620b57cec5SDimitry Andric if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
11630b57cec5SDimitry Andric // If there was a Cleanup, deactivate it.
11640b57cec5SDimitry Andric if (CleanupDominator)
11650b57cec5SDimitry Andric DeactivateCleanupBlock(Cleanup, CleanupDominator);
11660b57cec5SDimitry Andric return;
11670b57cec5SDimitry Andric }
11680b57cec5SDimitry Andric
11690b57cec5SDimitry Andric assert(Init && "have trailing elements to initialize but no initializer");
11700b57cec5SDimitry Andric
11710b57cec5SDimitry Andric // If this is a constructor call, try to optimize it out, and failing that
11720b57cec5SDimitry Andric // emit a single loop to initialize all remaining elements.
11730b57cec5SDimitry Andric if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
11740b57cec5SDimitry Andric CXXConstructorDecl *Ctor = CCE->getConstructor();
11750b57cec5SDimitry Andric if (Ctor->isTrivial()) {
11760b57cec5SDimitry Andric // If new expression did not specify value-initialization, then there
11770b57cec5SDimitry Andric // is no initialization.
11780b57cec5SDimitry Andric if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
11790b57cec5SDimitry Andric return;
11800b57cec5SDimitry Andric
11810b57cec5SDimitry Andric if (TryMemsetInitialization())
11820b57cec5SDimitry Andric return;
11830b57cec5SDimitry Andric }
11840b57cec5SDimitry Andric
11850b57cec5SDimitry Andric // Store the new Cleanup position for irregular Cleanups.
11860b57cec5SDimitry Andric //
11870b57cec5SDimitry Andric // FIXME: Share this cleanup with the constructor call emission rather than
11880b57cec5SDimitry Andric // having it create a cleanup of its own.
11890b57cec5SDimitry Andric if (EndOfInit.isValid())
11900b57cec5SDimitry Andric Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
11910b57cec5SDimitry Andric
11920b57cec5SDimitry Andric // Emit a constructor call loop to initialize the remaining elements.
11930b57cec5SDimitry Andric if (InitListElements)
11940b57cec5SDimitry Andric NumElements = Builder.CreateSub(
11950b57cec5SDimitry Andric NumElements,
11960b57cec5SDimitry Andric llvm::ConstantInt::get(NumElements->getType(), InitListElements));
11970b57cec5SDimitry Andric EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,
11980b57cec5SDimitry Andric /*NewPointerIsChecked*/true,
11990b57cec5SDimitry Andric CCE->requiresZeroInitialization());
12000b57cec5SDimitry Andric return;
12010b57cec5SDimitry Andric }
12020b57cec5SDimitry Andric
12030b57cec5SDimitry Andric // If this is value-initialization, we can usually use memset.
12040b57cec5SDimitry Andric ImplicitValueInitExpr IVIE(ElementType);
12050b57cec5SDimitry Andric if (isa<ImplicitValueInitExpr>(Init)) {
12060b57cec5SDimitry Andric if (TryMemsetInitialization())
12070b57cec5SDimitry Andric return;
12080b57cec5SDimitry Andric
12090b57cec5SDimitry Andric // Switch to an ImplicitValueInitExpr for the element type. This handles
12100b57cec5SDimitry Andric // only one case: multidimensional array new of pointers to members. In
12110b57cec5SDimitry Andric // all other cases, we already have an initializer for the array element.
12120b57cec5SDimitry Andric Init = &IVIE;
12130b57cec5SDimitry Andric }
12140b57cec5SDimitry Andric
12150b57cec5SDimitry Andric // At this point we should have found an initializer for the individual
12160b57cec5SDimitry Andric // elements of the array.
12170b57cec5SDimitry Andric assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&
12180b57cec5SDimitry Andric "got wrong type of element to initialize");
12190b57cec5SDimitry Andric
12200b57cec5SDimitry Andric // If we have an empty initializer list, we can usually use memset.
12210b57cec5SDimitry Andric if (auto *ILE = dyn_cast<InitListExpr>(Init))
12220b57cec5SDimitry Andric if (ILE->getNumInits() == 0 && TryMemsetInitialization())
12230b57cec5SDimitry Andric return;
12240b57cec5SDimitry Andric
12250b57cec5SDimitry Andric // If we have a struct whose every field is value-initialized, we can
12260b57cec5SDimitry Andric // usually use memset.
12270b57cec5SDimitry Andric if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
12280b57cec5SDimitry Andric if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
12290b57cec5SDimitry Andric if (RType->getDecl()->isStruct()) {
12300b57cec5SDimitry Andric unsigned NumElements = 0;
12310b57cec5SDimitry Andric if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RType->getDecl()))
12320b57cec5SDimitry Andric NumElements = CXXRD->getNumBases();
12330b57cec5SDimitry Andric for (auto *Field : RType->getDecl()->fields())
12340b57cec5SDimitry Andric if (!Field->isUnnamedBitfield())
12350b57cec5SDimitry Andric ++NumElements;
12360b57cec5SDimitry Andric // FIXME: Recurse into nested InitListExprs.
12370b57cec5SDimitry Andric if (ILE->getNumInits() == NumElements)
12380b57cec5SDimitry Andric for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
12390b57cec5SDimitry Andric if (!isa<ImplicitValueInitExpr>(ILE->getInit(i)))
12400b57cec5SDimitry Andric --NumElements;
12410b57cec5SDimitry Andric if (ILE->getNumInits() == NumElements && TryMemsetInitialization())
12420b57cec5SDimitry Andric return;
12430b57cec5SDimitry Andric }
12440b57cec5SDimitry Andric }
12450b57cec5SDimitry Andric }
12460b57cec5SDimitry Andric
12470b57cec5SDimitry Andric // Create the loop blocks.
12480b57cec5SDimitry Andric llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
12490b57cec5SDimitry Andric llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
12500b57cec5SDimitry Andric llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
12510b57cec5SDimitry Andric
12520b57cec5SDimitry Andric // Find the end of the array, hoisted out of the loop.
12530b57cec5SDimitry Andric llvm::Value *EndPtr =
1254fe6060f1SDimitry Andric Builder.CreateInBoundsGEP(BeginPtr.getElementType(), BeginPtr.getPointer(),
1255fe6060f1SDimitry Andric NumElements, "array.end");
12560b57cec5SDimitry Andric
12570b57cec5SDimitry Andric // If the number of elements isn't constant, we have to now check if there is
12580b57cec5SDimitry Andric // anything left to initialize.
12590b57cec5SDimitry Andric if (!ConstNum) {
12600b57cec5SDimitry Andric llvm::Value *IsEmpty =
12610b57cec5SDimitry Andric Builder.CreateICmpEQ(CurPtr.getPointer(), EndPtr, "array.isempty");
12620b57cec5SDimitry Andric Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
12630b57cec5SDimitry Andric }
12640b57cec5SDimitry Andric
12650b57cec5SDimitry Andric // Enter the loop.
12660b57cec5SDimitry Andric EmitBlock(LoopBB);
12670b57cec5SDimitry Andric
12680b57cec5SDimitry Andric // Set up the current-element phi.
12690b57cec5SDimitry Andric llvm::PHINode *CurPtrPhi =
12700b57cec5SDimitry Andric Builder.CreatePHI(CurPtr.getType(), 2, "array.cur");
12710b57cec5SDimitry Andric CurPtrPhi->addIncoming(CurPtr.getPointer(), EntryBB);
12720b57cec5SDimitry Andric
127381ad6265SDimitry Andric CurPtr = Address(CurPtrPhi, CurPtr.getElementType(), ElementAlign);
12740b57cec5SDimitry Andric
12750b57cec5SDimitry Andric // Store the new Cleanup position for irregular Cleanups.
12760b57cec5SDimitry Andric if (EndOfInit.isValid())
12770b57cec5SDimitry Andric Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
12780b57cec5SDimitry Andric
12790b57cec5SDimitry Andric // Enter a partial-destruction Cleanup if necessary.
12800b57cec5SDimitry Andric if (!CleanupDominator && needsEHCleanup(DtorKind)) {
12810b57cec5SDimitry Andric pushRegularPartialArrayCleanup(BeginPtr.getPointer(), CurPtr.getPointer(),
12820b57cec5SDimitry Andric ElementType, ElementAlign,
12830b57cec5SDimitry Andric getDestroyer(DtorKind));
12840b57cec5SDimitry Andric Cleanup = EHStack.stable_begin();
12850b57cec5SDimitry Andric CleanupDominator = Builder.CreateUnreachable();
12860b57cec5SDimitry Andric }
12870b57cec5SDimitry Andric
12880b57cec5SDimitry Andric // Emit the initializer into this element.
12890b57cec5SDimitry Andric StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr,
12900b57cec5SDimitry Andric AggValueSlot::DoesNotOverlap);
12910b57cec5SDimitry Andric
12920b57cec5SDimitry Andric // Leave the Cleanup if we entered one.
12930b57cec5SDimitry Andric if (CleanupDominator) {
12940b57cec5SDimitry Andric DeactivateCleanupBlock(Cleanup, CleanupDominator);
12950b57cec5SDimitry Andric CleanupDominator->eraseFromParent();
12960b57cec5SDimitry Andric }
12970b57cec5SDimitry Andric
12980b57cec5SDimitry Andric // Advance to the next element by adjusting the pointer type as necessary.
12990b57cec5SDimitry Andric llvm::Value *NextPtr =
13000b57cec5SDimitry Andric Builder.CreateConstInBoundsGEP1_32(ElementTy, CurPtr.getPointer(), 1,
13010b57cec5SDimitry Andric "array.next");
13020b57cec5SDimitry Andric
13030b57cec5SDimitry Andric // Check whether we've gotten to the end of the array and, if so,
13040b57cec5SDimitry Andric // exit the loop.
13050b57cec5SDimitry Andric llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
13060b57cec5SDimitry Andric Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
13070b57cec5SDimitry Andric CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
13080b57cec5SDimitry Andric
13090b57cec5SDimitry Andric EmitBlock(ContBB);
13100b57cec5SDimitry Andric }
13110b57cec5SDimitry Andric
EmitNewInitializer(CodeGenFunction & CGF,const CXXNewExpr * E,QualType ElementType,llvm::Type * ElementTy,Address NewPtr,llvm::Value * NumElements,llvm::Value * AllocSizeWithoutCookie)13120b57cec5SDimitry Andric static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
13130b57cec5SDimitry Andric QualType ElementType, llvm::Type *ElementTy,
13140b57cec5SDimitry Andric Address NewPtr, llvm::Value *NumElements,
13150b57cec5SDimitry Andric llvm::Value *AllocSizeWithoutCookie) {
13160b57cec5SDimitry Andric ApplyDebugLocation DL(CGF, E);
13170b57cec5SDimitry Andric if (E->isArray())
13180b57cec5SDimitry Andric CGF.EmitNewArrayInitializer(E, ElementType, ElementTy, NewPtr, NumElements,
13190b57cec5SDimitry Andric AllocSizeWithoutCookie);
13200b57cec5SDimitry Andric else if (const Expr *Init = E->getInitializer())
13210b57cec5SDimitry Andric StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr,
13220b57cec5SDimitry Andric AggValueSlot::DoesNotOverlap);
13230b57cec5SDimitry Andric }
13240b57cec5SDimitry Andric
13250b57cec5SDimitry Andric /// Emit a call to an operator new or operator delete function, as implicitly
13260b57cec5SDimitry Andric /// created by new-expressions and delete-expressions.
EmitNewDeleteCall(CodeGenFunction & CGF,const FunctionDecl * CalleeDecl,const FunctionProtoType * CalleeType,const CallArgList & Args)13270b57cec5SDimitry Andric static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
13280b57cec5SDimitry Andric const FunctionDecl *CalleeDecl,
13290b57cec5SDimitry Andric const FunctionProtoType *CalleeType,
13300b57cec5SDimitry Andric const CallArgList &Args) {
13310b57cec5SDimitry Andric llvm::CallBase *CallOrInvoke;
13320b57cec5SDimitry Andric llvm::Constant *CalleePtr = CGF.CGM.GetAddrOfFunction(CalleeDecl);
13330b57cec5SDimitry Andric CGCallee Callee = CGCallee::forDirect(CalleePtr, GlobalDecl(CalleeDecl));
13340b57cec5SDimitry Andric RValue RV =
13350b57cec5SDimitry Andric CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(
13360b57cec5SDimitry Andric Args, CalleeType, /*ChainCall=*/false),
13370b57cec5SDimitry Andric Callee, ReturnValueSlot(), Args, &CallOrInvoke);
13380b57cec5SDimitry Andric
13390b57cec5SDimitry Andric /// C++1y [expr.new]p10:
13400b57cec5SDimitry Andric /// [In a new-expression,] an implementation is allowed to omit a call
13410b57cec5SDimitry Andric /// to a replaceable global allocation function.
13420b57cec5SDimitry Andric ///
13430b57cec5SDimitry Andric /// We model such elidable calls with the 'builtin' attribute.
13440b57cec5SDimitry Andric llvm::Function *Fn = dyn_cast<llvm::Function>(CalleePtr);
13450b57cec5SDimitry Andric if (CalleeDecl->isReplaceableGlobalAllocationFunction() &&
13460b57cec5SDimitry Andric Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
1347349cc55cSDimitry Andric CallOrInvoke->addFnAttr(llvm::Attribute::Builtin);
13480b57cec5SDimitry Andric }
13490b57cec5SDimitry Andric
13500b57cec5SDimitry Andric return RV;
13510b57cec5SDimitry Andric }
13520b57cec5SDimitry Andric
EmitBuiltinNewDeleteCall(const FunctionProtoType * Type,const CallExpr * TheCall,bool IsDelete)13530b57cec5SDimitry Andric RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
13540b57cec5SDimitry Andric const CallExpr *TheCall,
13550b57cec5SDimitry Andric bool IsDelete) {
13560b57cec5SDimitry Andric CallArgList Args;
1357e8d8bef9SDimitry Andric EmitCallArgs(Args, Type, TheCall->arguments());
13580b57cec5SDimitry Andric // Find the allocation or deallocation function that we're calling.
13590b57cec5SDimitry Andric ASTContext &Ctx = getContext();
13600b57cec5SDimitry Andric DeclarationName Name = Ctx.DeclarationNames
13610b57cec5SDimitry Andric .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
13620b57cec5SDimitry Andric
13630b57cec5SDimitry Andric for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
13640b57cec5SDimitry Andric if (auto *FD = dyn_cast<FunctionDecl>(Decl))
13650b57cec5SDimitry Andric if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
13660b57cec5SDimitry Andric return EmitNewDeleteCall(*this, FD, Type, Args);
13670b57cec5SDimitry Andric llvm_unreachable("predeclared global operator new/delete is missing");
13680b57cec5SDimitry Andric }
13690b57cec5SDimitry Andric
13700b57cec5SDimitry Andric namespace {
13710b57cec5SDimitry Andric /// The parameters to pass to a usual operator delete.
13720b57cec5SDimitry Andric struct UsualDeleteParams {
13730b57cec5SDimitry Andric bool DestroyingDelete = false;
13740b57cec5SDimitry Andric bool Size = false;
13750b57cec5SDimitry Andric bool Alignment = false;
13760b57cec5SDimitry Andric };
13770b57cec5SDimitry Andric }
13780b57cec5SDimitry Andric
getUsualDeleteParams(const FunctionDecl * FD)13790b57cec5SDimitry Andric static UsualDeleteParams getUsualDeleteParams(const FunctionDecl *FD) {
13800b57cec5SDimitry Andric UsualDeleteParams Params;
13810b57cec5SDimitry Andric
13820b57cec5SDimitry Andric const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
13830b57cec5SDimitry Andric auto AI = FPT->param_type_begin(), AE = FPT->param_type_end();
13840b57cec5SDimitry Andric
13850b57cec5SDimitry Andric // The first argument is always a void*.
13860b57cec5SDimitry Andric ++AI;
13870b57cec5SDimitry Andric
13880b57cec5SDimitry Andric // The next parameter may be a std::destroying_delete_t.
13890b57cec5SDimitry Andric if (FD->isDestroyingOperatorDelete()) {
13900b57cec5SDimitry Andric Params.DestroyingDelete = true;
13910b57cec5SDimitry Andric assert(AI != AE);
13920b57cec5SDimitry Andric ++AI;
13930b57cec5SDimitry Andric }
13940b57cec5SDimitry Andric
13950b57cec5SDimitry Andric // Figure out what other parameters we should be implicitly passing.
13960b57cec5SDimitry Andric if (AI != AE && (*AI)->isIntegerType()) {
13970b57cec5SDimitry Andric Params.Size = true;
13980b57cec5SDimitry Andric ++AI;
13990b57cec5SDimitry Andric }
14000b57cec5SDimitry Andric
14010b57cec5SDimitry Andric if (AI != AE && (*AI)->isAlignValT()) {
14020b57cec5SDimitry Andric Params.Alignment = true;
14030b57cec5SDimitry Andric ++AI;
14040b57cec5SDimitry Andric }
14050b57cec5SDimitry Andric
14060b57cec5SDimitry Andric assert(AI == AE && "unexpected usual deallocation function parameter");
14070b57cec5SDimitry Andric return Params;
14080b57cec5SDimitry Andric }
14090b57cec5SDimitry Andric
14100b57cec5SDimitry Andric namespace {
14110b57cec5SDimitry Andric /// A cleanup to call the given 'operator delete' function upon abnormal
14120b57cec5SDimitry Andric /// exit from a new expression. Templated on a traits type that deals with
14130b57cec5SDimitry Andric /// ensuring that the arguments dominate the cleanup if necessary.
14140b57cec5SDimitry Andric template<typename Traits>
14150b57cec5SDimitry Andric class CallDeleteDuringNew final : public EHScopeStack::Cleanup {
14160b57cec5SDimitry Andric /// Type used to hold llvm::Value*s.
14170b57cec5SDimitry Andric typedef typename Traits::ValueTy ValueTy;
14180b57cec5SDimitry Andric /// Type used to hold RValues.
14190b57cec5SDimitry Andric typedef typename Traits::RValueTy RValueTy;
14200b57cec5SDimitry Andric struct PlacementArg {
14210b57cec5SDimitry Andric RValueTy ArgValue;
14220b57cec5SDimitry Andric QualType ArgType;
14230b57cec5SDimitry Andric };
14240b57cec5SDimitry Andric
14250b57cec5SDimitry Andric unsigned NumPlacementArgs : 31;
14260b57cec5SDimitry Andric unsigned PassAlignmentToPlacementDelete : 1;
14270b57cec5SDimitry Andric const FunctionDecl *OperatorDelete;
14280b57cec5SDimitry Andric ValueTy Ptr;
14290b57cec5SDimitry Andric ValueTy AllocSize;
14300b57cec5SDimitry Andric CharUnits AllocAlign;
14310b57cec5SDimitry Andric
getPlacementArgs()14320b57cec5SDimitry Andric PlacementArg *getPlacementArgs() {
14330b57cec5SDimitry Andric return reinterpret_cast<PlacementArg *>(this + 1);
14340b57cec5SDimitry Andric }
14350b57cec5SDimitry Andric
14360b57cec5SDimitry Andric public:
getExtraSize(size_t NumPlacementArgs)14370b57cec5SDimitry Andric static size_t getExtraSize(size_t NumPlacementArgs) {
14380b57cec5SDimitry Andric return NumPlacementArgs * sizeof(PlacementArg);
14390b57cec5SDimitry Andric }
14400b57cec5SDimitry Andric
CallDeleteDuringNew(size_t NumPlacementArgs,const FunctionDecl * OperatorDelete,ValueTy Ptr,ValueTy AllocSize,bool PassAlignmentToPlacementDelete,CharUnits AllocAlign)14410b57cec5SDimitry Andric CallDeleteDuringNew(size_t NumPlacementArgs,
14420b57cec5SDimitry Andric const FunctionDecl *OperatorDelete, ValueTy Ptr,
14430b57cec5SDimitry Andric ValueTy AllocSize, bool PassAlignmentToPlacementDelete,
14440b57cec5SDimitry Andric CharUnits AllocAlign)
14450b57cec5SDimitry Andric : NumPlacementArgs(NumPlacementArgs),
14460b57cec5SDimitry Andric PassAlignmentToPlacementDelete(PassAlignmentToPlacementDelete),
14470b57cec5SDimitry Andric OperatorDelete(OperatorDelete), Ptr(Ptr), AllocSize(AllocSize),
14480b57cec5SDimitry Andric AllocAlign(AllocAlign) {}
14490b57cec5SDimitry Andric
setPlacementArg(unsigned I,RValueTy Arg,QualType Type)14500b57cec5SDimitry Andric void setPlacementArg(unsigned I, RValueTy Arg, QualType Type) {
14510b57cec5SDimitry Andric assert(I < NumPlacementArgs && "index out of range");
14520b57cec5SDimitry Andric getPlacementArgs()[I] = {Arg, Type};
14530b57cec5SDimitry Andric }
14540b57cec5SDimitry Andric
Emit(CodeGenFunction & CGF,Flags flags)14550b57cec5SDimitry Andric void Emit(CodeGenFunction &CGF, Flags flags) override {
1456480093f4SDimitry Andric const auto *FPT = OperatorDelete->getType()->castAs<FunctionProtoType>();
14570b57cec5SDimitry Andric CallArgList DeleteArgs;
14580b57cec5SDimitry Andric
14590b57cec5SDimitry Andric // The first argument is always a void* (or C* for a destroying operator
14600b57cec5SDimitry Andric // delete for class type C).
14610b57cec5SDimitry Andric DeleteArgs.add(Traits::get(CGF, Ptr), FPT->getParamType(0));
14620b57cec5SDimitry Andric
14630b57cec5SDimitry Andric // Figure out what other parameters we should be implicitly passing.
14640b57cec5SDimitry Andric UsualDeleteParams Params;
14650b57cec5SDimitry Andric if (NumPlacementArgs) {
14660b57cec5SDimitry Andric // A placement deallocation function is implicitly passed an alignment
14670b57cec5SDimitry Andric // if the placement allocation function was, but is never passed a size.
14680b57cec5SDimitry Andric Params.Alignment = PassAlignmentToPlacementDelete;
14690b57cec5SDimitry Andric } else {
14700b57cec5SDimitry Andric // For a non-placement new-expression, 'operator delete' can take a
14710b57cec5SDimitry Andric // size and/or an alignment if it has the right parameters.
14720b57cec5SDimitry Andric Params = getUsualDeleteParams(OperatorDelete);
14730b57cec5SDimitry Andric }
14740b57cec5SDimitry Andric
14750b57cec5SDimitry Andric assert(!Params.DestroyingDelete &&
14760b57cec5SDimitry Andric "should not call destroying delete in a new-expression");
14770b57cec5SDimitry Andric
14780b57cec5SDimitry Andric // The second argument can be a std::size_t (for non-placement delete).
14790b57cec5SDimitry Andric if (Params.Size)
14800b57cec5SDimitry Andric DeleteArgs.add(Traits::get(CGF, AllocSize),
14810b57cec5SDimitry Andric CGF.getContext().getSizeType());
14820b57cec5SDimitry Andric
14830b57cec5SDimitry Andric // The next (second or third) argument can be a std::align_val_t, which
14840b57cec5SDimitry Andric // is an enum whose underlying type is std::size_t.
14850b57cec5SDimitry Andric // FIXME: Use the right type as the parameter type. Note that in a call
14860b57cec5SDimitry Andric // to operator delete(size_t, ...), we may not have it available.
14870b57cec5SDimitry Andric if (Params.Alignment)
14880b57cec5SDimitry Andric DeleteArgs.add(RValue::get(llvm::ConstantInt::get(
14890b57cec5SDimitry Andric CGF.SizeTy, AllocAlign.getQuantity())),
14900b57cec5SDimitry Andric CGF.getContext().getSizeType());
14910b57cec5SDimitry Andric
14920b57cec5SDimitry Andric // Pass the rest of the arguments, which must match exactly.
14930b57cec5SDimitry Andric for (unsigned I = 0; I != NumPlacementArgs; ++I) {
14940b57cec5SDimitry Andric auto Arg = getPlacementArgs()[I];
14950b57cec5SDimitry Andric DeleteArgs.add(Traits::get(CGF, Arg.ArgValue), Arg.ArgType);
14960b57cec5SDimitry Andric }
14970b57cec5SDimitry Andric
14980b57cec5SDimitry Andric // Call 'operator delete'.
14990b57cec5SDimitry Andric EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
15000b57cec5SDimitry Andric }
15010b57cec5SDimitry Andric };
15020b57cec5SDimitry Andric }
15030b57cec5SDimitry Andric
15040b57cec5SDimitry Andric /// Enter a cleanup to call 'operator delete' if the initializer in a
15050b57cec5SDimitry Andric /// new-expression throws.
EnterNewDeleteCleanup(CodeGenFunction & CGF,const CXXNewExpr * E,Address NewPtr,llvm::Value * AllocSize,CharUnits AllocAlign,const CallArgList & NewArgs)15060b57cec5SDimitry Andric static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
15070b57cec5SDimitry Andric const CXXNewExpr *E,
15080b57cec5SDimitry Andric Address NewPtr,
15090b57cec5SDimitry Andric llvm::Value *AllocSize,
15100b57cec5SDimitry Andric CharUnits AllocAlign,
15110b57cec5SDimitry Andric const CallArgList &NewArgs) {
15120b57cec5SDimitry Andric unsigned NumNonPlacementArgs = E->passAlignment() ? 2 : 1;
15130b57cec5SDimitry Andric
15140b57cec5SDimitry Andric // If we're not inside a conditional branch, then the cleanup will
15150b57cec5SDimitry Andric // dominate and we can do the easier (and more efficient) thing.
15160b57cec5SDimitry Andric if (!CGF.isInConditionalBranch()) {
15170b57cec5SDimitry Andric struct DirectCleanupTraits {
15180b57cec5SDimitry Andric typedef llvm::Value *ValueTy;
15190b57cec5SDimitry Andric typedef RValue RValueTy;
15200b57cec5SDimitry Andric static RValue get(CodeGenFunction &, ValueTy V) { return RValue::get(V); }
15210b57cec5SDimitry Andric static RValue get(CodeGenFunction &, RValueTy V) { return V; }
15220b57cec5SDimitry Andric };
15230b57cec5SDimitry Andric
15240b57cec5SDimitry Andric typedef CallDeleteDuringNew<DirectCleanupTraits> DirectCleanup;
15250b57cec5SDimitry Andric
15260b57cec5SDimitry Andric DirectCleanup *Cleanup = CGF.EHStack
15270b57cec5SDimitry Andric .pushCleanupWithExtra<DirectCleanup>(EHCleanup,
15280b57cec5SDimitry Andric E->getNumPlacementArgs(),
15290b57cec5SDimitry Andric E->getOperatorDelete(),
15300b57cec5SDimitry Andric NewPtr.getPointer(),
15310b57cec5SDimitry Andric AllocSize,
15320b57cec5SDimitry Andric E->passAlignment(),
15330b57cec5SDimitry Andric AllocAlign);
15340b57cec5SDimitry Andric for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
15350b57cec5SDimitry Andric auto &Arg = NewArgs[I + NumNonPlacementArgs];
15360b57cec5SDimitry Andric Cleanup->setPlacementArg(I, Arg.getRValue(CGF), Arg.Ty);
15370b57cec5SDimitry Andric }
15380b57cec5SDimitry Andric
15390b57cec5SDimitry Andric return;
15400b57cec5SDimitry Andric }
15410b57cec5SDimitry Andric
15420b57cec5SDimitry Andric // Otherwise, we need to save all this stuff.
15430b57cec5SDimitry Andric DominatingValue<RValue>::saved_type SavedNewPtr =
15440b57cec5SDimitry Andric DominatingValue<RValue>::save(CGF, RValue::get(NewPtr.getPointer()));
15450b57cec5SDimitry Andric DominatingValue<RValue>::saved_type SavedAllocSize =
15460b57cec5SDimitry Andric DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
15470b57cec5SDimitry Andric
15480b57cec5SDimitry Andric struct ConditionalCleanupTraits {
15490b57cec5SDimitry Andric typedef DominatingValue<RValue>::saved_type ValueTy;
15500b57cec5SDimitry Andric typedef DominatingValue<RValue>::saved_type RValueTy;
15510b57cec5SDimitry Andric static RValue get(CodeGenFunction &CGF, ValueTy V) {
15520b57cec5SDimitry Andric return V.restore(CGF);
15530b57cec5SDimitry Andric }
15540b57cec5SDimitry Andric };
15550b57cec5SDimitry Andric typedef CallDeleteDuringNew<ConditionalCleanupTraits> ConditionalCleanup;
15560b57cec5SDimitry Andric
15570b57cec5SDimitry Andric ConditionalCleanup *Cleanup = CGF.EHStack
15580b57cec5SDimitry Andric .pushCleanupWithExtra<ConditionalCleanup>(EHCleanup,
15590b57cec5SDimitry Andric E->getNumPlacementArgs(),
15600b57cec5SDimitry Andric E->getOperatorDelete(),
15610b57cec5SDimitry Andric SavedNewPtr,
15620b57cec5SDimitry Andric SavedAllocSize,
15630b57cec5SDimitry Andric E->passAlignment(),
15640b57cec5SDimitry Andric AllocAlign);
15650b57cec5SDimitry Andric for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
15660b57cec5SDimitry Andric auto &Arg = NewArgs[I + NumNonPlacementArgs];
15670b57cec5SDimitry Andric Cleanup->setPlacementArg(
15680b57cec5SDimitry Andric I, DominatingValue<RValue>::save(CGF, Arg.getRValue(CGF)), Arg.Ty);
15690b57cec5SDimitry Andric }
15700b57cec5SDimitry Andric
15710b57cec5SDimitry Andric CGF.initFullExprCleanup();
15720b57cec5SDimitry Andric }
15730b57cec5SDimitry Andric
EmitCXXNewExpr(const CXXNewExpr * E)15740b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
15750b57cec5SDimitry Andric // The element type being allocated.
15760b57cec5SDimitry Andric QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
15770b57cec5SDimitry Andric
15780b57cec5SDimitry Andric // 1. Build a call to the allocation function.
15790b57cec5SDimitry Andric FunctionDecl *allocator = E->getOperatorNew();
15800b57cec5SDimitry Andric
1581*a58f00eaSDimitry Andric // If there is a brace-initializer or C++20 parenthesized initializer, cannot
1582*a58f00eaSDimitry Andric // allocate fewer elements than inits.
15830b57cec5SDimitry Andric unsigned minElements = 0;
15840b57cec5SDimitry Andric if (E->isArray() && E->hasInitializer()) {
1585*a58f00eaSDimitry Andric const Expr *Init = E->getInitializer();
1586*a58f00eaSDimitry Andric const InitListExpr *ILE = dyn_cast<InitListExpr>(Init);
1587*a58f00eaSDimitry Andric const CXXParenListInitExpr *CPLIE = dyn_cast<CXXParenListInitExpr>(Init);
1588*a58f00eaSDimitry Andric const Expr *IgnoreParen = Init->IgnoreParenImpCasts();
1589*a58f00eaSDimitry Andric if ((ILE && ILE->isStringLiteralInit()) ||
1590*a58f00eaSDimitry Andric isa<StringLiteral>(IgnoreParen) || isa<ObjCEncodeExpr>(IgnoreParen)) {
15910b57cec5SDimitry Andric minElements =
1592*a58f00eaSDimitry Andric cast<ConstantArrayType>(Init->getType()->getAsArrayTypeUnsafe())
1593*a58f00eaSDimitry Andric ->getSize()
1594*a58f00eaSDimitry Andric .getZExtValue();
1595*a58f00eaSDimitry Andric } else if (ILE || CPLIE) {
1596*a58f00eaSDimitry Andric minElements = ILE ? ILE->getNumInits() : CPLIE->getInitExprs().size();
1597*a58f00eaSDimitry Andric }
15980b57cec5SDimitry Andric }
15990b57cec5SDimitry Andric
16000b57cec5SDimitry Andric llvm::Value *numElements = nullptr;
16010b57cec5SDimitry Andric llvm::Value *allocSizeWithoutCookie = nullptr;
16020b57cec5SDimitry Andric llvm::Value *allocSize =
16030b57cec5SDimitry Andric EmitCXXNewAllocSize(*this, E, minElements, numElements,
16040b57cec5SDimitry Andric allocSizeWithoutCookie);
16052a66634dSDimitry Andric CharUnits allocAlign = getContext().getTypeAlignInChars(allocType);
16060b57cec5SDimitry Andric
16070b57cec5SDimitry Andric // Emit the allocation call. If the allocator is a global placement
16080b57cec5SDimitry Andric // operator, just "inline" it directly.
16090b57cec5SDimitry Andric Address allocation = Address::invalid();
16100b57cec5SDimitry Andric CallArgList allocatorArgs;
16110b57cec5SDimitry Andric if (allocator->isReservedGlobalPlacementOperator()) {
16120b57cec5SDimitry Andric assert(E->getNumPlacementArgs() == 1);
16130b57cec5SDimitry Andric const Expr *arg = *E->placement_arguments().begin();
16140b57cec5SDimitry Andric
16150b57cec5SDimitry Andric LValueBaseInfo BaseInfo;
16160b57cec5SDimitry Andric allocation = EmitPointerWithAlignment(arg, &BaseInfo);
16170b57cec5SDimitry Andric
16180b57cec5SDimitry Andric // The pointer expression will, in many cases, be an opaque void*.
16190b57cec5SDimitry Andric // In these cases, discard the computed alignment and use the
16200b57cec5SDimitry Andric // formal alignment of the allocated type.
16210b57cec5SDimitry Andric if (BaseInfo.getAlignmentSource() != AlignmentSource::Decl)
16220eae32dcSDimitry Andric allocation = allocation.withAlignment(allocAlign);
16230b57cec5SDimitry Andric
16240b57cec5SDimitry Andric // Set up allocatorArgs for the call to operator delete if it's not
16250b57cec5SDimitry Andric // the reserved global operator.
16260b57cec5SDimitry Andric if (E->getOperatorDelete() &&
16270b57cec5SDimitry Andric !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
16280b57cec5SDimitry Andric allocatorArgs.add(RValue::get(allocSize), getContext().getSizeType());
16290b57cec5SDimitry Andric allocatorArgs.add(RValue::get(allocation.getPointer()), arg->getType());
16300b57cec5SDimitry Andric }
16310b57cec5SDimitry Andric
16320b57cec5SDimitry Andric } else {
16330b57cec5SDimitry Andric const FunctionProtoType *allocatorType =
16340b57cec5SDimitry Andric allocator->getType()->castAs<FunctionProtoType>();
16350b57cec5SDimitry Andric unsigned ParamsToSkip = 0;
16360b57cec5SDimitry Andric
16370b57cec5SDimitry Andric // The allocation size is the first argument.
16380b57cec5SDimitry Andric QualType sizeType = getContext().getSizeType();
16390b57cec5SDimitry Andric allocatorArgs.add(RValue::get(allocSize), sizeType);
16400b57cec5SDimitry Andric ++ParamsToSkip;
16410b57cec5SDimitry Andric
16420b57cec5SDimitry Andric if (allocSize != allocSizeWithoutCookie) {
16430b57cec5SDimitry Andric CharUnits cookieAlign = getSizeAlign(); // FIXME: Ask the ABI.
16440b57cec5SDimitry Andric allocAlign = std::max(allocAlign, cookieAlign);
16450b57cec5SDimitry Andric }
16460b57cec5SDimitry Andric
16470b57cec5SDimitry Andric // The allocation alignment may be passed as the second argument.
16480b57cec5SDimitry Andric if (E->passAlignment()) {
16490b57cec5SDimitry Andric QualType AlignValT = sizeType;
16500b57cec5SDimitry Andric if (allocatorType->getNumParams() > 1) {
16510b57cec5SDimitry Andric AlignValT = allocatorType->getParamType(1);
16520b57cec5SDimitry Andric assert(getContext().hasSameUnqualifiedType(
16530b57cec5SDimitry Andric AlignValT->castAs<EnumType>()->getDecl()->getIntegerType(),
16540b57cec5SDimitry Andric sizeType) &&
16550b57cec5SDimitry Andric "wrong type for alignment parameter");
16560b57cec5SDimitry Andric ++ParamsToSkip;
16570b57cec5SDimitry Andric } else {
16580b57cec5SDimitry Andric // Corner case, passing alignment to 'operator new(size_t, ...)'.
16590b57cec5SDimitry Andric assert(allocator->isVariadic() && "can't pass alignment to allocator");
16600b57cec5SDimitry Andric }
16610b57cec5SDimitry Andric allocatorArgs.add(
16620b57cec5SDimitry Andric RValue::get(llvm::ConstantInt::get(SizeTy, allocAlign.getQuantity())),
16630b57cec5SDimitry Andric AlignValT);
16640b57cec5SDimitry Andric }
16650b57cec5SDimitry Andric
16660b57cec5SDimitry Andric // FIXME: Why do we not pass a CalleeDecl here?
16670b57cec5SDimitry Andric EmitCallArgs(allocatorArgs, allocatorType, E->placement_arguments(),
16680b57cec5SDimitry Andric /*AC*/AbstractCallee(), /*ParamsToSkip*/ParamsToSkip);
16690b57cec5SDimitry Andric
16700b57cec5SDimitry Andric RValue RV =
16710b57cec5SDimitry Andric EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
16720b57cec5SDimitry Andric
16735ffd83dbSDimitry Andric // Set !heapallocsite metadata on the call to operator new.
16745ffd83dbSDimitry Andric if (getDebugInfo())
16755ffd83dbSDimitry Andric if (auto *newCall = dyn_cast<llvm::CallBase>(RV.getScalarVal()))
16765ffd83dbSDimitry Andric getDebugInfo()->addHeapAllocSiteMetadata(newCall, allocType,
16775ffd83dbSDimitry Andric E->getExprLoc());
16785ffd83dbSDimitry Andric
16790b57cec5SDimitry Andric // If this was a call to a global replaceable allocation function that does
16800b57cec5SDimitry Andric // not take an alignment argument, the allocator is known to produce
16810b57cec5SDimitry Andric // storage that's suitably aligned for any object that fits, up to a known
16820b57cec5SDimitry Andric // threshold. Otherwise assume it's suitably aligned for the allocated type.
16830b57cec5SDimitry Andric CharUnits allocationAlign = allocAlign;
16840b57cec5SDimitry Andric if (!E->passAlignment() &&
16850b57cec5SDimitry Andric allocator->isReplaceableGlobalAllocationFunction()) {
1686fe013be4SDimitry Andric unsigned AllocatorAlign = llvm::bit_floor(std::min<uint64_t>(
16870b57cec5SDimitry Andric Target.getNewAlign(), getContext().getTypeSize(allocType)));
16880b57cec5SDimitry Andric allocationAlign = std::max(
16890b57cec5SDimitry Andric allocationAlign, getContext().toCharUnitsFromBits(AllocatorAlign));
16900b57cec5SDimitry Andric }
16910b57cec5SDimitry Andric
16920eae32dcSDimitry Andric allocation = Address(RV.getScalarVal(), Int8Ty, allocationAlign);
16930b57cec5SDimitry Andric }
16940b57cec5SDimitry Andric
16950b57cec5SDimitry Andric // Emit a null check on the allocation result if the allocation
16960b57cec5SDimitry Andric // function is allowed to return null (because it has a non-throwing
16970b57cec5SDimitry Andric // exception spec or is the reserved placement new) and we have an
16980b57cec5SDimitry Andric // interesting initializer will be running sanitizers on the initialization.
16990b57cec5SDimitry Andric bool nullCheck = E->shouldNullCheckAllocation() &&
17000b57cec5SDimitry Andric (!allocType.isPODType(getContext()) || E->hasInitializer() ||
17010b57cec5SDimitry Andric sanitizePerformTypeCheck());
17020b57cec5SDimitry Andric
17030b57cec5SDimitry Andric llvm::BasicBlock *nullCheckBB = nullptr;
17040b57cec5SDimitry Andric llvm::BasicBlock *contBB = nullptr;
17050b57cec5SDimitry Andric
17060b57cec5SDimitry Andric // The null-check means that the initializer is conditionally
17070b57cec5SDimitry Andric // evaluated.
17080b57cec5SDimitry Andric ConditionalEvaluation conditional(*this);
17090b57cec5SDimitry Andric
17100b57cec5SDimitry Andric if (nullCheck) {
17110b57cec5SDimitry Andric conditional.begin(*this);
17120b57cec5SDimitry Andric
17130b57cec5SDimitry Andric nullCheckBB = Builder.GetInsertBlock();
17140b57cec5SDimitry Andric llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
17150b57cec5SDimitry Andric contBB = createBasicBlock("new.cont");
17160b57cec5SDimitry Andric
17170b57cec5SDimitry Andric llvm::Value *isNull =
17180b57cec5SDimitry Andric Builder.CreateIsNull(allocation.getPointer(), "new.isnull");
17190b57cec5SDimitry Andric Builder.CreateCondBr(isNull, contBB, notNullBB);
17200b57cec5SDimitry Andric EmitBlock(notNullBB);
17210b57cec5SDimitry Andric }
17220b57cec5SDimitry Andric
17230b57cec5SDimitry Andric // If there's an operator delete, enter a cleanup to call it if an
17240b57cec5SDimitry Andric // exception is thrown.
17250b57cec5SDimitry Andric EHScopeStack::stable_iterator operatorDeleteCleanup;
17260b57cec5SDimitry Andric llvm::Instruction *cleanupDominator = nullptr;
17270b57cec5SDimitry Andric if (E->getOperatorDelete() &&
17280b57cec5SDimitry Andric !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
17290b57cec5SDimitry Andric EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocAlign,
17300b57cec5SDimitry Andric allocatorArgs);
17310b57cec5SDimitry Andric operatorDeleteCleanup = EHStack.stable_begin();
17320b57cec5SDimitry Andric cleanupDominator = Builder.CreateUnreachable();
17330b57cec5SDimitry Andric }
17340b57cec5SDimitry Andric
17350b57cec5SDimitry Andric assert((allocSize == allocSizeWithoutCookie) ==
17360b57cec5SDimitry Andric CalculateCookiePadding(*this, E).isZero());
17370b57cec5SDimitry Andric if (allocSize != allocSizeWithoutCookie) {
17380b57cec5SDimitry Andric assert(E->isArray());
17390b57cec5SDimitry Andric allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
17400b57cec5SDimitry Andric numElements,
17410b57cec5SDimitry Andric E, allocType);
17420b57cec5SDimitry Andric }
17430b57cec5SDimitry Andric
17440b57cec5SDimitry Andric llvm::Type *elementTy = ConvertTypeForMem(allocType);
1745fe013be4SDimitry Andric Address result = allocation.withElementType(elementTy);
17460b57cec5SDimitry Andric
17470b57cec5SDimitry Andric // Passing pointer through launder.invariant.group to avoid propagation of
17480b57cec5SDimitry Andric // vptrs information which may be included in previous type.
17490b57cec5SDimitry Andric // To not break LTO with different optimizations levels, we do it regardless
17500b57cec5SDimitry Andric // of optimization level.
17510b57cec5SDimitry Andric if (CGM.getCodeGenOpts().StrictVTablePointers &&
17520b57cec5SDimitry Andric allocator->isReservedGlobalPlacementOperator())
17530eae32dcSDimitry Andric result = Builder.CreateLaunderInvariantGroup(result);
17540b57cec5SDimitry Andric
17550b57cec5SDimitry Andric // Emit sanitizer checks for pointer value now, so that in the case of an
17560b57cec5SDimitry Andric // array it was checked only once and not at each constructor call. We may
17570b57cec5SDimitry Andric // have already checked that the pointer is non-null.
17580b57cec5SDimitry Andric // FIXME: If we have an array cookie and a potentially-throwing allocator,
17590b57cec5SDimitry Andric // we'll null check the wrong pointer here.
17600b57cec5SDimitry Andric SanitizerSet SkippedChecks;
17610b57cec5SDimitry Andric SkippedChecks.set(SanitizerKind::Null, nullCheck);
17620b57cec5SDimitry Andric EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall,
17630b57cec5SDimitry Andric E->getAllocatedTypeSourceInfo()->getTypeLoc().getBeginLoc(),
17640b57cec5SDimitry Andric result.getPointer(), allocType, result.getAlignment(),
17650b57cec5SDimitry Andric SkippedChecks, numElements);
17660b57cec5SDimitry Andric
17670b57cec5SDimitry Andric EmitNewInitializer(*this, E, allocType, elementTy, result, numElements,
17680b57cec5SDimitry Andric allocSizeWithoutCookie);
176981ad6265SDimitry Andric llvm::Value *resultPtr = result.getPointer();
17700b57cec5SDimitry Andric if (E->isArray()) {
17710b57cec5SDimitry Andric // NewPtr is a pointer to the base element type. If we're
17720b57cec5SDimitry Andric // allocating an array of arrays, we'll need to cast back to the
17730b57cec5SDimitry Andric // array pointer type.
17740b57cec5SDimitry Andric llvm::Type *resultType = ConvertTypeForMem(E->getType());
177581ad6265SDimitry Andric if (resultPtr->getType() != resultType)
177681ad6265SDimitry Andric resultPtr = Builder.CreateBitCast(resultPtr, resultType);
17770b57cec5SDimitry Andric }
17780b57cec5SDimitry Andric
17790b57cec5SDimitry Andric // Deactivate the 'operator delete' cleanup if we finished
17800b57cec5SDimitry Andric // initialization.
17810b57cec5SDimitry Andric if (operatorDeleteCleanup.isValid()) {
17820b57cec5SDimitry Andric DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
17830b57cec5SDimitry Andric cleanupDominator->eraseFromParent();
17840b57cec5SDimitry Andric }
17850b57cec5SDimitry Andric
17860b57cec5SDimitry Andric if (nullCheck) {
17870b57cec5SDimitry Andric conditional.end(*this);
17880b57cec5SDimitry Andric
17890b57cec5SDimitry Andric llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
17900b57cec5SDimitry Andric EmitBlock(contBB);
17910b57cec5SDimitry Andric
17920b57cec5SDimitry Andric llvm::PHINode *PHI = Builder.CreatePHI(resultPtr->getType(), 2);
17930b57cec5SDimitry Andric PHI->addIncoming(resultPtr, notNullBB);
17940b57cec5SDimitry Andric PHI->addIncoming(llvm::Constant::getNullValue(resultPtr->getType()),
17950b57cec5SDimitry Andric nullCheckBB);
17960b57cec5SDimitry Andric
17970b57cec5SDimitry Andric resultPtr = PHI;
17980b57cec5SDimitry Andric }
17990b57cec5SDimitry Andric
18000b57cec5SDimitry Andric return resultPtr;
18010b57cec5SDimitry Andric }
18020b57cec5SDimitry Andric
EmitDeleteCall(const FunctionDecl * DeleteFD,llvm::Value * Ptr,QualType DeleteTy,llvm::Value * NumElements,CharUnits CookieSize)18030b57cec5SDimitry Andric void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
18040b57cec5SDimitry Andric llvm::Value *Ptr, QualType DeleteTy,
18050b57cec5SDimitry Andric llvm::Value *NumElements,
18060b57cec5SDimitry Andric CharUnits CookieSize) {
18070b57cec5SDimitry Andric assert((!NumElements && CookieSize.isZero()) ||
18080b57cec5SDimitry Andric DeleteFD->getOverloadedOperator() == OO_Array_Delete);
18090b57cec5SDimitry Andric
1810480093f4SDimitry Andric const auto *DeleteFTy = DeleteFD->getType()->castAs<FunctionProtoType>();
18110b57cec5SDimitry Andric CallArgList DeleteArgs;
18120b57cec5SDimitry Andric
18130b57cec5SDimitry Andric auto Params = getUsualDeleteParams(DeleteFD);
18140b57cec5SDimitry Andric auto ParamTypeIt = DeleteFTy->param_type_begin();
18150b57cec5SDimitry Andric
18160b57cec5SDimitry Andric // Pass the pointer itself.
18170b57cec5SDimitry Andric QualType ArgTy = *ParamTypeIt++;
18180b57cec5SDimitry Andric llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
18190b57cec5SDimitry Andric DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
18200b57cec5SDimitry Andric
18210b57cec5SDimitry Andric // Pass the std::destroying_delete tag if present.
1822e8d8bef9SDimitry Andric llvm::AllocaInst *DestroyingDeleteTag = nullptr;
18230b57cec5SDimitry Andric if (Params.DestroyingDelete) {
18240b57cec5SDimitry Andric QualType DDTag = *ParamTypeIt++;
1825e8d8bef9SDimitry Andric llvm::Type *Ty = getTypes().ConvertType(DDTag);
1826e8d8bef9SDimitry Andric CharUnits Align = CGM.getNaturalTypeAlignment(DDTag);
1827e8d8bef9SDimitry Andric DestroyingDeleteTag = CreateTempAlloca(Ty, "destroying.delete.tag");
1828e8d8bef9SDimitry Andric DestroyingDeleteTag->setAlignment(Align.getAsAlign());
182981ad6265SDimitry Andric DeleteArgs.add(
183081ad6265SDimitry Andric RValue::getAggregate(Address(DestroyingDeleteTag, Ty, Align)), DDTag);
18310b57cec5SDimitry Andric }
18320b57cec5SDimitry Andric
18330b57cec5SDimitry Andric // Pass the size if the delete function has a size_t parameter.
18340b57cec5SDimitry Andric if (Params.Size) {
18350b57cec5SDimitry Andric QualType SizeType = *ParamTypeIt++;
18360b57cec5SDimitry Andric CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
18370b57cec5SDimitry Andric llvm::Value *Size = llvm::ConstantInt::get(ConvertType(SizeType),
18380b57cec5SDimitry Andric DeleteTypeSize.getQuantity());
18390b57cec5SDimitry Andric
18400b57cec5SDimitry Andric // For array new, multiply by the number of elements.
18410b57cec5SDimitry Andric if (NumElements)
18420b57cec5SDimitry Andric Size = Builder.CreateMul(Size, NumElements);
18430b57cec5SDimitry Andric
18440b57cec5SDimitry Andric // If there is a cookie, add the cookie size.
18450b57cec5SDimitry Andric if (!CookieSize.isZero())
18460b57cec5SDimitry Andric Size = Builder.CreateAdd(
18470b57cec5SDimitry Andric Size, llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity()));
18480b57cec5SDimitry Andric
18490b57cec5SDimitry Andric DeleteArgs.add(RValue::get(Size), SizeType);
18500b57cec5SDimitry Andric }
18510b57cec5SDimitry Andric
18520b57cec5SDimitry Andric // Pass the alignment if the delete function has an align_val_t parameter.
18530b57cec5SDimitry Andric if (Params.Alignment) {
18540b57cec5SDimitry Andric QualType AlignValType = *ParamTypeIt++;
1855e8d8bef9SDimitry Andric CharUnits DeleteTypeAlign =
1856e8d8bef9SDimitry Andric getContext().toCharUnitsFromBits(getContext().getTypeAlignIfKnown(
1857e8d8bef9SDimitry Andric DeleteTy, true /* NeedsPreferredAlignment */));
18580b57cec5SDimitry Andric llvm::Value *Align = llvm::ConstantInt::get(ConvertType(AlignValType),
18590b57cec5SDimitry Andric DeleteTypeAlign.getQuantity());
18600b57cec5SDimitry Andric DeleteArgs.add(RValue::get(Align), AlignValType);
18610b57cec5SDimitry Andric }
18620b57cec5SDimitry Andric
18630b57cec5SDimitry Andric assert(ParamTypeIt == DeleteFTy->param_type_end() &&
18640b57cec5SDimitry Andric "unknown parameter to usual delete function");
18650b57cec5SDimitry Andric
18660b57cec5SDimitry Andric // Emit the call to delete.
18670b57cec5SDimitry Andric EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
1868e8d8bef9SDimitry Andric
1869e8d8bef9SDimitry Andric // If call argument lowering didn't use the destroying_delete_t alloca,
1870e8d8bef9SDimitry Andric // remove it again.
1871e8d8bef9SDimitry Andric if (DestroyingDeleteTag && DestroyingDeleteTag->use_empty())
1872e8d8bef9SDimitry Andric DestroyingDeleteTag->eraseFromParent();
18730b57cec5SDimitry Andric }
18740b57cec5SDimitry Andric
18750b57cec5SDimitry Andric namespace {
18760b57cec5SDimitry Andric /// Calls the given 'operator delete' on a single object.
18770b57cec5SDimitry Andric struct CallObjectDelete final : EHScopeStack::Cleanup {
18780b57cec5SDimitry Andric llvm::Value *Ptr;
18790b57cec5SDimitry Andric const FunctionDecl *OperatorDelete;
18800b57cec5SDimitry Andric QualType ElementType;
18810b57cec5SDimitry Andric
CallObjectDelete__anond149d7b00511::CallObjectDelete18820b57cec5SDimitry Andric CallObjectDelete(llvm::Value *Ptr,
18830b57cec5SDimitry Andric const FunctionDecl *OperatorDelete,
18840b57cec5SDimitry Andric QualType ElementType)
18850b57cec5SDimitry Andric : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
18860b57cec5SDimitry Andric
Emit__anond149d7b00511::CallObjectDelete18870b57cec5SDimitry Andric void Emit(CodeGenFunction &CGF, Flags flags) override {
18880b57cec5SDimitry Andric CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
18890b57cec5SDimitry Andric }
18900b57cec5SDimitry Andric };
18910b57cec5SDimitry Andric }
18920b57cec5SDimitry Andric
18930b57cec5SDimitry Andric void
pushCallObjectDeleteCleanup(const FunctionDecl * OperatorDelete,llvm::Value * CompletePtr,QualType ElementType)18940b57cec5SDimitry Andric CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
18950b57cec5SDimitry Andric llvm::Value *CompletePtr,
18960b57cec5SDimitry Andric QualType ElementType) {
18970b57cec5SDimitry Andric EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr,
18980b57cec5SDimitry Andric OperatorDelete, ElementType);
18990b57cec5SDimitry Andric }
19000b57cec5SDimitry Andric
19010b57cec5SDimitry Andric /// Emit the code for deleting a single object with a destroying operator
19020b57cec5SDimitry Andric /// delete. If the element type has a non-virtual destructor, Ptr has already
19030b57cec5SDimitry Andric /// been converted to the type of the parameter of 'operator delete'. Otherwise
19040b57cec5SDimitry Andric /// Ptr points to an object of the static type.
EmitDestroyingObjectDelete(CodeGenFunction & CGF,const CXXDeleteExpr * DE,Address Ptr,QualType ElementType)19050b57cec5SDimitry Andric static void EmitDestroyingObjectDelete(CodeGenFunction &CGF,
19060b57cec5SDimitry Andric const CXXDeleteExpr *DE, Address Ptr,
19070b57cec5SDimitry Andric QualType ElementType) {
19080b57cec5SDimitry Andric auto *Dtor = ElementType->getAsCXXRecordDecl()->getDestructor();
19090b57cec5SDimitry Andric if (Dtor && Dtor->isVirtual())
19100b57cec5SDimitry Andric CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
19110b57cec5SDimitry Andric Dtor);
19120b57cec5SDimitry Andric else
19130b57cec5SDimitry Andric CGF.EmitDeleteCall(DE->getOperatorDelete(), Ptr.getPointer(), ElementType);
19140b57cec5SDimitry Andric }
19150b57cec5SDimitry Andric
19160b57cec5SDimitry Andric /// Emit the code for deleting a single object.
19175ffd83dbSDimitry Andric /// \return \c true if we started emitting UnconditionalDeleteBlock, \c false
19185ffd83dbSDimitry Andric /// if not.
EmitObjectDelete(CodeGenFunction & CGF,const CXXDeleteExpr * DE,Address Ptr,QualType ElementType,llvm::BasicBlock * UnconditionalDeleteBlock)19195ffd83dbSDimitry Andric static bool EmitObjectDelete(CodeGenFunction &CGF,
19200b57cec5SDimitry Andric const CXXDeleteExpr *DE,
19210b57cec5SDimitry Andric Address Ptr,
19225ffd83dbSDimitry Andric QualType ElementType,
19235ffd83dbSDimitry Andric llvm::BasicBlock *UnconditionalDeleteBlock) {
19240b57cec5SDimitry Andric // C++11 [expr.delete]p3:
19250b57cec5SDimitry Andric // If the static type of the object to be deleted is different from its
19260b57cec5SDimitry Andric // dynamic type, the static type shall be a base class of the dynamic type
19270b57cec5SDimitry Andric // of the object to be deleted and the static type shall have a virtual
19280b57cec5SDimitry Andric // destructor or the behavior is undefined.
19290b57cec5SDimitry Andric CGF.EmitTypeCheck(CodeGenFunction::TCK_MemberCall,
19300b57cec5SDimitry Andric DE->getExprLoc(), Ptr.getPointer(),
19310b57cec5SDimitry Andric ElementType);
19320b57cec5SDimitry Andric
19330b57cec5SDimitry Andric const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
19340b57cec5SDimitry Andric assert(!OperatorDelete->isDestroyingOperatorDelete());
19350b57cec5SDimitry Andric
19360b57cec5SDimitry Andric // Find the destructor for the type, if applicable. If the
19370b57cec5SDimitry Andric // destructor is virtual, we'll just emit the vcall and return.
19380b57cec5SDimitry Andric const CXXDestructorDecl *Dtor = nullptr;
19390b57cec5SDimitry Andric if (const RecordType *RT = ElementType->getAs<RecordType>()) {
19400b57cec5SDimitry Andric CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
19410b57cec5SDimitry Andric if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
19420b57cec5SDimitry Andric Dtor = RD->getDestructor();
19430b57cec5SDimitry Andric
19440b57cec5SDimitry Andric if (Dtor->isVirtual()) {
1945a7dea167SDimitry Andric bool UseVirtualCall = true;
1946a7dea167SDimitry Andric const Expr *Base = DE->getArgument();
1947a7dea167SDimitry Andric if (auto *DevirtualizedDtor =
1948a7dea167SDimitry Andric dyn_cast_or_null<const CXXDestructorDecl>(
1949a7dea167SDimitry Andric Dtor->getDevirtualizedMethod(
1950a7dea167SDimitry Andric Base, CGF.CGM.getLangOpts().AppleKext))) {
1951a7dea167SDimitry Andric UseVirtualCall = false;
1952a7dea167SDimitry Andric const CXXRecordDecl *DevirtualizedClass =
1953a7dea167SDimitry Andric DevirtualizedDtor->getParent();
1954a7dea167SDimitry Andric if (declaresSameEntity(getCXXRecord(Base), DevirtualizedClass)) {
1955a7dea167SDimitry Andric // Devirtualized to the class of the base type (the type of the
1956a7dea167SDimitry Andric // whole expression).
1957a7dea167SDimitry Andric Dtor = DevirtualizedDtor;
1958a7dea167SDimitry Andric } else {
1959a7dea167SDimitry Andric // Devirtualized to some other type. Would need to cast the this
1960a7dea167SDimitry Andric // pointer to that type but we don't have support for that yet, so
1961a7dea167SDimitry Andric // do a virtual call. FIXME: handle the case where it is
1962a7dea167SDimitry Andric // devirtualized to the derived type (the type of the inner
1963a7dea167SDimitry Andric // expression) as in EmitCXXMemberOrOperatorMemberCallExpr.
1964a7dea167SDimitry Andric UseVirtualCall = true;
1965a7dea167SDimitry Andric }
1966a7dea167SDimitry Andric }
1967a7dea167SDimitry Andric if (UseVirtualCall) {
19680b57cec5SDimitry Andric CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
19690b57cec5SDimitry Andric Dtor);
19705ffd83dbSDimitry Andric return false;
19710b57cec5SDimitry Andric }
19720b57cec5SDimitry Andric }
19730b57cec5SDimitry Andric }
1974a7dea167SDimitry Andric }
19750b57cec5SDimitry Andric
19760b57cec5SDimitry Andric // Make sure that we call delete even if the dtor throws.
19770b57cec5SDimitry Andric // This doesn't have to a conditional cleanup because we're going
19780b57cec5SDimitry Andric // to pop it off in a second.
19790b57cec5SDimitry Andric CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
19800b57cec5SDimitry Andric Ptr.getPointer(),
19810b57cec5SDimitry Andric OperatorDelete, ElementType);
19820b57cec5SDimitry Andric
19830b57cec5SDimitry Andric if (Dtor)
19840b57cec5SDimitry Andric CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
19850b57cec5SDimitry Andric /*ForVirtualBase=*/false,
19860b57cec5SDimitry Andric /*Delegating=*/false,
19870b57cec5SDimitry Andric Ptr, ElementType);
19880b57cec5SDimitry Andric else if (auto Lifetime = ElementType.getObjCLifetime()) {
19890b57cec5SDimitry Andric switch (Lifetime) {
19900b57cec5SDimitry Andric case Qualifiers::OCL_None:
19910b57cec5SDimitry Andric case Qualifiers::OCL_ExplicitNone:
19920b57cec5SDimitry Andric case Qualifiers::OCL_Autoreleasing:
19930b57cec5SDimitry Andric break;
19940b57cec5SDimitry Andric
19950b57cec5SDimitry Andric case Qualifiers::OCL_Strong:
19960b57cec5SDimitry Andric CGF.EmitARCDestroyStrong(Ptr, ARCPreciseLifetime);
19970b57cec5SDimitry Andric break;
19980b57cec5SDimitry Andric
19990b57cec5SDimitry Andric case Qualifiers::OCL_Weak:
20000b57cec5SDimitry Andric CGF.EmitARCDestroyWeak(Ptr);
20010b57cec5SDimitry Andric break;
20020b57cec5SDimitry Andric }
20030b57cec5SDimitry Andric }
20040b57cec5SDimitry Andric
20055ffd83dbSDimitry Andric // When optimizing for size, call 'operator delete' unconditionally.
20065ffd83dbSDimitry Andric if (CGF.CGM.getCodeGenOpts().OptimizeSize > 1) {
20075ffd83dbSDimitry Andric CGF.EmitBlock(UnconditionalDeleteBlock);
20080b57cec5SDimitry Andric CGF.PopCleanupBlock();
20095ffd83dbSDimitry Andric return true;
20105ffd83dbSDimitry Andric }
20115ffd83dbSDimitry Andric
20125ffd83dbSDimitry Andric CGF.PopCleanupBlock();
20135ffd83dbSDimitry Andric return false;
20140b57cec5SDimitry Andric }
20150b57cec5SDimitry Andric
20160b57cec5SDimitry Andric namespace {
20170b57cec5SDimitry Andric /// Calls the given 'operator delete' on an array of objects.
20180b57cec5SDimitry Andric struct CallArrayDelete final : EHScopeStack::Cleanup {
20190b57cec5SDimitry Andric llvm::Value *Ptr;
20200b57cec5SDimitry Andric const FunctionDecl *OperatorDelete;
20210b57cec5SDimitry Andric llvm::Value *NumElements;
20220b57cec5SDimitry Andric QualType ElementType;
20230b57cec5SDimitry Andric CharUnits CookieSize;
20240b57cec5SDimitry Andric
CallArrayDelete__anond149d7b00611::CallArrayDelete20250b57cec5SDimitry Andric CallArrayDelete(llvm::Value *Ptr,
20260b57cec5SDimitry Andric const FunctionDecl *OperatorDelete,
20270b57cec5SDimitry Andric llvm::Value *NumElements,
20280b57cec5SDimitry Andric QualType ElementType,
20290b57cec5SDimitry Andric CharUnits CookieSize)
20300b57cec5SDimitry Andric : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
20310b57cec5SDimitry Andric ElementType(ElementType), CookieSize(CookieSize) {}
20320b57cec5SDimitry Andric
Emit__anond149d7b00611::CallArrayDelete20330b57cec5SDimitry Andric void Emit(CodeGenFunction &CGF, Flags flags) override {
20340b57cec5SDimitry Andric CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType, NumElements,
20350b57cec5SDimitry Andric CookieSize);
20360b57cec5SDimitry Andric }
20370b57cec5SDimitry Andric };
20380b57cec5SDimitry Andric }
20390b57cec5SDimitry Andric
20400b57cec5SDimitry Andric /// Emit the code for deleting an array of objects.
EmitArrayDelete(CodeGenFunction & CGF,const CXXDeleteExpr * E,Address deletedPtr,QualType elementType)20410b57cec5SDimitry Andric static void EmitArrayDelete(CodeGenFunction &CGF,
20420b57cec5SDimitry Andric const CXXDeleteExpr *E,
20430b57cec5SDimitry Andric Address deletedPtr,
20440b57cec5SDimitry Andric QualType elementType) {
20450b57cec5SDimitry Andric llvm::Value *numElements = nullptr;
20460b57cec5SDimitry Andric llvm::Value *allocatedPtr = nullptr;
20470b57cec5SDimitry Andric CharUnits cookieSize;
20480b57cec5SDimitry Andric CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
20490b57cec5SDimitry Andric numElements, allocatedPtr, cookieSize);
20500b57cec5SDimitry Andric
20510b57cec5SDimitry Andric assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
20520b57cec5SDimitry Andric
20530b57cec5SDimitry Andric // Make sure that we call delete even if one of the dtors throws.
20540b57cec5SDimitry Andric const FunctionDecl *operatorDelete = E->getOperatorDelete();
20550b57cec5SDimitry Andric CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
20560b57cec5SDimitry Andric allocatedPtr, operatorDelete,
20570b57cec5SDimitry Andric numElements, elementType,
20580b57cec5SDimitry Andric cookieSize);
20590b57cec5SDimitry Andric
20600b57cec5SDimitry Andric // Destroy the elements.
20610b57cec5SDimitry Andric if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
20620b57cec5SDimitry Andric assert(numElements && "no element count for a type with a destructor!");
20630b57cec5SDimitry Andric
20640b57cec5SDimitry Andric CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
20650b57cec5SDimitry Andric CharUnits elementAlign =
20660b57cec5SDimitry Andric deletedPtr.getAlignment().alignmentOfArrayElement(elementSize);
20670b57cec5SDimitry Andric
20680b57cec5SDimitry Andric llvm::Value *arrayBegin = deletedPtr.getPointer();
2069fe6060f1SDimitry Andric llvm::Value *arrayEnd = CGF.Builder.CreateInBoundsGEP(
2070fe6060f1SDimitry Andric deletedPtr.getElementType(), arrayBegin, numElements, "delete.end");
20710b57cec5SDimitry Andric
20720b57cec5SDimitry Andric // Note that it is legal to allocate a zero-length array, and we
20730b57cec5SDimitry Andric // can never fold the check away because the length should always
20740b57cec5SDimitry Andric // come from a cookie.
20750b57cec5SDimitry Andric CGF.emitArrayDestroy(arrayBegin, arrayEnd, elementType, elementAlign,
20760b57cec5SDimitry Andric CGF.getDestroyer(dtorKind),
20770b57cec5SDimitry Andric /*checkZeroLength*/ true,
20780b57cec5SDimitry Andric CGF.needsEHCleanup(dtorKind));
20790b57cec5SDimitry Andric }
20800b57cec5SDimitry Andric
20810b57cec5SDimitry Andric // Pop the cleanup block.
20820b57cec5SDimitry Andric CGF.PopCleanupBlock();
20830b57cec5SDimitry Andric }
20840b57cec5SDimitry Andric
EmitCXXDeleteExpr(const CXXDeleteExpr * E)20850b57cec5SDimitry Andric void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
20860b57cec5SDimitry Andric const Expr *Arg = E->getArgument();
20870b57cec5SDimitry Andric Address Ptr = EmitPointerWithAlignment(Arg);
20880b57cec5SDimitry Andric
20890b57cec5SDimitry Andric // Null check the pointer.
20905ffd83dbSDimitry Andric //
20915ffd83dbSDimitry Andric // We could avoid this null check if we can determine that the object
20925ffd83dbSDimitry Andric // destruction is trivial and doesn't require an array cookie; we can
20935ffd83dbSDimitry Andric // unconditionally perform the operator delete call in that case. For now, we
20945ffd83dbSDimitry Andric // assume that deleted pointers are null rarely enough that it's better to
20955ffd83dbSDimitry Andric // keep the branch. This might be worth revisiting for a -O0 code size win.
20960b57cec5SDimitry Andric llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
20970b57cec5SDimitry Andric llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
20980b57cec5SDimitry Andric
20990b57cec5SDimitry Andric llvm::Value *IsNull = Builder.CreateIsNull(Ptr.getPointer(), "isnull");
21000b57cec5SDimitry Andric
21010b57cec5SDimitry Andric Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
21020b57cec5SDimitry Andric EmitBlock(DeleteNotNull);
2103fe013be4SDimitry Andric Ptr.setKnownNonNull();
21040b57cec5SDimitry Andric
21050b57cec5SDimitry Andric QualType DeleteTy = E->getDestroyedType();
21060b57cec5SDimitry Andric
21070b57cec5SDimitry Andric // A destroying operator delete overrides the entire operation of the
21080b57cec5SDimitry Andric // delete expression.
21090b57cec5SDimitry Andric if (E->getOperatorDelete()->isDestroyingOperatorDelete()) {
21100b57cec5SDimitry Andric EmitDestroyingObjectDelete(*this, E, Ptr, DeleteTy);
21110b57cec5SDimitry Andric EmitBlock(DeleteEnd);
21120b57cec5SDimitry Andric return;
21130b57cec5SDimitry Andric }
21140b57cec5SDimitry Andric
21150b57cec5SDimitry Andric // We might be deleting a pointer to array. If so, GEP down to the
21160b57cec5SDimitry Andric // first non-array element.
21170b57cec5SDimitry Andric // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
21180b57cec5SDimitry Andric if (DeleteTy->isConstantArrayType()) {
21190b57cec5SDimitry Andric llvm::Value *Zero = Builder.getInt32(0);
21200b57cec5SDimitry Andric SmallVector<llvm::Value*,8> GEP;
21210b57cec5SDimitry Andric
21220b57cec5SDimitry Andric GEP.push_back(Zero); // point at the outermost array
21230b57cec5SDimitry Andric
21240b57cec5SDimitry Andric // For each layer of array type we're pointing at:
21250b57cec5SDimitry Andric while (const ConstantArrayType *Arr
21260b57cec5SDimitry Andric = getContext().getAsConstantArrayType(DeleteTy)) {
21270b57cec5SDimitry Andric // 1. Unpeel the array type.
21280b57cec5SDimitry Andric DeleteTy = Arr->getElementType();
21290b57cec5SDimitry Andric
21300b57cec5SDimitry Andric // 2. GEP to the first element of the array.
21310b57cec5SDimitry Andric GEP.push_back(Zero);
21320b57cec5SDimitry Andric }
21330b57cec5SDimitry Andric
2134fe6060f1SDimitry Andric Ptr = Address(Builder.CreateInBoundsGEP(Ptr.getElementType(),
2135fe6060f1SDimitry Andric Ptr.getPointer(), GEP, "del.first"),
2136fe013be4SDimitry Andric ConvertTypeForMem(DeleteTy), Ptr.getAlignment(),
2137fe013be4SDimitry Andric Ptr.isKnownNonNull());
21380b57cec5SDimitry Andric }
21390b57cec5SDimitry Andric
21400b57cec5SDimitry Andric assert(ConvertTypeForMem(DeleteTy) == Ptr.getElementType());
21410b57cec5SDimitry Andric
21420b57cec5SDimitry Andric if (E->isArrayForm()) {
21430b57cec5SDimitry Andric EmitArrayDelete(*this, E, Ptr, DeleteTy);
21440b57cec5SDimitry Andric EmitBlock(DeleteEnd);
21455ffd83dbSDimitry Andric } else {
21465ffd83dbSDimitry Andric if (!EmitObjectDelete(*this, E, Ptr, DeleteTy, DeleteEnd))
21475ffd83dbSDimitry Andric EmitBlock(DeleteEnd);
21485ffd83dbSDimitry Andric }
21490b57cec5SDimitry Andric }
21500b57cec5SDimitry Andric
isGLValueFromPointerDeref(const Expr * E)21510b57cec5SDimitry Andric static bool isGLValueFromPointerDeref(const Expr *E) {
21520b57cec5SDimitry Andric E = E->IgnoreParens();
21530b57cec5SDimitry Andric
21540b57cec5SDimitry Andric if (const auto *CE = dyn_cast<CastExpr>(E)) {
21550b57cec5SDimitry Andric if (!CE->getSubExpr()->isGLValue())
21560b57cec5SDimitry Andric return false;
21570b57cec5SDimitry Andric return isGLValueFromPointerDeref(CE->getSubExpr());
21580b57cec5SDimitry Andric }
21590b57cec5SDimitry Andric
21600b57cec5SDimitry Andric if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
21610b57cec5SDimitry Andric return isGLValueFromPointerDeref(OVE->getSourceExpr());
21620b57cec5SDimitry Andric
21630b57cec5SDimitry Andric if (const auto *BO = dyn_cast<BinaryOperator>(E))
21640b57cec5SDimitry Andric if (BO->getOpcode() == BO_Comma)
21650b57cec5SDimitry Andric return isGLValueFromPointerDeref(BO->getRHS());
21660b57cec5SDimitry Andric
21670b57cec5SDimitry Andric if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E))
21680b57cec5SDimitry Andric return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
21690b57cec5SDimitry Andric isGLValueFromPointerDeref(ACO->getFalseExpr());
21700b57cec5SDimitry Andric
21710b57cec5SDimitry Andric // C++11 [expr.sub]p1:
21720b57cec5SDimitry Andric // The expression E1[E2] is identical (by definition) to *((E1)+(E2))
21730b57cec5SDimitry Andric if (isa<ArraySubscriptExpr>(E))
21740b57cec5SDimitry Andric return true;
21750b57cec5SDimitry Andric
21760b57cec5SDimitry Andric if (const auto *UO = dyn_cast<UnaryOperator>(E))
21770b57cec5SDimitry Andric if (UO->getOpcode() == UO_Deref)
21780b57cec5SDimitry Andric return true;
21790b57cec5SDimitry Andric
21800b57cec5SDimitry Andric return false;
21810b57cec5SDimitry Andric }
21820b57cec5SDimitry Andric
EmitTypeidFromVTable(CodeGenFunction & CGF,const Expr * E,llvm::Type * StdTypeInfoPtrTy)21830b57cec5SDimitry Andric static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
21840b57cec5SDimitry Andric llvm::Type *StdTypeInfoPtrTy) {
21850b57cec5SDimitry Andric // Get the vtable pointer.
2186480093f4SDimitry Andric Address ThisPtr = CGF.EmitLValue(E).getAddress(CGF);
21870b57cec5SDimitry Andric
21880b57cec5SDimitry Andric QualType SrcRecordTy = E->getType();
21890b57cec5SDimitry Andric
21900b57cec5SDimitry Andric // C++ [class.cdtor]p4:
21910b57cec5SDimitry Andric // If the operand of typeid refers to the object under construction or
21920b57cec5SDimitry Andric // destruction and the static type of the operand is neither the constructor
21930b57cec5SDimitry Andric // or destructor’s class nor one of its bases, the behavior is undefined.
21940b57cec5SDimitry Andric CGF.EmitTypeCheck(CodeGenFunction::TCK_DynamicOperation, E->getExprLoc(),
21950b57cec5SDimitry Andric ThisPtr.getPointer(), SrcRecordTy);
21960b57cec5SDimitry Andric
21970b57cec5SDimitry Andric // C++ [expr.typeid]p2:
21980b57cec5SDimitry Andric // If the glvalue expression is obtained by applying the unary * operator to
21990b57cec5SDimitry Andric // a pointer and the pointer is a null pointer value, the typeid expression
22000b57cec5SDimitry Andric // throws the std::bad_typeid exception.
22010b57cec5SDimitry Andric //
22020b57cec5SDimitry Andric // However, this paragraph's intent is not clear. We choose a very generous
22030b57cec5SDimitry Andric // interpretation which implores us to consider comma operators, conditional
22040b57cec5SDimitry Andric // operators, parentheses and other such constructs.
22050b57cec5SDimitry Andric if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(
22060b57cec5SDimitry Andric isGLValueFromPointerDeref(E), SrcRecordTy)) {
22070b57cec5SDimitry Andric llvm::BasicBlock *BadTypeidBlock =
22080b57cec5SDimitry Andric CGF.createBasicBlock("typeid.bad_typeid");
22090b57cec5SDimitry Andric llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
22100b57cec5SDimitry Andric
22110b57cec5SDimitry Andric llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr.getPointer());
22120b57cec5SDimitry Andric CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
22130b57cec5SDimitry Andric
22140b57cec5SDimitry Andric CGF.EmitBlock(BadTypeidBlock);
22150b57cec5SDimitry Andric CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
22160b57cec5SDimitry Andric CGF.EmitBlock(EndBlock);
22170b57cec5SDimitry Andric }
22180b57cec5SDimitry Andric
22190b57cec5SDimitry Andric return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
22200b57cec5SDimitry Andric StdTypeInfoPtrTy);
22210b57cec5SDimitry Andric }
22220b57cec5SDimitry Andric
EmitCXXTypeidExpr(const CXXTypeidExpr * E)22230b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
2224fe013be4SDimitry Andric llvm::Type *PtrTy = llvm::PointerType::getUnqual(getLLVMContext());
2225c9157d92SDimitry Andric LangAS GlobAS = CGM.GetGlobalVarAddressSpace(nullptr);
2226c9157d92SDimitry Andric
2227c9157d92SDimitry Andric auto MaybeASCast = [=](auto &&TypeInfo) {
2228c9157d92SDimitry Andric if (GlobAS == LangAS::Default)
2229c9157d92SDimitry Andric return TypeInfo;
2230c9157d92SDimitry Andric return getTargetHooks().performAddrSpaceCast(CGM,TypeInfo, GlobAS,
2231c9157d92SDimitry Andric LangAS::Default, PtrTy);
2232c9157d92SDimitry Andric };
22330b57cec5SDimitry Andric
22340b57cec5SDimitry Andric if (E->isTypeOperand()) {
22350b57cec5SDimitry Andric llvm::Constant *TypeInfo =
22360b57cec5SDimitry Andric CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
2237c9157d92SDimitry Andric return MaybeASCast(TypeInfo);
22380b57cec5SDimitry Andric }
22390b57cec5SDimitry Andric
22400b57cec5SDimitry Andric // C++ [expr.typeid]p2:
22410b57cec5SDimitry Andric // When typeid is applied to a glvalue expression whose type is a
22420b57cec5SDimitry Andric // polymorphic class type, the result refers to a std::type_info object
22430b57cec5SDimitry Andric // representing the type of the most derived object (that is, the dynamic
22440b57cec5SDimitry Andric // type) to which the glvalue refers.
2245e8d8bef9SDimitry Andric // If the operand is already most derived object, no need to look up vtable.
2246e8d8bef9SDimitry Andric if (E->isPotentiallyEvaluated() && !E->isMostDerived(getContext()))
2247fe013be4SDimitry Andric return EmitTypeidFromVTable(*this, E->getExprOperand(), PtrTy);
22480b57cec5SDimitry Andric
22490b57cec5SDimitry Andric QualType OperandTy = E->getExprOperand()->getType();
2250c9157d92SDimitry Andric return MaybeASCast(CGM.GetAddrOfRTTIDescriptor(OperandTy));
22510b57cec5SDimitry Andric }
22520b57cec5SDimitry Andric
EmitDynamicCastToNull(CodeGenFunction & CGF,QualType DestTy)22530b57cec5SDimitry Andric static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
22540b57cec5SDimitry Andric QualType DestTy) {
22550b57cec5SDimitry Andric llvm::Type *DestLTy = CGF.ConvertType(DestTy);
22560b57cec5SDimitry Andric if (DestTy->isPointerType())
22570b57cec5SDimitry Andric return llvm::Constant::getNullValue(DestLTy);
22580b57cec5SDimitry Andric
22590b57cec5SDimitry Andric /// C++ [expr.dynamic.cast]p9:
22600b57cec5SDimitry Andric /// A failed cast to reference type throws std::bad_cast
22610b57cec5SDimitry Andric if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
22620b57cec5SDimitry Andric return nullptr;
22630b57cec5SDimitry Andric
2264fe013be4SDimitry Andric CGF.Builder.ClearInsertionPoint();
2265fe013be4SDimitry Andric return llvm::PoisonValue::get(DestLTy);
22660b57cec5SDimitry Andric }
22670b57cec5SDimitry Andric
EmitDynamicCast(Address ThisAddr,const CXXDynamicCastExpr * DCE)22680b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitDynamicCast(Address ThisAddr,
22690b57cec5SDimitry Andric const CXXDynamicCastExpr *DCE) {
22700b57cec5SDimitry Andric CGM.EmitExplicitCastExprType(DCE, this);
22710b57cec5SDimitry Andric QualType DestTy = DCE->getTypeAsWritten();
22720b57cec5SDimitry Andric
22730b57cec5SDimitry Andric QualType SrcTy = DCE->getSubExpr()->getType();
22740b57cec5SDimitry Andric
22750b57cec5SDimitry Andric // C++ [expr.dynamic.cast]p7:
22760b57cec5SDimitry Andric // If T is "pointer to cv void," then the result is a pointer to the most
22770b57cec5SDimitry Andric // derived object pointed to by v.
2278fe013be4SDimitry Andric bool IsDynamicCastToVoid = DestTy->isVoidPointerType();
22790b57cec5SDimitry Andric QualType SrcRecordTy;
22800b57cec5SDimitry Andric QualType DestRecordTy;
2281fe013be4SDimitry Andric if (IsDynamicCastToVoid) {
2282fe013be4SDimitry Andric SrcRecordTy = SrcTy->getPointeeType();
2283fe013be4SDimitry Andric // No DestRecordTy.
2284fe013be4SDimitry Andric } else if (const PointerType *DestPTy = DestTy->getAs<PointerType>()) {
22850b57cec5SDimitry Andric SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
22860b57cec5SDimitry Andric DestRecordTy = DestPTy->getPointeeType();
22870b57cec5SDimitry Andric } else {
22880b57cec5SDimitry Andric SrcRecordTy = SrcTy;
22890b57cec5SDimitry Andric DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
22900b57cec5SDimitry Andric }
22910b57cec5SDimitry Andric
22920b57cec5SDimitry Andric // C++ [class.cdtor]p5:
22930b57cec5SDimitry Andric // If the operand of the dynamic_cast refers to the object under
22940b57cec5SDimitry Andric // construction or destruction and the static type of the operand is not a
22950b57cec5SDimitry Andric // pointer to or object of the constructor or destructor’s own class or one
22960b57cec5SDimitry Andric // of its bases, the dynamic_cast results in undefined behavior.
22970b57cec5SDimitry Andric EmitTypeCheck(TCK_DynamicOperation, DCE->getExprLoc(), ThisAddr.getPointer(),
22980b57cec5SDimitry Andric SrcRecordTy);
22990b57cec5SDimitry Andric
2300fe013be4SDimitry Andric if (DCE->isAlwaysNull()) {
2301fe013be4SDimitry Andric if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy)) {
2302fe013be4SDimitry Andric // Expression emission is expected to retain a valid insertion point.
2303fe013be4SDimitry Andric if (!Builder.GetInsertBlock())
2304fe013be4SDimitry Andric EmitBlock(createBasicBlock("dynamic_cast.unreachable"));
23050b57cec5SDimitry Andric return T;
2306fe013be4SDimitry Andric }
2307fe013be4SDimitry Andric }
23080b57cec5SDimitry Andric
23090b57cec5SDimitry Andric assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
23100b57cec5SDimitry Andric
2311fe013be4SDimitry Andric // If the destination is effectively final, the cast succeeds if and only
2312fe013be4SDimitry Andric // if the dynamic type of the pointer is exactly the destination type.
2313fe013be4SDimitry Andric bool IsExact = !IsDynamicCastToVoid &&
2314fe013be4SDimitry Andric CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2315fe013be4SDimitry Andric DestRecordTy->getAsCXXRecordDecl()->isEffectivelyFinal() &&
2316fe013be4SDimitry Andric CGM.getCXXABI().shouldEmitExactDynamicCast(DestRecordTy);
2317fe013be4SDimitry Andric
23180b57cec5SDimitry Andric // C++ [expr.dynamic.cast]p4:
23190b57cec5SDimitry Andric // If the value of v is a null pointer value in the pointer case, the result
23200b57cec5SDimitry Andric // is the null pointer value of type T.
23210b57cec5SDimitry Andric bool ShouldNullCheckSrcValue =
2322fe013be4SDimitry Andric IsExact || CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(
2323fe013be4SDimitry Andric SrcTy->isPointerType(), SrcRecordTy);
23240b57cec5SDimitry Andric
23250b57cec5SDimitry Andric llvm::BasicBlock *CastNull = nullptr;
23260b57cec5SDimitry Andric llvm::BasicBlock *CastNotNull = nullptr;
23270b57cec5SDimitry Andric llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
23280b57cec5SDimitry Andric
23290b57cec5SDimitry Andric if (ShouldNullCheckSrcValue) {
23300b57cec5SDimitry Andric CastNull = createBasicBlock("dynamic_cast.null");
23310b57cec5SDimitry Andric CastNotNull = createBasicBlock("dynamic_cast.notnull");
23320b57cec5SDimitry Andric
23330b57cec5SDimitry Andric llvm::Value *IsNull = Builder.CreateIsNull(ThisAddr.getPointer());
23340b57cec5SDimitry Andric Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
23350b57cec5SDimitry Andric EmitBlock(CastNotNull);
23360b57cec5SDimitry Andric }
23370b57cec5SDimitry Andric
23380b57cec5SDimitry Andric llvm::Value *Value;
2339fe013be4SDimitry Andric if (IsDynamicCastToVoid) {
2340fe013be4SDimitry Andric Value = CGM.getCXXABI().emitDynamicCastToVoid(*this, ThisAddr, SrcRecordTy);
2341fe013be4SDimitry Andric } else if (IsExact) {
2342fe013be4SDimitry Andric // If the destination type is effectively final, this pointer points to the
2343fe013be4SDimitry Andric // right type if and only if its vptr has the right value.
2344fe013be4SDimitry Andric Value = CGM.getCXXABI().emitExactDynamicCast(
2345fe013be4SDimitry Andric *this, ThisAddr, SrcRecordTy, DestTy, DestRecordTy, CastEnd, CastNull);
23460b57cec5SDimitry Andric } else {
23470b57cec5SDimitry Andric assert(DestRecordTy->isRecordType() &&
23480b57cec5SDimitry Andric "destination type must be a record type!");
2349fe013be4SDimitry Andric Value = CGM.getCXXABI().emitDynamicCastCall(*this, ThisAddr, SrcRecordTy,
23500b57cec5SDimitry Andric DestTy, DestRecordTy, CastEnd);
23510b57cec5SDimitry Andric }
2352fe013be4SDimitry Andric CastNotNull = Builder.GetInsertBlock();
23530b57cec5SDimitry Andric
2354fe013be4SDimitry Andric llvm::Value *NullValue = nullptr;
23550b57cec5SDimitry Andric if (ShouldNullCheckSrcValue) {
23560b57cec5SDimitry Andric EmitBranch(CastEnd);
23570b57cec5SDimitry Andric
23580b57cec5SDimitry Andric EmitBlock(CastNull);
2359fe013be4SDimitry Andric NullValue = EmitDynamicCastToNull(*this, DestTy);
2360fe013be4SDimitry Andric CastNull = Builder.GetInsertBlock();
2361fe013be4SDimitry Andric
23620b57cec5SDimitry Andric EmitBranch(CastEnd);
23630b57cec5SDimitry Andric }
23640b57cec5SDimitry Andric
23650b57cec5SDimitry Andric EmitBlock(CastEnd);
23660b57cec5SDimitry Andric
2367fe013be4SDimitry Andric if (CastNull) {
23680b57cec5SDimitry Andric llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
23690b57cec5SDimitry Andric PHI->addIncoming(Value, CastNotNull);
2370fe013be4SDimitry Andric PHI->addIncoming(NullValue, CastNull);
23710b57cec5SDimitry Andric
23720b57cec5SDimitry Andric Value = PHI;
23730b57cec5SDimitry Andric }
23740b57cec5SDimitry Andric
23750b57cec5SDimitry Andric return Value;
23760b57cec5SDimitry Andric }
2377