159486a2dSAnders Carlsson //===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===// 259486a2dSAnders Carlsson // 32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information. 52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 659486a2dSAnders Carlsson // 759486a2dSAnders Carlsson //===----------------------------------------------------------------------===// 859486a2dSAnders Carlsson // 959486a2dSAnders Carlsson // This contains code dealing with code generation of C++ expressions 1059486a2dSAnders Carlsson // 1159486a2dSAnders Carlsson //===----------------------------------------------------------------------===// 1259486a2dSAnders Carlsson 13fe883422SPeter Collingbourne #include "CGCUDARuntime.h" 145d865c32SJohn McCall #include "CGCXXABI.h" 1591bbb554SDevang Patel #include "CGDebugInfo.h" 163a02247dSChandler Carruth #include "CGObjCRuntime.h" 1788559637SMarco Antognini #include "CodeGenFunction.h" 18de0fe07eSJohn McCall #include "ConstantEmitter.h" 1988559637SMarco Antognini #include "TargetInfo.h" 206368818fSRichard Trieu #include "clang/Basic/CodeGenOptions.h" 21a8e7df36SMark Lacey #include "clang/CodeGen/CGFunctionInfo.h" 22ffd5551bSChandler Carruth #include "llvm/IR/Intrinsics.h" 23bbe277c4SAnders Carlsson 2459486a2dSAnders Carlsson using namespace clang; 2559486a2dSAnders Carlsson using namespace CodeGen; 2659486a2dSAnders Carlsson 27d0a9e807SGeorge Burgess IV namespace { 28d0a9e807SGeorge Burgess IV struct MemberCallInfo { 29d0a9e807SGeorge Burgess IV RequiredArgs ReqArgs; 30d0a9e807SGeorge Burgess IV // Number of prefix arguments for the call. Ignores the `this` pointer. 31d0a9e807SGeorge Burgess IV unsigned PrefixSize; 32d0a9e807SGeorge Burgess IV }; 33d0a9e807SGeorge Burgess IV } 34d0a9e807SGeorge Burgess IV 35d0a9e807SGeorge Burgess IV static MemberCallInfo 36efa956ceSAlexey Samsonov commonEmitCXXMemberOrOperatorCall(CodeGenFunction &CGF, const CXXMethodDecl *MD, 37efa956ceSAlexey Samsonov llvm::Value *This, llvm::Value *ImplicitParam, 38efa956ceSAlexey Samsonov QualType ImplicitParamTy, const CallExpr *CE, 39762672a7SRichard Smith CallArgList &Args, CallArgList *RtlArgs) { 40a5bf76bdSAlexey Samsonov assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) || 41a5bf76bdSAlexey Samsonov isa<CXXOperatorCallExpr>(CE)); 4227da15baSAnders Carlsson assert(MD->isInstance() && 43a5bf76bdSAlexey Samsonov "Trying to emit a member or operator call expr on a static method!"); 4427da15baSAnders Carlsson 4527da15baSAnders Carlsson // Push the this ptr. 46034e7270SReid Kleckner const CXXRecordDecl *RD = 47034e7270SReid Kleckner CGF.CGM.getCXXABI().getThisArgumentTypeForMethod(MD); 48b92d290eSJames Y Knight Args.add(RValue::get(This), CGF.getTypes().DeriveThisType(RD, MD)); 4927da15baSAnders Carlsson 50ee6bc533STimur Iskhodzhanov // If there is an implicit parameter (e.g. VTT), emit it. 51ee6bc533STimur Iskhodzhanov if (ImplicitParam) { 52ee6bc533STimur Iskhodzhanov Args.add(RValue::get(ImplicitParam), ImplicitParamTy); 53e36a6b3eSAnders Carlsson } 54e36a6b3eSAnders Carlsson 55a729c62bSJohn McCall const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 56916db651SJames Y Knight RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size()); 57d0a9e807SGeorge Burgess IV unsigned PrefixSize = Args.size() - 1; 58a729c62bSJohn McCall 59a729c62bSJohn McCall // And the rest of the call args. 60762672a7SRichard Smith if (RtlArgs) { 61762672a7SRichard Smith // Special case: if the caller emitted the arguments right-to-left already 62762672a7SRichard Smith // (prior to emitting the *this argument), we're done. This happens for 63762672a7SRichard Smith // assignment operators. 64762672a7SRichard Smith Args.addFrom(*RtlArgs); 65762672a7SRichard Smith } else if (CE) { 66a5bf76bdSAlexey Samsonov // Special case: skip first argument of CXXOperatorCall (it is "this"). 678e1162c7SAlexey Samsonov unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0; 68f05779e2SDavid Blaikie CGF.EmitCallArgs(Args, FPT, drop_begin(CE->arguments(), ArgsToSkip), 698e1162c7SAlexey Samsonov CE->getDirectCallee()); 70a5bf76bdSAlexey Samsonov } else { 718e1162c7SAlexey Samsonov assert( 728e1162c7SAlexey Samsonov FPT->getNumParams() == 0 && 738e1162c7SAlexey Samsonov "No CallExpr specified for function with non-zero number of arguments"); 74a5bf76bdSAlexey Samsonov } 75d0a9e807SGeorge Burgess IV return {required, PrefixSize}; 760c0b6d9aSDavid Majnemer } 7727da15baSAnders Carlsson 780c0b6d9aSDavid Majnemer RValue CodeGenFunction::EmitCXXMemberOrOperatorCall( 79b92ab1afSJohn McCall const CXXMethodDecl *MD, const CGCallee &Callee, 80b92ab1afSJohn McCall ReturnValueSlot ReturnValue, 810c0b6d9aSDavid Majnemer llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy, 82762672a7SRichard Smith const CallExpr *CE, CallArgList *RtlArgs) { 830c0b6d9aSDavid Majnemer const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 840c0b6d9aSDavid Majnemer CallArgList Args; 85d0a9e807SGeorge Burgess IV MemberCallInfo CallInfo = commonEmitCXXMemberOrOperatorCall( 86762672a7SRichard Smith *this, MD, This, ImplicitParam, ImplicitParamTy, CE, Args, RtlArgs); 87d0a9e807SGeorge Burgess IV auto &FnInfo = CGM.getTypes().arrangeCXXMethodCall( 88d0a9e807SGeorge Burgess IV Args, FPT, CallInfo.ReqArgs, CallInfo.PrefixSize); 8909b5bfddSVedant Kumar return EmitCall(FnInfo, Callee, ReturnValue, Args, nullptr, 9009b5bfddSVedant Kumar CE ? CE->getExprLoc() : SourceLocation()); 9127da15baSAnders Carlsson } 9227da15baSAnders Carlsson 93ae81bbb4SAlexey Samsonov RValue CodeGenFunction::EmitCXXDestructorCall( 9488559637SMarco Antognini GlobalDecl Dtor, const CGCallee &Callee, llvm::Value *This, QualType ThisTy, 95d1c5b28cSPeter Collingbourne llvm::Value *ImplicitParam, QualType ImplicitParamTy, const CallExpr *CE) { 9688559637SMarco Antognini const CXXMethodDecl *DtorDecl = cast<CXXMethodDecl>(Dtor.getDecl()); 9788559637SMarco Antognini 9888559637SMarco Antognini assert(!ThisTy.isNull()); 9988559637SMarco Antognini assert(ThisTy->getAsCXXRecordDecl() == DtorDecl->getParent() && 10088559637SMarco Antognini "Pointer/Object mixup"); 10188559637SMarco Antognini 10288559637SMarco Antognini LangAS SrcAS = ThisTy.getAddressSpace(); 10388559637SMarco Antognini LangAS DstAS = DtorDecl->getMethodQualifiers().getAddressSpace(); 10488559637SMarco Antognini if (SrcAS != DstAS) { 10588559637SMarco Antognini QualType DstTy = DtorDecl->getThisType(); 10688559637SMarco Antognini llvm::Type *NewType = CGM.getTypes().ConvertType(DstTy); 10788559637SMarco Antognini This = getTargetHooks().performAddrSpaceCast(*this, This, SrcAS, DstAS, 10888559637SMarco Antognini NewType); 10988559637SMarco Antognini } 11088559637SMarco Antognini 1110c0b6d9aSDavid Majnemer CallArgList Args; 11288559637SMarco Antognini commonEmitCXXMemberOrOperatorCall(*this, DtorDecl, This, ImplicitParam, 11388559637SMarco Antognini ImplicitParamTy, CE, Args, nullptr); 114d1c5b28cSPeter Collingbourne return EmitCall(CGM.getTypes().arrangeCXXStructorDeclaration(Dtor), Callee, 115d1c5b28cSPeter Collingbourne ReturnValueSlot(), Args); 116b92ab1afSJohn McCall } 117b92ab1afSJohn McCall 118b92ab1afSJohn McCall RValue CodeGenFunction::EmitCXXPseudoDestructorExpr( 119b92ab1afSJohn McCall const CXXPseudoDestructorExpr *E) { 120b92ab1afSJohn McCall QualType DestroyedType = E->getDestroyedType(); 121b92ab1afSJohn McCall if (DestroyedType.hasStrongOrWeakObjCLifetime()) { 122b92ab1afSJohn McCall // Automatic Reference Counting: 123b92ab1afSJohn McCall // If the pseudo-expression names a retainable object with weak or 124b92ab1afSJohn McCall // strong lifetime, the object shall be released. 125b92ab1afSJohn McCall Expr *BaseExpr = E->getBase(); 126b92ab1afSJohn McCall Address BaseValue = Address::invalid(); 127b92ab1afSJohn McCall Qualifiers BaseQuals; 128b92ab1afSJohn McCall 129b92ab1afSJohn McCall // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar. 130b92ab1afSJohn McCall if (E->isArrow()) { 131b92ab1afSJohn McCall BaseValue = EmitPointerWithAlignment(BaseExpr); 132b92ab1afSJohn McCall const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>(); 133b92ab1afSJohn McCall BaseQuals = PTy->getPointeeType().getQualifiers(); 134b92ab1afSJohn McCall } else { 135b92ab1afSJohn McCall LValue BaseLV = EmitLValue(BaseExpr); 136*f139ae3dSAkira Hatanaka BaseValue = BaseLV.getAddress(*this); 137b92ab1afSJohn McCall QualType BaseTy = BaseExpr->getType(); 138b92ab1afSJohn McCall BaseQuals = BaseTy.getQualifiers(); 139b92ab1afSJohn McCall } 140b92ab1afSJohn McCall 141b92ab1afSJohn McCall switch (DestroyedType.getObjCLifetime()) { 142b92ab1afSJohn McCall case Qualifiers::OCL_None: 143b92ab1afSJohn McCall case Qualifiers::OCL_ExplicitNone: 144b92ab1afSJohn McCall case Qualifiers::OCL_Autoreleasing: 145b92ab1afSJohn McCall break; 146b92ab1afSJohn McCall 147b92ab1afSJohn McCall case Qualifiers::OCL_Strong: 148b92ab1afSJohn McCall EmitARCRelease(Builder.CreateLoad(BaseValue, 149b92ab1afSJohn McCall DestroyedType.isVolatileQualified()), 150b92ab1afSJohn McCall ARCPreciseLifetime); 151b92ab1afSJohn McCall break; 152b92ab1afSJohn McCall 153b92ab1afSJohn McCall case Qualifiers::OCL_Weak: 154b92ab1afSJohn McCall EmitARCDestroyWeak(BaseValue); 155b92ab1afSJohn McCall break; 156b92ab1afSJohn McCall } 157b92ab1afSJohn McCall } else { 158b92ab1afSJohn McCall // C++ [expr.pseudo]p1: 159b92ab1afSJohn McCall // The result shall only be used as the operand for the function call 160b92ab1afSJohn McCall // operator (), and the result of such a call has type void. The only 161b92ab1afSJohn McCall // effect is the evaluation of the postfix-expression before the dot or 162b92ab1afSJohn McCall // arrow. 163b92ab1afSJohn McCall EmitIgnoredExpr(E->getBase()); 164b92ab1afSJohn McCall } 165b92ab1afSJohn McCall 166b92ab1afSJohn McCall return RValue::get(nullptr); 1670c0b6d9aSDavid Majnemer } 1680c0b6d9aSDavid Majnemer 1693b33c4ecSRafael Espindola static CXXRecordDecl *getCXXRecord(const Expr *E) { 1703b33c4ecSRafael Espindola QualType T = E->getType(); 1713b33c4ecSRafael Espindola if (const PointerType *PTy = T->getAs<PointerType>()) 1723b33c4ecSRafael Espindola T = PTy->getPointeeType(); 1733b33c4ecSRafael Espindola const RecordType *Ty = T->castAs<RecordType>(); 1743b33c4ecSRafael Espindola return cast<CXXRecordDecl>(Ty->getDecl()); 1753b33c4ecSRafael Espindola } 1763b33c4ecSRafael Espindola 17764225794SFrancois Pichet // Note: This function also emit constructor calls to support a MSVC 17864225794SFrancois Pichet // extensions allowing explicit constructor function call. 17927da15baSAnders Carlsson RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE, 18027da15baSAnders Carlsson ReturnValueSlot ReturnValue) { 1812d2e8707SJohn McCall const Expr *callee = CE->getCallee()->IgnoreParens(); 1822d2e8707SJohn McCall 1832d2e8707SJohn McCall if (isa<BinaryOperator>(callee)) 18427da15baSAnders Carlsson return EmitCXXMemberPointerCallExpr(CE, ReturnValue); 18527da15baSAnders Carlsson 1862d2e8707SJohn McCall const MemberExpr *ME = cast<MemberExpr>(callee); 18727da15baSAnders Carlsson const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl()); 18827da15baSAnders Carlsson 18927da15baSAnders Carlsson if (MD->isStatic()) { 19027da15baSAnders Carlsson // The method is static, emit it as we would a regular call. 191de6480a3SErich Keane CGCallee callee = 192de6480a3SErich Keane CGCallee::forDirect(CGM.GetAddrOfFunction(MD), GlobalDecl(MD)); 193b92ab1afSJohn McCall return EmitCall(getContext().getPointerType(MD->getType()), callee, CE, 19470b9c01bSAlexey Samsonov ReturnValue); 19527da15baSAnders Carlsson } 19627da15baSAnders Carlsson 197aad4af6dSNico Weber bool HasQualifier = ME->hasQualifier(); 198aad4af6dSNico Weber NestedNameSpecifier *Qualifier = HasQualifier ? ME->getQualifier() : nullptr; 199aad4af6dSNico Weber bool IsArrow = ME->isArrow(); 200ecbe2e97SRafael Espindola const Expr *Base = ME->getBase(); 201aad4af6dSNico Weber 202aad4af6dSNico Weber return EmitCXXMemberOrOperatorMemberCallExpr( 203aad4af6dSNico Weber CE, MD, ReturnValue, HasQualifier, Qualifier, IsArrow, Base); 204aad4af6dSNico Weber } 205aad4af6dSNico Weber 206aad4af6dSNico Weber RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr( 207aad4af6dSNico Weber const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue, 208aad4af6dSNico Weber bool HasQualifier, NestedNameSpecifier *Qualifier, bool IsArrow, 209aad4af6dSNico Weber const Expr *Base) { 210aad4af6dSNico Weber assert(isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE)); 211aad4af6dSNico Weber 212aad4af6dSNico Weber // Compute the object pointer. 213aad4af6dSNico Weber bool CanUseVirtualCall = MD->isVirtual() && !HasQualifier; 214ecbe2e97SRafael Espindola 2158a13c418SCraig Topper const CXXMethodDecl *DevirtualizedMethod = nullptr; 21622461673SAkira Hatanaka if (CanUseVirtualCall && 21722461673SAkira Hatanaka MD->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) { 2183b33c4ecSRafael Espindola const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType(); 2193b33c4ecSRafael Espindola DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl); 2203b33c4ecSRafael Espindola assert(DevirtualizedMethod); 2213b33c4ecSRafael Espindola const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent(); 2223b33c4ecSRafael Espindola const Expr *Inner = Base->ignoreParenBaseCasts(); 2235bd68794SAlexey Bataev if (DevirtualizedMethod->getReturnType().getCanonicalType() != 2245bd68794SAlexey Bataev MD->getReturnType().getCanonicalType()) 2255bd68794SAlexey Bataev // If the return types are not the same, this might be a case where more 2265bd68794SAlexey Bataev // code needs to run to compensate for it. For example, the derived 2275bd68794SAlexey Bataev // method might return a type that inherits form from the return 2285bd68794SAlexey Bataev // type of MD and has a prefix. 2295bd68794SAlexey Bataev // For now we just avoid devirtualizing these covariant cases. 2305bd68794SAlexey Bataev DevirtualizedMethod = nullptr; 2315bd68794SAlexey Bataev else if (getCXXRecord(Inner) == DevirtualizedClass) 2323b33c4ecSRafael Espindola // If the class of the Inner expression is where the dynamic method 2333b33c4ecSRafael Espindola // is defined, build the this pointer from it. 2343b33c4ecSRafael Espindola Base = Inner; 2353b33c4ecSRafael Espindola else if (getCXXRecord(Base) != DevirtualizedClass) { 2363b33c4ecSRafael Espindola // If the method is defined in a class that is not the best dynamic 2373b33c4ecSRafael Espindola // one or the one of the full expression, we would have to build 2383b33c4ecSRafael Espindola // a derived-to-base cast to compute the correct this pointer, but 2393b33c4ecSRafael Espindola // we don't have support for that yet, so do a virtual call. 2408a13c418SCraig Topper DevirtualizedMethod = nullptr; 2413b33c4ecSRafael Espindola } 2423b33c4ecSRafael Espindola } 243ecbe2e97SRafael Espindola 244762672a7SRichard Smith // C++17 demands that we evaluate the RHS of a (possibly-compound) assignment 245762672a7SRichard Smith // operator before the LHS. 246762672a7SRichard Smith CallArgList RtlArgStorage; 247762672a7SRichard Smith CallArgList *RtlArgs = nullptr; 248762672a7SRichard Smith if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(CE)) { 249762672a7SRichard Smith if (OCE->isAssignmentOp()) { 250762672a7SRichard Smith RtlArgs = &RtlArgStorage; 251762672a7SRichard Smith EmitCallArgs(*RtlArgs, MD->getType()->castAs<FunctionProtoType>(), 252762672a7SRichard Smith drop_begin(CE->arguments(), 1), CE->getDirectCallee(), 253a560ccf2SRichard Smith /*ParamsToSkip*/0, EvaluationOrder::ForceRightToLeft); 254762672a7SRichard Smith } 255762672a7SRichard Smith } 256762672a7SRichard Smith 2571860b520SIvan A. Kosarev LValue This; 2581860b520SIvan A. Kosarev if (IsArrow) { 2591860b520SIvan A. Kosarev LValueBaseInfo BaseInfo; 2601860b520SIvan A. Kosarev TBAAAccessInfo TBAAInfo; 2611860b520SIvan A. Kosarev Address ThisValue = EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo); 2621860b520SIvan A. Kosarev This = MakeAddrLValue(ThisValue, Base->getType(), BaseInfo, TBAAInfo); 2631860b520SIvan A. Kosarev } else { 2641860b520SIvan A. Kosarev This = EmitLValue(Base); 2651860b520SIvan A. Kosarev } 266ecbe2e97SRafael Espindola 267ab4f7f14SJames Y Knight if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 268ab4f7f14SJames Y Knight // This is the MSVC p->Ctor::Ctor(...) extension. We assume that's 269ab4f7f14SJames Y Knight // constructing a new complete object of type Ctor. 270ab4f7f14SJames Y Knight assert(!RtlArgs); 271ab4f7f14SJames Y Knight assert(ReturnValue.isNull() && "Constructor shouldn't have return value"); 272ab4f7f14SJames Y Knight CallArgList Args; 273ab4f7f14SJames Y Knight commonEmitCXXMemberOrOperatorCall( 274*f139ae3dSAkira Hatanaka *this, Ctor, This.getPointer(*this), /*ImplicitParam=*/nullptr, 275ab4f7f14SJames Y Knight /*ImplicitParamTy=*/QualType(), CE, Args, nullptr); 276ab4f7f14SJames Y Knight 277ab4f7f14SJames Y Knight EmitCXXConstructorCall(Ctor, Ctor_Complete, /*ForVirtualBase=*/false, 278*f139ae3dSAkira Hatanaka /*Delegating=*/false, This.getAddress(*this), Args, 279ab4f7f14SJames Y Knight AggValueSlot::DoesNotOverlap, CE->getExprLoc(), 280ab4f7f14SJames Y Knight /*NewPointerIsChecked=*/false); 281ab4f7f14SJames Y Knight return RValue::get(nullptr); 282ab4f7f14SJames Y Knight } 28327da15baSAnders Carlsson 284419bd094SRichard Smith if (MD->isTrivial() || (MD->isDefaulted() && MD->getParent()->isUnion())) { 2858a13c418SCraig Topper if (isa<CXXDestructorDecl>(MD)) return RValue::get(nullptr); 286aad4af6dSNico Weber if (!MD->getParent()->mayInsertExtraPadding()) { 28722653bacSSebastian Redl if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) { 28822653bacSSebastian Redl // We don't like to generate the trivial copy/move assignment operator 28922653bacSSebastian Redl // when it isn't necessary; just produce the proper effect here. 290762672a7SRichard Smith LValue RHS = isa<CXXOperatorCallExpr>(CE) 291762672a7SRichard Smith ? MakeNaturalAlignAddrLValue( 2925b330e8dSYaxun Liu (*RtlArgs)[0].getRValue(*this).getScalarVal(), 293762672a7SRichard Smith (*(CE->arg_begin() + 1))->getType()) 294762672a7SRichard Smith : EmitLValue(*CE->arg_begin()); 2951860b520SIvan A. Kosarev EmitAggregateAssign(This, RHS, CE->getType()); 296*f139ae3dSAkira Hatanaka return RValue::get(This.getPointer(*this)); 29727da15baSAnders Carlsson } 29864225794SFrancois Pichet llvm_unreachable("unknown trivial member function"); 29964225794SFrancois Pichet } 300aad4af6dSNico Weber } 30164225794SFrancois Pichet 3020d635f53SJohn McCall // Compute the function type we're calling. 3033abfe958SNico Weber const CXXMethodDecl *CalleeDecl = 3043abfe958SNico Weber DevirtualizedMethod ? DevirtualizedMethod : MD; 3058a13c418SCraig Topper const CGFunctionInfo *FInfo = nullptr; 3063abfe958SNico Weber if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl)) 3078d2a19b4SRafael Espindola FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration( 308d1c5b28cSPeter Collingbourne GlobalDecl(Dtor, Dtor_Complete)); 30964225794SFrancois Pichet else 310ade60977SEli Friedman FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl); 3110d635f53SJohn McCall 312e7de47efSReid Kleckner llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo); 3130d635f53SJohn McCall 314d98f5d78SIvan Krasin // C++11 [class.mfct.non-static]p2: 315d98f5d78SIvan Krasin // If a non-static member function of a class X is called for an object that 316d98f5d78SIvan Krasin // is not of type X, or of a type derived from X, the behavior is undefined. 317d98f5d78SIvan Krasin SourceLocation CallLoc; 318d98f5d78SIvan Krasin ASTContext &C = getContext(); 319d98f5d78SIvan Krasin if (CE) 320d98f5d78SIvan Krasin CallLoc = CE->getExprLoc(); 321d98f5d78SIvan Krasin 32234b1fd6aSVedant Kumar SanitizerSet SkippedChecks; 323ffd7c887SVedant Kumar if (const auto *CMCE = dyn_cast<CXXMemberCallExpr>(CE)) { 324ffd7c887SVedant Kumar auto *IOA = CMCE->getImplicitObjectArgument(); 325ffd7c887SVedant Kumar bool IsImplicitObjectCXXThis = IsWrappedCXXThis(IOA); 326ffd7c887SVedant Kumar if (IsImplicitObjectCXXThis) 327ffd7c887SVedant Kumar SkippedChecks.set(SanitizerKind::Alignment, true); 328ffd7c887SVedant Kumar if (IsImplicitObjectCXXThis || isa<DeclRefExpr>(IOA)) 32934b1fd6aSVedant Kumar SkippedChecks.set(SanitizerKind::Null, true); 330ffd7c887SVedant Kumar } 331*f139ae3dSAkira Hatanaka EmitTypeCheck(CodeGenFunction::TCK_MemberCall, CallLoc, 332*f139ae3dSAkira Hatanaka This.getPointer(*this), 333ab4f7f14SJames Y Knight C.getRecordType(CalleeDecl->getParent()), 33434b1fd6aSVedant Kumar /*Alignment=*/CharUnits::Zero(), SkippedChecks); 335d98f5d78SIvan Krasin 33627da15baSAnders Carlsson // C++ [class.virtual]p12: 33727da15baSAnders Carlsson // Explicit qualification with the scope operator (5.1) suppresses the 33827da15baSAnders Carlsson // virtual call mechanism. 33927da15baSAnders Carlsson // 34027da15baSAnders Carlsson // We also don't emit a virtual call if the base expression has a record type 34127da15baSAnders Carlsson // because then we know what the type is. 3423b33c4ecSRafael Espindola bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod; 3439dc6eef7SStephen Lin 344b92d290eSJames Y Knight if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl)) { 34519cee187SStephen Lin assert(CE->arg_begin() == CE->arg_end() && 3469dc6eef7SStephen Lin "Destructor shouldn't have explicit parameters"); 3479dc6eef7SStephen Lin assert(ReturnValue.isNull() && "Destructor shouldn't have return value"); 3489dc6eef7SStephen Lin if (UseVirtualCall) { 349*f139ae3dSAkira Hatanaka CGM.getCXXABI().EmitVirtualDestructorCall(*this, Dtor, Dtor_Complete, 350*f139ae3dSAkira Hatanaka This.getAddress(*this), 3511860b520SIvan A. Kosarev cast<CXXMemberCallExpr>(CE)); 35227da15baSAnders Carlsson } else { 353d1c5b28cSPeter Collingbourne GlobalDecl GD(Dtor, Dtor_Complete); 354b92ab1afSJohn McCall CGCallee Callee; 355b92d290eSJames Y Knight if (getLangOpts().AppleKext && Dtor->isVirtual() && HasQualifier) 356b92d290eSJames Y Knight Callee = BuildAppleKextVirtualCall(Dtor, Qualifier, Ty); 3573b33c4ecSRafael Espindola else if (!DevirtualizedMethod) 358d1c5b28cSPeter Collingbourne Callee = 359d1c5b28cSPeter Collingbourne CGCallee::forDirect(CGM.getAddrOfCXXStructor(GD, FInfo, Ty), GD); 36049e860b2SRafael Espindola else { 361d1c5b28cSPeter Collingbourne Callee = CGCallee::forDirect(CGM.GetAddrOfFunction(GD, Ty), GD); 36249e860b2SRafael Espindola } 363b92d290eSJames Y Knight 36488559637SMarco Antognini QualType ThisTy = 36588559637SMarco Antognini IsArrow ? Base->getType()->getPointeeType() : Base->getType(); 366*f139ae3dSAkira Hatanaka EmitCXXDestructorCall(GD, Callee, This.getPointer(*this), ThisTy, 367b92d290eSJames Y Knight /*ImplicitParam=*/nullptr, 368d1c5b28cSPeter Collingbourne /*ImplicitParamTy=*/QualType(), nullptr); 36927da15baSAnders Carlsson } 3708a13c418SCraig Topper return RValue::get(nullptr); 3719dc6eef7SStephen Lin } 3729dc6eef7SStephen Lin 373b92d290eSJames Y Knight // FIXME: Uses of 'MD' past this point need to be audited. We may need to use 374b92d290eSJames Y Knight // 'CalleeDecl' instead. 375b92d290eSJames Y Knight 376b92ab1afSJohn McCall CGCallee Callee; 377ab4f7f14SJames Y Knight if (UseVirtualCall) { 378*f139ae3dSAkira Hatanaka Callee = CGCallee::forVirtual(CE, MD, This.getAddress(*this), Ty); 37927da15baSAnders Carlsson } else { 3801a7488afSPeter Collingbourne if (SanOpts.has(SanitizerKind::CFINVCall) && 3811a7488afSPeter Collingbourne MD->getParent()->isDynamicClass()) { 3826010880bSPeter Collingbourne llvm::Value *VTable; 3836010880bSPeter Collingbourne const CXXRecordDecl *RD; 384*f139ae3dSAkira Hatanaka std::tie(VTable, RD) = CGM.getCXXABI().LoadVTablePtr( 385*f139ae3dSAkira Hatanaka *this, This.getAddress(*this), CalleeDecl->getParent()); 386f2ceec48SStephen Kelly EmitVTablePtrCheckForCall(RD, VTable, CFITCK_NVCall, CE->getBeginLoc()); 3871a7488afSPeter Collingbourne } 3881a7488afSPeter Collingbourne 389aad4af6dSNico Weber if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier) 390aad4af6dSNico Weber Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty); 3913b33c4ecSRafael Espindola else if (!DevirtualizedMethod) 392de6480a3SErich Keane Callee = 393de6480a3SErich Keane CGCallee::forDirect(CGM.GetAddrOfFunction(MD, Ty), GlobalDecl(MD)); 39449e860b2SRafael Espindola else { 395de6480a3SErich Keane Callee = 396de6480a3SErich Keane CGCallee::forDirect(CGM.GetAddrOfFunction(DevirtualizedMethod, Ty), 397de6480a3SErich Keane GlobalDecl(DevirtualizedMethod)); 39849e860b2SRafael Espindola } 39927da15baSAnders Carlsson } 40027da15baSAnders Carlsson 401f1749427STimur Iskhodzhanov if (MD->isVirtual()) { 4021860b520SIvan A. Kosarev Address NewThisAddr = 4031860b520SIvan A. Kosarev CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall( 404*f139ae3dSAkira Hatanaka *this, CalleeDecl, This.getAddress(*this), UseVirtualCall); 4051860b520SIvan A. Kosarev This.setAddress(NewThisAddr); 406f1749427STimur Iskhodzhanov } 40788fd439aSTimur Iskhodzhanov 408018f266bSVedant Kumar return EmitCXXMemberOrOperatorCall( 409*f139ae3dSAkira Hatanaka CalleeDecl, Callee, ReturnValue, This.getPointer(*this), 410018f266bSVedant Kumar /*ImplicitParam=*/nullptr, QualType(), CE, RtlArgs); 41127da15baSAnders Carlsson } 41227da15baSAnders Carlsson 41327da15baSAnders Carlsson RValue 41427da15baSAnders Carlsson CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E, 41527da15baSAnders Carlsson ReturnValueSlot ReturnValue) { 41627da15baSAnders Carlsson const BinaryOperator *BO = 41727da15baSAnders Carlsson cast<BinaryOperator>(E->getCallee()->IgnoreParens()); 41827da15baSAnders Carlsson const Expr *BaseExpr = BO->getLHS(); 41927da15baSAnders Carlsson const Expr *MemFnExpr = BO->getRHS(); 42027da15baSAnders Carlsson 4211cd399c9SSimon Pilgrim const auto *MPT = MemFnExpr->getType()->castAs<MemberPointerType>(); 4221cd399c9SSimon Pilgrim const auto *FPT = MPT->getPointeeType()->castAs<FunctionProtoType>(); 4231cd399c9SSimon Pilgrim const auto *RD = 4241cd399c9SSimon Pilgrim cast<CXXRecordDecl>(MPT->getClass()->castAs<RecordType>()->getDecl()); 42527da15baSAnders Carlsson 42627da15baSAnders Carlsson // Emit the 'this' pointer. 4277f416cc4SJohn McCall Address This = Address::invalid(); 428e302792bSJohn McCall if (BO->getOpcode() == BO_PtrMemI) 4297f416cc4SJohn McCall This = EmitPointerWithAlignment(BaseExpr); 43027da15baSAnders Carlsson else 431*f139ae3dSAkira Hatanaka This = EmitLValue(BaseExpr).getAddress(*this); 43227da15baSAnders Carlsson 4337f416cc4SJohn McCall EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This.getPointer(), 434e30752c9SRichard Smith QualType(MPT->getClass(), 0)); 43569d0d262SRichard Smith 436bde62d78SRichard Smith // Get the member function pointer. 437bde62d78SRichard Smith llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr); 438bde62d78SRichard Smith 439475999dcSJohn McCall // Ask the ABI to load the callee. Note that This is modified. 4407f416cc4SJohn McCall llvm::Value *ThisPtrForCall = nullptr; 441b92ab1afSJohn McCall CGCallee Callee = 4427f416cc4SJohn McCall CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This, 4437f416cc4SJohn McCall ThisPtrForCall, MemFnPtr, MPT); 44427da15baSAnders Carlsson 44527da15baSAnders Carlsson CallArgList Args; 44627da15baSAnders Carlsson 44727da15baSAnders Carlsson QualType ThisType = 44827da15baSAnders Carlsson getContext().getPointerType(getContext().getTagDeclType(RD)); 44927da15baSAnders Carlsson 45027da15baSAnders Carlsson // Push the this ptr. 4517f416cc4SJohn McCall Args.add(RValue::get(ThisPtrForCall), ThisType); 45227da15baSAnders Carlsson 453916db651SJames Y Knight RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1); 4548dda7b27SJohn McCall 45527da15baSAnders Carlsson // And the rest of the call args 456419996ccSGeorge Burgess IV EmitCallArgs(Args, FPT, E->arguments()); 457d0a9e807SGeorge Burgess IV return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required, 458d0a9e807SGeorge Burgess IV /*PrefixSize=*/0), 45909b5bfddSVedant Kumar Callee, ReturnValue, Args, nullptr, E->getExprLoc()); 46027da15baSAnders Carlsson } 46127da15baSAnders Carlsson 46227da15baSAnders Carlsson RValue 46327da15baSAnders Carlsson CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E, 46427da15baSAnders Carlsson const CXXMethodDecl *MD, 46527da15baSAnders Carlsson ReturnValueSlot ReturnValue) { 46627da15baSAnders Carlsson assert(MD->isInstance() && 46727da15baSAnders Carlsson "Trying to emit a member call expr on a static method!"); 468aad4af6dSNico Weber return EmitCXXMemberOrOperatorMemberCallExpr( 469aad4af6dSNico Weber E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr, 470aad4af6dSNico Weber /*IsArrow=*/false, E->getArg(0)); 47127da15baSAnders Carlsson } 47227da15baSAnders Carlsson 473fe883422SPeter Collingbourne RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E, 474fe883422SPeter Collingbourne ReturnValueSlot ReturnValue) { 475fe883422SPeter Collingbourne return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue); 476fe883422SPeter Collingbourne } 477fe883422SPeter Collingbourne 478fde961dbSEli Friedman static void EmitNullBaseClassInitialization(CodeGenFunction &CGF, 4797f416cc4SJohn McCall Address DestPtr, 480fde961dbSEli Friedman const CXXRecordDecl *Base) { 481fde961dbSEli Friedman if (Base->isEmpty()) 482fde961dbSEli Friedman return; 483fde961dbSEli Friedman 4847f416cc4SJohn McCall DestPtr = CGF.Builder.CreateElementBitCast(DestPtr, CGF.Int8Ty); 485fde961dbSEli Friedman 486fde961dbSEli Friedman const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base); 4878671c6e0SDavid Majnemer CharUnits NVSize = Layout.getNonVirtualSize(); 4888671c6e0SDavid Majnemer 4898671c6e0SDavid Majnemer // We cannot simply zero-initialize the entire base sub-object if vbptrs are 4908671c6e0SDavid Majnemer // present, they are initialized by the most derived class before calling the 4918671c6e0SDavid Majnemer // constructor. 4928671c6e0SDavid Majnemer SmallVector<std::pair<CharUnits, CharUnits>, 1> Stores; 4938671c6e0SDavid Majnemer Stores.emplace_back(CharUnits::Zero(), NVSize); 4948671c6e0SDavid Majnemer 4958671c6e0SDavid Majnemer // Each store is split by the existence of a vbptr. 4968671c6e0SDavid Majnemer CharUnits VBPtrWidth = CGF.getPointerSize(); 4978671c6e0SDavid Majnemer std::vector<CharUnits> VBPtrOffsets = 4988671c6e0SDavid Majnemer CGF.CGM.getCXXABI().getVBPtrOffsets(Base); 4998671c6e0SDavid Majnemer for (CharUnits VBPtrOffset : VBPtrOffsets) { 5007f980d84SDavid Majnemer // Stop before we hit any virtual base pointers located in virtual bases. 5017f980d84SDavid Majnemer if (VBPtrOffset >= NVSize) 5027f980d84SDavid Majnemer break; 5038671c6e0SDavid Majnemer std::pair<CharUnits, CharUnits> LastStore = Stores.pop_back_val(); 5048671c6e0SDavid Majnemer CharUnits LastStoreOffset = LastStore.first; 5058671c6e0SDavid Majnemer CharUnits LastStoreSize = LastStore.second; 5068671c6e0SDavid Majnemer 5078671c6e0SDavid Majnemer CharUnits SplitBeforeOffset = LastStoreOffset; 5088671c6e0SDavid Majnemer CharUnits SplitBeforeSize = VBPtrOffset - SplitBeforeOffset; 5098671c6e0SDavid Majnemer assert(!SplitBeforeSize.isNegative() && "negative store size!"); 5108671c6e0SDavid Majnemer if (!SplitBeforeSize.isZero()) 5118671c6e0SDavid Majnemer Stores.emplace_back(SplitBeforeOffset, SplitBeforeSize); 5128671c6e0SDavid Majnemer 5138671c6e0SDavid Majnemer CharUnits SplitAfterOffset = VBPtrOffset + VBPtrWidth; 5148671c6e0SDavid Majnemer CharUnits SplitAfterSize = LastStoreSize - SplitAfterOffset; 5158671c6e0SDavid Majnemer assert(!SplitAfterSize.isNegative() && "negative store size!"); 5168671c6e0SDavid Majnemer if (!SplitAfterSize.isZero()) 5178671c6e0SDavid Majnemer Stores.emplace_back(SplitAfterOffset, SplitAfterSize); 5188671c6e0SDavid Majnemer } 519fde961dbSEli Friedman 520fde961dbSEli Friedman // If the type contains a pointer to data member we can't memset it to zero. 521fde961dbSEli Friedman // Instead, create a null constant and copy it to the destination. 522fde961dbSEli Friedman // TODO: there are other patterns besides zero that we can usefully memset, 523fde961dbSEli Friedman // like -1, which happens to be the pattern used by member-pointers. 524fde961dbSEli Friedman // TODO: isZeroInitializable can be over-conservative in the case where a 525fde961dbSEli Friedman // virtual base contains a member pointer. 5268671c6e0SDavid Majnemer llvm::Constant *NullConstantForBase = CGF.CGM.EmitNullConstantForBase(Base); 5278671c6e0SDavid Majnemer if (!NullConstantForBase->isNullValue()) { 5288671c6e0SDavid Majnemer llvm::GlobalVariable *NullVariable = new llvm::GlobalVariable( 5298671c6e0SDavid Majnemer CGF.CGM.getModule(), NullConstantForBase->getType(), 5308671c6e0SDavid Majnemer /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, 5318671c6e0SDavid Majnemer NullConstantForBase, Twine()); 5327f416cc4SJohn McCall 5337f416cc4SJohn McCall CharUnits Align = std::max(Layout.getNonVirtualAlignment(), 5347f416cc4SJohn McCall DestPtr.getAlignment()); 535c79099e0SGuillaume Chatelet NullVariable->setAlignment(Align.getAsAlign()); 5367f416cc4SJohn McCall 5377f416cc4SJohn McCall Address SrcPtr = Address(CGF.EmitCastToVoidPtr(NullVariable), Align); 538fde961dbSEli Friedman 539fde961dbSEli Friedman // Get and call the appropriate llvm.memcpy overload. 5408671c6e0SDavid Majnemer for (std::pair<CharUnits, CharUnits> Store : Stores) { 5418671c6e0SDavid Majnemer CharUnits StoreOffset = Store.first; 5428671c6e0SDavid Majnemer CharUnits StoreSize = Store.second; 5438671c6e0SDavid Majnemer llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize); 5448671c6e0SDavid Majnemer CGF.Builder.CreateMemCpy( 5458671c6e0SDavid Majnemer CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset), 5468671c6e0SDavid Majnemer CGF.Builder.CreateConstInBoundsByteGEP(SrcPtr, StoreOffset), 5478671c6e0SDavid Majnemer StoreSizeVal); 548fde961dbSEli Friedman } 549fde961dbSEli Friedman 550fde961dbSEli Friedman // Otherwise, just memset the whole thing to zero. This is legal 551fde961dbSEli Friedman // because in LLVM, all default initializers (other than the ones we just 552fde961dbSEli Friedman // handled above) are guaranteed to have a bit pattern of all zeros. 5538671c6e0SDavid Majnemer } else { 5548671c6e0SDavid Majnemer for (std::pair<CharUnits, CharUnits> Store : Stores) { 5558671c6e0SDavid Majnemer CharUnits StoreOffset = Store.first; 5568671c6e0SDavid Majnemer CharUnits StoreSize = Store.second; 5578671c6e0SDavid Majnemer llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize); 5588671c6e0SDavid Majnemer CGF.Builder.CreateMemSet( 5598671c6e0SDavid Majnemer CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset), 5608671c6e0SDavid Majnemer CGF.Builder.getInt8(0), StoreSizeVal); 5618671c6e0SDavid Majnemer } 5628671c6e0SDavid Majnemer } 563fde961dbSEli Friedman } 564fde961dbSEli Friedman 56527da15baSAnders Carlsson void 5667a626f63SJohn McCall CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E, 5677a626f63SJohn McCall AggValueSlot Dest) { 5687a626f63SJohn McCall assert(!Dest.isIgnored() && "Must have a destination!"); 56927da15baSAnders Carlsson const CXXConstructorDecl *CD = E->getConstructor(); 570630c76efSDouglas Gregor 571630c76efSDouglas Gregor // If we require zero initialization before (or instead of) calling the 572630c76efSDouglas Gregor // constructor, as can be the case with a non-user-provided default 57303535265SArgyrios Kyrtzidis // constructor, emit the zero initialization now, unless destination is 57403535265SArgyrios Kyrtzidis // already zeroed. 575fde961dbSEli Friedman if (E->requiresZeroInitialization() && !Dest.isZeroed()) { 576fde961dbSEli Friedman switch (E->getConstructionKind()) { 577fde961dbSEli Friedman case CXXConstructExpr::CK_Delegating: 578fde961dbSEli Friedman case CXXConstructExpr::CK_Complete: 5797f416cc4SJohn McCall EmitNullInitialization(Dest.getAddress(), E->getType()); 580fde961dbSEli Friedman break; 581fde961dbSEli Friedman case CXXConstructExpr::CK_VirtualBase: 582fde961dbSEli Friedman case CXXConstructExpr::CK_NonVirtualBase: 5837f416cc4SJohn McCall EmitNullBaseClassInitialization(*this, Dest.getAddress(), 5847f416cc4SJohn McCall CD->getParent()); 585fde961dbSEli Friedman break; 586fde961dbSEli Friedman } 587fde961dbSEli Friedman } 588630c76efSDouglas Gregor 589630c76efSDouglas Gregor // If this is a call to a trivial default constructor, do nothing. 590630c76efSDouglas Gregor if (CD->isTrivial() && CD->isDefaultConstructor()) 59127da15baSAnders Carlsson return; 592630c76efSDouglas Gregor 5938ea46b66SJohn McCall // Elide the constructor if we're constructing from a temporary. 5948ea46b66SJohn McCall // The temporary check is required because Sema sets this on NRVO 5958ea46b66SJohn McCall // returns. 5969c6890a7SRichard Smith if (getLangOpts().ElideConstructors && E->isElidable()) { 5978ea46b66SJohn McCall assert(getContext().hasSameUnqualifiedType(E->getType(), 5988ea46b66SJohn McCall E->getArg(0)->getType())); 5997a626f63SJohn McCall if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) { 6007a626f63SJohn McCall EmitAggExpr(E->getArg(0), Dest); 60127da15baSAnders Carlsson return; 60227da15baSAnders Carlsson } 603222cf0efSDouglas Gregor } 604630c76efSDouglas Gregor 605e7545b33SAlexey Bataev if (const ArrayType *arrayType 606e7545b33SAlexey Bataev = getContext().getAsArrayType(E->getType())) { 60737605182SSerge Pavlov EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddress(), E, 60837605182SSerge Pavlov Dest.isSanitizerChecked()); 609f677a8e9SJohn McCall } else { 610bceca20aSCameron Esfahani CXXCtorType Type = Ctor_Complete; 611271c3681SAlexis Hunt bool ForVirtualBase = false; 61261535005SDouglas Gregor bool Delegating = false; 613271c3681SAlexis Hunt 614271c3681SAlexis Hunt switch (E->getConstructionKind()) { 615271c3681SAlexis Hunt case CXXConstructExpr::CK_Delegating: 61661bc1737SAlexis Hunt // We should be emitting a constructor; GlobalDecl will assert this 61761bc1737SAlexis Hunt Type = CurGD.getCtorType(); 61861535005SDouglas Gregor Delegating = true; 619271c3681SAlexis Hunt break; 62061bc1737SAlexis Hunt 621271c3681SAlexis Hunt case CXXConstructExpr::CK_Complete: 622271c3681SAlexis Hunt Type = Ctor_Complete; 623271c3681SAlexis Hunt break; 624271c3681SAlexis Hunt 625271c3681SAlexis Hunt case CXXConstructExpr::CK_VirtualBase: 626271c3681SAlexis Hunt ForVirtualBase = true; 627f3b3ccdaSAdrian Prantl LLVM_FALLTHROUGH; 628271c3681SAlexis Hunt 629271c3681SAlexis Hunt case CXXConstructExpr::CK_NonVirtualBase: 630271c3681SAlexis Hunt Type = Ctor_Base; 631271c3681SAlexis Hunt } 632e11f9ce9SAnders Carlsson 63327da15baSAnders Carlsson // Call the constructor. 634094c7266SAnastasia Stulova EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating, Dest, E); 63527da15baSAnders Carlsson } 636e11f9ce9SAnders Carlsson } 63727da15baSAnders Carlsson 6387f416cc4SJohn McCall void CodeGenFunction::EmitSynthesizedCXXCopyCtor(Address Dest, Address Src, 63950198098SFariborz Jahanian const Expr *Exp) { 6405d413781SJohn McCall if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp)) 641e988bdacSFariborz Jahanian Exp = E->getSubExpr(); 642e988bdacSFariborz Jahanian assert(isa<CXXConstructExpr>(Exp) && 643e988bdacSFariborz Jahanian "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr"); 644e988bdacSFariborz Jahanian const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp); 645e988bdacSFariborz Jahanian const CXXConstructorDecl *CD = E->getConstructor(); 646e988bdacSFariborz Jahanian RunCleanupsScope Scope(*this); 647e988bdacSFariborz Jahanian 648e988bdacSFariborz Jahanian // If we require zero initialization before (or instead of) calling the 649e988bdacSFariborz Jahanian // constructor, as can be the case with a non-user-provided default 650e988bdacSFariborz Jahanian // constructor, emit the zero initialization now. 651e988bdacSFariborz Jahanian // FIXME. Do I still need this for a copy ctor synthesis? 652e988bdacSFariborz Jahanian if (E->requiresZeroInitialization()) 653e988bdacSFariborz Jahanian EmitNullInitialization(Dest, E->getType()); 654e988bdacSFariborz Jahanian 65599da11cfSChandler Carruth assert(!getContext().getAsConstantArrayType(E->getType()) 65699da11cfSChandler Carruth && "EmitSynthesizedCXXCopyCtor - Copied-in Array"); 657525bf650SAlexey Samsonov EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E); 658e988bdacSFariborz Jahanian } 659e988bdacSFariborz Jahanian 6608ed55a54SJohn McCall static CharUnits CalculateCookiePadding(CodeGenFunction &CGF, 6618ed55a54SJohn McCall const CXXNewExpr *E) { 66221122cf6SAnders Carlsson if (!E->isArray()) 6633eb55cfeSKen Dyck return CharUnits::Zero(); 66421122cf6SAnders Carlsson 6657ec4b434SJohn McCall // No cookie is required if the operator new[] being used is the 6667ec4b434SJohn McCall // reserved placement operator new[]. 6677ec4b434SJohn McCall if (E->getOperatorNew()->isReservedGlobalPlacementOperator()) 6683eb55cfeSKen Dyck return CharUnits::Zero(); 669399f499fSAnders Carlsson 670284c48ffSJohn McCall return CGF.CGM.getCXXABI().GetArrayCookieSize(E); 67159486a2dSAnders Carlsson } 67259486a2dSAnders Carlsson 673036f2f6bSJohn McCall static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF, 674036f2f6bSJohn McCall const CXXNewExpr *e, 675f862eb6aSSebastian Redl unsigned minElements, 676036f2f6bSJohn McCall llvm::Value *&numElements, 677036f2f6bSJohn McCall llvm::Value *&sizeWithoutCookie) { 678036f2f6bSJohn McCall QualType type = e->getAllocatedType(); 67959486a2dSAnders Carlsson 680036f2f6bSJohn McCall if (!e->isArray()) { 681036f2f6bSJohn McCall CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type); 682036f2f6bSJohn McCall sizeWithoutCookie 683036f2f6bSJohn McCall = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity()); 684036f2f6bSJohn McCall return sizeWithoutCookie; 68505fc5be3SDouglas Gregor } 68659486a2dSAnders Carlsson 687036f2f6bSJohn McCall // The width of size_t. 688036f2f6bSJohn McCall unsigned sizeWidth = CGF.SizeTy->getBitWidth(); 689036f2f6bSJohn McCall 6908ed55a54SJohn McCall // Figure out the cookie size. 691036f2f6bSJohn McCall llvm::APInt cookieSize(sizeWidth, 692036f2f6bSJohn McCall CalculateCookiePadding(CGF, e).getQuantity()); 6938ed55a54SJohn McCall 69459486a2dSAnders Carlsson // Emit the array size expression. 6957648fb46SArgyrios Kyrtzidis // We multiply the size of all dimensions for NumElements. 6967648fb46SArgyrios Kyrtzidis // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6. 697de0fe07eSJohn McCall numElements = 698b9fb121aSRichard Smith ConstantEmitter(CGF).tryEmitAbstract(*e->getArraySize(), e->getType()); 69907527621SNick Lewycky if (!numElements) 700b9fb121aSRichard Smith numElements = CGF.EmitScalarExpr(*e->getArraySize()); 701036f2f6bSJohn McCall assert(isa<llvm::IntegerType>(numElements->getType())); 7028ed55a54SJohn McCall 703036f2f6bSJohn McCall // The number of elements can be have an arbitrary integer type; 704036f2f6bSJohn McCall // essentially, we need to multiply it by a constant factor, add a 705036f2f6bSJohn McCall // cookie size, and verify that the result is representable as a 706036f2f6bSJohn McCall // size_t. That's just a gloss, though, and it's wrong in one 707036f2f6bSJohn McCall // important way: if the count is negative, it's an error even if 708036f2f6bSJohn McCall // the cookie size would bring the total size >= 0. 7096ab2fa8fSDouglas Gregor bool isSigned 710b9fb121aSRichard Smith = (*e->getArraySize())->getType()->isSignedIntegerOrEnumerationType(); 7112192fe50SChris Lattner llvm::IntegerType *numElementsType 712036f2f6bSJohn McCall = cast<llvm::IntegerType>(numElements->getType()); 713036f2f6bSJohn McCall unsigned numElementsWidth = numElementsType->getBitWidth(); 714036f2f6bSJohn McCall 715036f2f6bSJohn McCall // Compute the constant factor. 716036f2f6bSJohn McCall llvm::APInt arraySizeMultiplier(sizeWidth, 1); 7177648fb46SArgyrios Kyrtzidis while (const ConstantArrayType *CAT 718036f2f6bSJohn McCall = CGF.getContext().getAsConstantArrayType(type)) { 719036f2f6bSJohn McCall type = CAT->getElementType(); 720036f2f6bSJohn McCall arraySizeMultiplier *= CAT->getSize(); 7217648fb46SArgyrios Kyrtzidis } 72259486a2dSAnders Carlsson 723036f2f6bSJohn McCall CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type); 724036f2f6bSJohn McCall llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity()); 725036f2f6bSJohn McCall typeSizeMultiplier *= arraySizeMultiplier; 726036f2f6bSJohn McCall 727036f2f6bSJohn McCall // This will be a size_t. 728036f2f6bSJohn McCall llvm::Value *size; 72932ac583dSChris Lattner 73032ac583dSChris Lattner // If someone is doing 'new int[42]' there is no need to do a dynamic check. 73132ac583dSChris Lattner // Don't bloat the -O0 code. 732036f2f6bSJohn McCall if (llvm::ConstantInt *numElementsC = 733036f2f6bSJohn McCall dyn_cast<llvm::ConstantInt>(numElements)) { 734036f2f6bSJohn McCall const llvm::APInt &count = numElementsC->getValue(); 73532ac583dSChris Lattner 736036f2f6bSJohn McCall bool hasAnyOverflow = false; 73732ac583dSChris Lattner 738036f2f6bSJohn McCall // If 'count' was a negative number, it's an overflow. 739036f2f6bSJohn McCall if (isSigned && count.isNegative()) 740036f2f6bSJohn McCall hasAnyOverflow = true; 7418ed55a54SJohn McCall 742036f2f6bSJohn McCall // We want to do all this arithmetic in size_t. If numElements is 743036f2f6bSJohn McCall // wider than that, check whether it's already too big, and if so, 744036f2f6bSJohn McCall // overflow. 745036f2f6bSJohn McCall else if (numElementsWidth > sizeWidth && 746036f2f6bSJohn McCall numElementsWidth - sizeWidth > count.countLeadingZeros()) 747036f2f6bSJohn McCall hasAnyOverflow = true; 748036f2f6bSJohn McCall 749036f2f6bSJohn McCall // Okay, compute a count at the right width. 750036f2f6bSJohn McCall llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth); 751036f2f6bSJohn McCall 752f862eb6aSSebastian Redl // If there is a brace-initializer, we cannot allocate fewer elements than 753f862eb6aSSebastian Redl // there are initializers. If we do, that's treated like an overflow. 754f862eb6aSSebastian Redl if (adjustedCount.ult(minElements)) 755f862eb6aSSebastian Redl hasAnyOverflow = true; 756f862eb6aSSebastian Redl 757036f2f6bSJohn McCall // Scale numElements by that. This might overflow, but we don't 758036f2f6bSJohn McCall // care because it only overflows if allocationSize does, too, and 759036f2f6bSJohn McCall // if that overflows then we shouldn't use this. 760036f2f6bSJohn McCall numElements = llvm::ConstantInt::get(CGF.SizeTy, 761036f2f6bSJohn McCall adjustedCount * arraySizeMultiplier); 762036f2f6bSJohn McCall 763036f2f6bSJohn McCall // Compute the size before cookie, and track whether it overflowed. 764036f2f6bSJohn McCall bool overflow; 765036f2f6bSJohn McCall llvm::APInt allocationSize 766036f2f6bSJohn McCall = adjustedCount.umul_ov(typeSizeMultiplier, overflow); 767036f2f6bSJohn McCall hasAnyOverflow |= overflow; 768036f2f6bSJohn McCall 769036f2f6bSJohn McCall // Add in the cookie, and check whether it's overflowed. 770036f2f6bSJohn McCall if (cookieSize != 0) { 771036f2f6bSJohn McCall // Save the current size without a cookie. This shouldn't be 772036f2f6bSJohn McCall // used if there was overflow. 773036f2f6bSJohn McCall sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize); 774036f2f6bSJohn McCall 775036f2f6bSJohn McCall allocationSize = allocationSize.uadd_ov(cookieSize, overflow); 776036f2f6bSJohn McCall hasAnyOverflow |= overflow; 7778ed55a54SJohn McCall } 7788ed55a54SJohn McCall 779036f2f6bSJohn McCall // On overflow, produce a -1 so operator new will fail. 780455f42c9SAaron Ballman if (hasAnyOverflow) { 781455f42c9SAaron Ballman size = llvm::Constant::getAllOnesValue(CGF.SizeTy); 782455f42c9SAaron Ballman } else { 783036f2f6bSJohn McCall size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize); 784455f42c9SAaron Ballman } 78532ac583dSChris Lattner 786036f2f6bSJohn McCall // Otherwise, we might need to use the overflow intrinsics. 7878ed55a54SJohn McCall } else { 788f862eb6aSSebastian Redl // There are up to five conditions we need to test for: 789036f2f6bSJohn McCall // 1) if isSigned, we need to check whether numElements is negative; 790036f2f6bSJohn McCall // 2) if numElementsWidth > sizeWidth, we need to check whether 791036f2f6bSJohn McCall // numElements is larger than something representable in size_t; 792f862eb6aSSebastian Redl // 3) if minElements > 0, we need to check whether numElements is smaller 793f862eb6aSSebastian Redl // than that. 794f862eb6aSSebastian Redl // 4) we need to compute 795036f2f6bSJohn McCall // sizeWithoutCookie := numElements * typeSizeMultiplier 796036f2f6bSJohn McCall // and check whether it overflows; and 797f862eb6aSSebastian Redl // 5) if we need a cookie, we need to compute 798036f2f6bSJohn McCall // size := sizeWithoutCookie + cookieSize 799036f2f6bSJohn McCall // and check whether it overflows. 8008ed55a54SJohn McCall 8018a13c418SCraig Topper llvm::Value *hasOverflow = nullptr; 8028ed55a54SJohn McCall 803036f2f6bSJohn McCall // If numElementsWidth > sizeWidth, then one way or another, we're 804036f2f6bSJohn McCall // going to have to do a comparison for (2), and this happens to 805036f2f6bSJohn McCall // take care of (1), too. 806036f2f6bSJohn McCall if (numElementsWidth > sizeWidth) { 807036f2f6bSJohn McCall llvm::APInt threshold(numElementsWidth, 1); 808036f2f6bSJohn McCall threshold <<= sizeWidth; 8098ed55a54SJohn McCall 810036f2f6bSJohn McCall llvm::Value *thresholdV 811036f2f6bSJohn McCall = llvm::ConstantInt::get(numElementsType, threshold); 812036f2f6bSJohn McCall 813036f2f6bSJohn McCall hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV); 814036f2f6bSJohn McCall numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy); 815036f2f6bSJohn McCall 816036f2f6bSJohn McCall // Otherwise, if we're signed, we want to sext up to size_t. 817036f2f6bSJohn McCall } else if (isSigned) { 818036f2f6bSJohn McCall if (numElementsWidth < sizeWidth) 819036f2f6bSJohn McCall numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy); 820036f2f6bSJohn McCall 821036f2f6bSJohn McCall // If there's a non-1 type size multiplier, then we can do the 822036f2f6bSJohn McCall // signedness check at the same time as we do the multiply 823036f2f6bSJohn McCall // because a negative number times anything will cause an 824f862eb6aSSebastian Redl // unsigned overflow. Otherwise, we have to do it here. But at least 825f862eb6aSSebastian Redl // in this case, we can subsume the >= minElements check. 826036f2f6bSJohn McCall if (typeSizeMultiplier == 1) 827036f2f6bSJohn McCall hasOverflow = CGF.Builder.CreateICmpSLT(numElements, 828f862eb6aSSebastian Redl llvm::ConstantInt::get(CGF.SizeTy, minElements)); 829036f2f6bSJohn McCall 830036f2f6bSJohn McCall // Otherwise, zext up to size_t if necessary. 831036f2f6bSJohn McCall } else if (numElementsWidth < sizeWidth) { 832036f2f6bSJohn McCall numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy); 833036f2f6bSJohn McCall } 834036f2f6bSJohn McCall 835036f2f6bSJohn McCall assert(numElements->getType() == CGF.SizeTy); 836036f2f6bSJohn McCall 837f862eb6aSSebastian Redl if (minElements) { 838f862eb6aSSebastian Redl // Don't allow allocation of fewer elements than we have initializers. 839f862eb6aSSebastian Redl if (!hasOverflow) { 840f862eb6aSSebastian Redl hasOverflow = CGF.Builder.CreateICmpULT(numElements, 841f862eb6aSSebastian Redl llvm::ConstantInt::get(CGF.SizeTy, minElements)); 842f862eb6aSSebastian Redl } else if (numElementsWidth > sizeWidth) { 843f862eb6aSSebastian Redl // The other existing overflow subsumes this check. 844f862eb6aSSebastian Redl // We do an unsigned comparison, since any signed value < -1 is 845f862eb6aSSebastian Redl // taken care of either above or below. 846f862eb6aSSebastian Redl hasOverflow = CGF.Builder.CreateOr(hasOverflow, 847f862eb6aSSebastian Redl CGF.Builder.CreateICmpULT(numElements, 848f862eb6aSSebastian Redl llvm::ConstantInt::get(CGF.SizeTy, minElements))); 849f862eb6aSSebastian Redl } 850f862eb6aSSebastian Redl } 851f862eb6aSSebastian Redl 852036f2f6bSJohn McCall size = numElements; 853036f2f6bSJohn McCall 854036f2f6bSJohn McCall // Multiply by the type size if necessary. This multiplier 855036f2f6bSJohn McCall // includes all the factors for nested arrays. 8568ed55a54SJohn McCall // 857036f2f6bSJohn McCall // This step also causes numElements to be scaled up by the 858036f2f6bSJohn McCall // nested-array factor if necessary. Overflow on this computation 859036f2f6bSJohn McCall // can be ignored because the result shouldn't be used if 860036f2f6bSJohn McCall // allocation fails. 861036f2f6bSJohn McCall if (typeSizeMultiplier != 1) { 8628799caeeSJames Y Knight llvm::Function *umul_with_overflow 8638d375cefSBenjamin Kramer = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy); 8648ed55a54SJohn McCall 865036f2f6bSJohn McCall llvm::Value *tsmV = 866036f2f6bSJohn McCall llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier); 867036f2f6bSJohn McCall llvm::Value *result = 86843f9bb73SDavid Blaikie CGF.Builder.CreateCall(umul_with_overflow, {size, tsmV}); 8698ed55a54SJohn McCall 870036f2f6bSJohn McCall llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1); 871036f2f6bSJohn McCall if (hasOverflow) 872036f2f6bSJohn McCall hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed); 8738ed55a54SJohn McCall else 874036f2f6bSJohn McCall hasOverflow = overflowed; 87559486a2dSAnders Carlsson 876036f2f6bSJohn McCall size = CGF.Builder.CreateExtractValue(result, 0); 877036f2f6bSJohn McCall 878036f2f6bSJohn McCall // Also scale up numElements by the array size multiplier. 879036f2f6bSJohn McCall if (arraySizeMultiplier != 1) { 880036f2f6bSJohn McCall // If the base element type size is 1, then we can re-use the 881036f2f6bSJohn McCall // multiply we just did. 882036f2f6bSJohn McCall if (typeSize.isOne()) { 883036f2f6bSJohn McCall assert(arraySizeMultiplier == typeSizeMultiplier); 884036f2f6bSJohn McCall numElements = size; 885036f2f6bSJohn McCall 886036f2f6bSJohn McCall // Otherwise we need a separate multiply. 887036f2f6bSJohn McCall } else { 888036f2f6bSJohn McCall llvm::Value *asmV = 889036f2f6bSJohn McCall llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier); 890036f2f6bSJohn McCall numElements = CGF.Builder.CreateMul(numElements, asmV); 891036f2f6bSJohn McCall } 892036f2f6bSJohn McCall } 893036f2f6bSJohn McCall } else { 894036f2f6bSJohn McCall // numElements doesn't need to be scaled. 895036f2f6bSJohn McCall assert(arraySizeMultiplier == 1); 896036f2f6bSJohn McCall } 897036f2f6bSJohn McCall 898036f2f6bSJohn McCall // Add in the cookie size if necessary. 899036f2f6bSJohn McCall if (cookieSize != 0) { 900036f2f6bSJohn McCall sizeWithoutCookie = size; 901036f2f6bSJohn McCall 9028799caeeSJames Y Knight llvm::Function *uadd_with_overflow 9038d375cefSBenjamin Kramer = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy); 904036f2f6bSJohn McCall 905036f2f6bSJohn McCall llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize); 906036f2f6bSJohn McCall llvm::Value *result = 90743f9bb73SDavid Blaikie CGF.Builder.CreateCall(uadd_with_overflow, {size, cookieSizeV}); 908036f2f6bSJohn McCall 909036f2f6bSJohn McCall llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1); 910036f2f6bSJohn McCall if (hasOverflow) 911036f2f6bSJohn McCall hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed); 912036f2f6bSJohn McCall else 913036f2f6bSJohn McCall hasOverflow = overflowed; 914036f2f6bSJohn McCall 915036f2f6bSJohn McCall size = CGF.Builder.CreateExtractValue(result, 0); 916036f2f6bSJohn McCall } 917036f2f6bSJohn McCall 918036f2f6bSJohn McCall // If we had any possibility of dynamic overflow, make a select to 919036f2f6bSJohn McCall // overwrite 'size' with an all-ones value, which should cause 920036f2f6bSJohn McCall // operator new to throw. 921036f2f6bSJohn McCall if (hasOverflow) 922455f42c9SAaron Ballman size = CGF.Builder.CreateSelect(hasOverflow, 923455f42c9SAaron Ballman llvm::Constant::getAllOnesValue(CGF.SizeTy), 924036f2f6bSJohn McCall size); 925036f2f6bSJohn McCall } 926036f2f6bSJohn McCall 927036f2f6bSJohn McCall if (cookieSize == 0) 928036f2f6bSJohn McCall sizeWithoutCookie = size; 929036f2f6bSJohn McCall else 930036f2f6bSJohn McCall assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?"); 931036f2f6bSJohn McCall 932036f2f6bSJohn McCall return size; 93359486a2dSAnders Carlsson } 93459486a2dSAnders Carlsson 935f862eb6aSSebastian Redl static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init, 936e78fac51SRichard Smith QualType AllocType, Address NewPtr, 937e78fac51SRichard Smith AggValueSlot::Overlap_t MayOverlap) { 9381c96bc5dSRichard Smith // FIXME: Refactor with EmitExprAsInit. 93947fb9508SJohn McCall switch (CGF.getEvaluationKind(AllocType)) { 94047fb9508SJohn McCall case TEK_Scalar: 941a2c1124fSDavid Blaikie CGF.EmitScalarInit(Init, nullptr, 9427f416cc4SJohn McCall CGF.MakeAddrLValue(NewPtr, AllocType), false); 94347fb9508SJohn McCall return; 94447fb9508SJohn McCall case TEK_Complex: 9457f416cc4SJohn McCall CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType), 94647fb9508SJohn McCall /*isInit*/ true); 94747fb9508SJohn McCall return; 94847fb9508SJohn McCall case TEK_Aggregate: { 9497a626f63SJohn McCall AggValueSlot Slot 9507f416cc4SJohn McCall = AggValueSlot::forAddr(NewPtr, AllocType.getQualifiers(), 9518d6fc958SJohn McCall AggValueSlot::IsDestructed, 95246759f4fSJohn McCall AggValueSlot::DoesNotNeedGCBarriers, 953e78fac51SRichard Smith AggValueSlot::IsNotAliased, 95437605182SSerge Pavlov MayOverlap, AggValueSlot::IsNotZeroed, 95537605182SSerge Pavlov AggValueSlot::IsSanitizerChecked); 9567a626f63SJohn McCall CGF.EmitAggExpr(Init, Slot); 95747fb9508SJohn McCall return; 9587a626f63SJohn McCall } 959d5202e09SFariborz Jahanian } 96047fb9508SJohn McCall llvm_unreachable("bad evaluation kind"); 96147fb9508SJohn McCall } 962d5202e09SFariborz Jahanian 963fb901c7aSDavid Blaikie void CodeGenFunction::EmitNewArrayInitializer( 964fb901c7aSDavid Blaikie const CXXNewExpr *E, QualType ElementType, llvm::Type *ElementTy, 9657f416cc4SJohn McCall Address BeginPtr, llvm::Value *NumElements, 96606a67e2cSRichard Smith llvm::Value *AllocSizeWithoutCookie) { 96706a67e2cSRichard Smith // If we have a type with trivial initialization and no initializer, 96806a67e2cSRichard Smith // there's nothing to do. 9696047f07eSSebastian Redl if (!E->hasInitializer()) 97006a67e2cSRichard Smith return; 971b66b08efSFariborz Jahanian 9727f416cc4SJohn McCall Address CurPtr = BeginPtr; 973d5202e09SFariborz Jahanian 97406a67e2cSRichard Smith unsigned InitListElements = 0; 975f862eb6aSSebastian Redl 976f862eb6aSSebastian Redl const Expr *Init = E->getInitializer(); 9777f416cc4SJohn McCall Address EndOfInit = Address::invalid(); 97806a67e2cSRichard Smith QualType::DestructionKind DtorKind = ElementType.isDestructedType(); 97906a67e2cSRichard Smith EHScopeStack::stable_iterator Cleanup; 98006a67e2cSRichard Smith llvm::Instruction *CleanupDominator = nullptr; 9811c96bc5dSRichard Smith 9827f416cc4SJohn McCall CharUnits ElementSize = getContext().getTypeSizeInChars(ElementType); 9837f416cc4SJohn McCall CharUnits ElementAlign = 9847f416cc4SJohn McCall BeginPtr.getAlignment().alignmentOfArrayElement(ElementSize); 9857f416cc4SJohn McCall 9860511d23aSRichard Smith // Attempt to perform zero-initialization using memset. 9870511d23aSRichard Smith auto TryMemsetInitialization = [&]() -> bool { 9880511d23aSRichard Smith // FIXME: If the type is a pointer-to-data-member under the Itanium ABI, 9890511d23aSRichard Smith // we can initialize with a memset to -1. 9900511d23aSRichard Smith if (!CGM.getTypes().isZeroInitializable(ElementType)) 9910511d23aSRichard Smith return false; 9920511d23aSRichard Smith 9930511d23aSRichard Smith // Optimization: since zero initialization will just set the memory 9940511d23aSRichard Smith // to all zeroes, generate a single memset to do it in one shot. 9950511d23aSRichard Smith 9960511d23aSRichard Smith // Subtract out the size of any elements we've already initialized. 9970511d23aSRichard Smith auto *RemainingSize = AllocSizeWithoutCookie; 9980511d23aSRichard Smith if (InitListElements) { 9990511d23aSRichard Smith // We know this can't overflow; we check this when doing the allocation. 10000511d23aSRichard Smith auto *InitializedSize = llvm::ConstantInt::get( 10010511d23aSRichard Smith RemainingSize->getType(), 10020511d23aSRichard Smith getContext().getTypeSizeInChars(ElementType).getQuantity() * 10030511d23aSRichard Smith InitListElements); 10040511d23aSRichard Smith RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize); 10050511d23aSRichard Smith } 10060511d23aSRichard Smith 10070511d23aSRichard Smith // Create the memset. 10080511d23aSRichard Smith Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize, false); 10090511d23aSRichard Smith return true; 10100511d23aSRichard Smith }; 10110511d23aSRichard Smith 1012f862eb6aSSebastian Redl // If the initializer is an initializer list, first do the explicit elements. 1013f862eb6aSSebastian Redl if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) { 10140511d23aSRichard Smith // Initializing from a (braced) string literal is a special case; the init 10150511d23aSRichard Smith // list element does not initialize a (single) array element. 10160511d23aSRichard Smith if (ILE->isStringLiteralInit()) { 10170511d23aSRichard Smith // Initialize the initial portion of length equal to that of the string 10180511d23aSRichard Smith // literal. The allocation must be for at least this much; we emitted a 10190511d23aSRichard Smith // check for that earlier. 10200511d23aSRichard Smith AggValueSlot Slot = 10210511d23aSRichard Smith AggValueSlot::forAddr(CurPtr, ElementType.getQualifiers(), 10220511d23aSRichard Smith AggValueSlot::IsDestructed, 10230511d23aSRichard Smith AggValueSlot::DoesNotNeedGCBarriers, 1024e78fac51SRichard Smith AggValueSlot::IsNotAliased, 102537605182SSerge Pavlov AggValueSlot::DoesNotOverlap, 102637605182SSerge Pavlov AggValueSlot::IsNotZeroed, 102737605182SSerge Pavlov AggValueSlot::IsSanitizerChecked); 10280511d23aSRichard Smith EmitAggExpr(ILE->getInit(0), Slot); 10290511d23aSRichard Smith 10300511d23aSRichard Smith // Move past these elements. 10310511d23aSRichard Smith InitListElements = 10320511d23aSRichard Smith cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe()) 10330511d23aSRichard Smith ->getSize().getZExtValue(); 10340511d23aSRichard Smith CurPtr = 10350511d23aSRichard Smith Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(), 10360511d23aSRichard Smith Builder.getSize(InitListElements), 10370511d23aSRichard Smith "string.init.end"), 10380511d23aSRichard Smith CurPtr.getAlignment().alignmentAtOffset(InitListElements * 10390511d23aSRichard Smith ElementSize)); 10400511d23aSRichard Smith 10410511d23aSRichard Smith // Zero out the rest, if any remain. 10420511d23aSRichard Smith llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements); 10430511d23aSRichard Smith if (!ConstNum || !ConstNum->equalsInt(InitListElements)) { 10440511d23aSRichard Smith bool OK = TryMemsetInitialization(); 10450511d23aSRichard Smith (void)OK; 10460511d23aSRichard Smith assert(OK && "couldn't memset character type?"); 10470511d23aSRichard Smith } 10480511d23aSRichard Smith return; 10490511d23aSRichard Smith } 10500511d23aSRichard Smith 105106a67e2cSRichard Smith InitListElements = ILE->getNumInits(); 1052f62290a1SChad Rosier 10531c96bc5dSRichard Smith // If this is a multi-dimensional array new, we will initialize multiple 10541c96bc5dSRichard Smith // elements with each init list element. 10551c96bc5dSRichard Smith QualType AllocType = E->getAllocatedType(); 10561c96bc5dSRichard Smith if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>( 10571c96bc5dSRichard Smith AllocType->getAsArrayTypeUnsafe())) { 1058fb901c7aSDavid Blaikie ElementTy = ConvertTypeForMem(AllocType); 10597f416cc4SJohn McCall CurPtr = Builder.CreateElementBitCast(CurPtr, ElementTy); 106006a67e2cSRichard Smith InitListElements *= getContext().getConstantArrayElementCount(CAT); 10611c96bc5dSRichard Smith } 10621c96bc5dSRichard Smith 106306a67e2cSRichard Smith // Enter a partial-destruction Cleanup if necessary. 106406a67e2cSRichard Smith if (needsEHCleanup(DtorKind)) { 106506a67e2cSRichard Smith // In principle we could tell the Cleanup where we are more 1066f62290a1SChad Rosier // directly, but the control flow can get so varied here that it 1067f62290a1SChad Rosier // would actually be quite complex. Therefore we go through an 1068f62290a1SChad Rosier // alloca. 10697f416cc4SJohn McCall EndOfInit = CreateTempAlloca(BeginPtr.getType(), getPointerAlign(), 10707f416cc4SJohn McCall "array.init.end"); 10717f416cc4SJohn McCall CleanupDominator = Builder.CreateStore(BeginPtr.getPointer(), EndOfInit); 10727f416cc4SJohn McCall pushIrregularPartialArrayCleanup(BeginPtr.getPointer(), EndOfInit, 10737f416cc4SJohn McCall ElementType, ElementAlign, 107406a67e2cSRichard Smith getDestroyer(DtorKind)); 107506a67e2cSRichard Smith Cleanup = EHStack.stable_begin(); 1076f62290a1SChad Rosier } 1077f62290a1SChad Rosier 10787f416cc4SJohn McCall CharUnits StartAlign = CurPtr.getAlignment(); 1079f862eb6aSSebastian Redl for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) { 1080f62290a1SChad Rosier // Tell the cleanup that it needs to destroy up to this 1081f62290a1SChad Rosier // element. TODO: some of these stores can be trivially 1082f62290a1SChad Rosier // observed to be unnecessary. 10837f416cc4SJohn McCall if (EndOfInit.isValid()) { 10847f416cc4SJohn McCall auto FinishedPtr = 10857f416cc4SJohn McCall Builder.CreateBitCast(CurPtr.getPointer(), BeginPtr.getType()); 10867f416cc4SJohn McCall Builder.CreateStore(FinishedPtr, EndOfInit); 10877f416cc4SJohn McCall } 108806a67e2cSRichard Smith // FIXME: If the last initializer is an incomplete initializer list for 108906a67e2cSRichard Smith // an array, and we have an array filler, we can fold together the two 109006a67e2cSRichard Smith // initialization loops. 10911c96bc5dSRichard Smith StoreAnyExprIntoOneUnit(*this, ILE->getInit(i), 1092e78fac51SRichard Smith ILE->getInit(i)->getType(), CurPtr, 1093e78fac51SRichard Smith AggValueSlot::DoesNotOverlap); 10947f416cc4SJohn McCall CurPtr = Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(), 10957f416cc4SJohn McCall Builder.getSize(1), 10967f416cc4SJohn McCall "array.exp.next"), 10977f416cc4SJohn McCall StartAlign.alignmentAtOffset((i + 1) * ElementSize)); 1098f862eb6aSSebastian Redl } 1099f862eb6aSSebastian Redl 1100f862eb6aSSebastian Redl // The remaining elements are filled with the array filler expression. 1101f862eb6aSSebastian Redl Init = ILE->getArrayFiller(); 11021c96bc5dSRichard Smith 110306a67e2cSRichard Smith // Extract the initializer for the individual array elements by pulling 110406a67e2cSRichard Smith // out the array filler from all the nested initializer lists. This avoids 110506a67e2cSRichard Smith // generating a nested loop for the initialization. 110606a67e2cSRichard Smith while (Init && Init->getType()->isConstantArrayType()) { 110706a67e2cSRichard Smith auto *SubILE = dyn_cast<InitListExpr>(Init); 110806a67e2cSRichard Smith if (!SubILE) 110906a67e2cSRichard Smith break; 111006a67e2cSRichard Smith assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?"); 111106a67e2cSRichard Smith Init = SubILE->getArrayFiller(); 1112f862eb6aSSebastian Redl } 1113f862eb6aSSebastian Redl 111406a67e2cSRichard Smith // Switch back to initializing one base element at a time. 11157f416cc4SJohn McCall CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr.getType()); 1116f62290a1SChad Rosier } 1117e6c980c4SChandler Carruth 1118454a7cdfSRichard Smith // If all elements have already been initialized, skip any further 1119454a7cdfSRichard Smith // initialization. 1120454a7cdfSRichard Smith llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements); 1121454a7cdfSRichard Smith if (ConstNum && ConstNum->getZExtValue() <= InitListElements) { 1122454a7cdfSRichard Smith // If there was a Cleanup, deactivate it. 1123454a7cdfSRichard Smith if (CleanupDominator) 1124454a7cdfSRichard Smith DeactivateCleanupBlock(Cleanup, CleanupDominator); 1125454a7cdfSRichard Smith return; 1126454a7cdfSRichard Smith } 1127454a7cdfSRichard Smith 1128454a7cdfSRichard Smith assert(Init && "have trailing elements to initialize but no initializer"); 1129454a7cdfSRichard Smith 113006a67e2cSRichard Smith // If this is a constructor call, try to optimize it out, and failing that 113106a67e2cSRichard Smith // emit a single loop to initialize all remaining elements. 1132454a7cdfSRichard Smith if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) { 11336047f07eSSebastian Redl CXXConstructorDecl *Ctor = CCE->getConstructor(); 1134d153103cSDouglas Gregor if (Ctor->isTrivial()) { 113505fc5be3SDouglas Gregor // If new expression did not specify value-initialization, then there 113605fc5be3SDouglas Gregor // is no initialization. 11376047f07eSSebastian Redl if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty()) 113805fc5be3SDouglas Gregor return; 113905fc5be3SDouglas Gregor 114006a67e2cSRichard Smith if (TryMemsetInitialization()) 11413a202f60SAnders Carlsson return; 11423a202f60SAnders Carlsson } 114305fc5be3SDouglas Gregor 114406a67e2cSRichard Smith // Store the new Cleanup position for irregular Cleanups. 114506a67e2cSRichard Smith // 114606a67e2cSRichard Smith // FIXME: Share this cleanup with the constructor call emission rather than 114706a67e2cSRichard Smith // having it create a cleanup of its own. 11487f416cc4SJohn McCall if (EndOfInit.isValid()) 11497f416cc4SJohn McCall Builder.CreateStore(CurPtr.getPointer(), EndOfInit); 115006a67e2cSRichard Smith 115106a67e2cSRichard Smith // Emit a constructor call loop to initialize the remaining elements. 115206a67e2cSRichard Smith if (InitListElements) 115306a67e2cSRichard Smith NumElements = Builder.CreateSub( 115406a67e2cSRichard Smith NumElements, 115506a67e2cSRichard Smith llvm::ConstantInt::get(NumElements->getType(), InitListElements)); 115670b9c01bSAlexey Samsonov EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE, 115737605182SSerge Pavlov /*NewPointerIsChecked*/true, 115848ddcf2cSEli Friedman CCE->requiresZeroInitialization()); 115905fc5be3SDouglas Gregor return; 11606047f07eSSebastian Redl } 116106a67e2cSRichard Smith 116206a67e2cSRichard Smith // If this is value-initialization, we can usually use memset. 116306a67e2cSRichard Smith ImplicitValueInitExpr IVIE(ElementType); 1164454a7cdfSRichard Smith if (isa<ImplicitValueInitExpr>(Init)) { 116506a67e2cSRichard Smith if (TryMemsetInitialization()) 116606a67e2cSRichard Smith return; 116706a67e2cSRichard Smith 116806a67e2cSRichard Smith // Switch to an ImplicitValueInitExpr for the element type. This handles 116906a67e2cSRichard Smith // only one case: multidimensional array new of pointers to members. In 117006a67e2cSRichard Smith // all other cases, we already have an initializer for the array element. 117106a67e2cSRichard Smith Init = &IVIE; 117206a67e2cSRichard Smith } 117306a67e2cSRichard Smith 117406a67e2cSRichard Smith // At this point we should have found an initializer for the individual 117506a67e2cSRichard Smith // elements of the array. 117606a67e2cSRichard Smith assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) && 117706a67e2cSRichard Smith "got wrong type of element to initialize"); 117806a67e2cSRichard Smith 1179454a7cdfSRichard Smith // If we have an empty initializer list, we can usually use memset. 1180454a7cdfSRichard Smith if (auto *ILE = dyn_cast<InitListExpr>(Init)) 1181454a7cdfSRichard Smith if (ILE->getNumInits() == 0 && TryMemsetInitialization()) 1182d5202e09SFariborz Jahanian return; 118359486a2dSAnders Carlsson 1184cb77930dSYunzhong Gao // If we have a struct whose every field is value-initialized, we can 1185cb77930dSYunzhong Gao // usually use memset. 1186cb77930dSYunzhong Gao if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 1187cb77930dSYunzhong Gao if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) { 1188cb77930dSYunzhong Gao if (RType->getDecl()->isStruct()) { 1189872307e2SRichard Smith unsigned NumElements = 0; 1190872307e2SRichard Smith if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RType->getDecl())) 1191872307e2SRichard Smith NumElements = CXXRD->getNumBases(); 1192cb77930dSYunzhong Gao for (auto *Field : RType->getDecl()->fields()) 1193cb77930dSYunzhong Gao if (!Field->isUnnamedBitfield()) 1194872307e2SRichard Smith ++NumElements; 1195872307e2SRichard Smith // FIXME: Recurse into nested InitListExprs. 1196872307e2SRichard Smith if (ILE->getNumInits() == NumElements) 1197cb77930dSYunzhong Gao for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) 1198cb77930dSYunzhong Gao if (!isa<ImplicitValueInitExpr>(ILE->getInit(i))) 1199872307e2SRichard Smith --NumElements; 1200872307e2SRichard Smith if (ILE->getNumInits() == NumElements && TryMemsetInitialization()) 1201cb77930dSYunzhong Gao return; 1202cb77930dSYunzhong Gao } 1203cb77930dSYunzhong Gao } 1204cb77930dSYunzhong Gao } 1205cb77930dSYunzhong Gao 120606a67e2cSRichard Smith // Create the loop blocks. 120706a67e2cSRichard Smith llvm::BasicBlock *EntryBB = Builder.GetInsertBlock(); 120806a67e2cSRichard Smith llvm::BasicBlock *LoopBB = createBasicBlock("new.loop"); 120906a67e2cSRichard Smith llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end"); 121059486a2dSAnders Carlsson 121106a67e2cSRichard Smith // Find the end of the array, hoisted out of the loop. 121206a67e2cSRichard Smith llvm::Value *EndPtr = 12137f416cc4SJohn McCall Builder.CreateInBoundsGEP(BeginPtr.getPointer(), NumElements, "array.end"); 121406a67e2cSRichard Smith 121506a67e2cSRichard Smith // If the number of elements isn't constant, we have to now check if there is 121606a67e2cSRichard Smith // anything left to initialize. 121706a67e2cSRichard Smith if (!ConstNum) { 12187f416cc4SJohn McCall llvm::Value *IsEmpty = 12197f416cc4SJohn McCall Builder.CreateICmpEQ(CurPtr.getPointer(), EndPtr, "array.isempty"); 122006a67e2cSRichard Smith Builder.CreateCondBr(IsEmpty, ContBB, LoopBB); 122106a67e2cSRichard Smith } 122206a67e2cSRichard Smith 122306a67e2cSRichard Smith // Enter the loop. 122406a67e2cSRichard Smith EmitBlock(LoopBB); 122506a67e2cSRichard Smith 122606a67e2cSRichard Smith // Set up the current-element phi. 122706a67e2cSRichard Smith llvm::PHINode *CurPtrPhi = 12287f416cc4SJohn McCall Builder.CreatePHI(CurPtr.getType(), 2, "array.cur"); 12297f416cc4SJohn McCall CurPtrPhi->addIncoming(CurPtr.getPointer(), EntryBB); 12307f416cc4SJohn McCall 12317f416cc4SJohn McCall CurPtr = Address(CurPtrPhi, ElementAlign); 123206a67e2cSRichard Smith 123306a67e2cSRichard Smith // Store the new Cleanup position for irregular Cleanups. 12347f416cc4SJohn McCall if (EndOfInit.isValid()) 12357f416cc4SJohn McCall Builder.CreateStore(CurPtr.getPointer(), EndOfInit); 123606a67e2cSRichard Smith 123706a67e2cSRichard Smith // Enter a partial-destruction Cleanup if necessary. 123806a67e2cSRichard Smith if (!CleanupDominator && needsEHCleanup(DtorKind)) { 12397f416cc4SJohn McCall pushRegularPartialArrayCleanup(BeginPtr.getPointer(), CurPtr.getPointer(), 12407f416cc4SJohn McCall ElementType, ElementAlign, 124106a67e2cSRichard Smith getDestroyer(DtorKind)); 124206a67e2cSRichard Smith Cleanup = EHStack.stable_begin(); 124306a67e2cSRichard Smith CleanupDominator = Builder.CreateUnreachable(); 124406a67e2cSRichard Smith } 124506a67e2cSRichard Smith 124606a67e2cSRichard Smith // Emit the initializer into this element. 1247e78fac51SRichard Smith StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr, 1248e78fac51SRichard Smith AggValueSlot::DoesNotOverlap); 124906a67e2cSRichard Smith 125006a67e2cSRichard Smith // Leave the Cleanup if we entered one. 125106a67e2cSRichard Smith if (CleanupDominator) { 125206a67e2cSRichard Smith DeactivateCleanupBlock(Cleanup, CleanupDominator); 125306a67e2cSRichard Smith CleanupDominator->eraseFromParent(); 125406a67e2cSRichard Smith } 125506a67e2cSRichard Smith 125606a67e2cSRichard Smith // Advance to the next element by adjusting the pointer type as necessary. 125706a67e2cSRichard Smith llvm::Value *NextPtr = 12587f416cc4SJohn McCall Builder.CreateConstInBoundsGEP1_32(ElementTy, CurPtr.getPointer(), 1, 12597f416cc4SJohn McCall "array.next"); 126006a67e2cSRichard Smith 126106a67e2cSRichard Smith // Check whether we've gotten to the end of the array and, if so, 126206a67e2cSRichard Smith // exit the loop. 126306a67e2cSRichard Smith llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend"); 126406a67e2cSRichard Smith Builder.CreateCondBr(IsEnd, ContBB, LoopBB); 126506a67e2cSRichard Smith CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock()); 126606a67e2cSRichard Smith 126706a67e2cSRichard Smith EmitBlock(ContBB); 126806a67e2cSRichard Smith } 126906a67e2cSRichard Smith 127006a67e2cSRichard Smith static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E, 1271fb901c7aSDavid Blaikie QualType ElementType, llvm::Type *ElementTy, 12727f416cc4SJohn McCall Address NewPtr, llvm::Value *NumElements, 127306a67e2cSRichard Smith llvm::Value *AllocSizeWithoutCookie) { 12749b479666SDavid Blaikie ApplyDebugLocation DL(CGF, E); 127506a67e2cSRichard Smith if (E->isArray()) 1276fb901c7aSDavid Blaikie CGF.EmitNewArrayInitializer(E, ElementType, ElementTy, NewPtr, NumElements, 127706a67e2cSRichard Smith AllocSizeWithoutCookie); 127806a67e2cSRichard Smith else if (const Expr *Init = E->getInitializer()) 1279e78fac51SRichard Smith StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr, 1280e78fac51SRichard Smith AggValueSlot::DoesNotOverlap); 128159486a2dSAnders Carlsson } 128259486a2dSAnders Carlsson 12838d0dc31dSRichard Smith /// Emit a call to an operator new or operator delete function, as implicitly 12848d0dc31dSRichard Smith /// created by new-expressions and delete-expressions. 12858d0dc31dSRichard Smith static RValue EmitNewDeleteCall(CodeGenFunction &CGF, 1286b92ab1afSJohn McCall const FunctionDecl *CalleeDecl, 12878d0dc31dSRichard Smith const FunctionProtoType *CalleeType, 12888d0dc31dSRichard Smith const CallArgList &Args) { 12893933adddSJames Y Knight llvm::CallBase *CallOrInvoke; 1290b92ab1afSJohn McCall llvm::Constant *CalleePtr = CGF.CGM.GetAddrOfFunction(CalleeDecl); 1291de6480a3SErich Keane CGCallee Callee = CGCallee::forDirect(CalleePtr, GlobalDecl(CalleeDecl)); 12928d0dc31dSRichard Smith RValue RV = 1293f770683fSPeter Collingbourne CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall( 129449a3ad21SRui Ueyama Args, CalleeType, /*ChainCall=*/false), 1295b92ab1afSJohn McCall Callee, ReturnValueSlot(), Args, &CallOrInvoke); 12968d0dc31dSRichard Smith 12978d0dc31dSRichard Smith /// C++1y [expr.new]p10: 12988d0dc31dSRichard Smith /// [In a new-expression,] an implementation is allowed to omit a call 12998d0dc31dSRichard Smith /// to a replaceable global allocation function. 13008d0dc31dSRichard Smith /// 13018d0dc31dSRichard Smith /// We model such elidable calls with the 'builtin' attribute. 1302b92ab1afSJohn McCall llvm::Function *Fn = dyn_cast<llvm::Function>(CalleePtr); 1303b92ab1afSJohn McCall if (CalleeDecl->isReplaceableGlobalAllocationFunction() && 13046956d587SRafael Espindola Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) { 13053933adddSJames Y Knight CallOrInvoke->addAttribute(llvm::AttributeList::FunctionIndex, 13068d0dc31dSRichard Smith llvm::Attribute::Builtin); 13078d0dc31dSRichard Smith } 13088d0dc31dSRichard Smith 13098d0dc31dSRichard Smith return RV; 13108d0dc31dSRichard Smith } 13118d0dc31dSRichard Smith 1312760520bcSRichard Smith RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type, 1313fa752f23SEric Fiselier const CallExpr *TheCall, 1314760520bcSRichard Smith bool IsDelete) { 1315760520bcSRichard Smith CallArgList Args; 1316fa752f23SEric Fiselier EmitCallArgs(Args, Type->getParamTypes(), TheCall->arguments()); 1317760520bcSRichard Smith // Find the allocation or deallocation function that we're calling. 1318760520bcSRichard Smith ASTContext &Ctx = getContext(); 1319760520bcSRichard Smith DeclarationName Name = Ctx.DeclarationNames 1320760520bcSRichard Smith .getCXXOperatorName(IsDelete ? OO_Delete : OO_New); 1321fa752f23SEric Fiselier 1322760520bcSRichard Smith for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name)) 1323599bed75SRichard Smith if (auto *FD = dyn_cast<FunctionDecl>(Decl)) 1324599bed75SRichard Smith if (Ctx.hasSameType(FD->getType(), QualType(Type, 0))) 1325fa752f23SEric Fiselier return EmitNewDeleteCall(*this, FD, Type, Args); 1326760520bcSRichard Smith llvm_unreachable("predeclared global operator new/delete is missing"); 1327760520bcSRichard Smith } 1328760520bcSRichard Smith 13295b34958bSRichard Smith namespace { 13305b34958bSRichard Smith /// The parameters to pass to a usual operator delete. 13315b34958bSRichard Smith struct UsualDeleteParams { 13325b34958bSRichard Smith bool DestroyingDelete = false; 13335b34958bSRichard Smith bool Size = false; 13345b34958bSRichard Smith bool Alignment = false; 13355b34958bSRichard Smith }; 13365b34958bSRichard Smith } 13375b34958bSRichard Smith 13385b34958bSRichard Smith static UsualDeleteParams getUsualDeleteParams(const FunctionDecl *FD) { 13395b34958bSRichard Smith UsualDeleteParams Params; 13405b34958bSRichard Smith 13415b34958bSRichard Smith const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>(); 1342b2f0f057SRichard Smith auto AI = FPT->param_type_begin(), AE = FPT->param_type_end(); 1343e9abe648SDaniel Jasper 1344b2f0f057SRichard Smith // The first argument is always a void*. 1345b2f0f057SRichard Smith ++AI; 1346b2f0f057SRichard Smith 13475b34958bSRichard Smith // The next parameter may be a std::destroying_delete_t. 13485b34958bSRichard Smith if (FD->isDestroyingOperatorDelete()) { 13495b34958bSRichard Smith Params.DestroyingDelete = true; 13505b34958bSRichard Smith assert(AI != AE); 13515b34958bSRichard Smith ++AI; 13525b34958bSRichard Smith } 1353b2f0f057SRichard Smith 13545b34958bSRichard Smith // Figure out what other parameters we should be implicitly passing. 1355b2f0f057SRichard Smith if (AI != AE && (*AI)->isIntegerType()) { 13565b34958bSRichard Smith Params.Size = true; 1357b2f0f057SRichard Smith ++AI; 1358b2f0f057SRichard Smith } 1359b2f0f057SRichard Smith 1360b2f0f057SRichard Smith if (AI != AE && (*AI)->isAlignValT()) { 13615b34958bSRichard Smith Params.Alignment = true; 1362b2f0f057SRichard Smith ++AI; 1363b2f0f057SRichard Smith } 1364b2f0f057SRichard Smith 1365b2f0f057SRichard Smith assert(AI == AE && "unexpected usual deallocation function parameter"); 13665b34958bSRichard Smith return Params; 1367b2f0f057SRichard Smith } 1368b2f0f057SRichard Smith 1369b2f0f057SRichard Smith namespace { 1370b2f0f057SRichard Smith /// A cleanup to call the given 'operator delete' function upon abnormal 1371b2f0f057SRichard Smith /// exit from a new expression. Templated on a traits type that deals with 1372b2f0f057SRichard Smith /// ensuring that the arguments dominate the cleanup if necessary. 1373b2f0f057SRichard Smith template<typename Traits> 1374b2f0f057SRichard Smith class CallDeleteDuringNew final : public EHScopeStack::Cleanup { 1375b2f0f057SRichard Smith /// Type used to hold llvm::Value*s. 1376b2f0f057SRichard Smith typedef typename Traits::ValueTy ValueTy; 1377b2f0f057SRichard Smith /// Type used to hold RValues. 1378b2f0f057SRichard Smith typedef typename Traits::RValueTy RValueTy; 1379b2f0f057SRichard Smith struct PlacementArg { 1380b2f0f057SRichard Smith RValueTy ArgValue; 1381b2f0f057SRichard Smith QualType ArgType; 1382b2f0f057SRichard Smith }; 1383b2f0f057SRichard Smith 1384b2f0f057SRichard Smith unsigned NumPlacementArgs : 31; 1385b2f0f057SRichard Smith unsigned PassAlignmentToPlacementDelete : 1; 1386b2f0f057SRichard Smith const FunctionDecl *OperatorDelete; 1387b2f0f057SRichard Smith ValueTy Ptr; 1388b2f0f057SRichard Smith ValueTy AllocSize; 1389b2f0f057SRichard Smith CharUnits AllocAlign; 1390b2f0f057SRichard Smith 1391b2f0f057SRichard Smith PlacementArg *getPlacementArgs() { 1392b2f0f057SRichard Smith return reinterpret_cast<PlacementArg *>(this + 1); 1393b2f0f057SRichard Smith } 1394e9abe648SDaniel Jasper 1395e9abe648SDaniel Jasper public: 1396e9abe648SDaniel Jasper static size_t getExtraSize(size_t NumPlacementArgs) { 1397b2f0f057SRichard Smith return NumPlacementArgs * sizeof(PlacementArg); 1398e9abe648SDaniel Jasper } 1399e9abe648SDaniel Jasper 1400e9abe648SDaniel Jasper CallDeleteDuringNew(size_t NumPlacementArgs, 1401b2f0f057SRichard Smith const FunctionDecl *OperatorDelete, ValueTy Ptr, 1402b2f0f057SRichard Smith ValueTy AllocSize, bool PassAlignmentToPlacementDelete, 1403b2f0f057SRichard Smith CharUnits AllocAlign) 1404b2f0f057SRichard Smith : NumPlacementArgs(NumPlacementArgs), 1405b2f0f057SRichard Smith PassAlignmentToPlacementDelete(PassAlignmentToPlacementDelete), 1406b2f0f057SRichard Smith OperatorDelete(OperatorDelete), Ptr(Ptr), AllocSize(AllocSize), 1407b2f0f057SRichard Smith AllocAlign(AllocAlign) {} 1408e9abe648SDaniel Jasper 1409b2f0f057SRichard Smith void setPlacementArg(unsigned I, RValueTy Arg, QualType Type) { 1410e9abe648SDaniel Jasper assert(I < NumPlacementArgs && "index out of range"); 1411b2f0f057SRichard Smith getPlacementArgs()[I] = {Arg, Type}; 1412e9abe648SDaniel Jasper } 1413e9abe648SDaniel Jasper 1414e9abe648SDaniel Jasper void Emit(CodeGenFunction &CGF, Flags flags) override { 1415b2f0f057SRichard Smith const FunctionProtoType *FPT = 1416b2f0f057SRichard Smith OperatorDelete->getType()->getAs<FunctionProtoType>(); 1417e9abe648SDaniel Jasper CallArgList DeleteArgs; 1418824c2f53SJohn McCall 14195b34958bSRichard Smith // The first argument is always a void* (or C* for a destroying operator 14205b34958bSRichard Smith // delete for class type C). 1421b2f0f057SRichard Smith DeleteArgs.add(Traits::get(CGF, Ptr), FPT->getParamType(0)); 1422189e52fcSRichard Smith 1423b2f0f057SRichard Smith // Figure out what other parameters we should be implicitly passing. 14245b34958bSRichard Smith UsualDeleteParams Params; 1425b2f0f057SRichard Smith if (NumPlacementArgs) { 1426b2f0f057SRichard Smith // A placement deallocation function is implicitly passed an alignment 1427b2f0f057SRichard Smith // if the placement allocation function was, but is never passed a size. 14285b34958bSRichard Smith Params.Alignment = PassAlignmentToPlacementDelete; 1429b2f0f057SRichard Smith } else { 1430b2f0f057SRichard Smith // For a non-placement new-expression, 'operator delete' can take a 1431b2f0f057SRichard Smith // size and/or an alignment if it has the right parameters. 14325b34958bSRichard Smith Params = getUsualDeleteParams(OperatorDelete); 1433189e52fcSRichard Smith } 1434824c2f53SJohn McCall 14355b34958bSRichard Smith assert(!Params.DestroyingDelete && 14365b34958bSRichard Smith "should not call destroying delete in a new-expression"); 14375b34958bSRichard Smith 1438b2f0f057SRichard Smith // The second argument can be a std::size_t (for non-placement delete). 14395b34958bSRichard Smith if (Params.Size) 1440b2f0f057SRichard Smith DeleteArgs.add(Traits::get(CGF, AllocSize), 1441b2f0f057SRichard Smith CGF.getContext().getSizeType()); 1442824c2f53SJohn McCall 1443b2f0f057SRichard Smith // The next (second or third) argument can be a std::align_val_t, which 1444b2f0f057SRichard Smith // is an enum whose underlying type is std::size_t. 1445b2f0f057SRichard Smith // FIXME: Use the right type as the parameter type. Note that in a call 1446b2f0f057SRichard Smith // to operator delete(size_t, ...), we may not have it available. 14475b34958bSRichard Smith if (Params.Alignment) 1448b2f0f057SRichard Smith DeleteArgs.add(RValue::get(llvm::ConstantInt::get( 1449b2f0f057SRichard Smith CGF.SizeTy, AllocAlign.getQuantity())), 1450b2f0f057SRichard Smith CGF.getContext().getSizeType()); 14517f9c92a9SJohn McCall 14527f9c92a9SJohn McCall // Pass the rest of the arguments, which must match exactly. 14537f9c92a9SJohn McCall for (unsigned I = 0; I != NumPlacementArgs; ++I) { 1454b2f0f057SRichard Smith auto Arg = getPlacementArgs()[I]; 1455b2f0f057SRichard Smith DeleteArgs.add(Traits::get(CGF, Arg.ArgValue), Arg.ArgType); 14567f9c92a9SJohn McCall } 14577f9c92a9SJohn McCall 14587f9c92a9SJohn McCall // Call 'operator delete'. 14598d0dc31dSRichard Smith EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs); 14607f9c92a9SJohn McCall } 14617f9c92a9SJohn McCall }; 1462ab9db510SAlexander Kornienko } 14637f9c92a9SJohn McCall 14647f9c92a9SJohn McCall /// Enter a cleanup to call 'operator delete' if the initializer in a 14657f9c92a9SJohn McCall /// new-expression throws. 14667f9c92a9SJohn McCall static void EnterNewDeleteCleanup(CodeGenFunction &CGF, 14677f9c92a9SJohn McCall const CXXNewExpr *E, 14687f416cc4SJohn McCall Address NewPtr, 14697f9c92a9SJohn McCall llvm::Value *AllocSize, 1470b2f0f057SRichard Smith CharUnits AllocAlign, 14717f9c92a9SJohn McCall const CallArgList &NewArgs) { 1472b2f0f057SRichard Smith unsigned NumNonPlacementArgs = E->passAlignment() ? 2 : 1; 1473b2f0f057SRichard Smith 14747f9c92a9SJohn McCall // If we're not inside a conditional branch, then the cleanup will 14757f9c92a9SJohn McCall // dominate and we can do the easier (and more efficient) thing. 14767f9c92a9SJohn McCall if (!CGF.isInConditionalBranch()) { 1477b2f0f057SRichard Smith struct DirectCleanupTraits { 1478b2f0f057SRichard Smith typedef llvm::Value *ValueTy; 1479b2f0f057SRichard Smith typedef RValue RValueTy; 1480b2f0f057SRichard Smith static RValue get(CodeGenFunction &, ValueTy V) { return RValue::get(V); } 1481b2f0f057SRichard Smith static RValue get(CodeGenFunction &, RValueTy V) { return V; } 1482b2f0f057SRichard Smith }; 1483b2f0f057SRichard Smith 1484b2f0f057SRichard Smith typedef CallDeleteDuringNew<DirectCleanupTraits> DirectCleanup; 1485b2f0f057SRichard Smith 1486b2f0f057SRichard Smith DirectCleanup *Cleanup = CGF.EHStack 1487b2f0f057SRichard Smith .pushCleanupWithExtra<DirectCleanup>(EHCleanup, 14887f9c92a9SJohn McCall E->getNumPlacementArgs(), 14897f9c92a9SJohn McCall E->getOperatorDelete(), 14907f416cc4SJohn McCall NewPtr.getPointer(), 1491b2f0f057SRichard Smith AllocSize, 1492b2f0f057SRichard Smith E->passAlignment(), 1493b2f0f057SRichard Smith AllocAlign); 1494b2f0f057SRichard Smith for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) { 1495b2f0f057SRichard Smith auto &Arg = NewArgs[I + NumNonPlacementArgs]; 14965b330e8dSYaxun Liu Cleanup->setPlacementArg(I, Arg.getRValue(CGF), Arg.Ty); 1497b2f0f057SRichard Smith } 14987f9c92a9SJohn McCall 14997f9c92a9SJohn McCall return; 15007f9c92a9SJohn McCall } 15017f9c92a9SJohn McCall 15027f9c92a9SJohn McCall // Otherwise, we need to save all this stuff. 1503cb5f77f0SJohn McCall DominatingValue<RValue>::saved_type SavedNewPtr = 15047f416cc4SJohn McCall DominatingValue<RValue>::save(CGF, RValue::get(NewPtr.getPointer())); 1505cb5f77f0SJohn McCall DominatingValue<RValue>::saved_type SavedAllocSize = 1506cb5f77f0SJohn McCall DominatingValue<RValue>::save(CGF, RValue::get(AllocSize)); 15077f9c92a9SJohn McCall 1508b2f0f057SRichard Smith struct ConditionalCleanupTraits { 1509b2f0f057SRichard Smith typedef DominatingValue<RValue>::saved_type ValueTy; 1510b2f0f057SRichard Smith typedef DominatingValue<RValue>::saved_type RValueTy; 1511b2f0f057SRichard Smith static RValue get(CodeGenFunction &CGF, ValueTy V) { 1512b2f0f057SRichard Smith return V.restore(CGF); 1513b2f0f057SRichard Smith } 1514b2f0f057SRichard Smith }; 1515b2f0f057SRichard Smith typedef CallDeleteDuringNew<ConditionalCleanupTraits> ConditionalCleanup; 1516b2f0f057SRichard Smith 1517b2f0f057SRichard Smith ConditionalCleanup *Cleanup = CGF.EHStack 1518b2f0f057SRichard Smith .pushCleanupWithExtra<ConditionalCleanup>(EHCleanup, 15197f9c92a9SJohn McCall E->getNumPlacementArgs(), 15207f9c92a9SJohn McCall E->getOperatorDelete(), 15217f9c92a9SJohn McCall SavedNewPtr, 1522b2f0f057SRichard Smith SavedAllocSize, 1523b2f0f057SRichard Smith E->passAlignment(), 1524b2f0f057SRichard Smith AllocAlign); 1525b2f0f057SRichard Smith for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) { 1526b2f0f057SRichard Smith auto &Arg = NewArgs[I + NumNonPlacementArgs]; 15275b330e8dSYaxun Liu Cleanup->setPlacementArg( 15285b330e8dSYaxun Liu I, DominatingValue<RValue>::save(CGF, Arg.getRValue(CGF)), Arg.Ty); 1529b2f0f057SRichard Smith } 15307f9c92a9SJohn McCall 1531f4beacd0SJohn McCall CGF.initFullExprCleanup(); 1532824c2f53SJohn McCall } 1533824c2f53SJohn McCall 153459486a2dSAnders Carlsson llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) { 153575f9498aSJohn McCall // The element type being allocated. 153675f9498aSJohn McCall QualType allocType = getContext().getBaseElementType(E->getAllocatedType()); 15378ed55a54SJohn McCall 153875f9498aSJohn McCall // 1. Build a call to the allocation function. 153975f9498aSJohn McCall FunctionDecl *allocator = E->getOperatorNew(); 154059486a2dSAnders Carlsson 1541f862eb6aSSebastian Redl // If there is a brace-initializer, cannot allocate fewer elements than inits. 1542f862eb6aSSebastian Redl unsigned minElements = 0; 1543f862eb6aSSebastian Redl if (E->isArray() && E->hasInitializer()) { 15440511d23aSRichard Smith const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer()); 15450511d23aSRichard Smith if (ILE && ILE->isStringLiteralInit()) 15460511d23aSRichard Smith minElements = 15470511d23aSRichard Smith cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe()) 15480511d23aSRichard Smith ->getSize().getZExtValue(); 15490511d23aSRichard Smith else if (ILE) 1550f862eb6aSSebastian Redl minElements = ILE->getNumInits(); 1551f862eb6aSSebastian Redl } 1552f862eb6aSSebastian Redl 15538a13c418SCraig Topper llvm::Value *numElements = nullptr; 15548a13c418SCraig Topper llvm::Value *allocSizeWithoutCookie = nullptr; 155575f9498aSJohn McCall llvm::Value *allocSize = 1556f862eb6aSSebastian Redl EmitCXXNewAllocSize(*this, E, minElements, numElements, 1557f862eb6aSSebastian Redl allocSizeWithoutCookie); 1558b2f0f057SRichard Smith CharUnits allocAlign = getContext().getTypeAlignInChars(allocType); 155959486a2dSAnders Carlsson 15607f416cc4SJohn McCall // Emit the allocation call. If the allocator is a global placement 15617f416cc4SJohn McCall // operator, just "inline" it directly. 15627f416cc4SJohn McCall Address allocation = Address::invalid(); 15637f416cc4SJohn McCall CallArgList allocatorArgs; 15647f416cc4SJohn McCall if (allocator->isReservedGlobalPlacementOperator()) { 156553dcf94dSJohn McCall assert(E->getNumPlacementArgs() == 1); 156653dcf94dSJohn McCall const Expr *arg = *E->placement_arguments().begin(); 156753dcf94dSJohn McCall 15688f248234SKrzysztof Parzyszek LValueBaseInfo BaseInfo; 15698f248234SKrzysztof Parzyszek allocation = EmitPointerWithAlignment(arg, &BaseInfo); 15707f416cc4SJohn McCall 15717f416cc4SJohn McCall // The pointer expression will, in many cases, be an opaque void*. 15727f416cc4SJohn McCall // In these cases, discard the computed alignment and use the 15737f416cc4SJohn McCall // formal alignment of the allocated type. 15748f248234SKrzysztof Parzyszek if (BaseInfo.getAlignmentSource() != AlignmentSource::Decl) 1575b2f0f057SRichard Smith allocation = Address(allocation.getPointer(), allocAlign); 15767f416cc4SJohn McCall 157753dcf94dSJohn McCall // Set up allocatorArgs for the call to operator delete if it's not 157853dcf94dSJohn McCall // the reserved global operator. 157953dcf94dSJohn McCall if (E->getOperatorDelete() && 158053dcf94dSJohn McCall !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) { 158153dcf94dSJohn McCall allocatorArgs.add(RValue::get(allocSize), getContext().getSizeType()); 158253dcf94dSJohn McCall allocatorArgs.add(RValue::get(allocation.getPointer()), arg->getType()); 158353dcf94dSJohn McCall } 158453dcf94dSJohn McCall 15857f416cc4SJohn McCall } else { 15867f416cc4SJohn McCall const FunctionProtoType *allocatorType = 15877f416cc4SJohn McCall allocator->getType()->castAs<FunctionProtoType>(); 1588b2f0f057SRichard Smith unsigned ParamsToSkip = 0; 15897f416cc4SJohn McCall 15907f416cc4SJohn McCall // The allocation size is the first argument. 15917f416cc4SJohn McCall QualType sizeType = getContext().getSizeType(); 159243dca6a8SEli Friedman allocatorArgs.add(RValue::get(allocSize), sizeType); 1593b2f0f057SRichard Smith ++ParamsToSkip; 159459486a2dSAnders Carlsson 1595b2f0f057SRichard Smith if (allocSize != allocSizeWithoutCookie) { 1596b2f0f057SRichard Smith CharUnits cookieAlign = getSizeAlign(); // FIXME: Ask the ABI. 1597b2f0f057SRichard Smith allocAlign = std::max(allocAlign, cookieAlign); 1598b2f0f057SRichard Smith } 1599b2f0f057SRichard Smith 1600b2f0f057SRichard Smith // The allocation alignment may be passed as the second argument. 1601b2f0f057SRichard Smith if (E->passAlignment()) { 1602b2f0f057SRichard Smith QualType AlignValT = sizeType; 1603b2f0f057SRichard Smith if (allocatorType->getNumParams() > 1) { 1604b2f0f057SRichard Smith AlignValT = allocatorType->getParamType(1); 1605b2f0f057SRichard Smith assert(getContext().hasSameUnqualifiedType( 1606b2f0f057SRichard Smith AlignValT->castAs<EnumType>()->getDecl()->getIntegerType(), 1607b2f0f057SRichard Smith sizeType) && 1608b2f0f057SRichard Smith "wrong type for alignment parameter"); 1609b2f0f057SRichard Smith ++ParamsToSkip; 1610b2f0f057SRichard Smith } else { 1611b2f0f057SRichard Smith // Corner case, passing alignment to 'operator new(size_t, ...)'. 1612b2f0f057SRichard Smith assert(allocator->isVariadic() && "can't pass alignment to allocator"); 1613b2f0f057SRichard Smith } 1614b2f0f057SRichard Smith allocatorArgs.add( 1615b2f0f057SRichard Smith RValue::get(llvm::ConstantInt::get(SizeTy, allocAlign.getQuantity())), 1616b2f0f057SRichard Smith AlignValT); 1617b2f0f057SRichard Smith } 1618b2f0f057SRichard Smith 1619b2f0f057SRichard Smith // FIXME: Why do we not pass a CalleeDecl here? 1620f05779e2SDavid Blaikie EmitCallArgs(allocatorArgs, allocatorType, E->placement_arguments(), 1621ed00ea08SVedant Kumar /*AC*/AbstractCallee(), /*ParamsToSkip*/ParamsToSkip); 162259486a2dSAnders Carlsson 16237f416cc4SJohn McCall RValue RV = 16247f416cc4SJohn McCall EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs); 16257f416cc4SJohn McCall 1626b2f0f057SRichard Smith // If this was a call to a global replaceable allocation function that does 1627b2f0f057SRichard Smith // not take an alignment argument, the allocator is known to produce 1628b2f0f057SRichard Smith // storage that's suitably aligned for any object that fits, up to a known 1629b2f0f057SRichard Smith // threshold. Otherwise assume it's suitably aligned for the allocated type. 1630b2f0f057SRichard Smith CharUnits allocationAlign = allocAlign; 1631b2f0f057SRichard Smith if (!E->passAlignment() && 1632b2f0f057SRichard Smith allocator->isReplaceableGlobalAllocationFunction()) { 1633b2f0f057SRichard Smith unsigned AllocatorAlign = llvm::PowerOf2Floor(std::min<uint64_t>( 1634b2f0f057SRichard Smith Target.getNewAlign(), getContext().getTypeSize(allocType))); 1635b2f0f057SRichard Smith allocationAlign = std::max( 1636b2f0f057SRichard Smith allocationAlign, getContext().toCharUnitsFromBits(AllocatorAlign)); 16377f416cc4SJohn McCall } 16387f416cc4SJohn McCall 16397f416cc4SJohn McCall allocation = Address(RV.getScalarVal(), allocationAlign); 16407ec4b434SJohn McCall } 164159486a2dSAnders Carlsson 164275f9498aSJohn McCall // Emit a null check on the allocation result if the allocation 164375f9498aSJohn McCall // function is allowed to return null (because it has a non-throwing 1644902a0238SRichard Smith // exception spec or is the reserved placement new) and we have an 16452f72a752SRichard Smith // interesting initializer will be running sanitizers on the initialization. 16469b6dfac5SBruno Ricci bool nullCheck = E->shouldNullCheckAllocation() && 16472f72a752SRichard Smith (!allocType.isPODType(getContext()) || E->hasInitializer() || 16482f72a752SRichard Smith sanitizePerformTypeCheck()); 164959486a2dSAnders Carlsson 16508a13c418SCraig Topper llvm::BasicBlock *nullCheckBB = nullptr; 16518a13c418SCraig Topper llvm::BasicBlock *contBB = nullptr; 165259486a2dSAnders Carlsson 1653f7dcf320SJohn McCall // The null-check means that the initializer is conditionally 1654f7dcf320SJohn McCall // evaluated. 1655f7dcf320SJohn McCall ConditionalEvaluation conditional(*this); 1656f7dcf320SJohn McCall 165775f9498aSJohn McCall if (nullCheck) { 1658f7dcf320SJohn McCall conditional.begin(*this); 165975f9498aSJohn McCall 166075f9498aSJohn McCall nullCheckBB = Builder.GetInsertBlock(); 166175f9498aSJohn McCall llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull"); 166275f9498aSJohn McCall contBB = createBasicBlock("new.cont"); 166375f9498aSJohn McCall 16647f416cc4SJohn McCall llvm::Value *isNull = 16657f416cc4SJohn McCall Builder.CreateIsNull(allocation.getPointer(), "new.isnull"); 166675f9498aSJohn McCall Builder.CreateCondBr(isNull, contBB, notNullBB); 166775f9498aSJohn McCall EmitBlock(notNullBB); 166859486a2dSAnders Carlsson } 166959486a2dSAnders Carlsson 1670824c2f53SJohn McCall // If there's an operator delete, enter a cleanup to call it if an 1671824c2f53SJohn McCall // exception is thrown. 167275f9498aSJohn McCall EHScopeStack::stable_iterator operatorDeleteCleanup; 16738a13c418SCraig Topper llvm::Instruction *cleanupDominator = nullptr; 16747ec4b434SJohn McCall if (E->getOperatorDelete() && 16757ec4b434SJohn McCall !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) { 1676b2f0f057SRichard Smith EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocAlign, 1677b2f0f057SRichard Smith allocatorArgs); 167875f9498aSJohn McCall operatorDeleteCleanup = EHStack.stable_begin(); 1679f4beacd0SJohn McCall cleanupDominator = Builder.CreateUnreachable(); 1680824c2f53SJohn McCall } 1681824c2f53SJohn McCall 1682cf9b1f65SEli Friedman assert((allocSize == allocSizeWithoutCookie) == 1683cf9b1f65SEli Friedman CalculateCookiePadding(*this, E).isZero()); 1684cf9b1f65SEli Friedman if (allocSize != allocSizeWithoutCookie) { 1685cf9b1f65SEli Friedman assert(E->isArray()); 1686cf9b1f65SEli Friedman allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation, 1687cf9b1f65SEli Friedman numElements, 1688cf9b1f65SEli Friedman E, allocType); 1689cf9b1f65SEli Friedman } 1690cf9b1f65SEli Friedman 1691fb901c7aSDavid Blaikie llvm::Type *elementTy = ConvertTypeForMem(allocType); 16927f416cc4SJohn McCall Address result = Builder.CreateElementBitCast(allocation, elementTy); 1693824c2f53SJohn McCall 16945dde8094SPiotr Padlewski // Passing pointer through launder.invariant.group to avoid propagation of 1695338c9d0aSPiotr Padlewski // vptrs information which may be included in previous type. 169631fd99cfSPiotr Padlewski // To not break LTO with different optimizations levels, we do it regardless 169731fd99cfSPiotr Padlewski // of optimization level. 1698338c9d0aSPiotr Padlewski if (CGM.getCodeGenOpts().StrictVTablePointers && 1699338c9d0aSPiotr Padlewski allocator->isReservedGlobalPlacementOperator()) 17005dde8094SPiotr Padlewski result = Address(Builder.CreateLaunderInvariantGroup(result.getPointer()), 1701338c9d0aSPiotr Padlewski result.getAlignment()); 1702338c9d0aSPiotr Padlewski 170337605182SSerge Pavlov // Emit sanitizer checks for pointer value now, so that in the case of an 1704cfa79b27SRichard Smith // array it was checked only once and not at each constructor call. We may 1705cfa79b27SRichard Smith // have already checked that the pointer is non-null. 1706cfa79b27SRichard Smith // FIXME: If we have an array cookie and a potentially-throwing allocator, 1707cfa79b27SRichard Smith // we'll null check the wrong pointer here. 1708cfa79b27SRichard Smith SanitizerSet SkippedChecks; 1709cfa79b27SRichard Smith SkippedChecks.set(SanitizerKind::Null, nullCheck); 171037605182SSerge Pavlov EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, 171137605182SSerge Pavlov E->getAllocatedTypeSourceInfo()->getTypeLoc().getBeginLoc(), 1712cfa79b27SRichard Smith result.getPointer(), allocType, result.getAlignment(), 1713cfa79b27SRichard Smith SkippedChecks, numElements); 171437605182SSerge Pavlov 1715fb901c7aSDavid Blaikie EmitNewInitializer(*this, E, allocType, elementTy, result, numElements, 171699210dc9SJohn McCall allocSizeWithoutCookie); 17178ed55a54SJohn McCall if (E->isArray()) { 17188ed55a54SJohn McCall // NewPtr is a pointer to the base element type. If we're 17198ed55a54SJohn McCall // allocating an array of arrays, we'll need to cast back to the 17208ed55a54SJohn McCall // array pointer type. 17212192fe50SChris Lattner llvm::Type *resultType = ConvertTypeForMem(E->getType()); 17227f416cc4SJohn McCall if (result.getType() != resultType) 172375f9498aSJohn McCall result = Builder.CreateBitCast(result, resultType); 172447b4629bSFariborz Jahanian } 172559486a2dSAnders Carlsson 1726824c2f53SJohn McCall // Deactivate the 'operator delete' cleanup if we finished 1727824c2f53SJohn McCall // initialization. 1728f4beacd0SJohn McCall if (operatorDeleteCleanup.isValid()) { 1729f4beacd0SJohn McCall DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator); 1730f4beacd0SJohn McCall cleanupDominator->eraseFromParent(); 1731f4beacd0SJohn McCall } 1732824c2f53SJohn McCall 17337f416cc4SJohn McCall llvm::Value *resultPtr = result.getPointer(); 173475f9498aSJohn McCall if (nullCheck) { 1735f7dcf320SJohn McCall conditional.end(*this); 1736f7dcf320SJohn McCall 173775f9498aSJohn McCall llvm::BasicBlock *notNullBB = Builder.GetInsertBlock(); 173875f9498aSJohn McCall EmitBlock(contBB); 173959486a2dSAnders Carlsson 17407f416cc4SJohn McCall llvm::PHINode *PHI = Builder.CreatePHI(resultPtr->getType(), 2); 17417f416cc4SJohn McCall PHI->addIncoming(resultPtr, notNullBB); 17427f416cc4SJohn McCall PHI->addIncoming(llvm::Constant::getNullValue(resultPtr->getType()), 174375f9498aSJohn McCall nullCheckBB); 174459486a2dSAnders Carlsson 17457f416cc4SJohn McCall resultPtr = PHI; 174659486a2dSAnders Carlsson } 174759486a2dSAnders Carlsson 17487f416cc4SJohn McCall return resultPtr; 174959486a2dSAnders Carlsson } 175059486a2dSAnders Carlsson 175159486a2dSAnders Carlsson void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD, 1752b2f0f057SRichard Smith llvm::Value *Ptr, QualType DeleteTy, 1753b2f0f057SRichard Smith llvm::Value *NumElements, 1754b2f0f057SRichard Smith CharUnits CookieSize) { 1755b2f0f057SRichard Smith assert((!NumElements && CookieSize.isZero()) || 1756b2f0f057SRichard Smith DeleteFD->getOverloadedOperator() == OO_Array_Delete); 17578ed55a54SJohn McCall 175859486a2dSAnders Carlsson const FunctionProtoType *DeleteFTy = 175959486a2dSAnders Carlsson DeleteFD->getType()->getAs<FunctionProtoType>(); 176059486a2dSAnders Carlsson 176159486a2dSAnders Carlsson CallArgList DeleteArgs; 176259486a2dSAnders Carlsson 17635b34958bSRichard Smith auto Params = getUsualDeleteParams(DeleteFD); 1764b2f0f057SRichard Smith auto ParamTypeIt = DeleteFTy->param_type_begin(); 1765b2f0f057SRichard Smith 1766b2f0f057SRichard Smith // Pass the pointer itself. 1767b2f0f057SRichard Smith QualType ArgTy = *ParamTypeIt++; 176859486a2dSAnders Carlsson llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy)); 176943dca6a8SEli Friedman DeleteArgs.add(RValue::get(DeletePtr), ArgTy); 177059486a2dSAnders Carlsson 17715b34958bSRichard Smith // Pass the std::destroying_delete tag if present. 17725b34958bSRichard Smith if (Params.DestroyingDelete) { 17735b34958bSRichard Smith QualType DDTag = *ParamTypeIt++; 17745b34958bSRichard Smith // Just pass an 'undef'. We expect the tag type to be an empty struct. 17755b34958bSRichard Smith auto *V = llvm::UndefValue::get(getTypes().ConvertType(DDTag)); 17765b34958bSRichard Smith DeleteArgs.add(RValue::get(V), DDTag); 17775b34958bSRichard Smith } 17785b34958bSRichard Smith 1779b2f0f057SRichard Smith // Pass the size if the delete function has a size_t parameter. 17805b34958bSRichard Smith if (Params.Size) { 1781b2f0f057SRichard Smith QualType SizeType = *ParamTypeIt++; 1782b2f0f057SRichard Smith CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy); 1783b2f0f057SRichard Smith llvm::Value *Size = llvm::ConstantInt::get(ConvertType(SizeType), 1784b2f0f057SRichard Smith DeleteTypeSize.getQuantity()); 1785b2f0f057SRichard Smith 1786b2f0f057SRichard Smith // For array new, multiply by the number of elements. 1787b2f0f057SRichard Smith if (NumElements) 1788b2f0f057SRichard Smith Size = Builder.CreateMul(Size, NumElements); 1789b2f0f057SRichard Smith 1790b2f0f057SRichard Smith // If there is a cookie, add the cookie size. 1791b2f0f057SRichard Smith if (!CookieSize.isZero()) 1792b2f0f057SRichard Smith Size = Builder.CreateAdd( 1793b2f0f057SRichard Smith Size, llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity())); 1794b2f0f057SRichard Smith 1795b2f0f057SRichard Smith DeleteArgs.add(RValue::get(Size), SizeType); 1796b2f0f057SRichard Smith } 1797b2f0f057SRichard Smith 1798b2f0f057SRichard Smith // Pass the alignment if the delete function has an align_val_t parameter. 17995b34958bSRichard Smith if (Params.Alignment) { 1800b2f0f057SRichard Smith QualType AlignValType = *ParamTypeIt++; 1801b2f0f057SRichard Smith CharUnits DeleteTypeAlign = getContext().toCharUnitsFromBits( 1802b2f0f057SRichard Smith getContext().getTypeAlignIfKnown(DeleteTy)); 1803b2f0f057SRichard Smith llvm::Value *Align = llvm::ConstantInt::get(ConvertType(AlignValType), 1804b2f0f057SRichard Smith DeleteTypeAlign.getQuantity()); 1805b2f0f057SRichard Smith DeleteArgs.add(RValue::get(Align), AlignValType); 1806b2f0f057SRichard Smith } 1807b2f0f057SRichard Smith 1808b2f0f057SRichard Smith assert(ParamTypeIt == DeleteFTy->param_type_end() && 1809b2f0f057SRichard Smith "unknown parameter to usual delete function"); 181059486a2dSAnders Carlsson 181159486a2dSAnders Carlsson // Emit the call to delete. 18128d0dc31dSRichard Smith EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs); 181359486a2dSAnders Carlsson } 181459486a2dSAnders Carlsson 18158ed55a54SJohn McCall namespace { 18168ed55a54SJohn McCall /// Calls the given 'operator delete' on a single object. 18177e70d680SDavid Blaikie struct CallObjectDelete final : EHScopeStack::Cleanup { 18188ed55a54SJohn McCall llvm::Value *Ptr; 18198ed55a54SJohn McCall const FunctionDecl *OperatorDelete; 18208ed55a54SJohn McCall QualType ElementType; 18218ed55a54SJohn McCall 18228ed55a54SJohn McCall CallObjectDelete(llvm::Value *Ptr, 18238ed55a54SJohn McCall const FunctionDecl *OperatorDelete, 18248ed55a54SJohn McCall QualType ElementType) 18258ed55a54SJohn McCall : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {} 18268ed55a54SJohn McCall 18274f12f10dSCraig Topper void Emit(CodeGenFunction &CGF, Flags flags) override { 18288ed55a54SJohn McCall CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType); 18298ed55a54SJohn McCall } 18308ed55a54SJohn McCall }; 1831ab9db510SAlexander Kornienko } 18328ed55a54SJohn McCall 18330c0b6d9aSDavid Majnemer void 18340c0b6d9aSDavid Majnemer CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete, 18350c0b6d9aSDavid Majnemer llvm::Value *CompletePtr, 18360c0b6d9aSDavid Majnemer QualType ElementType) { 18370c0b6d9aSDavid Majnemer EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr, 18380c0b6d9aSDavid Majnemer OperatorDelete, ElementType); 18390c0b6d9aSDavid Majnemer } 18400c0b6d9aSDavid Majnemer 18415b34958bSRichard Smith /// Emit the code for deleting a single object with a destroying operator 18425b34958bSRichard Smith /// delete. If the element type has a non-virtual destructor, Ptr has already 18435b34958bSRichard Smith /// been converted to the type of the parameter of 'operator delete'. Otherwise 18445b34958bSRichard Smith /// Ptr points to an object of the static type. 18455b34958bSRichard Smith static void EmitDestroyingObjectDelete(CodeGenFunction &CGF, 18465b34958bSRichard Smith const CXXDeleteExpr *DE, Address Ptr, 18475b34958bSRichard Smith QualType ElementType) { 18485b34958bSRichard Smith auto *Dtor = ElementType->getAsCXXRecordDecl()->getDestructor(); 18495b34958bSRichard Smith if (Dtor && Dtor->isVirtual()) 18505b34958bSRichard Smith CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType, 18515b34958bSRichard Smith Dtor); 18525b34958bSRichard Smith else 18535b34958bSRichard Smith CGF.EmitDeleteCall(DE->getOperatorDelete(), Ptr.getPointer(), ElementType); 18545b34958bSRichard Smith } 18555b34958bSRichard Smith 18568ed55a54SJohn McCall /// Emit the code for deleting a single object. 18578ed55a54SJohn McCall static void EmitObjectDelete(CodeGenFunction &CGF, 18580868137aSDavid Majnemer const CXXDeleteExpr *DE, 18597f416cc4SJohn McCall Address Ptr, 18600868137aSDavid Majnemer QualType ElementType) { 1861d98f5d78SIvan Krasin // C++11 [expr.delete]p3: 1862d98f5d78SIvan Krasin // If the static type of the object to be deleted is different from its 1863d98f5d78SIvan Krasin // dynamic type, the static type shall be a base class of the dynamic type 1864d98f5d78SIvan Krasin // of the object to be deleted and the static type shall have a virtual 1865d98f5d78SIvan Krasin // destructor or the behavior is undefined. 1866d98f5d78SIvan Krasin CGF.EmitTypeCheck(CodeGenFunction::TCK_MemberCall, 1867d98f5d78SIvan Krasin DE->getExprLoc(), Ptr.getPointer(), 1868d98f5d78SIvan Krasin ElementType); 1869d98f5d78SIvan Krasin 18705b34958bSRichard Smith const FunctionDecl *OperatorDelete = DE->getOperatorDelete(); 18715b34958bSRichard Smith assert(!OperatorDelete->isDestroyingOperatorDelete()); 18725b34958bSRichard Smith 18738ed55a54SJohn McCall // Find the destructor for the type, if applicable. If the 18748ed55a54SJohn McCall // destructor is virtual, we'll just emit the vcall and return. 18758a13c418SCraig Topper const CXXDestructorDecl *Dtor = nullptr; 18768ed55a54SJohn McCall if (const RecordType *RT = ElementType->getAs<RecordType>()) { 18778ed55a54SJohn McCall CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 1878b23533dbSEli Friedman if (RD->hasDefinition() && !RD->hasTrivialDestructor()) { 18798ed55a54SJohn McCall Dtor = RD->getDestructor(); 18808ed55a54SJohn McCall 18818ed55a54SJohn McCall if (Dtor->isVirtual()) { 1882cb30590dSHiroshi Yamauchi bool UseVirtualCall = true; 1883cb30590dSHiroshi Yamauchi const Expr *Base = DE->getArgument(); 1884cb30590dSHiroshi Yamauchi if (auto *DevirtualizedDtor = 1885cb30590dSHiroshi Yamauchi dyn_cast_or_null<const CXXDestructorDecl>( 1886cb30590dSHiroshi Yamauchi Dtor->getDevirtualizedMethod( 1887cb30590dSHiroshi Yamauchi Base, CGF.CGM.getLangOpts().AppleKext))) { 1888cb30590dSHiroshi Yamauchi UseVirtualCall = false; 1889cb30590dSHiroshi Yamauchi const CXXRecordDecl *DevirtualizedClass = 1890cb30590dSHiroshi Yamauchi DevirtualizedDtor->getParent(); 1891cb30590dSHiroshi Yamauchi if (declaresSameEntity(getCXXRecord(Base), DevirtualizedClass)) { 1892cb30590dSHiroshi Yamauchi // Devirtualized to the class of the base type (the type of the 1893cb30590dSHiroshi Yamauchi // whole expression). 1894cb30590dSHiroshi Yamauchi Dtor = DevirtualizedDtor; 1895cb30590dSHiroshi Yamauchi } else { 1896cb30590dSHiroshi Yamauchi // Devirtualized to some other type. Would need to cast the this 1897cb30590dSHiroshi Yamauchi // pointer to that type but we don't have support for that yet, so 1898cb30590dSHiroshi Yamauchi // do a virtual call. FIXME: handle the case where it is 1899cb30590dSHiroshi Yamauchi // devirtualized to the derived type (the type of the inner 1900cb30590dSHiroshi Yamauchi // expression) as in EmitCXXMemberOrOperatorMemberCallExpr. 1901cb30590dSHiroshi Yamauchi UseVirtualCall = true; 1902cb30590dSHiroshi Yamauchi } 1903cb30590dSHiroshi Yamauchi } 1904cb30590dSHiroshi Yamauchi if (UseVirtualCall) { 19050868137aSDavid Majnemer CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType, 19060868137aSDavid Majnemer Dtor); 19078ed55a54SJohn McCall return; 19088ed55a54SJohn McCall } 19098ed55a54SJohn McCall } 19108ed55a54SJohn McCall } 1911cb30590dSHiroshi Yamauchi } 19128ed55a54SJohn McCall 19138ed55a54SJohn McCall // Make sure that we call delete even if the dtor throws. 1914e4df6c8dSJohn McCall // This doesn't have to a conditional cleanup because we're going 1915e4df6c8dSJohn McCall // to pop it off in a second. 19168ed55a54SJohn McCall CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, 19177f416cc4SJohn McCall Ptr.getPointer(), 19187f416cc4SJohn McCall OperatorDelete, ElementType); 19198ed55a54SJohn McCall 19208ed55a54SJohn McCall if (Dtor) 19218ed55a54SJohn McCall CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, 192261535005SDouglas Gregor /*ForVirtualBase=*/false, 192361535005SDouglas Gregor /*Delegating=*/false, 192488559637SMarco Antognini Ptr, ElementType); 1925460ce58fSJohn McCall else if (auto Lifetime = ElementType.getObjCLifetime()) { 1926460ce58fSJohn McCall switch (Lifetime) { 192731168b07SJohn McCall case Qualifiers::OCL_None: 192831168b07SJohn McCall case Qualifiers::OCL_ExplicitNone: 192931168b07SJohn McCall case Qualifiers::OCL_Autoreleasing: 193031168b07SJohn McCall break; 193131168b07SJohn McCall 19327f416cc4SJohn McCall case Qualifiers::OCL_Strong: 19337f416cc4SJohn McCall CGF.EmitARCDestroyStrong(Ptr, ARCPreciseLifetime); 193431168b07SJohn McCall break; 193531168b07SJohn McCall 193631168b07SJohn McCall case Qualifiers::OCL_Weak: 193731168b07SJohn McCall CGF.EmitARCDestroyWeak(Ptr); 193831168b07SJohn McCall break; 193931168b07SJohn McCall } 194031168b07SJohn McCall } 19418ed55a54SJohn McCall 19428ed55a54SJohn McCall CGF.PopCleanupBlock(); 19438ed55a54SJohn McCall } 19448ed55a54SJohn McCall 19458ed55a54SJohn McCall namespace { 19468ed55a54SJohn McCall /// Calls the given 'operator delete' on an array of objects. 19477e70d680SDavid Blaikie struct CallArrayDelete final : EHScopeStack::Cleanup { 19488ed55a54SJohn McCall llvm::Value *Ptr; 19498ed55a54SJohn McCall const FunctionDecl *OperatorDelete; 19508ed55a54SJohn McCall llvm::Value *NumElements; 19518ed55a54SJohn McCall QualType ElementType; 19528ed55a54SJohn McCall CharUnits CookieSize; 19538ed55a54SJohn McCall 19548ed55a54SJohn McCall CallArrayDelete(llvm::Value *Ptr, 19558ed55a54SJohn McCall const FunctionDecl *OperatorDelete, 19568ed55a54SJohn McCall llvm::Value *NumElements, 19578ed55a54SJohn McCall QualType ElementType, 19588ed55a54SJohn McCall CharUnits CookieSize) 19598ed55a54SJohn McCall : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements), 19608ed55a54SJohn McCall ElementType(ElementType), CookieSize(CookieSize) {} 19618ed55a54SJohn McCall 19624f12f10dSCraig Topper void Emit(CodeGenFunction &CGF, Flags flags) override { 1963b2f0f057SRichard Smith CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType, NumElements, 1964b2f0f057SRichard Smith CookieSize); 19658ed55a54SJohn McCall } 19668ed55a54SJohn McCall }; 1967ab9db510SAlexander Kornienko } 19688ed55a54SJohn McCall 19698ed55a54SJohn McCall /// Emit the code for deleting an array of objects. 19708ed55a54SJohn McCall static void EmitArrayDelete(CodeGenFunction &CGF, 1971284c48ffSJohn McCall const CXXDeleteExpr *E, 19727f416cc4SJohn McCall Address deletedPtr, 1973ca2c56f2SJohn McCall QualType elementType) { 19748a13c418SCraig Topper llvm::Value *numElements = nullptr; 19758a13c418SCraig Topper llvm::Value *allocatedPtr = nullptr; 1976ca2c56f2SJohn McCall CharUnits cookieSize; 1977ca2c56f2SJohn McCall CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType, 1978ca2c56f2SJohn McCall numElements, allocatedPtr, cookieSize); 19798ed55a54SJohn McCall 1980ca2c56f2SJohn McCall assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer"); 19818ed55a54SJohn McCall 19828ed55a54SJohn McCall // Make sure that we call delete even if one of the dtors throws. 1983ca2c56f2SJohn McCall const FunctionDecl *operatorDelete = E->getOperatorDelete(); 19848ed55a54SJohn McCall CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup, 1985ca2c56f2SJohn McCall allocatedPtr, operatorDelete, 1986ca2c56f2SJohn McCall numElements, elementType, 1987ca2c56f2SJohn McCall cookieSize); 19888ed55a54SJohn McCall 1989ca2c56f2SJohn McCall // Destroy the elements. 1990ca2c56f2SJohn McCall if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) { 1991ca2c56f2SJohn McCall assert(numElements && "no element count for a type with a destructor!"); 199231168b07SJohn McCall 19937f416cc4SJohn McCall CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType); 19947f416cc4SJohn McCall CharUnits elementAlign = 19957f416cc4SJohn McCall deletedPtr.getAlignment().alignmentOfArrayElement(elementSize); 19967f416cc4SJohn McCall 19977f416cc4SJohn McCall llvm::Value *arrayBegin = deletedPtr.getPointer(); 1998ca2c56f2SJohn McCall llvm::Value *arrayEnd = 19997f416cc4SJohn McCall CGF.Builder.CreateInBoundsGEP(arrayBegin, numElements, "delete.end"); 200097eab0a2SJohn McCall 200197eab0a2SJohn McCall // Note that it is legal to allocate a zero-length array, and we 200297eab0a2SJohn McCall // can never fold the check away because the length should always 200397eab0a2SJohn McCall // come from a cookie. 20047f416cc4SJohn McCall CGF.emitArrayDestroy(arrayBegin, arrayEnd, elementType, elementAlign, 2005ca2c56f2SJohn McCall CGF.getDestroyer(dtorKind), 200697eab0a2SJohn McCall /*checkZeroLength*/ true, 2007ca2c56f2SJohn McCall CGF.needsEHCleanup(dtorKind)); 20088ed55a54SJohn McCall } 20098ed55a54SJohn McCall 2010ca2c56f2SJohn McCall // Pop the cleanup block. 20118ed55a54SJohn McCall CGF.PopCleanupBlock(); 20128ed55a54SJohn McCall } 20138ed55a54SJohn McCall 201459486a2dSAnders Carlsson void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) { 201559486a2dSAnders Carlsson const Expr *Arg = E->getArgument(); 20167f416cc4SJohn McCall Address Ptr = EmitPointerWithAlignment(Arg); 201759486a2dSAnders Carlsson 201859486a2dSAnders Carlsson // Null check the pointer. 201959486a2dSAnders Carlsson llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull"); 202059486a2dSAnders Carlsson llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end"); 202159486a2dSAnders Carlsson 20227f416cc4SJohn McCall llvm::Value *IsNull = Builder.CreateIsNull(Ptr.getPointer(), "isnull"); 202359486a2dSAnders Carlsson 202459486a2dSAnders Carlsson Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull); 202559486a2dSAnders Carlsson EmitBlock(DeleteNotNull); 202659486a2dSAnders Carlsson 20275b34958bSRichard Smith QualType DeleteTy = E->getDestroyedType(); 20285b34958bSRichard Smith 20295b34958bSRichard Smith // A destroying operator delete overrides the entire operation of the 20305b34958bSRichard Smith // delete expression. 20315b34958bSRichard Smith if (E->getOperatorDelete()->isDestroyingOperatorDelete()) { 20325b34958bSRichard Smith EmitDestroyingObjectDelete(*this, E, Ptr, DeleteTy); 20335b34958bSRichard Smith EmitBlock(DeleteEnd); 20345b34958bSRichard Smith return; 20355b34958bSRichard Smith } 20365b34958bSRichard Smith 20378ed55a54SJohn McCall // We might be deleting a pointer to array. If so, GEP down to the 20388ed55a54SJohn McCall // first non-array element. 20398ed55a54SJohn McCall // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*) 20408ed55a54SJohn McCall if (DeleteTy->isConstantArrayType()) { 20418ed55a54SJohn McCall llvm::Value *Zero = Builder.getInt32(0); 20420e62c1ccSChris Lattner SmallVector<llvm::Value*,8> GEP; 204359486a2dSAnders Carlsson 20448ed55a54SJohn McCall GEP.push_back(Zero); // point at the outermost array 20458ed55a54SJohn McCall 20468ed55a54SJohn McCall // For each layer of array type we're pointing at: 20478ed55a54SJohn McCall while (const ConstantArrayType *Arr 20488ed55a54SJohn McCall = getContext().getAsConstantArrayType(DeleteTy)) { 20498ed55a54SJohn McCall // 1. Unpeel the array type. 20508ed55a54SJohn McCall DeleteTy = Arr->getElementType(); 20518ed55a54SJohn McCall 20528ed55a54SJohn McCall // 2. GEP to the first element of the array. 20538ed55a54SJohn McCall GEP.push_back(Zero); 20548ed55a54SJohn McCall } 20558ed55a54SJohn McCall 20567f416cc4SJohn McCall Ptr = Address(Builder.CreateInBoundsGEP(Ptr.getPointer(), GEP, "del.first"), 20577f416cc4SJohn McCall Ptr.getAlignment()); 20588ed55a54SJohn McCall } 20598ed55a54SJohn McCall 20607f416cc4SJohn McCall assert(ConvertTypeForMem(DeleteTy) == Ptr.getElementType()); 20618ed55a54SJohn McCall 20627270ef57SReid Kleckner if (E->isArrayForm()) { 20637270ef57SReid Kleckner EmitArrayDelete(*this, E, Ptr, DeleteTy); 20647270ef57SReid Kleckner } else { 20657270ef57SReid Kleckner EmitObjectDelete(*this, E, Ptr, DeleteTy); 20667270ef57SReid Kleckner } 206759486a2dSAnders Carlsson 206859486a2dSAnders Carlsson EmitBlock(DeleteEnd); 206959486a2dSAnders Carlsson } 207059486a2dSAnders Carlsson 20711c3d95ebSDavid Majnemer static bool isGLValueFromPointerDeref(const Expr *E) { 20721c3d95ebSDavid Majnemer E = E->IgnoreParens(); 20731c3d95ebSDavid Majnemer 20741c3d95ebSDavid Majnemer if (const auto *CE = dyn_cast<CastExpr>(E)) { 20751c3d95ebSDavid Majnemer if (!CE->getSubExpr()->isGLValue()) 20761c3d95ebSDavid Majnemer return false; 20771c3d95ebSDavid Majnemer return isGLValueFromPointerDeref(CE->getSubExpr()); 20781c3d95ebSDavid Majnemer } 20791c3d95ebSDavid Majnemer 20801c3d95ebSDavid Majnemer if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 20811c3d95ebSDavid Majnemer return isGLValueFromPointerDeref(OVE->getSourceExpr()); 20821c3d95ebSDavid Majnemer 20831c3d95ebSDavid Majnemer if (const auto *BO = dyn_cast<BinaryOperator>(E)) 20841c3d95ebSDavid Majnemer if (BO->getOpcode() == BO_Comma) 20851c3d95ebSDavid Majnemer return isGLValueFromPointerDeref(BO->getRHS()); 20861c3d95ebSDavid Majnemer 20871c3d95ebSDavid Majnemer if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E)) 20881c3d95ebSDavid Majnemer return isGLValueFromPointerDeref(ACO->getTrueExpr()) || 20891c3d95ebSDavid Majnemer isGLValueFromPointerDeref(ACO->getFalseExpr()); 20901c3d95ebSDavid Majnemer 20911c3d95ebSDavid Majnemer // C++11 [expr.sub]p1: 20921c3d95ebSDavid Majnemer // The expression E1[E2] is identical (by definition) to *((E1)+(E2)) 20931c3d95ebSDavid Majnemer if (isa<ArraySubscriptExpr>(E)) 20941c3d95ebSDavid Majnemer return true; 20951c3d95ebSDavid Majnemer 20961c3d95ebSDavid Majnemer if (const auto *UO = dyn_cast<UnaryOperator>(E)) 20971c3d95ebSDavid Majnemer if (UO->getOpcode() == UO_Deref) 20981c3d95ebSDavid Majnemer return true; 20991c3d95ebSDavid Majnemer 21001c3d95ebSDavid Majnemer return false; 21011c3d95ebSDavid Majnemer } 21021c3d95ebSDavid Majnemer 2103747e301eSWarren Hunt static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E, 21042192fe50SChris Lattner llvm::Type *StdTypeInfoPtrTy) { 2105940f02d2SAnders Carlsson // Get the vtable pointer. 2106*f139ae3dSAkira Hatanaka Address ThisPtr = CGF.EmitLValue(E).getAddress(CGF); 2107940f02d2SAnders Carlsson 2108d71ad177SStephan Bergmann QualType SrcRecordTy = E->getType(); 2109d71ad177SStephan Bergmann 2110d71ad177SStephan Bergmann // C++ [class.cdtor]p4: 2111d71ad177SStephan Bergmann // If the operand of typeid refers to the object under construction or 2112d71ad177SStephan Bergmann // destruction and the static type of the operand is neither the constructor 2113d71ad177SStephan Bergmann // or destructor’s class nor one of its bases, the behavior is undefined. 2114d71ad177SStephan Bergmann CGF.EmitTypeCheck(CodeGenFunction::TCK_DynamicOperation, E->getExprLoc(), 2115d71ad177SStephan Bergmann ThisPtr.getPointer(), SrcRecordTy); 2116d71ad177SStephan Bergmann 2117940f02d2SAnders Carlsson // C++ [expr.typeid]p2: 2118940f02d2SAnders Carlsson // If the glvalue expression is obtained by applying the unary * operator to 2119940f02d2SAnders Carlsson // a pointer and the pointer is a null pointer value, the typeid expression 2120940f02d2SAnders Carlsson // throws the std::bad_typeid exception. 21211c3d95ebSDavid Majnemer // 21221c3d95ebSDavid Majnemer // However, this paragraph's intent is not clear. We choose a very generous 21231c3d95ebSDavid Majnemer // interpretation which implores us to consider comma operators, conditional 21241c3d95ebSDavid Majnemer // operators, parentheses and other such constructs. 21251c3d95ebSDavid Majnemer if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked( 21261c3d95ebSDavid Majnemer isGLValueFromPointerDeref(E), SrcRecordTy)) { 2127940f02d2SAnders Carlsson llvm::BasicBlock *BadTypeidBlock = 2128940f02d2SAnders Carlsson CGF.createBasicBlock("typeid.bad_typeid"); 21291162d25cSDavid Majnemer llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end"); 2130940f02d2SAnders Carlsson 21317f416cc4SJohn McCall llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr.getPointer()); 2132940f02d2SAnders Carlsson CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock); 2133940f02d2SAnders Carlsson 2134940f02d2SAnders Carlsson CGF.EmitBlock(BadTypeidBlock); 21351162d25cSDavid Majnemer CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF); 2136940f02d2SAnders Carlsson CGF.EmitBlock(EndBlock); 2137940f02d2SAnders Carlsson } 2138940f02d2SAnders Carlsson 21391162d25cSDavid Majnemer return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr, 21401162d25cSDavid Majnemer StdTypeInfoPtrTy); 2141940f02d2SAnders Carlsson } 2142940f02d2SAnders Carlsson 214359486a2dSAnders Carlsson llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) { 21442192fe50SChris Lattner llvm::Type *StdTypeInfoPtrTy = 2145940f02d2SAnders Carlsson ConvertType(E->getType())->getPointerTo(); 2146fd7dfeb7SAnders Carlsson 21473f4336cbSAnders Carlsson if (E->isTypeOperand()) { 21483f4336cbSAnders Carlsson llvm::Constant *TypeInfo = 2149143c55eaSDavid Majnemer CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext())); 2150940f02d2SAnders Carlsson return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy); 21513f4336cbSAnders Carlsson } 2152fd7dfeb7SAnders Carlsson 2153940f02d2SAnders Carlsson // C++ [expr.typeid]p2: 2154940f02d2SAnders Carlsson // When typeid is applied to a glvalue expression whose type is a 2155940f02d2SAnders Carlsson // polymorphic class type, the result refers to a std::type_info object 2156940f02d2SAnders Carlsson // representing the type of the most derived object (that is, the dynamic 2157940f02d2SAnders Carlsson // type) to which the glvalue refers. 2158ef8bf436SRichard Smith if (E->isPotentiallyEvaluated()) 2159940f02d2SAnders Carlsson return EmitTypeidFromVTable(*this, E->getExprOperand(), 2160940f02d2SAnders Carlsson StdTypeInfoPtrTy); 2161940f02d2SAnders Carlsson 2162940f02d2SAnders Carlsson QualType OperandTy = E->getExprOperand()->getType(); 2163940f02d2SAnders Carlsson return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy), 2164940f02d2SAnders Carlsson StdTypeInfoPtrTy); 216559486a2dSAnders Carlsson } 216659486a2dSAnders Carlsson 2167c1c9971cSAnders Carlsson static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF, 2168c1c9971cSAnders Carlsson QualType DestTy) { 21692192fe50SChris Lattner llvm::Type *DestLTy = CGF.ConvertType(DestTy); 2170c1c9971cSAnders Carlsson if (DestTy->isPointerType()) 2171c1c9971cSAnders Carlsson return llvm::Constant::getNullValue(DestLTy); 2172c1c9971cSAnders Carlsson 2173c1c9971cSAnders Carlsson /// C++ [expr.dynamic.cast]p9: 2174c1c9971cSAnders Carlsson /// A failed cast to reference type throws std::bad_cast 21751162d25cSDavid Majnemer if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF)) 21761162d25cSDavid Majnemer return nullptr; 2177c1c9971cSAnders Carlsson 2178c1c9971cSAnders Carlsson CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end")); 2179c1c9971cSAnders Carlsson return llvm::UndefValue::get(DestLTy); 2180c1c9971cSAnders Carlsson } 2181c1c9971cSAnders Carlsson 21827f416cc4SJohn McCall llvm::Value *CodeGenFunction::EmitDynamicCast(Address ThisAddr, 218359486a2dSAnders Carlsson const CXXDynamicCastExpr *DCE) { 21842bf9b4c0SAlexey Bataev CGM.EmitExplicitCastExprType(DCE, this); 21853f4336cbSAnders Carlsson QualType DestTy = DCE->getTypeAsWritten(); 21863f4336cbSAnders Carlsson 2187c1c9971cSAnders Carlsson QualType SrcTy = DCE->getSubExpr()->getType(); 2188c1c9971cSAnders Carlsson 21891162d25cSDavid Majnemer // C++ [expr.dynamic.cast]p7: 21901162d25cSDavid Majnemer // If T is "pointer to cv void," then the result is a pointer to the most 21911162d25cSDavid Majnemer // derived object pointed to by v. 21921162d25cSDavid Majnemer const PointerType *DestPTy = DestTy->getAs<PointerType>(); 21931162d25cSDavid Majnemer 21941162d25cSDavid Majnemer bool isDynamicCastToVoid; 21951162d25cSDavid Majnemer QualType SrcRecordTy; 21961162d25cSDavid Majnemer QualType DestRecordTy; 21971162d25cSDavid Majnemer if (DestPTy) { 21981162d25cSDavid Majnemer isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType(); 21991162d25cSDavid Majnemer SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType(); 22001162d25cSDavid Majnemer DestRecordTy = DestPTy->getPointeeType(); 22011162d25cSDavid Majnemer } else { 22021162d25cSDavid Majnemer isDynamicCastToVoid = false; 22031162d25cSDavid Majnemer SrcRecordTy = SrcTy; 22041162d25cSDavid Majnemer DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType(); 22051162d25cSDavid Majnemer } 22061162d25cSDavid Majnemer 2207d71ad177SStephan Bergmann // C++ [class.cdtor]p5: 2208d71ad177SStephan Bergmann // If the operand of the dynamic_cast refers to the object under 2209d71ad177SStephan Bergmann // construction or destruction and the static type of the operand is not a 2210d71ad177SStephan Bergmann // pointer to or object of the constructor or destructor’s own class or one 2211d71ad177SStephan Bergmann // of its bases, the dynamic_cast results in undefined behavior. 2212d71ad177SStephan Bergmann EmitTypeCheck(TCK_DynamicOperation, DCE->getExprLoc(), ThisAddr.getPointer(), 2213d71ad177SStephan Bergmann SrcRecordTy); 2214d71ad177SStephan Bergmann 2215d71ad177SStephan Bergmann if (DCE->isAlwaysNull()) 2216d71ad177SStephan Bergmann if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy)) 2217d71ad177SStephan Bergmann return T; 2218d71ad177SStephan Bergmann 22191162d25cSDavid Majnemer assert(SrcRecordTy->isRecordType() && "source type must be a record type!"); 22201162d25cSDavid Majnemer 2221882d790fSAnders Carlsson // C++ [expr.dynamic.cast]p4: 2222882d790fSAnders Carlsson // If the value of v is a null pointer value in the pointer case, the result 2223882d790fSAnders Carlsson // is the null pointer value of type T. 22241162d25cSDavid Majnemer bool ShouldNullCheckSrcValue = 22251162d25cSDavid Majnemer CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(), 22261162d25cSDavid Majnemer SrcRecordTy); 222759486a2dSAnders Carlsson 22288a13c418SCraig Topper llvm::BasicBlock *CastNull = nullptr; 22298a13c418SCraig Topper llvm::BasicBlock *CastNotNull = nullptr; 2230882d790fSAnders Carlsson llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end"); 2231fa8b4955SDouglas Gregor 2232882d790fSAnders Carlsson if (ShouldNullCheckSrcValue) { 2233882d790fSAnders Carlsson CastNull = createBasicBlock("dynamic_cast.null"); 2234882d790fSAnders Carlsson CastNotNull = createBasicBlock("dynamic_cast.notnull"); 2235882d790fSAnders Carlsson 22367f416cc4SJohn McCall llvm::Value *IsNull = Builder.CreateIsNull(ThisAddr.getPointer()); 2237882d790fSAnders Carlsson Builder.CreateCondBr(IsNull, CastNull, CastNotNull); 2238882d790fSAnders Carlsson EmitBlock(CastNotNull); 223959486a2dSAnders Carlsson } 224059486a2dSAnders Carlsson 22417f416cc4SJohn McCall llvm::Value *Value; 22421162d25cSDavid Majnemer if (isDynamicCastToVoid) { 22437f416cc4SJohn McCall Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, ThisAddr, SrcRecordTy, 22441162d25cSDavid Majnemer DestTy); 22451162d25cSDavid Majnemer } else { 22461162d25cSDavid Majnemer assert(DestRecordTy->isRecordType() && 22471162d25cSDavid Majnemer "destination type must be a record type!"); 22487f416cc4SJohn McCall Value = CGM.getCXXABI().EmitDynamicCastCall(*this, ThisAddr, SrcRecordTy, 22491162d25cSDavid Majnemer DestTy, DestRecordTy, CastEnd); 225067528eaaSDavid Majnemer CastNotNull = Builder.GetInsertBlock(); 22511162d25cSDavid Majnemer } 22523f4336cbSAnders Carlsson 2253882d790fSAnders Carlsson if (ShouldNullCheckSrcValue) { 2254882d790fSAnders Carlsson EmitBranch(CastEnd); 225559486a2dSAnders Carlsson 2256882d790fSAnders Carlsson EmitBlock(CastNull); 2257882d790fSAnders Carlsson EmitBranch(CastEnd); 225859486a2dSAnders Carlsson } 225959486a2dSAnders Carlsson 2260882d790fSAnders Carlsson EmitBlock(CastEnd); 226159486a2dSAnders Carlsson 2262882d790fSAnders Carlsson if (ShouldNullCheckSrcValue) { 2263882d790fSAnders Carlsson llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2); 2264882d790fSAnders Carlsson PHI->addIncoming(Value, CastNotNull); 2265882d790fSAnders Carlsson PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull); 226659486a2dSAnders Carlsson 2267882d790fSAnders Carlsson Value = PHI; 226859486a2dSAnders Carlsson } 226959486a2dSAnders Carlsson 2270882d790fSAnders Carlsson return Value; 227159486a2dSAnders Carlsson } 2272