159486a2dSAnders Carlsson //===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===// 259486a2dSAnders Carlsson // 359486a2dSAnders Carlsson // The LLVM Compiler Infrastructure 459486a2dSAnders Carlsson // 559486a2dSAnders Carlsson // This file is distributed under the University of Illinois Open Source 659486a2dSAnders Carlsson // License. See LICENSE.TXT for details. 759486a2dSAnders Carlsson // 859486a2dSAnders Carlsson //===----------------------------------------------------------------------===// 959486a2dSAnders Carlsson // 1059486a2dSAnders Carlsson // This contains code dealing with code generation of C++ expressions 1159486a2dSAnders Carlsson // 1259486a2dSAnders Carlsson //===----------------------------------------------------------------------===// 1359486a2dSAnders Carlsson 1459486a2dSAnders Carlsson #include "CodeGenFunction.h" 15fe883422SPeter Collingbourne #include "CGCUDARuntime.h" 165d865c32SJohn McCall #include "CGCXXABI.h" 1791bbb554SDevang Patel #include "CGDebugInfo.h" 183a02247dSChandler Carruth #include "CGObjCRuntime.h" 19a8e7df36SMark Lacey #include "clang/CodeGen/CGFunctionInfo.h" 2010a4972aSSaleem Abdulrasool #include "clang/Frontend/CodeGenOptions.h" 21c80ceea9SChandler Carruth #include "llvm/IR/CallSite.h" 22ffd5551bSChandler Carruth #include "llvm/IR/Intrinsics.h" 23bbe277c4SAnders Carlsson 2459486a2dSAnders Carlsson using namespace clang; 2559486a2dSAnders Carlsson using namespace CodeGen; 2659486a2dSAnders Carlsson 27efa956ceSAlexey Samsonov static RequiredArgs 28efa956ceSAlexey Samsonov commonEmitCXXMemberOrOperatorCall(CodeGenFunction &CGF, const CXXMethodDecl *MD, 29efa956ceSAlexey Samsonov llvm::Value *This, llvm::Value *ImplicitParam, 30efa956ceSAlexey Samsonov QualType ImplicitParamTy, const CallExpr *CE, 31762672a7SRichard Smith CallArgList &Args, CallArgList *RtlArgs) { 32a5bf76bdSAlexey Samsonov assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) || 33a5bf76bdSAlexey Samsonov isa<CXXOperatorCallExpr>(CE)); 3427da15baSAnders Carlsson assert(MD->isInstance() && 35a5bf76bdSAlexey Samsonov "Trying to emit a member or operator call expr on a static method!"); 36034e7270SReid Kleckner ASTContext &C = CGF.getContext(); 3727da15baSAnders Carlsson 3869d0d262SRichard Smith // C++11 [class.mfct.non-static]p2: 3969d0d262SRichard Smith // If a non-static member function of a class X is called for an object that 4069d0d262SRichard Smith // is not of type X, or of a type derived from X, the behavior is undefined. 41a5bf76bdSAlexey Samsonov SourceLocation CallLoc; 42a5bf76bdSAlexey Samsonov if (CE) 43a5bf76bdSAlexey Samsonov CallLoc = CE->getExprLoc(); 44034e7270SReid Kleckner CGF.EmitTypeCheck(isa<CXXConstructorDecl>(MD) 45034e7270SReid Kleckner ? CodeGenFunction::TCK_ConstructorCall 460c0b6d9aSDavid Majnemer : CodeGenFunction::TCK_MemberCall, 47034e7270SReid Kleckner CallLoc, This, C.getRecordType(MD->getParent())); 4827da15baSAnders Carlsson 4927da15baSAnders Carlsson // Push the this ptr. 50034e7270SReid Kleckner const CXXRecordDecl *RD = 51034e7270SReid Kleckner CGF.CGM.getCXXABI().getThisArgumentTypeForMethod(MD); 52034e7270SReid Kleckner Args.add(RValue::get(This), 53034e7270SReid Kleckner RD ? C.getPointerType(C.getTypeDeclType(RD)) : C.VoidPtrTy); 5427da15baSAnders Carlsson 55ee6bc533STimur Iskhodzhanov // If there is an implicit parameter (e.g. VTT), emit it. 56ee6bc533STimur Iskhodzhanov if (ImplicitParam) { 57ee6bc533STimur Iskhodzhanov Args.add(RValue::get(ImplicitParam), ImplicitParamTy); 58e36a6b3eSAnders Carlsson } 59e36a6b3eSAnders Carlsson 60a729c62bSJohn McCall const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 61419996ccSGeorge Burgess IV RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size(), MD); 62a729c62bSJohn McCall 63a729c62bSJohn McCall // And the rest of the call args. 64762672a7SRichard Smith if (RtlArgs) { 65762672a7SRichard Smith // Special case: if the caller emitted the arguments right-to-left already 66762672a7SRichard Smith // (prior to emitting the *this argument), we're done. This happens for 67762672a7SRichard Smith // assignment operators. 68762672a7SRichard Smith Args.addFrom(*RtlArgs); 69762672a7SRichard Smith } else if (CE) { 70a5bf76bdSAlexey Samsonov // Special case: skip first argument of CXXOperatorCall (it is "this"). 718e1162c7SAlexey Samsonov unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0; 72f05779e2SDavid Blaikie CGF.EmitCallArgs(Args, FPT, drop_begin(CE->arguments(), ArgsToSkip), 738e1162c7SAlexey Samsonov CE->getDirectCallee()); 74a5bf76bdSAlexey Samsonov } else { 758e1162c7SAlexey Samsonov assert( 768e1162c7SAlexey Samsonov FPT->getNumParams() == 0 && 778e1162c7SAlexey Samsonov "No CallExpr specified for function with non-zero number of arguments"); 78a5bf76bdSAlexey Samsonov } 790c0b6d9aSDavid Majnemer return required; 800c0b6d9aSDavid Majnemer } 8127da15baSAnders Carlsson 820c0b6d9aSDavid Majnemer RValue CodeGenFunction::EmitCXXMemberOrOperatorCall( 83*b92ab1afSJohn McCall const CXXMethodDecl *MD, const CGCallee &Callee, 84*b92ab1afSJohn McCall ReturnValueSlot ReturnValue, 850c0b6d9aSDavid Majnemer llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy, 86762672a7SRichard Smith const CallExpr *CE, CallArgList *RtlArgs) { 870c0b6d9aSDavid Majnemer const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 880c0b6d9aSDavid Majnemer CallArgList Args; 890c0b6d9aSDavid Majnemer RequiredArgs required = commonEmitCXXMemberOrOperatorCall( 90762672a7SRichard Smith *this, MD, This, ImplicitParam, ImplicitParamTy, CE, Args, RtlArgs); 91*b92ab1afSJohn McCall auto &FnInfo = CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required); 92*b92ab1afSJohn McCall return EmitCall(FnInfo, Callee, ReturnValue, Args); 9327da15baSAnders Carlsson } 9427da15baSAnders Carlsson 95ae81bbb4SAlexey Samsonov RValue CodeGenFunction::EmitCXXDestructorCall( 96*b92ab1afSJohn McCall const CXXDestructorDecl *DD, const CGCallee &Callee, llvm::Value *This, 97ae81bbb4SAlexey Samsonov llvm::Value *ImplicitParam, QualType ImplicitParamTy, const CallExpr *CE, 98ae81bbb4SAlexey Samsonov StructorType Type) { 990c0b6d9aSDavid Majnemer CallArgList Args; 100ae81bbb4SAlexey Samsonov commonEmitCXXMemberOrOperatorCall(*this, DD, This, ImplicitParam, 101762672a7SRichard Smith ImplicitParamTy, CE, Args, nullptr); 102ae81bbb4SAlexey Samsonov return EmitCall(CGM.getTypes().arrangeCXXStructorDeclaration(DD, Type), 103*b92ab1afSJohn McCall Callee, ReturnValueSlot(), Args); 104*b92ab1afSJohn McCall } 105*b92ab1afSJohn McCall 106*b92ab1afSJohn McCall RValue CodeGenFunction::EmitCXXPseudoDestructorExpr( 107*b92ab1afSJohn McCall const CXXPseudoDestructorExpr *E) { 108*b92ab1afSJohn McCall QualType DestroyedType = E->getDestroyedType(); 109*b92ab1afSJohn McCall if (DestroyedType.hasStrongOrWeakObjCLifetime()) { 110*b92ab1afSJohn McCall // Automatic Reference Counting: 111*b92ab1afSJohn McCall // If the pseudo-expression names a retainable object with weak or 112*b92ab1afSJohn McCall // strong lifetime, the object shall be released. 113*b92ab1afSJohn McCall Expr *BaseExpr = E->getBase(); 114*b92ab1afSJohn McCall Address BaseValue = Address::invalid(); 115*b92ab1afSJohn McCall Qualifiers BaseQuals; 116*b92ab1afSJohn McCall 117*b92ab1afSJohn McCall // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar. 118*b92ab1afSJohn McCall if (E->isArrow()) { 119*b92ab1afSJohn McCall BaseValue = EmitPointerWithAlignment(BaseExpr); 120*b92ab1afSJohn McCall const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>(); 121*b92ab1afSJohn McCall BaseQuals = PTy->getPointeeType().getQualifiers(); 122*b92ab1afSJohn McCall } else { 123*b92ab1afSJohn McCall LValue BaseLV = EmitLValue(BaseExpr); 124*b92ab1afSJohn McCall BaseValue = BaseLV.getAddress(); 125*b92ab1afSJohn McCall QualType BaseTy = BaseExpr->getType(); 126*b92ab1afSJohn McCall BaseQuals = BaseTy.getQualifiers(); 127*b92ab1afSJohn McCall } 128*b92ab1afSJohn McCall 129*b92ab1afSJohn McCall switch (DestroyedType.getObjCLifetime()) { 130*b92ab1afSJohn McCall case Qualifiers::OCL_None: 131*b92ab1afSJohn McCall case Qualifiers::OCL_ExplicitNone: 132*b92ab1afSJohn McCall case Qualifiers::OCL_Autoreleasing: 133*b92ab1afSJohn McCall break; 134*b92ab1afSJohn McCall 135*b92ab1afSJohn McCall case Qualifiers::OCL_Strong: 136*b92ab1afSJohn McCall EmitARCRelease(Builder.CreateLoad(BaseValue, 137*b92ab1afSJohn McCall DestroyedType.isVolatileQualified()), 138*b92ab1afSJohn McCall ARCPreciseLifetime); 139*b92ab1afSJohn McCall break; 140*b92ab1afSJohn McCall 141*b92ab1afSJohn McCall case Qualifiers::OCL_Weak: 142*b92ab1afSJohn McCall EmitARCDestroyWeak(BaseValue); 143*b92ab1afSJohn McCall break; 144*b92ab1afSJohn McCall } 145*b92ab1afSJohn McCall } else { 146*b92ab1afSJohn McCall // C++ [expr.pseudo]p1: 147*b92ab1afSJohn McCall // The result shall only be used as the operand for the function call 148*b92ab1afSJohn McCall // operator (), and the result of such a call has type void. The only 149*b92ab1afSJohn McCall // effect is the evaluation of the postfix-expression before the dot or 150*b92ab1afSJohn McCall // arrow. 151*b92ab1afSJohn McCall EmitIgnoredExpr(E->getBase()); 152*b92ab1afSJohn McCall } 153*b92ab1afSJohn McCall 154*b92ab1afSJohn McCall return RValue::get(nullptr); 1550c0b6d9aSDavid Majnemer } 1560c0b6d9aSDavid Majnemer 1573b33c4ecSRafael Espindola static CXXRecordDecl *getCXXRecord(const Expr *E) { 1583b33c4ecSRafael Espindola QualType T = E->getType(); 1593b33c4ecSRafael Espindola if (const PointerType *PTy = T->getAs<PointerType>()) 1603b33c4ecSRafael Espindola T = PTy->getPointeeType(); 1613b33c4ecSRafael Espindola const RecordType *Ty = T->castAs<RecordType>(); 1623b33c4ecSRafael Espindola return cast<CXXRecordDecl>(Ty->getDecl()); 1633b33c4ecSRafael Espindola } 1643b33c4ecSRafael Espindola 16564225794SFrancois Pichet // Note: This function also emit constructor calls to support a MSVC 16664225794SFrancois Pichet // extensions allowing explicit constructor function call. 16727da15baSAnders Carlsson RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE, 16827da15baSAnders Carlsson ReturnValueSlot ReturnValue) { 1692d2e8707SJohn McCall const Expr *callee = CE->getCallee()->IgnoreParens(); 1702d2e8707SJohn McCall 1712d2e8707SJohn McCall if (isa<BinaryOperator>(callee)) 17227da15baSAnders Carlsson return EmitCXXMemberPointerCallExpr(CE, ReturnValue); 17327da15baSAnders Carlsson 1742d2e8707SJohn McCall const MemberExpr *ME = cast<MemberExpr>(callee); 17527da15baSAnders Carlsson const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl()); 17627da15baSAnders Carlsson 17727da15baSAnders Carlsson if (MD->isStatic()) { 17827da15baSAnders Carlsson // The method is static, emit it as we would a regular call. 179*b92ab1afSJohn McCall CGCallee callee = CGCallee::forDirect(CGM.GetAddrOfFunction(MD), MD); 180*b92ab1afSJohn McCall return EmitCall(getContext().getPointerType(MD->getType()), callee, CE, 18170b9c01bSAlexey Samsonov ReturnValue); 18227da15baSAnders Carlsson } 18327da15baSAnders Carlsson 184aad4af6dSNico Weber bool HasQualifier = ME->hasQualifier(); 185aad4af6dSNico Weber NestedNameSpecifier *Qualifier = HasQualifier ? ME->getQualifier() : nullptr; 186aad4af6dSNico Weber bool IsArrow = ME->isArrow(); 187ecbe2e97SRafael Espindola const Expr *Base = ME->getBase(); 188aad4af6dSNico Weber 189aad4af6dSNico Weber return EmitCXXMemberOrOperatorMemberCallExpr( 190aad4af6dSNico Weber CE, MD, ReturnValue, HasQualifier, Qualifier, IsArrow, Base); 191aad4af6dSNico Weber } 192aad4af6dSNico Weber 193aad4af6dSNico Weber RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr( 194aad4af6dSNico Weber const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue, 195aad4af6dSNico Weber bool HasQualifier, NestedNameSpecifier *Qualifier, bool IsArrow, 196aad4af6dSNico Weber const Expr *Base) { 197aad4af6dSNico Weber assert(isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE)); 198aad4af6dSNico Weber 199aad4af6dSNico Weber // Compute the object pointer. 200aad4af6dSNico Weber bool CanUseVirtualCall = MD->isVirtual() && !HasQualifier; 201ecbe2e97SRafael Espindola 2028a13c418SCraig Topper const CXXMethodDecl *DevirtualizedMethod = nullptr; 2037463ed7cSBenjamin Kramer if (CanUseVirtualCall && CanDevirtualizeMemberFunctionCall(Base, MD)) { 2043b33c4ecSRafael Espindola const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType(); 2053b33c4ecSRafael Espindola DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl); 2063b33c4ecSRafael Espindola assert(DevirtualizedMethod); 2073b33c4ecSRafael Espindola const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent(); 2083b33c4ecSRafael Espindola const Expr *Inner = Base->ignoreParenBaseCasts(); 2095bd68794SAlexey Bataev if (DevirtualizedMethod->getReturnType().getCanonicalType() != 2105bd68794SAlexey Bataev MD->getReturnType().getCanonicalType()) 2115bd68794SAlexey Bataev // If the return types are not the same, this might be a case where more 2125bd68794SAlexey Bataev // code needs to run to compensate for it. For example, the derived 2135bd68794SAlexey Bataev // method might return a type that inherits form from the return 2145bd68794SAlexey Bataev // type of MD and has a prefix. 2155bd68794SAlexey Bataev // For now we just avoid devirtualizing these covariant cases. 2165bd68794SAlexey Bataev DevirtualizedMethod = nullptr; 2175bd68794SAlexey Bataev else if (getCXXRecord(Inner) == DevirtualizedClass) 2183b33c4ecSRafael Espindola // If the class of the Inner expression is where the dynamic method 2193b33c4ecSRafael Espindola // is defined, build the this pointer from it. 2203b33c4ecSRafael Espindola Base = Inner; 2213b33c4ecSRafael Espindola else if (getCXXRecord(Base) != DevirtualizedClass) { 2223b33c4ecSRafael Espindola // If the method is defined in a class that is not the best dynamic 2233b33c4ecSRafael Espindola // one or the one of the full expression, we would have to build 2243b33c4ecSRafael Espindola // a derived-to-base cast to compute the correct this pointer, but 2253b33c4ecSRafael Espindola // we don't have support for that yet, so do a virtual call. 2268a13c418SCraig Topper DevirtualizedMethod = nullptr; 2273b33c4ecSRafael Espindola } 2283b33c4ecSRafael Espindola } 229ecbe2e97SRafael Espindola 230762672a7SRichard Smith // C++17 demands that we evaluate the RHS of a (possibly-compound) assignment 231762672a7SRichard Smith // operator before the LHS. 232762672a7SRichard Smith CallArgList RtlArgStorage; 233762672a7SRichard Smith CallArgList *RtlArgs = nullptr; 234762672a7SRichard Smith if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(CE)) { 235762672a7SRichard Smith if (OCE->isAssignmentOp()) { 236762672a7SRichard Smith RtlArgs = &RtlArgStorage; 237762672a7SRichard Smith EmitCallArgs(*RtlArgs, MD->getType()->castAs<FunctionProtoType>(), 238762672a7SRichard Smith drop_begin(CE->arguments(), 1), CE->getDirectCallee(), 239a560ccf2SRichard Smith /*ParamsToSkip*/0, EvaluationOrder::ForceRightToLeft); 240762672a7SRichard Smith } 241762672a7SRichard Smith } 242762672a7SRichard Smith 2437f416cc4SJohn McCall Address This = Address::invalid(); 244aad4af6dSNico Weber if (IsArrow) 2457f416cc4SJohn McCall This = EmitPointerWithAlignment(Base); 246f93ac894SFariborz Jahanian else 2473b33c4ecSRafael Espindola This = EmitLValue(Base).getAddress(); 248ecbe2e97SRafael Espindola 24927da15baSAnders Carlsson 250419bd094SRichard Smith if (MD->isTrivial() || (MD->isDefaulted() && MD->getParent()->isUnion())) { 2518a13c418SCraig Topper if (isa<CXXDestructorDecl>(MD)) return RValue::get(nullptr); 25264225794SFrancois Pichet if (isa<CXXConstructorDecl>(MD) && 25364225794SFrancois Pichet cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) 2548a13c418SCraig Topper return RValue::get(nullptr); 2550d635f53SJohn McCall 256aad4af6dSNico Weber if (!MD->getParent()->mayInsertExtraPadding()) { 25722653bacSSebastian Redl if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) { 25822653bacSSebastian Redl // We don't like to generate the trivial copy/move assignment operator 25922653bacSSebastian Redl // when it isn't necessary; just produce the proper effect here. 260762672a7SRichard Smith LValue RHS = isa<CXXOperatorCallExpr>(CE) 261762672a7SRichard Smith ? MakeNaturalAlignAddrLValue( 262762672a7SRichard Smith (*RtlArgs)[0].RV.getScalarVal(), 263762672a7SRichard Smith (*(CE->arg_begin() + 1))->getType()) 264762672a7SRichard Smith : EmitLValue(*CE->arg_begin()); 265762672a7SRichard Smith EmitAggregateAssign(This, RHS.getAddress(), CE->getType()); 2667f416cc4SJohn McCall return RValue::get(This.getPointer()); 26727da15baSAnders Carlsson } 26827da15baSAnders Carlsson 26964225794SFrancois Pichet if (isa<CXXConstructorDecl>(MD) && 27022653bacSSebastian Redl cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) { 27122653bacSSebastian Redl // Trivial move and copy ctor are the same. 272525bf650SAlexey Samsonov assert(CE->getNumArgs() == 1 && "unexpected argcount for trivial ctor"); 2737f416cc4SJohn McCall Address RHS = EmitLValue(*CE->arg_begin()).getAddress(); 274f48ee448SBenjamin Kramer EmitAggregateCopy(This, RHS, (*CE->arg_begin())->getType()); 2757f416cc4SJohn McCall return RValue::get(This.getPointer()); 27664225794SFrancois Pichet } 27764225794SFrancois Pichet llvm_unreachable("unknown trivial member function"); 27864225794SFrancois Pichet } 279aad4af6dSNico Weber } 28064225794SFrancois Pichet 2810d635f53SJohn McCall // Compute the function type we're calling. 2823abfe958SNico Weber const CXXMethodDecl *CalleeDecl = 2833abfe958SNico Weber DevirtualizedMethod ? DevirtualizedMethod : MD; 2848a13c418SCraig Topper const CGFunctionInfo *FInfo = nullptr; 2853abfe958SNico Weber if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl)) 2868d2a19b4SRafael Espindola FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration( 2878d2a19b4SRafael Espindola Dtor, StructorType::Complete); 2883abfe958SNico Weber else if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(CalleeDecl)) 2898d2a19b4SRafael Espindola FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration( 2908d2a19b4SRafael Espindola Ctor, StructorType::Complete); 29164225794SFrancois Pichet else 292ade60977SEli Friedman FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl); 2930d635f53SJohn McCall 294e7de47efSReid Kleckner llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo); 2950d635f53SJohn McCall 296018f266bSVedant Kumar // FIXME: Uses of 'MD' past this point need to be audited. We may need to use 297018f266bSVedant Kumar // 'CalleeDecl' instead. 298018f266bSVedant Kumar 29927da15baSAnders Carlsson // C++ [class.virtual]p12: 30027da15baSAnders Carlsson // Explicit qualification with the scope operator (5.1) suppresses the 30127da15baSAnders Carlsson // virtual call mechanism. 30227da15baSAnders Carlsson // 30327da15baSAnders Carlsson // We also don't emit a virtual call if the base expression has a record type 30427da15baSAnders Carlsson // because then we know what the type is. 3053b33c4ecSRafael Espindola bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod; 3069dc6eef7SStephen Lin 3070d635f53SJohn McCall if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) { 30819cee187SStephen Lin assert(CE->arg_begin() == CE->arg_end() && 3099dc6eef7SStephen Lin "Destructor shouldn't have explicit parameters"); 3109dc6eef7SStephen Lin assert(ReturnValue.isNull() && "Destructor shouldn't have return value"); 3119dc6eef7SStephen Lin if (UseVirtualCall) { 312aad4af6dSNico Weber CGM.getCXXABI().EmitVirtualDestructorCall( 313aad4af6dSNico Weber *this, Dtor, Dtor_Complete, This, cast<CXXMemberCallExpr>(CE)); 31427da15baSAnders Carlsson } else { 315*b92ab1afSJohn McCall CGCallee Callee; 316aad4af6dSNico Weber if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier) 317aad4af6dSNico Weber Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty); 3183b33c4ecSRafael Espindola else if (!DevirtualizedMethod) 319*b92ab1afSJohn McCall Callee = CGCallee::forDirect( 320*b92ab1afSJohn McCall CGM.getAddrOfCXXStructor(Dtor, StructorType::Complete, FInfo, Ty), 321*b92ab1afSJohn McCall Dtor); 32249e860b2SRafael Espindola else { 3233b33c4ecSRafael Espindola const CXXDestructorDecl *DDtor = 3243b33c4ecSRafael Espindola cast<CXXDestructorDecl>(DevirtualizedMethod); 325*b92ab1afSJohn McCall Callee = CGCallee::forDirect( 326*b92ab1afSJohn McCall CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty), 327*b92ab1afSJohn McCall DDtor); 32849e860b2SRafael Espindola } 329018f266bSVedant Kumar EmitCXXMemberOrOperatorCall( 330018f266bSVedant Kumar CalleeDecl, Callee, ReturnValue, This.getPointer(), 331018f266bSVedant Kumar /*ImplicitParam=*/nullptr, QualType(), CE, nullptr); 33227da15baSAnders Carlsson } 3338a13c418SCraig Topper return RValue::get(nullptr); 3349dc6eef7SStephen Lin } 3359dc6eef7SStephen Lin 336*b92ab1afSJohn McCall CGCallee Callee; 3379dc6eef7SStephen Lin if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 338*b92ab1afSJohn McCall Callee = CGCallee::forDirect( 339*b92ab1afSJohn McCall CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty), 340*b92ab1afSJohn McCall Ctor); 3410d635f53SJohn McCall } else if (UseVirtualCall) { 3426708c4a1SPeter Collingbourne Callee = CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, Ty, 3436708c4a1SPeter Collingbourne CE->getLocStart()); 34427da15baSAnders Carlsson } else { 3451a7488afSPeter Collingbourne if (SanOpts.has(SanitizerKind::CFINVCall) && 3461a7488afSPeter Collingbourne MD->getParent()->isDynamicClass()) { 3474b1ac72cSPiotr Padlewski llvm::Value *VTable = GetVTablePtr(This, Int8PtrTy, MD->getParent()); 348fb532b9aSPeter Collingbourne EmitVTablePtrCheckForCall(MD->getParent(), VTable, CFITCK_NVCall, 349fb532b9aSPeter Collingbourne CE->getLocStart()); 3501a7488afSPeter Collingbourne } 3511a7488afSPeter Collingbourne 352aad4af6dSNico Weber if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier) 353aad4af6dSNico Weber Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty); 3543b33c4ecSRafael Espindola else if (!DevirtualizedMethod) 355*b92ab1afSJohn McCall Callee = CGCallee::forDirect(CGM.GetAddrOfFunction(MD, Ty), MD); 35649e860b2SRafael Espindola else { 357*b92ab1afSJohn McCall Callee = CGCallee::forDirect( 358*b92ab1afSJohn McCall CGM.GetAddrOfFunction(DevirtualizedMethod, Ty), 359*b92ab1afSJohn McCall DevirtualizedMethod); 36049e860b2SRafael Espindola } 36127da15baSAnders Carlsson } 36227da15baSAnders Carlsson 363f1749427STimur Iskhodzhanov if (MD->isVirtual()) { 364f1749427STimur Iskhodzhanov This = CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall( 3654b60f30aSReid Kleckner *this, CalleeDecl, This, UseVirtualCall); 366f1749427STimur Iskhodzhanov } 36788fd439aSTimur Iskhodzhanov 368018f266bSVedant Kumar return EmitCXXMemberOrOperatorCall( 369018f266bSVedant Kumar CalleeDecl, Callee, ReturnValue, This.getPointer(), 370018f266bSVedant Kumar /*ImplicitParam=*/nullptr, QualType(), CE, RtlArgs); 37127da15baSAnders Carlsson } 37227da15baSAnders Carlsson 37327da15baSAnders Carlsson RValue 37427da15baSAnders Carlsson CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E, 37527da15baSAnders Carlsson ReturnValueSlot ReturnValue) { 37627da15baSAnders Carlsson const BinaryOperator *BO = 37727da15baSAnders Carlsson cast<BinaryOperator>(E->getCallee()->IgnoreParens()); 37827da15baSAnders Carlsson const Expr *BaseExpr = BO->getLHS(); 37927da15baSAnders Carlsson const Expr *MemFnExpr = BO->getRHS(); 38027da15baSAnders Carlsson 38127da15baSAnders Carlsson const MemberPointerType *MPT = 3820009fcc3SJohn McCall MemFnExpr->getType()->castAs<MemberPointerType>(); 383475999dcSJohn McCall 38427da15baSAnders Carlsson const FunctionProtoType *FPT = 3850009fcc3SJohn McCall MPT->getPointeeType()->castAs<FunctionProtoType>(); 38627da15baSAnders Carlsson const CXXRecordDecl *RD = 38727da15baSAnders Carlsson cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl()); 38827da15baSAnders Carlsson 38927da15baSAnders Carlsson // Emit the 'this' pointer. 3907f416cc4SJohn McCall Address This = Address::invalid(); 391e302792bSJohn McCall if (BO->getOpcode() == BO_PtrMemI) 3927f416cc4SJohn McCall This = EmitPointerWithAlignment(BaseExpr); 39327da15baSAnders Carlsson else 39427da15baSAnders Carlsson This = EmitLValue(BaseExpr).getAddress(); 39527da15baSAnders Carlsson 3967f416cc4SJohn McCall EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This.getPointer(), 397e30752c9SRichard Smith QualType(MPT->getClass(), 0)); 39869d0d262SRichard Smith 399bde62d78SRichard Smith // Get the member function pointer. 400bde62d78SRichard Smith llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr); 401bde62d78SRichard Smith 402475999dcSJohn McCall // Ask the ABI to load the callee. Note that This is modified. 4037f416cc4SJohn McCall llvm::Value *ThisPtrForCall = nullptr; 404*b92ab1afSJohn McCall CGCallee Callee = 4057f416cc4SJohn McCall CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This, 4067f416cc4SJohn McCall ThisPtrForCall, MemFnPtr, MPT); 40727da15baSAnders Carlsson 40827da15baSAnders Carlsson CallArgList Args; 40927da15baSAnders Carlsson 41027da15baSAnders Carlsson QualType ThisType = 41127da15baSAnders Carlsson getContext().getPointerType(getContext().getTagDeclType(RD)); 41227da15baSAnders Carlsson 41327da15baSAnders Carlsson // Push the this ptr. 4147f416cc4SJohn McCall Args.add(RValue::get(ThisPtrForCall), ThisType); 41527da15baSAnders Carlsson 416419996ccSGeorge Burgess IV RequiredArgs required = 417419996ccSGeorge Burgess IV RequiredArgs::forPrototypePlus(FPT, 1, /*FD=*/nullptr); 4188dda7b27SJohn McCall 41927da15baSAnders Carlsson // And the rest of the call args 420419996ccSGeorge Burgess IV EmitCallArgs(Args, FPT, E->arguments()); 4215fa40c3bSNick Lewycky return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required), 4225fa40c3bSNick Lewycky Callee, ReturnValue, Args); 42327da15baSAnders Carlsson } 42427da15baSAnders Carlsson 42527da15baSAnders Carlsson RValue 42627da15baSAnders Carlsson CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E, 42727da15baSAnders Carlsson const CXXMethodDecl *MD, 42827da15baSAnders Carlsson ReturnValueSlot ReturnValue) { 42927da15baSAnders Carlsson assert(MD->isInstance() && 43027da15baSAnders Carlsson "Trying to emit a member call expr on a static method!"); 431aad4af6dSNico Weber return EmitCXXMemberOrOperatorMemberCallExpr( 432aad4af6dSNico Weber E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr, 433aad4af6dSNico Weber /*IsArrow=*/false, E->getArg(0)); 43427da15baSAnders Carlsson } 43527da15baSAnders Carlsson 436fe883422SPeter Collingbourne RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E, 437fe883422SPeter Collingbourne ReturnValueSlot ReturnValue) { 438fe883422SPeter Collingbourne return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue); 439fe883422SPeter Collingbourne } 440fe883422SPeter Collingbourne 441fde961dbSEli Friedman static void EmitNullBaseClassInitialization(CodeGenFunction &CGF, 4427f416cc4SJohn McCall Address DestPtr, 443fde961dbSEli Friedman const CXXRecordDecl *Base) { 444fde961dbSEli Friedman if (Base->isEmpty()) 445fde961dbSEli Friedman return; 446fde961dbSEli Friedman 4477f416cc4SJohn McCall DestPtr = CGF.Builder.CreateElementBitCast(DestPtr, CGF.Int8Ty); 448fde961dbSEli Friedman 449fde961dbSEli Friedman const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base); 4508671c6e0SDavid Majnemer CharUnits NVSize = Layout.getNonVirtualSize(); 4518671c6e0SDavid Majnemer 4528671c6e0SDavid Majnemer // We cannot simply zero-initialize the entire base sub-object if vbptrs are 4538671c6e0SDavid Majnemer // present, they are initialized by the most derived class before calling the 4548671c6e0SDavid Majnemer // constructor. 4558671c6e0SDavid Majnemer SmallVector<std::pair<CharUnits, CharUnits>, 1> Stores; 4568671c6e0SDavid Majnemer Stores.emplace_back(CharUnits::Zero(), NVSize); 4578671c6e0SDavid Majnemer 4588671c6e0SDavid Majnemer // Each store is split by the existence of a vbptr. 4598671c6e0SDavid Majnemer CharUnits VBPtrWidth = CGF.getPointerSize(); 4608671c6e0SDavid Majnemer std::vector<CharUnits> VBPtrOffsets = 4618671c6e0SDavid Majnemer CGF.CGM.getCXXABI().getVBPtrOffsets(Base); 4628671c6e0SDavid Majnemer for (CharUnits VBPtrOffset : VBPtrOffsets) { 4637f980d84SDavid Majnemer // Stop before we hit any virtual base pointers located in virtual bases. 4647f980d84SDavid Majnemer if (VBPtrOffset >= NVSize) 4657f980d84SDavid Majnemer break; 4668671c6e0SDavid Majnemer std::pair<CharUnits, CharUnits> LastStore = Stores.pop_back_val(); 4678671c6e0SDavid Majnemer CharUnits LastStoreOffset = LastStore.first; 4688671c6e0SDavid Majnemer CharUnits LastStoreSize = LastStore.second; 4698671c6e0SDavid Majnemer 4708671c6e0SDavid Majnemer CharUnits SplitBeforeOffset = LastStoreOffset; 4718671c6e0SDavid Majnemer CharUnits SplitBeforeSize = VBPtrOffset - SplitBeforeOffset; 4728671c6e0SDavid Majnemer assert(!SplitBeforeSize.isNegative() && "negative store size!"); 4738671c6e0SDavid Majnemer if (!SplitBeforeSize.isZero()) 4748671c6e0SDavid Majnemer Stores.emplace_back(SplitBeforeOffset, SplitBeforeSize); 4758671c6e0SDavid Majnemer 4768671c6e0SDavid Majnemer CharUnits SplitAfterOffset = VBPtrOffset + VBPtrWidth; 4778671c6e0SDavid Majnemer CharUnits SplitAfterSize = LastStoreSize - SplitAfterOffset; 4788671c6e0SDavid Majnemer assert(!SplitAfterSize.isNegative() && "negative store size!"); 4798671c6e0SDavid Majnemer if (!SplitAfterSize.isZero()) 4808671c6e0SDavid Majnemer Stores.emplace_back(SplitAfterOffset, SplitAfterSize); 4818671c6e0SDavid Majnemer } 482fde961dbSEli Friedman 483fde961dbSEli Friedman // If the type contains a pointer to data member we can't memset it to zero. 484fde961dbSEli Friedman // Instead, create a null constant and copy it to the destination. 485fde961dbSEli Friedman // TODO: there are other patterns besides zero that we can usefully memset, 486fde961dbSEli Friedman // like -1, which happens to be the pattern used by member-pointers. 487fde961dbSEli Friedman // TODO: isZeroInitializable can be over-conservative in the case where a 488fde961dbSEli Friedman // virtual base contains a member pointer. 4898671c6e0SDavid Majnemer llvm::Constant *NullConstantForBase = CGF.CGM.EmitNullConstantForBase(Base); 4908671c6e0SDavid Majnemer if (!NullConstantForBase->isNullValue()) { 4918671c6e0SDavid Majnemer llvm::GlobalVariable *NullVariable = new llvm::GlobalVariable( 4928671c6e0SDavid Majnemer CGF.CGM.getModule(), NullConstantForBase->getType(), 4938671c6e0SDavid Majnemer /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, 4948671c6e0SDavid Majnemer NullConstantForBase, Twine()); 4957f416cc4SJohn McCall 4967f416cc4SJohn McCall CharUnits Align = std::max(Layout.getNonVirtualAlignment(), 4977f416cc4SJohn McCall DestPtr.getAlignment()); 498fde961dbSEli Friedman NullVariable->setAlignment(Align.getQuantity()); 4997f416cc4SJohn McCall 5007f416cc4SJohn McCall Address SrcPtr = Address(CGF.EmitCastToVoidPtr(NullVariable), Align); 501fde961dbSEli Friedman 502fde961dbSEli Friedman // Get and call the appropriate llvm.memcpy overload. 5038671c6e0SDavid Majnemer for (std::pair<CharUnits, CharUnits> Store : Stores) { 5048671c6e0SDavid Majnemer CharUnits StoreOffset = Store.first; 5058671c6e0SDavid Majnemer CharUnits StoreSize = Store.second; 5068671c6e0SDavid Majnemer llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize); 5078671c6e0SDavid Majnemer CGF.Builder.CreateMemCpy( 5088671c6e0SDavid Majnemer CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset), 5098671c6e0SDavid Majnemer CGF.Builder.CreateConstInBoundsByteGEP(SrcPtr, StoreOffset), 5108671c6e0SDavid Majnemer StoreSizeVal); 511fde961dbSEli Friedman } 512fde961dbSEli Friedman 513fde961dbSEli Friedman // Otherwise, just memset the whole thing to zero. This is legal 514fde961dbSEli Friedman // because in LLVM, all default initializers (other than the ones we just 515fde961dbSEli Friedman // handled above) are guaranteed to have a bit pattern of all zeros. 5168671c6e0SDavid Majnemer } else { 5178671c6e0SDavid Majnemer for (std::pair<CharUnits, CharUnits> Store : Stores) { 5188671c6e0SDavid Majnemer CharUnits StoreOffset = Store.first; 5198671c6e0SDavid Majnemer CharUnits StoreSize = Store.second; 5208671c6e0SDavid Majnemer llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize); 5218671c6e0SDavid Majnemer CGF.Builder.CreateMemSet( 5228671c6e0SDavid Majnemer CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset), 5238671c6e0SDavid Majnemer CGF.Builder.getInt8(0), StoreSizeVal); 5248671c6e0SDavid Majnemer } 5258671c6e0SDavid Majnemer } 526fde961dbSEli Friedman } 527fde961dbSEli Friedman 52827da15baSAnders Carlsson void 5297a626f63SJohn McCall CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E, 5307a626f63SJohn McCall AggValueSlot Dest) { 5317a626f63SJohn McCall assert(!Dest.isIgnored() && "Must have a destination!"); 53227da15baSAnders Carlsson const CXXConstructorDecl *CD = E->getConstructor(); 533630c76efSDouglas Gregor 534630c76efSDouglas Gregor // If we require zero initialization before (or instead of) calling the 535630c76efSDouglas Gregor // constructor, as can be the case with a non-user-provided default 53603535265SArgyrios Kyrtzidis // constructor, emit the zero initialization now, unless destination is 53703535265SArgyrios Kyrtzidis // already zeroed. 538fde961dbSEli Friedman if (E->requiresZeroInitialization() && !Dest.isZeroed()) { 539fde961dbSEli Friedman switch (E->getConstructionKind()) { 540fde961dbSEli Friedman case CXXConstructExpr::CK_Delegating: 541fde961dbSEli Friedman case CXXConstructExpr::CK_Complete: 5427f416cc4SJohn McCall EmitNullInitialization(Dest.getAddress(), E->getType()); 543fde961dbSEli Friedman break; 544fde961dbSEli Friedman case CXXConstructExpr::CK_VirtualBase: 545fde961dbSEli Friedman case CXXConstructExpr::CK_NonVirtualBase: 5467f416cc4SJohn McCall EmitNullBaseClassInitialization(*this, Dest.getAddress(), 5477f416cc4SJohn McCall CD->getParent()); 548fde961dbSEli Friedman break; 549fde961dbSEli Friedman } 550fde961dbSEli Friedman } 551630c76efSDouglas Gregor 552630c76efSDouglas Gregor // If this is a call to a trivial default constructor, do nothing. 553630c76efSDouglas Gregor if (CD->isTrivial() && CD->isDefaultConstructor()) 55427da15baSAnders Carlsson return; 555630c76efSDouglas Gregor 5568ea46b66SJohn McCall // Elide the constructor if we're constructing from a temporary. 5578ea46b66SJohn McCall // The temporary check is required because Sema sets this on NRVO 5588ea46b66SJohn McCall // returns. 5599c6890a7SRichard Smith if (getLangOpts().ElideConstructors && E->isElidable()) { 5608ea46b66SJohn McCall assert(getContext().hasSameUnqualifiedType(E->getType(), 5618ea46b66SJohn McCall E->getArg(0)->getType())); 5627a626f63SJohn McCall if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) { 5637a626f63SJohn McCall EmitAggExpr(E->getArg(0), Dest); 56427da15baSAnders Carlsson return; 56527da15baSAnders Carlsson } 566222cf0efSDouglas Gregor } 567630c76efSDouglas Gregor 568e7545b33SAlexey Bataev if (const ArrayType *arrayType 569e7545b33SAlexey Bataev = getContext().getAsArrayType(E->getType())) { 5707f416cc4SJohn McCall EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddress(), E); 571f677a8e9SJohn McCall } else { 572bceca20aSCameron Esfahani CXXCtorType Type = Ctor_Complete; 573271c3681SAlexis Hunt bool ForVirtualBase = false; 57461535005SDouglas Gregor bool Delegating = false; 575271c3681SAlexis Hunt 576271c3681SAlexis Hunt switch (E->getConstructionKind()) { 577271c3681SAlexis Hunt case CXXConstructExpr::CK_Delegating: 57861bc1737SAlexis Hunt // We should be emitting a constructor; GlobalDecl will assert this 57961bc1737SAlexis Hunt Type = CurGD.getCtorType(); 58061535005SDouglas Gregor Delegating = true; 581271c3681SAlexis Hunt break; 58261bc1737SAlexis Hunt 583271c3681SAlexis Hunt case CXXConstructExpr::CK_Complete: 584271c3681SAlexis Hunt Type = Ctor_Complete; 585271c3681SAlexis Hunt break; 586271c3681SAlexis Hunt 587271c3681SAlexis Hunt case CXXConstructExpr::CK_VirtualBase: 588271c3681SAlexis Hunt ForVirtualBase = true; 589271c3681SAlexis Hunt // fall-through 590271c3681SAlexis Hunt 591271c3681SAlexis Hunt case CXXConstructExpr::CK_NonVirtualBase: 592271c3681SAlexis Hunt Type = Ctor_Base; 593271c3681SAlexis Hunt } 594e11f9ce9SAnders Carlsson 59527da15baSAnders Carlsson // Call the constructor. 5967f416cc4SJohn McCall EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating, 5977f416cc4SJohn McCall Dest.getAddress(), E); 59827da15baSAnders Carlsson } 599e11f9ce9SAnders Carlsson } 60027da15baSAnders Carlsson 6017f416cc4SJohn McCall void CodeGenFunction::EmitSynthesizedCXXCopyCtor(Address Dest, Address Src, 60250198098SFariborz Jahanian const Expr *Exp) { 6035d413781SJohn McCall if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp)) 604e988bdacSFariborz Jahanian Exp = E->getSubExpr(); 605e988bdacSFariborz Jahanian assert(isa<CXXConstructExpr>(Exp) && 606e988bdacSFariborz Jahanian "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr"); 607e988bdacSFariborz Jahanian const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp); 608e988bdacSFariborz Jahanian const CXXConstructorDecl *CD = E->getConstructor(); 609e988bdacSFariborz Jahanian RunCleanupsScope Scope(*this); 610e988bdacSFariborz Jahanian 611e988bdacSFariborz Jahanian // If we require zero initialization before (or instead of) calling the 612e988bdacSFariborz Jahanian // constructor, as can be the case with a non-user-provided default 613e988bdacSFariborz Jahanian // constructor, emit the zero initialization now. 614e988bdacSFariborz Jahanian // FIXME. Do I still need this for a copy ctor synthesis? 615e988bdacSFariborz Jahanian if (E->requiresZeroInitialization()) 616e988bdacSFariborz Jahanian EmitNullInitialization(Dest, E->getType()); 617e988bdacSFariborz Jahanian 61899da11cfSChandler Carruth assert(!getContext().getAsConstantArrayType(E->getType()) 61999da11cfSChandler Carruth && "EmitSynthesizedCXXCopyCtor - Copied-in Array"); 620525bf650SAlexey Samsonov EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E); 621e988bdacSFariborz Jahanian } 622e988bdacSFariborz Jahanian 6238ed55a54SJohn McCall static CharUnits CalculateCookiePadding(CodeGenFunction &CGF, 6248ed55a54SJohn McCall const CXXNewExpr *E) { 62521122cf6SAnders Carlsson if (!E->isArray()) 6263eb55cfeSKen Dyck return CharUnits::Zero(); 62721122cf6SAnders Carlsson 6287ec4b434SJohn McCall // No cookie is required if the operator new[] being used is the 6297ec4b434SJohn McCall // reserved placement operator new[]. 6307ec4b434SJohn McCall if (E->getOperatorNew()->isReservedGlobalPlacementOperator()) 6313eb55cfeSKen Dyck return CharUnits::Zero(); 632399f499fSAnders Carlsson 633284c48ffSJohn McCall return CGF.CGM.getCXXABI().GetArrayCookieSize(E); 63459486a2dSAnders Carlsson } 63559486a2dSAnders Carlsson 636036f2f6bSJohn McCall static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF, 637036f2f6bSJohn McCall const CXXNewExpr *e, 638f862eb6aSSebastian Redl unsigned minElements, 639036f2f6bSJohn McCall llvm::Value *&numElements, 640036f2f6bSJohn McCall llvm::Value *&sizeWithoutCookie) { 641036f2f6bSJohn McCall QualType type = e->getAllocatedType(); 64259486a2dSAnders Carlsson 643036f2f6bSJohn McCall if (!e->isArray()) { 644036f2f6bSJohn McCall CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type); 645036f2f6bSJohn McCall sizeWithoutCookie 646036f2f6bSJohn McCall = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity()); 647036f2f6bSJohn McCall return sizeWithoutCookie; 64805fc5be3SDouglas Gregor } 64959486a2dSAnders Carlsson 650036f2f6bSJohn McCall // The width of size_t. 651036f2f6bSJohn McCall unsigned sizeWidth = CGF.SizeTy->getBitWidth(); 652036f2f6bSJohn McCall 6538ed55a54SJohn McCall // Figure out the cookie size. 654036f2f6bSJohn McCall llvm::APInt cookieSize(sizeWidth, 655036f2f6bSJohn McCall CalculateCookiePadding(CGF, e).getQuantity()); 6568ed55a54SJohn McCall 65759486a2dSAnders Carlsson // Emit the array size expression. 6587648fb46SArgyrios Kyrtzidis // We multiply the size of all dimensions for NumElements. 6597648fb46SArgyrios Kyrtzidis // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6. 660036f2f6bSJohn McCall numElements = CGF.EmitScalarExpr(e->getArraySize()); 661036f2f6bSJohn McCall assert(isa<llvm::IntegerType>(numElements->getType())); 6628ed55a54SJohn McCall 663036f2f6bSJohn McCall // The number of elements can be have an arbitrary integer type; 664036f2f6bSJohn McCall // essentially, we need to multiply it by a constant factor, add a 665036f2f6bSJohn McCall // cookie size, and verify that the result is representable as a 666036f2f6bSJohn McCall // size_t. That's just a gloss, though, and it's wrong in one 667036f2f6bSJohn McCall // important way: if the count is negative, it's an error even if 668036f2f6bSJohn McCall // the cookie size would bring the total size >= 0. 6696ab2fa8fSDouglas Gregor bool isSigned 6706ab2fa8fSDouglas Gregor = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType(); 6712192fe50SChris Lattner llvm::IntegerType *numElementsType 672036f2f6bSJohn McCall = cast<llvm::IntegerType>(numElements->getType()); 673036f2f6bSJohn McCall unsigned numElementsWidth = numElementsType->getBitWidth(); 674036f2f6bSJohn McCall 675036f2f6bSJohn McCall // Compute the constant factor. 676036f2f6bSJohn McCall llvm::APInt arraySizeMultiplier(sizeWidth, 1); 6777648fb46SArgyrios Kyrtzidis while (const ConstantArrayType *CAT 678036f2f6bSJohn McCall = CGF.getContext().getAsConstantArrayType(type)) { 679036f2f6bSJohn McCall type = CAT->getElementType(); 680036f2f6bSJohn McCall arraySizeMultiplier *= CAT->getSize(); 6817648fb46SArgyrios Kyrtzidis } 68259486a2dSAnders Carlsson 683036f2f6bSJohn McCall CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type); 684036f2f6bSJohn McCall llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity()); 685036f2f6bSJohn McCall typeSizeMultiplier *= arraySizeMultiplier; 686036f2f6bSJohn McCall 687036f2f6bSJohn McCall // This will be a size_t. 688036f2f6bSJohn McCall llvm::Value *size; 68932ac583dSChris Lattner 69032ac583dSChris Lattner // If someone is doing 'new int[42]' there is no need to do a dynamic check. 69132ac583dSChris Lattner // Don't bloat the -O0 code. 692036f2f6bSJohn McCall if (llvm::ConstantInt *numElementsC = 693036f2f6bSJohn McCall dyn_cast<llvm::ConstantInt>(numElements)) { 694036f2f6bSJohn McCall const llvm::APInt &count = numElementsC->getValue(); 69532ac583dSChris Lattner 696036f2f6bSJohn McCall bool hasAnyOverflow = false; 69732ac583dSChris Lattner 698036f2f6bSJohn McCall // If 'count' was a negative number, it's an overflow. 699036f2f6bSJohn McCall if (isSigned && count.isNegative()) 700036f2f6bSJohn McCall hasAnyOverflow = true; 7018ed55a54SJohn McCall 702036f2f6bSJohn McCall // We want to do all this arithmetic in size_t. If numElements is 703036f2f6bSJohn McCall // wider than that, check whether it's already too big, and if so, 704036f2f6bSJohn McCall // overflow. 705036f2f6bSJohn McCall else if (numElementsWidth > sizeWidth && 706036f2f6bSJohn McCall numElementsWidth - sizeWidth > count.countLeadingZeros()) 707036f2f6bSJohn McCall hasAnyOverflow = true; 708036f2f6bSJohn McCall 709036f2f6bSJohn McCall // Okay, compute a count at the right width. 710036f2f6bSJohn McCall llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth); 711036f2f6bSJohn McCall 712f862eb6aSSebastian Redl // If there is a brace-initializer, we cannot allocate fewer elements than 713f862eb6aSSebastian Redl // there are initializers. If we do, that's treated like an overflow. 714f862eb6aSSebastian Redl if (adjustedCount.ult(minElements)) 715f862eb6aSSebastian Redl hasAnyOverflow = true; 716f862eb6aSSebastian Redl 717036f2f6bSJohn McCall // Scale numElements by that. This might overflow, but we don't 718036f2f6bSJohn McCall // care because it only overflows if allocationSize does, too, and 719036f2f6bSJohn McCall // if that overflows then we shouldn't use this. 720036f2f6bSJohn McCall numElements = llvm::ConstantInt::get(CGF.SizeTy, 721036f2f6bSJohn McCall adjustedCount * arraySizeMultiplier); 722036f2f6bSJohn McCall 723036f2f6bSJohn McCall // Compute the size before cookie, and track whether it overflowed. 724036f2f6bSJohn McCall bool overflow; 725036f2f6bSJohn McCall llvm::APInt allocationSize 726036f2f6bSJohn McCall = adjustedCount.umul_ov(typeSizeMultiplier, overflow); 727036f2f6bSJohn McCall hasAnyOverflow |= overflow; 728036f2f6bSJohn McCall 729036f2f6bSJohn McCall // Add in the cookie, and check whether it's overflowed. 730036f2f6bSJohn McCall if (cookieSize != 0) { 731036f2f6bSJohn McCall // Save the current size without a cookie. This shouldn't be 732036f2f6bSJohn McCall // used if there was overflow. 733036f2f6bSJohn McCall sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize); 734036f2f6bSJohn McCall 735036f2f6bSJohn McCall allocationSize = allocationSize.uadd_ov(cookieSize, overflow); 736036f2f6bSJohn McCall hasAnyOverflow |= overflow; 7378ed55a54SJohn McCall } 7388ed55a54SJohn McCall 739036f2f6bSJohn McCall // On overflow, produce a -1 so operator new will fail. 740455f42c9SAaron Ballman if (hasAnyOverflow) { 741455f42c9SAaron Ballman size = llvm::Constant::getAllOnesValue(CGF.SizeTy); 742455f42c9SAaron Ballman } else { 743036f2f6bSJohn McCall size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize); 744455f42c9SAaron Ballman } 74532ac583dSChris Lattner 746036f2f6bSJohn McCall // Otherwise, we might need to use the overflow intrinsics. 7478ed55a54SJohn McCall } else { 748f862eb6aSSebastian Redl // There are up to five conditions we need to test for: 749036f2f6bSJohn McCall // 1) if isSigned, we need to check whether numElements is negative; 750036f2f6bSJohn McCall // 2) if numElementsWidth > sizeWidth, we need to check whether 751036f2f6bSJohn McCall // numElements is larger than something representable in size_t; 752f862eb6aSSebastian Redl // 3) if minElements > 0, we need to check whether numElements is smaller 753f862eb6aSSebastian Redl // than that. 754f862eb6aSSebastian Redl // 4) we need to compute 755036f2f6bSJohn McCall // sizeWithoutCookie := numElements * typeSizeMultiplier 756036f2f6bSJohn McCall // and check whether it overflows; and 757f862eb6aSSebastian Redl // 5) if we need a cookie, we need to compute 758036f2f6bSJohn McCall // size := sizeWithoutCookie + cookieSize 759036f2f6bSJohn McCall // and check whether it overflows. 7608ed55a54SJohn McCall 7618a13c418SCraig Topper llvm::Value *hasOverflow = nullptr; 7628ed55a54SJohn McCall 763036f2f6bSJohn McCall // If numElementsWidth > sizeWidth, then one way or another, we're 764036f2f6bSJohn McCall // going to have to do a comparison for (2), and this happens to 765036f2f6bSJohn McCall // take care of (1), too. 766036f2f6bSJohn McCall if (numElementsWidth > sizeWidth) { 767036f2f6bSJohn McCall llvm::APInt threshold(numElementsWidth, 1); 768036f2f6bSJohn McCall threshold <<= sizeWidth; 7698ed55a54SJohn McCall 770036f2f6bSJohn McCall llvm::Value *thresholdV 771036f2f6bSJohn McCall = llvm::ConstantInt::get(numElementsType, threshold); 772036f2f6bSJohn McCall 773036f2f6bSJohn McCall hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV); 774036f2f6bSJohn McCall numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy); 775036f2f6bSJohn McCall 776036f2f6bSJohn McCall // Otherwise, if we're signed, we want to sext up to size_t. 777036f2f6bSJohn McCall } else if (isSigned) { 778036f2f6bSJohn McCall if (numElementsWidth < sizeWidth) 779036f2f6bSJohn McCall numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy); 780036f2f6bSJohn McCall 781036f2f6bSJohn McCall // If there's a non-1 type size multiplier, then we can do the 782036f2f6bSJohn McCall // signedness check at the same time as we do the multiply 783036f2f6bSJohn McCall // because a negative number times anything will cause an 784f862eb6aSSebastian Redl // unsigned overflow. Otherwise, we have to do it here. But at least 785f862eb6aSSebastian Redl // in this case, we can subsume the >= minElements check. 786036f2f6bSJohn McCall if (typeSizeMultiplier == 1) 787036f2f6bSJohn McCall hasOverflow = CGF.Builder.CreateICmpSLT(numElements, 788f862eb6aSSebastian Redl llvm::ConstantInt::get(CGF.SizeTy, minElements)); 789036f2f6bSJohn McCall 790036f2f6bSJohn McCall // Otherwise, zext up to size_t if necessary. 791036f2f6bSJohn McCall } else if (numElementsWidth < sizeWidth) { 792036f2f6bSJohn McCall numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy); 793036f2f6bSJohn McCall } 794036f2f6bSJohn McCall 795036f2f6bSJohn McCall assert(numElements->getType() == CGF.SizeTy); 796036f2f6bSJohn McCall 797f862eb6aSSebastian Redl if (minElements) { 798f862eb6aSSebastian Redl // Don't allow allocation of fewer elements than we have initializers. 799f862eb6aSSebastian Redl if (!hasOverflow) { 800f862eb6aSSebastian Redl hasOverflow = CGF.Builder.CreateICmpULT(numElements, 801f862eb6aSSebastian Redl llvm::ConstantInt::get(CGF.SizeTy, minElements)); 802f862eb6aSSebastian Redl } else if (numElementsWidth > sizeWidth) { 803f862eb6aSSebastian Redl // The other existing overflow subsumes this check. 804f862eb6aSSebastian Redl // We do an unsigned comparison, since any signed value < -1 is 805f862eb6aSSebastian Redl // taken care of either above or below. 806f862eb6aSSebastian Redl hasOverflow = CGF.Builder.CreateOr(hasOverflow, 807f862eb6aSSebastian Redl CGF.Builder.CreateICmpULT(numElements, 808f862eb6aSSebastian Redl llvm::ConstantInt::get(CGF.SizeTy, minElements))); 809f862eb6aSSebastian Redl } 810f862eb6aSSebastian Redl } 811f862eb6aSSebastian Redl 812036f2f6bSJohn McCall size = numElements; 813036f2f6bSJohn McCall 814036f2f6bSJohn McCall // Multiply by the type size if necessary. This multiplier 815036f2f6bSJohn McCall // includes all the factors for nested arrays. 8168ed55a54SJohn McCall // 817036f2f6bSJohn McCall // This step also causes numElements to be scaled up by the 818036f2f6bSJohn McCall // nested-array factor if necessary. Overflow on this computation 819036f2f6bSJohn McCall // can be ignored because the result shouldn't be used if 820036f2f6bSJohn McCall // allocation fails. 821036f2f6bSJohn McCall if (typeSizeMultiplier != 1) { 822036f2f6bSJohn McCall llvm::Value *umul_with_overflow 8238d375cefSBenjamin Kramer = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy); 8248ed55a54SJohn McCall 825036f2f6bSJohn McCall llvm::Value *tsmV = 826036f2f6bSJohn McCall llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier); 827036f2f6bSJohn McCall llvm::Value *result = 82843f9bb73SDavid Blaikie CGF.Builder.CreateCall(umul_with_overflow, {size, tsmV}); 8298ed55a54SJohn McCall 830036f2f6bSJohn McCall llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1); 831036f2f6bSJohn McCall if (hasOverflow) 832036f2f6bSJohn McCall hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed); 8338ed55a54SJohn McCall else 834036f2f6bSJohn McCall hasOverflow = overflowed; 83559486a2dSAnders Carlsson 836036f2f6bSJohn McCall size = CGF.Builder.CreateExtractValue(result, 0); 837036f2f6bSJohn McCall 838036f2f6bSJohn McCall // Also scale up numElements by the array size multiplier. 839036f2f6bSJohn McCall if (arraySizeMultiplier != 1) { 840036f2f6bSJohn McCall // If the base element type size is 1, then we can re-use the 841036f2f6bSJohn McCall // multiply we just did. 842036f2f6bSJohn McCall if (typeSize.isOne()) { 843036f2f6bSJohn McCall assert(arraySizeMultiplier == typeSizeMultiplier); 844036f2f6bSJohn McCall numElements = size; 845036f2f6bSJohn McCall 846036f2f6bSJohn McCall // Otherwise we need a separate multiply. 847036f2f6bSJohn McCall } else { 848036f2f6bSJohn McCall llvm::Value *asmV = 849036f2f6bSJohn McCall llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier); 850036f2f6bSJohn McCall numElements = CGF.Builder.CreateMul(numElements, asmV); 851036f2f6bSJohn McCall } 852036f2f6bSJohn McCall } 853036f2f6bSJohn McCall } else { 854036f2f6bSJohn McCall // numElements doesn't need to be scaled. 855036f2f6bSJohn McCall assert(arraySizeMultiplier == 1); 856036f2f6bSJohn McCall } 857036f2f6bSJohn McCall 858036f2f6bSJohn McCall // Add in the cookie size if necessary. 859036f2f6bSJohn McCall if (cookieSize != 0) { 860036f2f6bSJohn McCall sizeWithoutCookie = size; 861036f2f6bSJohn McCall 862036f2f6bSJohn McCall llvm::Value *uadd_with_overflow 8638d375cefSBenjamin Kramer = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy); 864036f2f6bSJohn McCall 865036f2f6bSJohn McCall llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize); 866036f2f6bSJohn McCall llvm::Value *result = 86743f9bb73SDavid Blaikie CGF.Builder.CreateCall(uadd_with_overflow, {size, cookieSizeV}); 868036f2f6bSJohn McCall 869036f2f6bSJohn McCall llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1); 870036f2f6bSJohn McCall if (hasOverflow) 871036f2f6bSJohn McCall hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed); 872036f2f6bSJohn McCall else 873036f2f6bSJohn McCall hasOverflow = overflowed; 874036f2f6bSJohn McCall 875036f2f6bSJohn McCall size = CGF.Builder.CreateExtractValue(result, 0); 876036f2f6bSJohn McCall } 877036f2f6bSJohn McCall 878036f2f6bSJohn McCall // If we had any possibility of dynamic overflow, make a select to 879036f2f6bSJohn McCall // overwrite 'size' with an all-ones value, which should cause 880036f2f6bSJohn McCall // operator new to throw. 881036f2f6bSJohn McCall if (hasOverflow) 882455f42c9SAaron Ballman size = CGF.Builder.CreateSelect(hasOverflow, 883455f42c9SAaron Ballman llvm::Constant::getAllOnesValue(CGF.SizeTy), 884036f2f6bSJohn McCall size); 885036f2f6bSJohn McCall } 886036f2f6bSJohn McCall 887036f2f6bSJohn McCall if (cookieSize == 0) 888036f2f6bSJohn McCall sizeWithoutCookie = size; 889036f2f6bSJohn McCall else 890036f2f6bSJohn McCall assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?"); 891036f2f6bSJohn McCall 892036f2f6bSJohn McCall return size; 89359486a2dSAnders Carlsson } 89459486a2dSAnders Carlsson 895f862eb6aSSebastian Redl static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init, 8967f416cc4SJohn McCall QualType AllocType, Address NewPtr) { 8971c96bc5dSRichard Smith // FIXME: Refactor with EmitExprAsInit. 89847fb9508SJohn McCall switch (CGF.getEvaluationKind(AllocType)) { 89947fb9508SJohn McCall case TEK_Scalar: 900a2c1124fSDavid Blaikie CGF.EmitScalarInit(Init, nullptr, 9017f416cc4SJohn McCall CGF.MakeAddrLValue(NewPtr, AllocType), false); 90247fb9508SJohn McCall return; 90347fb9508SJohn McCall case TEK_Complex: 9047f416cc4SJohn McCall CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType), 90547fb9508SJohn McCall /*isInit*/ true); 90647fb9508SJohn McCall return; 90747fb9508SJohn McCall case TEK_Aggregate: { 9087a626f63SJohn McCall AggValueSlot Slot 9097f416cc4SJohn McCall = AggValueSlot::forAddr(NewPtr, AllocType.getQualifiers(), 9108d6fc958SJohn McCall AggValueSlot::IsDestructed, 91146759f4fSJohn McCall AggValueSlot::DoesNotNeedGCBarriers, 912615ed1a3SChad Rosier AggValueSlot::IsNotAliased); 9137a626f63SJohn McCall CGF.EmitAggExpr(Init, Slot); 91447fb9508SJohn McCall return; 9157a626f63SJohn McCall } 916d5202e09SFariborz Jahanian } 91747fb9508SJohn McCall llvm_unreachable("bad evaluation kind"); 91847fb9508SJohn McCall } 919d5202e09SFariborz Jahanian 920fb901c7aSDavid Blaikie void CodeGenFunction::EmitNewArrayInitializer( 921fb901c7aSDavid Blaikie const CXXNewExpr *E, QualType ElementType, llvm::Type *ElementTy, 9227f416cc4SJohn McCall Address BeginPtr, llvm::Value *NumElements, 92306a67e2cSRichard Smith llvm::Value *AllocSizeWithoutCookie) { 92406a67e2cSRichard Smith // If we have a type with trivial initialization and no initializer, 92506a67e2cSRichard Smith // there's nothing to do. 9266047f07eSSebastian Redl if (!E->hasInitializer()) 92706a67e2cSRichard Smith return; 928b66b08efSFariborz Jahanian 9297f416cc4SJohn McCall Address CurPtr = BeginPtr; 930d5202e09SFariborz Jahanian 93106a67e2cSRichard Smith unsigned InitListElements = 0; 932f862eb6aSSebastian Redl 933f862eb6aSSebastian Redl const Expr *Init = E->getInitializer(); 9347f416cc4SJohn McCall Address EndOfInit = Address::invalid(); 93506a67e2cSRichard Smith QualType::DestructionKind DtorKind = ElementType.isDestructedType(); 93606a67e2cSRichard Smith EHScopeStack::stable_iterator Cleanup; 93706a67e2cSRichard Smith llvm::Instruction *CleanupDominator = nullptr; 9381c96bc5dSRichard Smith 9397f416cc4SJohn McCall CharUnits ElementSize = getContext().getTypeSizeInChars(ElementType); 9407f416cc4SJohn McCall CharUnits ElementAlign = 9417f416cc4SJohn McCall BeginPtr.getAlignment().alignmentOfArrayElement(ElementSize); 9427f416cc4SJohn McCall 9430511d23aSRichard Smith // Attempt to perform zero-initialization using memset. 9440511d23aSRichard Smith auto TryMemsetInitialization = [&]() -> bool { 9450511d23aSRichard Smith // FIXME: If the type is a pointer-to-data-member under the Itanium ABI, 9460511d23aSRichard Smith // we can initialize with a memset to -1. 9470511d23aSRichard Smith if (!CGM.getTypes().isZeroInitializable(ElementType)) 9480511d23aSRichard Smith return false; 9490511d23aSRichard Smith 9500511d23aSRichard Smith // Optimization: since zero initialization will just set the memory 9510511d23aSRichard Smith // to all zeroes, generate a single memset to do it in one shot. 9520511d23aSRichard Smith 9530511d23aSRichard Smith // Subtract out the size of any elements we've already initialized. 9540511d23aSRichard Smith auto *RemainingSize = AllocSizeWithoutCookie; 9550511d23aSRichard Smith if (InitListElements) { 9560511d23aSRichard Smith // We know this can't overflow; we check this when doing the allocation. 9570511d23aSRichard Smith auto *InitializedSize = llvm::ConstantInt::get( 9580511d23aSRichard Smith RemainingSize->getType(), 9590511d23aSRichard Smith getContext().getTypeSizeInChars(ElementType).getQuantity() * 9600511d23aSRichard Smith InitListElements); 9610511d23aSRichard Smith RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize); 9620511d23aSRichard Smith } 9630511d23aSRichard Smith 9640511d23aSRichard Smith // Create the memset. 9650511d23aSRichard Smith Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize, false); 9660511d23aSRichard Smith return true; 9670511d23aSRichard Smith }; 9680511d23aSRichard Smith 969f862eb6aSSebastian Redl // If the initializer is an initializer list, first do the explicit elements. 970f862eb6aSSebastian Redl if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) { 9710511d23aSRichard Smith // Initializing from a (braced) string literal is a special case; the init 9720511d23aSRichard Smith // list element does not initialize a (single) array element. 9730511d23aSRichard Smith if (ILE->isStringLiteralInit()) { 9740511d23aSRichard Smith // Initialize the initial portion of length equal to that of the string 9750511d23aSRichard Smith // literal. The allocation must be for at least this much; we emitted a 9760511d23aSRichard Smith // check for that earlier. 9770511d23aSRichard Smith AggValueSlot Slot = 9780511d23aSRichard Smith AggValueSlot::forAddr(CurPtr, ElementType.getQualifiers(), 9790511d23aSRichard Smith AggValueSlot::IsDestructed, 9800511d23aSRichard Smith AggValueSlot::DoesNotNeedGCBarriers, 9810511d23aSRichard Smith AggValueSlot::IsNotAliased); 9820511d23aSRichard Smith EmitAggExpr(ILE->getInit(0), Slot); 9830511d23aSRichard Smith 9840511d23aSRichard Smith // Move past these elements. 9850511d23aSRichard Smith InitListElements = 9860511d23aSRichard Smith cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe()) 9870511d23aSRichard Smith ->getSize().getZExtValue(); 9880511d23aSRichard Smith CurPtr = 9890511d23aSRichard Smith Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(), 9900511d23aSRichard Smith Builder.getSize(InitListElements), 9910511d23aSRichard Smith "string.init.end"), 9920511d23aSRichard Smith CurPtr.getAlignment().alignmentAtOffset(InitListElements * 9930511d23aSRichard Smith ElementSize)); 9940511d23aSRichard Smith 9950511d23aSRichard Smith // Zero out the rest, if any remain. 9960511d23aSRichard Smith llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements); 9970511d23aSRichard Smith if (!ConstNum || !ConstNum->equalsInt(InitListElements)) { 9980511d23aSRichard Smith bool OK = TryMemsetInitialization(); 9990511d23aSRichard Smith (void)OK; 10000511d23aSRichard Smith assert(OK && "couldn't memset character type?"); 10010511d23aSRichard Smith } 10020511d23aSRichard Smith return; 10030511d23aSRichard Smith } 10040511d23aSRichard Smith 100506a67e2cSRichard Smith InitListElements = ILE->getNumInits(); 1006f62290a1SChad Rosier 10071c96bc5dSRichard Smith // If this is a multi-dimensional array new, we will initialize multiple 10081c96bc5dSRichard Smith // elements with each init list element. 10091c96bc5dSRichard Smith QualType AllocType = E->getAllocatedType(); 10101c96bc5dSRichard Smith if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>( 10111c96bc5dSRichard Smith AllocType->getAsArrayTypeUnsafe())) { 1012fb901c7aSDavid Blaikie ElementTy = ConvertTypeForMem(AllocType); 10137f416cc4SJohn McCall CurPtr = Builder.CreateElementBitCast(CurPtr, ElementTy); 101406a67e2cSRichard Smith InitListElements *= getContext().getConstantArrayElementCount(CAT); 10151c96bc5dSRichard Smith } 10161c96bc5dSRichard Smith 101706a67e2cSRichard Smith // Enter a partial-destruction Cleanup if necessary. 101806a67e2cSRichard Smith if (needsEHCleanup(DtorKind)) { 101906a67e2cSRichard Smith // In principle we could tell the Cleanup where we are more 1020f62290a1SChad Rosier // directly, but the control flow can get so varied here that it 1021f62290a1SChad Rosier // would actually be quite complex. Therefore we go through an 1022f62290a1SChad Rosier // alloca. 10237f416cc4SJohn McCall EndOfInit = CreateTempAlloca(BeginPtr.getType(), getPointerAlign(), 10247f416cc4SJohn McCall "array.init.end"); 10257f416cc4SJohn McCall CleanupDominator = Builder.CreateStore(BeginPtr.getPointer(), EndOfInit); 10267f416cc4SJohn McCall pushIrregularPartialArrayCleanup(BeginPtr.getPointer(), EndOfInit, 10277f416cc4SJohn McCall ElementType, ElementAlign, 102806a67e2cSRichard Smith getDestroyer(DtorKind)); 102906a67e2cSRichard Smith Cleanup = EHStack.stable_begin(); 1030f62290a1SChad Rosier } 1031f62290a1SChad Rosier 10327f416cc4SJohn McCall CharUnits StartAlign = CurPtr.getAlignment(); 1033f862eb6aSSebastian Redl for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) { 1034f62290a1SChad Rosier // Tell the cleanup that it needs to destroy up to this 1035f62290a1SChad Rosier // element. TODO: some of these stores can be trivially 1036f62290a1SChad Rosier // observed to be unnecessary. 10377f416cc4SJohn McCall if (EndOfInit.isValid()) { 10387f416cc4SJohn McCall auto FinishedPtr = 10397f416cc4SJohn McCall Builder.CreateBitCast(CurPtr.getPointer(), BeginPtr.getType()); 10407f416cc4SJohn McCall Builder.CreateStore(FinishedPtr, EndOfInit); 10417f416cc4SJohn McCall } 104206a67e2cSRichard Smith // FIXME: If the last initializer is an incomplete initializer list for 104306a67e2cSRichard Smith // an array, and we have an array filler, we can fold together the two 104406a67e2cSRichard Smith // initialization loops. 10451c96bc5dSRichard Smith StoreAnyExprIntoOneUnit(*this, ILE->getInit(i), 104606a67e2cSRichard Smith ILE->getInit(i)->getType(), CurPtr); 10477f416cc4SJohn McCall CurPtr = Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(), 10487f416cc4SJohn McCall Builder.getSize(1), 10497f416cc4SJohn McCall "array.exp.next"), 10507f416cc4SJohn McCall StartAlign.alignmentAtOffset((i + 1) * ElementSize)); 1051f862eb6aSSebastian Redl } 1052f862eb6aSSebastian Redl 1053f862eb6aSSebastian Redl // The remaining elements are filled with the array filler expression. 1054f862eb6aSSebastian Redl Init = ILE->getArrayFiller(); 10551c96bc5dSRichard Smith 105606a67e2cSRichard Smith // Extract the initializer for the individual array elements by pulling 105706a67e2cSRichard Smith // out the array filler from all the nested initializer lists. This avoids 105806a67e2cSRichard Smith // generating a nested loop for the initialization. 105906a67e2cSRichard Smith while (Init && Init->getType()->isConstantArrayType()) { 106006a67e2cSRichard Smith auto *SubILE = dyn_cast<InitListExpr>(Init); 106106a67e2cSRichard Smith if (!SubILE) 106206a67e2cSRichard Smith break; 106306a67e2cSRichard Smith assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?"); 106406a67e2cSRichard Smith Init = SubILE->getArrayFiller(); 1065f862eb6aSSebastian Redl } 1066f862eb6aSSebastian Redl 106706a67e2cSRichard Smith // Switch back to initializing one base element at a time. 10687f416cc4SJohn McCall CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr.getType()); 1069f62290a1SChad Rosier } 1070e6c980c4SChandler Carruth 1071454a7cdfSRichard Smith // If all elements have already been initialized, skip any further 1072454a7cdfSRichard Smith // initialization. 1073454a7cdfSRichard Smith llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements); 1074454a7cdfSRichard Smith if (ConstNum && ConstNum->getZExtValue() <= InitListElements) { 1075454a7cdfSRichard Smith // If there was a Cleanup, deactivate it. 1076454a7cdfSRichard Smith if (CleanupDominator) 1077454a7cdfSRichard Smith DeactivateCleanupBlock(Cleanup, CleanupDominator); 1078454a7cdfSRichard Smith return; 1079454a7cdfSRichard Smith } 1080454a7cdfSRichard Smith 1081454a7cdfSRichard Smith assert(Init && "have trailing elements to initialize but no initializer"); 1082454a7cdfSRichard Smith 108306a67e2cSRichard Smith // If this is a constructor call, try to optimize it out, and failing that 108406a67e2cSRichard Smith // emit a single loop to initialize all remaining elements. 1085454a7cdfSRichard Smith if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) { 10866047f07eSSebastian Redl CXXConstructorDecl *Ctor = CCE->getConstructor(); 1087d153103cSDouglas Gregor if (Ctor->isTrivial()) { 108805fc5be3SDouglas Gregor // If new expression did not specify value-initialization, then there 108905fc5be3SDouglas Gregor // is no initialization. 10906047f07eSSebastian Redl if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty()) 109105fc5be3SDouglas Gregor return; 109205fc5be3SDouglas Gregor 109306a67e2cSRichard Smith if (TryMemsetInitialization()) 10943a202f60SAnders Carlsson return; 10953a202f60SAnders Carlsson } 109605fc5be3SDouglas Gregor 109706a67e2cSRichard Smith // Store the new Cleanup position for irregular Cleanups. 109806a67e2cSRichard Smith // 109906a67e2cSRichard Smith // FIXME: Share this cleanup with the constructor call emission rather than 110006a67e2cSRichard Smith // having it create a cleanup of its own. 11017f416cc4SJohn McCall if (EndOfInit.isValid()) 11027f416cc4SJohn McCall Builder.CreateStore(CurPtr.getPointer(), EndOfInit); 110306a67e2cSRichard Smith 110406a67e2cSRichard Smith // Emit a constructor call loop to initialize the remaining elements. 110506a67e2cSRichard Smith if (InitListElements) 110606a67e2cSRichard Smith NumElements = Builder.CreateSub( 110706a67e2cSRichard Smith NumElements, 110806a67e2cSRichard Smith llvm::ConstantInt::get(NumElements->getType(), InitListElements)); 110970b9c01bSAlexey Samsonov EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE, 111048ddcf2cSEli Friedman CCE->requiresZeroInitialization()); 111105fc5be3SDouglas Gregor return; 11126047f07eSSebastian Redl } 111306a67e2cSRichard Smith 111406a67e2cSRichard Smith // If this is value-initialization, we can usually use memset. 111506a67e2cSRichard Smith ImplicitValueInitExpr IVIE(ElementType); 1116454a7cdfSRichard Smith if (isa<ImplicitValueInitExpr>(Init)) { 111706a67e2cSRichard Smith if (TryMemsetInitialization()) 111806a67e2cSRichard Smith return; 111906a67e2cSRichard Smith 112006a67e2cSRichard Smith // Switch to an ImplicitValueInitExpr for the element type. This handles 112106a67e2cSRichard Smith // only one case: multidimensional array new of pointers to members. In 112206a67e2cSRichard Smith // all other cases, we already have an initializer for the array element. 112306a67e2cSRichard Smith Init = &IVIE; 112406a67e2cSRichard Smith } 112506a67e2cSRichard Smith 112606a67e2cSRichard Smith // At this point we should have found an initializer for the individual 112706a67e2cSRichard Smith // elements of the array. 112806a67e2cSRichard Smith assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) && 112906a67e2cSRichard Smith "got wrong type of element to initialize"); 113006a67e2cSRichard Smith 1131454a7cdfSRichard Smith // If we have an empty initializer list, we can usually use memset. 1132454a7cdfSRichard Smith if (auto *ILE = dyn_cast<InitListExpr>(Init)) 1133454a7cdfSRichard Smith if (ILE->getNumInits() == 0 && TryMemsetInitialization()) 1134d5202e09SFariborz Jahanian return; 113559486a2dSAnders Carlsson 1136cb77930dSYunzhong Gao // If we have a struct whose every field is value-initialized, we can 1137cb77930dSYunzhong Gao // usually use memset. 1138cb77930dSYunzhong Gao if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 1139cb77930dSYunzhong Gao if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) { 1140cb77930dSYunzhong Gao if (RType->getDecl()->isStruct()) { 1141872307e2SRichard Smith unsigned NumElements = 0; 1142872307e2SRichard Smith if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RType->getDecl())) 1143872307e2SRichard Smith NumElements = CXXRD->getNumBases(); 1144cb77930dSYunzhong Gao for (auto *Field : RType->getDecl()->fields()) 1145cb77930dSYunzhong Gao if (!Field->isUnnamedBitfield()) 1146872307e2SRichard Smith ++NumElements; 1147872307e2SRichard Smith // FIXME: Recurse into nested InitListExprs. 1148872307e2SRichard Smith if (ILE->getNumInits() == NumElements) 1149cb77930dSYunzhong Gao for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) 1150cb77930dSYunzhong Gao if (!isa<ImplicitValueInitExpr>(ILE->getInit(i))) 1151872307e2SRichard Smith --NumElements; 1152872307e2SRichard Smith if (ILE->getNumInits() == NumElements && TryMemsetInitialization()) 1153cb77930dSYunzhong Gao return; 1154cb77930dSYunzhong Gao } 1155cb77930dSYunzhong Gao } 1156cb77930dSYunzhong Gao } 1157cb77930dSYunzhong Gao 115806a67e2cSRichard Smith // Create the loop blocks. 115906a67e2cSRichard Smith llvm::BasicBlock *EntryBB = Builder.GetInsertBlock(); 116006a67e2cSRichard Smith llvm::BasicBlock *LoopBB = createBasicBlock("new.loop"); 116106a67e2cSRichard Smith llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end"); 116259486a2dSAnders Carlsson 116306a67e2cSRichard Smith // Find the end of the array, hoisted out of the loop. 116406a67e2cSRichard Smith llvm::Value *EndPtr = 11657f416cc4SJohn McCall Builder.CreateInBoundsGEP(BeginPtr.getPointer(), NumElements, "array.end"); 116606a67e2cSRichard Smith 116706a67e2cSRichard Smith // If the number of elements isn't constant, we have to now check if there is 116806a67e2cSRichard Smith // anything left to initialize. 116906a67e2cSRichard Smith if (!ConstNum) { 11707f416cc4SJohn McCall llvm::Value *IsEmpty = 11717f416cc4SJohn McCall Builder.CreateICmpEQ(CurPtr.getPointer(), EndPtr, "array.isempty"); 117206a67e2cSRichard Smith Builder.CreateCondBr(IsEmpty, ContBB, LoopBB); 117306a67e2cSRichard Smith } 117406a67e2cSRichard Smith 117506a67e2cSRichard Smith // Enter the loop. 117606a67e2cSRichard Smith EmitBlock(LoopBB); 117706a67e2cSRichard Smith 117806a67e2cSRichard Smith // Set up the current-element phi. 117906a67e2cSRichard Smith llvm::PHINode *CurPtrPhi = 11807f416cc4SJohn McCall Builder.CreatePHI(CurPtr.getType(), 2, "array.cur"); 11817f416cc4SJohn McCall CurPtrPhi->addIncoming(CurPtr.getPointer(), EntryBB); 11827f416cc4SJohn McCall 11837f416cc4SJohn McCall CurPtr = Address(CurPtrPhi, ElementAlign); 118406a67e2cSRichard Smith 118506a67e2cSRichard Smith // Store the new Cleanup position for irregular Cleanups. 11867f416cc4SJohn McCall if (EndOfInit.isValid()) 11877f416cc4SJohn McCall Builder.CreateStore(CurPtr.getPointer(), EndOfInit); 118806a67e2cSRichard Smith 118906a67e2cSRichard Smith // Enter a partial-destruction Cleanup if necessary. 119006a67e2cSRichard Smith if (!CleanupDominator && needsEHCleanup(DtorKind)) { 11917f416cc4SJohn McCall pushRegularPartialArrayCleanup(BeginPtr.getPointer(), CurPtr.getPointer(), 11927f416cc4SJohn McCall ElementType, ElementAlign, 119306a67e2cSRichard Smith getDestroyer(DtorKind)); 119406a67e2cSRichard Smith Cleanup = EHStack.stable_begin(); 119506a67e2cSRichard Smith CleanupDominator = Builder.CreateUnreachable(); 119606a67e2cSRichard Smith } 119706a67e2cSRichard Smith 119806a67e2cSRichard Smith // Emit the initializer into this element. 119906a67e2cSRichard Smith StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr); 120006a67e2cSRichard Smith 120106a67e2cSRichard Smith // Leave the Cleanup if we entered one. 120206a67e2cSRichard Smith if (CleanupDominator) { 120306a67e2cSRichard Smith DeactivateCleanupBlock(Cleanup, CleanupDominator); 120406a67e2cSRichard Smith CleanupDominator->eraseFromParent(); 120506a67e2cSRichard Smith } 120606a67e2cSRichard Smith 120706a67e2cSRichard Smith // Advance to the next element by adjusting the pointer type as necessary. 120806a67e2cSRichard Smith llvm::Value *NextPtr = 12097f416cc4SJohn McCall Builder.CreateConstInBoundsGEP1_32(ElementTy, CurPtr.getPointer(), 1, 12107f416cc4SJohn McCall "array.next"); 121106a67e2cSRichard Smith 121206a67e2cSRichard Smith // Check whether we've gotten to the end of the array and, if so, 121306a67e2cSRichard Smith // exit the loop. 121406a67e2cSRichard Smith llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend"); 121506a67e2cSRichard Smith Builder.CreateCondBr(IsEnd, ContBB, LoopBB); 121606a67e2cSRichard Smith CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock()); 121706a67e2cSRichard Smith 121806a67e2cSRichard Smith EmitBlock(ContBB); 121906a67e2cSRichard Smith } 122006a67e2cSRichard Smith 122106a67e2cSRichard Smith static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E, 1222fb901c7aSDavid Blaikie QualType ElementType, llvm::Type *ElementTy, 12237f416cc4SJohn McCall Address NewPtr, llvm::Value *NumElements, 122406a67e2cSRichard Smith llvm::Value *AllocSizeWithoutCookie) { 12259b479666SDavid Blaikie ApplyDebugLocation DL(CGF, E); 122606a67e2cSRichard Smith if (E->isArray()) 1227fb901c7aSDavid Blaikie CGF.EmitNewArrayInitializer(E, ElementType, ElementTy, NewPtr, NumElements, 122806a67e2cSRichard Smith AllocSizeWithoutCookie); 122906a67e2cSRichard Smith else if (const Expr *Init = E->getInitializer()) 123066e4197fSDavid Blaikie StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr); 123159486a2dSAnders Carlsson } 123259486a2dSAnders Carlsson 12338d0dc31dSRichard Smith /// Emit a call to an operator new or operator delete function, as implicitly 12348d0dc31dSRichard Smith /// created by new-expressions and delete-expressions. 12358d0dc31dSRichard Smith static RValue EmitNewDeleteCall(CodeGenFunction &CGF, 1236*b92ab1afSJohn McCall const FunctionDecl *CalleeDecl, 12378d0dc31dSRichard Smith const FunctionProtoType *CalleeType, 12388d0dc31dSRichard Smith const CallArgList &Args) { 12398d0dc31dSRichard Smith llvm::Instruction *CallOrInvoke; 1240*b92ab1afSJohn McCall llvm::Constant *CalleePtr = CGF.CGM.GetAddrOfFunction(CalleeDecl); 1241*b92ab1afSJohn McCall CGCallee Callee = CGCallee::forDirect(CalleePtr, CalleeDecl); 12428d0dc31dSRichard Smith RValue RV = 1243f770683fSPeter Collingbourne CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall( 1244f770683fSPeter Collingbourne Args, CalleeType, /*chainCall=*/false), 1245*b92ab1afSJohn McCall Callee, ReturnValueSlot(), Args, &CallOrInvoke); 12468d0dc31dSRichard Smith 12478d0dc31dSRichard Smith /// C++1y [expr.new]p10: 12488d0dc31dSRichard Smith /// [In a new-expression,] an implementation is allowed to omit a call 12498d0dc31dSRichard Smith /// to a replaceable global allocation function. 12508d0dc31dSRichard Smith /// 12518d0dc31dSRichard Smith /// We model such elidable calls with the 'builtin' attribute. 1252*b92ab1afSJohn McCall llvm::Function *Fn = dyn_cast<llvm::Function>(CalleePtr); 1253*b92ab1afSJohn McCall if (CalleeDecl->isReplaceableGlobalAllocationFunction() && 12546956d587SRafael Espindola Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) { 12558d0dc31dSRichard Smith // FIXME: Add addAttribute to CallSite. 12568d0dc31dSRichard Smith if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(CallOrInvoke)) 12578d0dc31dSRichard Smith CI->addAttribute(llvm::AttributeSet::FunctionIndex, 12588d0dc31dSRichard Smith llvm::Attribute::Builtin); 12598d0dc31dSRichard Smith else if (llvm::InvokeInst *II = dyn_cast<llvm::InvokeInst>(CallOrInvoke)) 12608d0dc31dSRichard Smith II->addAttribute(llvm::AttributeSet::FunctionIndex, 12618d0dc31dSRichard Smith llvm::Attribute::Builtin); 12628d0dc31dSRichard Smith else 12638d0dc31dSRichard Smith llvm_unreachable("unexpected kind of call instruction"); 12648d0dc31dSRichard Smith } 12658d0dc31dSRichard Smith 12668d0dc31dSRichard Smith return RV; 12678d0dc31dSRichard Smith } 12688d0dc31dSRichard Smith 1269760520bcSRichard Smith RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type, 1270760520bcSRichard Smith const Expr *Arg, 1271760520bcSRichard Smith bool IsDelete) { 1272760520bcSRichard Smith CallArgList Args; 1273760520bcSRichard Smith const Stmt *ArgS = Arg; 1274f05779e2SDavid Blaikie EmitCallArgs(Args, *Type->param_type_begin(), llvm::makeArrayRef(ArgS)); 1275760520bcSRichard Smith // Find the allocation or deallocation function that we're calling. 1276760520bcSRichard Smith ASTContext &Ctx = getContext(); 1277760520bcSRichard Smith DeclarationName Name = Ctx.DeclarationNames 1278760520bcSRichard Smith .getCXXOperatorName(IsDelete ? OO_Delete : OO_New); 1279760520bcSRichard Smith for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name)) 1280599bed75SRichard Smith if (auto *FD = dyn_cast<FunctionDecl>(Decl)) 1281599bed75SRichard Smith if (Ctx.hasSameType(FD->getType(), QualType(Type, 0))) 1282760520bcSRichard Smith return EmitNewDeleteCall(*this, cast<FunctionDecl>(Decl), Type, Args); 1283760520bcSRichard Smith llvm_unreachable("predeclared global operator new/delete is missing"); 1284760520bcSRichard Smith } 1285760520bcSRichard Smith 1286b2f0f057SRichard Smith static std::pair<bool, bool> 1287b2f0f057SRichard Smith shouldPassSizeAndAlignToUsualDelete(const FunctionProtoType *FPT) { 1288b2f0f057SRichard Smith auto AI = FPT->param_type_begin(), AE = FPT->param_type_end(); 1289e9abe648SDaniel Jasper 1290b2f0f057SRichard Smith // The first argument is always a void*. 1291b2f0f057SRichard Smith ++AI; 1292b2f0f057SRichard Smith 1293b2f0f057SRichard Smith // Figure out what other parameters we should be implicitly passing. 1294b2f0f057SRichard Smith bool PassSize = false; 1295b2f0f057SRichard Smith bool PassAlignment = false; 1296b2f0f057SRichard Smith 1297b2f0f057SRichard Smith if (AI != AE && (*AI)->isIntegerType()) { 1298b2f0f057SRichard Smith PassSize = true; 1299b2f0f057SRichard Smith ++AI; 1300b2f0f057SRichard Smith } 1301b2f0f057SRichard Smith 1302b2f0f057SRichard Smith if (AI != AE && (*AI)->isAlignValT()) { 1303b2f0f057SRichard Smith PassAlignment = true; 1304b2f0f057SRichard Smith ++AI; 1305b2f0f057SRichard Smith } 1306b2f0f057SRichard Smith 1307b2f0f057SRichard Smith assert(AI == AE && "unexpected usual deallocation function parameter"); 1308b2f0f057SRichard Smith return {PassSize, PassAlignment}; 1309b2f0f057SRichard Smith } 1310b2f0f057SRichard Smith 1311b2f0f057SRichard Smith namespace { 1312b2f0f057SRichard Smith /// A cleanup to call the given 'operator delete' function upon abnormal 1313b2f0f057SRichard Smith /// exit from a new expression. Templated on a traits type that deals with 1314b2f0f057SRichard Smith /// ensuring that the arguments dominate the cleanup if necessary. 1315b2f0f057SRichard Smith template<typename Traits> 1316b2f0f057SRichard Smith class CallDeleteDuringNew final : public EHScopeStack::Cleanup { 1317b2f0f057SRichard Smith /// Type used to hold llvm::Value*s. 1318b2f0f057SRichard Smith typedef typename Traits::ValueTy ValueTy; 1319b2f0f057SRichard Smith /// Type used to hold RValues. 1320b2f0f057SRichard Smith typedef typename Traits::RValueTy RValueTy; 1321b2f0f057SRichard Smith struct PlacementArg { 1322b2f0f057SRichard Smith RValueTy ArgValue; 1323b2f0f057SRichard Smith QualType ArgType; 1324b2f0f057SRichard Smith }; 1325b2f0f057SRichard Smith 1326b2f0f057SRichard Smith unsigned NumPlacementArgs : 31; 1327b2f0f057SRichard Smith unsigned PassAlignmentToPlacementDelete : 1; 1328b2f0f057SRichard Smith const FunctionDecl *OperatorDelete; 1329b2f0f057SRichard Smith ValueTy Ptr; 1330b2f0f057SRichard Smith ValueTy AllocSize; 1331b2f0f057SRichard Smith CharUnits AllocAlign; 1332b2f0f057SRichard Smith 1333b2f0f057SRichard Smith PlacementArg *getPlacementArgs() { 1334b2f0f057SRichard Smith return reinterpret_cast<PlacementArg *>(this + 1); 1335b2f0f057SRichard Smith } 1336e9abe648SDaniel Jasper 1337e9abe648SDaniel Jasper public: 1338e9abe648SDaniel Jasper static size_t getExtraSize(size_t NumPlacementArgs) { 1339b2f0f057SRichard Smith return NumPlacementArgs * sizeof(PlacementArg); 1340e9abe648SDaniel Jasper } 1341e9abe648SDaniel Jasper 1342e9abe648SDaniel Jasper CallDeleteDuringNew(size_t NumPlacementArgs, 1343b2f0f057SRichard Smith const FunctionDecl *OperatorDelete, ValueTy Ptr, 1344b2f0f057SRichard Smith ValueTy AllocSize, bool PassAlignmentToPlacementDelete, 1345b2f0f057SRichard Smith CharUnits AllocAlign) 1346b2f0f057SRichard Smith : NumPlacementArgs(NumPlacementArgs), 1347b2f0f057SRichard Smith PassAlignmentToPlacementDelete(PassAlignmentToPlacementDelete), 1348b2f0f057SRichard Smith OperatorDelete(OperatorDelete), Ptr(Ptr), AllocSize(AllocSize), 1349b2f0f057SRichard Smith AllocAlign(AllocAlign) {} 1350e9abe648SDaniel Jasper 1351b2f0f057SRichard Smith void setPlacementArg(unsigned I, RValueTy Arg, QualType Type) { 1352e9abe648SDaniel Jasper assert(I < NumPlacementArgs && "index out of range"); 1353b2f0f057SRichard Smith getPlacementArgs()[I] = {Arg, Type}; 1354e9abe648SDaniel Jasper } 1355e9abe648SDaniel Jasper 1356e9abe648SDaniel Jasper void Emit(CodeGenFunction &CGF, Flags flags) override { 1357b2f0f057SRichard Smith const FunctionProtoType *FPT = 1358b2f0f057SRichard Smith OperatorDelete->getType()->getAs<FunctionProtoType>(); 1359e9abe648SDaniel Jasper CallArgList DeleteArgs; 1360824c2f53SJohn McCall 1361189e52fcSRichard Smith // The first argument is always a void*. 1362b2f0f057SRichard Smith DeleteArgs.add(Traits::get(CGF, Ptr), FPT->getParamType(0)); 1363189e52fcSRichard Smith 1364b2f0f057SRichard Smith // Figure out what other parameters we should be implicitly passing. 1365b2f0f057SRichard Smith bool PassSize = false; 1366b2f0f057SRichard Smith bool PassAlignment = false; 1367b2f0f057SRichard Smith if (NumPlacementArgs) { 1368b2f0f057SRichard Smith // A placement deallocation function is implicitly passed an alignment 1369b2f0f057SRichard Smith // if the placement allocation function was, but is never passed a size. 1370b2f0f057SRichard Smith PassAlignment = PassAlignmentToPlacementDelete; 1371b2f0f057SRichard Smith } else { 1372b2f0f057SRichard Smith // For a non-placement new-expression, 'operator delete' can take a 1373b2f0f057SRichard Smith // size and/or an alignment if it has the right parameters. 1374b2f0f057SRichard Smith std::tie(PassSize, PassAlignment) = 1375b2f0f057SRichard Smith shouldPassSizeAndAlignToUsualDelete(FPT); 1376189e52fcSRichard Smith } 1377824c2f53SJohn McCall 1378b2f0f057SRichard Smith // The second argument can be a std::size_t (for non-placement delete). 1379b2f0f057SRichard Smith if (PassSize) 1380b2f0f057SRichard Smith DeleteArgs.add(Traits::get(CGF, AllocSize), 1381b2f0f057SRichard Smith CGF.getContext().getSizeType()); 1382824c2f53SJohn McCall 1383b2f0f057SRichard Smith // The next (second or third) argument can be a std::align_val_t, which 1384b2f0f057SRichard Smith // is an enum whose underlying type is std::size_t. 1385b2f0f057SRichard Smith // FIXME: Use the right type as the parameter type. Note that in a call 1386b2f0f057SRichard Smith // to operator delete(size_t, ...), we may not have it available. 1387b2f0f057SRichard Smith if (PassAlignment) 1388b2f0f057SRichard Smith DeleteArgs.add(RValue::get(llvm::ConstantInt::get( 1389b2f0f057SRichard Smith CGF.SizeTy, AllocAlign.getQuantity())), 1390b2f0f057SRichard Smith CGF.getContext().getSizeType()); 13917f9c92a9SJohn McCall 13927f9c92a9SJohn McCall // Pass the rest of the arguments, which must match exactly. 13937f9c92a9SJohn McCall for (unsigned I = 0; I != NumPlacementArgs; ++I) { 1394b2f0f057SRichard Smith auto Arg = getPlacementArgs()[I]; 1395b2f0f057SRichard Smith DeleteArgs.add(Traits::get(CGF, Arg.ArgValue), Arg.ArgType); 13967f9c92a9SJohn McCall } 13977f9c92a9SJohn McCall 13987f9c92a9SJohn McCall // Call 'operator delete'. 13998d0dc31dSRichard Smith EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs); 14007f9c92a9SJohn McCall } 14017f9c92a9SJohn McCall }; 1402ab9db510SAlexander Kornienko } 14037f9c92a9SJohn McCall 14047f9c92a9SJohn McCall /// Enter a cleanup to call 'operator delete' if the initializer in a 14057f9c92a9SJohn McCall /// new-expression throws. 14067f9c92a9SJohn McCall static void EnterNewDeleteCleanup(CodeGenFunction &CGF, 14077f9c92a9SJohn McCall const CXXNewExpr *E, 14087f416cc4SJohn McCall Address NewPtr, 14097f9c92a9SJohn McCall llvm::Value *AllocSize, 1410b2f0f057SRichard Smith CharUnits AllocAlign, 14117f9c92a9SJohn McCall const CallArgList &NewArgs) { 1412b2f0f057SRichard Smith unsigned NumNonPlacementArgs = E->passAlignment() ? 2 : 1; 1413b2f0f057SRichard Smith 14147f9c92a9SJohn McCall // If we're not inside a conditional branch, then the cleanup will 14157f9c92a9SJohn McCall // dominate and we can do the easier (and more efficient) thing. 14167f9c92a9SJohn McCall if (!CGF.isInConditionalBranch()) { 1417b2f0f057SRichard Smith struct DirectCleanupTraits { 1418b2f0f057SRichard Smith typedef llvm::Value *ValueTy; 1419b2f0f057SRichard Smith typedef RValue RValueTy; 1420b2f0f057SRichard Smith static RValue get(CodeGenFunction &, ValueTy V) { return RValue::get(V); } 1421b2f0f057SRichard Smith static RValue get(CodeGenFunction &, RValueTy V) { return V; } 1422b2f0f057SRichard Smith }; 1423b2f0f057SRichard Smith 1424b2f0f057SRichard Smith typedef CallDeleteDuringNew<DirectCleanupTraits> DirectCleanup; 1425b2f0f057SRichard Smith 1426b2f0f057SRichard Smith DirectCleanup *Cleanup = CGF.EHStack 1427b2f0f057SRichard Smith .pushCleanupWithExtra<DirectCleanup>(EHCleanup, 14287f9c92a9SJohn McCall E->getNumPlacementArgs(), 14297f9c92a9SJohn McCall E->getOperatorDelete(), 14307f416cc4SJohn McCall NewPtr.getPointer(), 1431b2f0f057SRichard Smith AllocSize, 1432b2f0f057SRichard Smith E->passAlignment(), 1433b2f0f057SRichard Smith AllocAlign); 1434b2f0f057SRichard Smith for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) { 1435b2f0f057SRichard Smith auto &Arg = NewArgs[I + NumNonPlacementArgs]; 1436b2f0f057SRichard Smith Cleanup->setPlacementArg(I, Arg.RV, Arg.Ty); 1437b2f0f057SRichard Smith } 14387f9c92a9SJohn McCall 14397f9c92a9SJohn McCall return; 14407f9c92a9SJohn McCall } 14417f9c92a9SJohn McCall 14427f9c92a9SJohn McCall // Otherwise, we need to save all this stuff. 1443cb5f77f0SJohn McCall DominatingValue<RValue>::saved_type SavedNewPtr = 14447f416cc4SJohn McCall DominatingValue<RValue>::save(CGF, RValue::get(NewPtr.getPointer())); 1445cb5f77f0SJohn McCall DominatingValue<RValue>::saved_type SavedAllocSize = 1446cb5f77f0SJohn McCall DominatingValue<RValue>::save(CGF, RValue::get(AllocSize)); 14477f9c92a9SJohn McCall 1448b2f0f057SRichard Smith struct ConditionalCleanupTraits { 1449b2f0f057SRichard Smith typedef DominatingValue<RValue>::saved_type ValueTy; 1450b2f0f057SRichard Smith typedef DominatingValue<RValue>::saved_type RValueTy; 1451b2f0f057SRichard Smith static RValue get(CodeGenFunction &CGF, ValueTy V) { 1452b2f0f057SRichard Smith return V.restore(CGF); 1453b2f0f057SRichard Smith } 1454b2f0f057SRichard Smith }; 1455b2f0f057SRichard Smith typedef CallDeleteDuringNew<ConditionalCleanupTraits> ConditionalCleanup; 1456b2f0f057SRichard Smith 1457b2f0f057SRichard Smith ConditionalCleanup *Cleanup = CGF.EHStack 1458b2f0f057SRichard Smith .pushCleanupWithExtra<ConditionalCleanup>(EHCleanup, 14597f9c92a9SJohn McCall E->getNumPlacementArgs(), 14607f9c92a9SJohn McCall E->getOperatorDelete(), 14617f9c92a9SJohn McCall SavedNewPtr, 1462b2f0f057SRichard Smith SavedAllocSize, 1463b2f0f057SRichard Smith E->passAlignment(), 1464b2f0f057SRichard Smith AllocAlign); 1465b2f0f057SRichard Smith for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) { 1466b2f0f057SRichard Smith auto &Arg = NewArgs[I + NumNonPlacementArgs]; 1467b2f0f057SRichard Smith Cleanup->setPlacementArg(I, DominatingValue<RValue>::save(CGF, Arg.RV), 1468b2f0f057SRichard Smith Arg.Ty); 1469b2f0f057SRichard Smith } 14707f9c92a9SJohn McCall 1471f4beacd0SJohn McCall CGF.initFullExprCleanup(); 1472824c2f53SJohn McCall } 1473824c2f53SJohn McCall 147459486a2dSAnders Carlsson llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) { 147575f9498aSJohn McCall // The element type being allocated. 147675f9498aSJohn McCall QualType allocType = getContext().getBaseElementType(E->getAllocatedType()); 14778ed55a54SJohn McCall 147875f9498aSJohn McCall // 1. Build a call to the allocation function. 147975f9498aSJohn McCall FunctionDecl *allocator = E->getOperatorNew(); 148059486a2dSAnders Carlsson 1481f862eb6aSSebastian Redl // If there is a brace-initializer, cannot allocate fewer elements than inits. 1482f862eb6aSSebastian Redl unsigned minElements = 0; 1483f862eb6aSSebastian Redl if (E->isArray() && E->hasInitializer()) { 14840511d23aSRichard Smith const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer()); 14850511d23aSRichard Smith if (ILE && ILE->isStringLiteralInit()) 14860511d23aSRichard Smith minElements = 14870511d23aSRichard Smith cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe()) 14880511d23aSRichard Smith ->getSize().getZExtValue(); 14890511d23aSRichard Smith else if (ILE) 1490f862eb6aSSebastian Redl minElements = ILE->getNumInits(); 1491f862eb6aSSebastian Redl } 1492f862eb6aSSebastian Redl 14938a13c418SCraig Topper llvm::Value *numElements = nullptr; 14948a13c418SCraig Topper llvm::Value *allocSizeWithoutCookie = nullptr; 149575f9498aSJohn McCall llvm::Value *allocSize = 1496f862eb6aSSebastian Redl EmitCXXNewAllocSize(*this, E, minElements, numElements, 1497f862eb6aSSebastian Redl allocSizeWithoutCookie); 1498b2f0f057SRichard Smith CharUnits allocAlign = getContext().getTypeAlignInChars(allocType); 149959486a2dSAnders Carlsson 15007f416cc4SJohn McCall // Emit the allocation call. If the allocator is a global placement 15017f416cc4SJohn McCall // operator, just "inline" it directly. 15027f416cc4SJohn McCall Address allocation = Address::invalid(); 15037f416cc4SJohn McCall CallArgList allocatorArgs; 15047f416cc4SJohn McCall if (allocator->isReservedGlobalPlacementOperator()) { 150553dcf94dSJohn McCall assert(E->getNumPlacementArgs() == 1); 150653dcf94dSJohn McCall const Expr *arg = *E->placement_arguments().begin(); 150753dcf94dSJohn McCall 15087f416cc4SJohn McCall AlignmentSource alignSource; 150953dcf94dSJohn McCall allocation = EmitPointerWithAlignment(arg, &alignSource); 15107f416cc4SJohn McCall 15117f416cc4SJohn McCall // The pointer expression will, in many cases, be an opaque void*. 15127f416cc4SJohn McCall // In these cases, discard the computed alignment and use the 15137f416cc4SJohn McCall // formal alignment of the allocated type. 1514b2f0f057SRichard Smith if (alignSource != AlignmentSource::Decl) 1515b2f0f057SRichard Smith allocation = Address(allocation.getPointer(), allocAlign); 15167f416cc4SJohn McCall 151753dcf94dSJohn McCall // Set up allocatorArgs for the call to operator delete if it's not 151853dcf94dSJohn McCall // the reserved global operator. 151953dcf94dSJohn McCall if (E->getOperatorDelete() && 152053dcf94dSJohn McCall !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) { 152153dcf94dSJohn McCall allocatorArgs.add(RValue::get(allocSize), getContext().getSizeType()); 152253dcf94dSJohn McCall allocatorArgs.add(RValue::get(allocation.getPointer()), arg->getType()); 152353dcf94dSJohn McCall } 152453dcf94dSJohn McCall 15257f416cc4SJohn McCall } else { 15267f416cc4SJohn McCall const FunctionProtoType *allocatorType = 15277f416cc4SJohn McCall allocator->getType()->castAs<FunctionProtoType>(); 1528b2f0f057SRichard Smith unsigned ParamsToSkip = 0; 15297f416cc4SJohn McCall 15307f416cc4SJohn McCall // The allocation size is the first argument. 15317f416cc4SJohn McCall QualType sizeType = getContext().getSizeType(); 153243dca6a8SEli Friedman allocatorArgs.add(RValue::get(allocSize), sizeType); 1533b2f0f057SRichard Smith ++ParamsToSkip; 153459486a2dSAnders Carlsson 1535b2f0f057SRichard Smith if (allocSize != allocSizeWithoutCookie) { 1536b2f0f057SRichard Smith CharUnits cookieAlign = getSizeAlign(); // FIXME: Ask the ABI. 1537b2f0f057SRichard Smith allocAlign = std::max(allocAlign, cookieAlign); 1538b2f0f057SRichard Smith } 1539b2f0f057SRichard Smith 1540b2f0f057SRichard Smith // The allocation alignment may be passed as the second argument. 1541b2f0f057SRichard Smith if (E->passAlignment()) { 1542b2f0f057SRichard Smith QualType AlignValT = sizeType; 1543b2f0f057SRichard Smith if (allocatorType->getNumParams() > 1) { 1544b2f0f057SRichard Smith AlignValT = allocatorType->getParamType(1); 1545b2f0f057SRichard Smith assert(getContext().hasSameUnqualifiedType( 1546b2f0f057SRichard Smith AlignValT->castAs<EnumType>()->getDecl()->getIntegerType(), 1547b2f0f057SRichard Smith sizeType) && 1548b2f0f057SRichard Smith "wrong type for alignment parameter"); 1549b2f0f057SRichard Smith ++ParamsToSkip; 1550b2f0f057SRichard Smith } else { 1551b2f0f057SRichard Smith // Corner case, passing alignment to 'operator new(size_t, ...)'. 1552b2f0f057SRichard Smith assert(allocator->isVariadic() && "can't pass alignment to allocator"); 1553b2f0f057SRichard Smith } 1554b2f0f057SRichard Smith allocatorArgs.add( 1555b2f0f057SRichard Smith RValue::get(llvm::ConstantInt::get(SizeTy, allocAlign.getQuantity())), 1556b2f0f057SRichard Smith AlignValT); 1557b2f0f057SRichard Smith } 1558b2f0f057SRichard Smith 1559b2f0f057SRichard Smith // FIXME: Why do we not pass a CalleeDecl here? 1560f05779e2SDavid Blaikie EmitCallArgs(allocatorArgs, allocatorType, E->placement_arguments(), 1561b2f0f057SRichard Smith /*CalleeDecl*/nullptr, /*ParamsToSkip*/ParamsToSkip); 156259486a2dSAnders Carlsson 15637f416cc4SJohn McCall RValue RV = 15647f416cc4SJohn McCall EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs); 15657f416cc4SJohn McCall 1566b2f0f057SRichard Smith // If this was a call to a global replaceable allocation function that does 1567b2f0f057SRichard Smith // not take an alignment argument, the allocator is known to produce 1568b2f0f057SRichard Smith // storage that's suitably aligned for any object that fits, up to a known 1569b2f0f057SRichard Smith // threshold. Otherwise assume it's suitably aligned for the allocated type. 1570b2f0f057SRichard Smith CharUnits allocationAlign = allocAlign; 1571b2f0f057SRichard Smith if (!E->passAlignment() && 1572b2f0f057SRichard Smith allocator->isReplaceableGlobalAllocationFunction()) { 1573b2f0f057SRichard Smith unsigned AllocatorAlign = llvm::PowerOf2Floor(std::min<uint64_t>( 1574b2f0f057SRichard Smith Target.getNewAlign(), getContext().getTypeSize(allocType))); 1575b2f0f057SRichard Smith allocationAlign = std::max( 1576b2f0f057SRichard Smith allocationAlign, getContext().toCharUnitsFromBits(AllocatorAlign)); 15777f416cc4SJohn McCall } 15787f416cc4SJohn McCall 15797f416cc4SJohn McCall allocation = Address(RV.getScalarVal(), allocationAlign); 15807ec4b434SJohn McCall } 158159486a2dSAnders Carlsson 158275f9498aSJohn McCall // Emit a null check on the allocation result if the allocation 158375f9498aSJohn McCall // function is allowed to return null (because it has a non-throwing 1584902a0238SRichard Smith // exception spec or is the reserved placement new) and we have an 158575f9498aSJohn McCall // interesting initializer. 1586902a0238SRichard Smith bool nullCheck = E->shouldNullCheckAllocation(getContext()) && 15876047f07eSSebastian Redl (!allocType.isPODType(getContext()) || E->hasInitializer()); 158859486a2dSAnders Carlsson 15898a13c418SCraig Topper llvm::BasicBlock *nullCheckBB = nullptr; 15908a13c418SCraig Topper llvm::BasicBlock *contBB = nullptr; 159159486a2dSAnders Carlsson 1592f7dcf320SJohn McCall // The null-check means that the initializer is conditionally 1593f7dcf320SJohn McCall // evaluated. 1594f7dcf320SJohn McCall ConditionalEvaluation conditional(*this); 1595f7dcf320SJohn McCall 159675f9498aSJohn McCall if (nullCheck) { 1597f7dcf320SJohn McCall conditional.begin(*this); 159875f9498aSJohn McCall 159975f9498aSJohn McCall nullCheckBB = Builder.GetInsertBlock(); 160075f9498aSJohn McCall llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull"); 160175f9498aSJohn McCall contBB = createBasicBlock("new.cont"); 160275f9498aSJohn McCall 16037f416cc4SJohn McCall llvm::Value *isNull = 16047f416cc4SJohn McCall Builder.CreateIsNull(allocation.getPointer(), "new.isnull"); 160575f9498aSJohn McCall Builder.CreateCondBr(isNull, contBB, notNullBB); 160675f9498aSJohn McCall EmitBlock(notNullBB); 160759486a2dSAnders Carlsson } 160859486a2dSAnders Carlsson 1609824c2f53SJohn McCall // If there's an operator delete, enter a cleanup to call it if an 1610824c2f53SJohn McCall // exception is thrown. 161175f9498aSJohn McCall EHScopeStack::stable_iterator operatorDeleteCleanup; 16128a13c418SCraig Topper llvm::Instruction *cleanupDominator = nullptr; 16137ec4b434SJohn McCall if (E->getOperatorDelete() && 16147ec4b434SJohn McCall !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) { 1615b2f0f057SRichard Smith EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocAlign, 1616b2f0f057SRichard Smith allocatorArgs); 161775f9498aSJohn McCall operatorDeleteCleanup = EHStack.stable_begin(); 1618f4beacd0SJohn McCall cleanupDominator = Builder.CreateUnreachable(); 1619824c2f53SJohn McCall } 1620824c2f53SJohn McCall 1621cf9b1f65SEli Friedman assert((allocSize == allocSizeWithoutCookie) == 1622cf9b1f65SEli Friedman CalculateCookiePadding(*this, E).isZero()); 1623cf9b1f65SEli Friedman if (allocSize != allocSizeWithoutCookie) { 1624cf9b1f65SEli Friedman assert(E->isArray()); 1625cf9b1f65SEli Friedman allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation, 1626cf9b1f65SEli Friedman numElements, 1627cf9b1f65SEli Friedman E, allocType); 1628cf9b1f65SEli Friedman } 1629cf9b1f65SEli Friedman 1630fb901c7aSDavid Blaikie llvm::Type *elementTy = ConvertTypeForMem(allocType); 16317f416cc4SJohn McCall Address result = Builder.CreateElementBitCast(allocation, elementTy); 1632824c2f53SJohn McCall 1633338c9d0aSPiotr Padlewski // Passing pointer through invariant.group.barrier to avoid propagation of 1634338c9d0aSPiotr Padlewski // vptrs information which may be included in previous type. 1635338c9d0aSPiotr Padlewski if (CGM.getCodeGenOpts().StrictVTablePointers && 1636338c9d0aSPiotr Padlewski CGM.getCodeGenOpts().OptimizationLevel > 0 && 1637338c9d0aSPiotr Padlewski allocator->isReservedGlobalPlacementOperator()) 1638338c9d0aSPiotr Padlewski result = Address(Builder.CreateInvariantGroupBarrier(result.getPointer()), 1639338c9d0aSPiotr Padlewski result.getAlignment()); 1640338c9d0aSPiotr Padlewski 1641fb901c7aSDavid Blaikie EmitNewInitializer(*this, E, allocType, elementTy, result, numElements, 164299210dc9SJohn McCall allocSizeWithoutCookie); 16438ed55a54SJohn McCall if (E->isArray()) { 16448ed55a54SJohn McCall // NewPtr is a pointer to the base element type. If we're 16458ed55a54SJohn McCall // allocating an array of arrays, we'll need to cast back to the 16468ed55a54SJohn McCall // array pointer type. 16472192fe50SChris Lattner llvm::Type *resultType = ConvertTypeForMem(E->getType()); 16487f416cc4SJohn McCall if (result.getType() != resultType) 164975f9498aSJohn McCall result = Builder.CreateBitCast(result, resultType); 165047b4629bSFariborz Jahanian } 165159486a2dSAnders Carlsson 1652824c2f53SJohn McCall // Deactivate the 'operator delete' cleanup if we finished 1653824c2f53SJohn McCall // initialization. 1654f4beacd0SJohn McCall if (operatorDeleteCleanup.isValid()) { 1655f4beacd0SJohn McCall DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator); 1656f4beacd0SJohn McCall cleanupDominator->eraseFromParent(); 1657f4beacd0SJohn McCall } 1658824c2f53SJohn McCall 16597f416cc4SJohn McCall llvm::Value *resultPtr = result.getPointer(); 166075f9498aSJohn McCall if (nullCheck) { 1661f7dcf320SJohn McCall conditional.end(*this); 1662f7dcf320SJohn McCall 166375f9498aSJohn McCall llvm::BasicBlock *notNullBB = Builder.GetInsertBlock(); 166475f9498aSJohn McCall EmitBlock(contBB); 166559486a2dSAnders Carlsson 16667f416cc4SJohn McCall llvm::PHINode *PHI = Builder.CreatePHI(resultPtr->getType(), 2); 16677f416cc4SJohn McCall PHI->addIncoming(resultPtr, notNullBB); 16687f416cc4SJohn McCall PHI->addIncoming(llvm::Constant::getNullValue(resultPtr->getType()), 166975f9498aSJohn McCall nullCheckBB); 167059486a2dSAnders Carlsson 16717f416cc4SJohn McCall resultPtr = PHI; 167259486a2dSAnders Carlsson } 167359486a2dSAnders Carlsson 16747f416cc4SJohn McCall return resultPtr; 167559486a2dSAnders Carlsson } 167659486a2dSAnders Carlsson 167759486a2dSAnders Carlsson void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD, 1678b2f0f057SRichard Smith llvm::Value *Ptr, QualType DeleteTy, 1679b2f0f057SRichard Smith llvm::Value *NumElements, 1680b2f0f057SRichard Smith CharUnits CookieSize) { 1681b2f0f057SRichard Smith assert((!NumElements && CookieSize.isZero()) || 1682b2f0f057SRichard Smith DeleteFD->getOverloadedOperator() == OO_Array_Delete); 16838ed55a54SJohn McCall 168459486a2dSAnders Carlsson const FunctionProtoType *DeleteFTy = 168559486a2dSAnders Carlsson DeleteFD->getType()->getAs<FunctionProtoType>(); 168659486a2dSAnders Carlsson 168759486a2dSAnders Carlsson CallArgList DeleteArgs; 168859486a2dSAnders Carlsson 1689b2f0f057SRichard Smith std::pair<bool, bool> PassSizeAndAlign = 1690b2f0f057SRichard Smith shouldPassSizeAndAlignToUsualDelete(DeleteFTy); 169121122cf6SAnders Carlsson 1692b2f0f057SRichard Smith auto ParamTypeIt = DeleteFTy->param_type_begin(); 1693b2f0f057SRichard Smith 1694b2f0f057SRichard Smith // Pass the pointer itself. 1695b2f0f057SRichard Smith QualType ArgTy = *ParamTypeIt++; 169659486a2dSAnders Carlsson llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy)); 169743dca6a8SEli Friedman DeleteArgs.add(RValue::get(DeletePtr), ArgTy); 169859486a2dSAnders Carlsson 1699b2f0f057SRichard Smith // Pass the size if the delete function has a size_t parameter. 1700b2f0f057SRichard Smith if (PassSizeAndAlign.first) { 1701b2f0f057SRichard Smith QualType SizeType = *ParamTypeIt++; 1702b2f0f057SRichard Smith CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy); 1703b2f0f057SRichard Smith llvm::Value *Size = llvm::ConstantInt::get(ConvertType(SizeType), 1704b2f0f057SRichard Smith DeleteTypeSize.getQuantity()); 1705b2f0f057SRichard Smith 1706b2f0f057SRichard Smith // For array new, multiply by the number of elements. 1707b2f0f057SRichard Smith if (NumElements) 1708b2f0f057SRichard Smith Size = Builder.CreateMul(Size, NumElements); 1709b2f0f057SRichard Smith 1710b2f0f057SRichard Smith // If there is a cookie, add the cookie size. 1711b2f0f057SRichard Smith if (!CookieSize.isZero()) 1712b2f0f057SRichard Smith Size = Builder.CreateAdd( 1713b2f0f057SRichard Smith Size, llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity())); 1714b2f0f057SRichard Smith 1715b2f0f057SRichard Smith DeleteArgs.add(RValue::get(Size), SizeType); 1716b2f0f057SRichard Smith } 1717b2f0f057SRichard Smith 1718b2f0f057SRichard Smith // Pass the alignment if the delete function has an align_val_t parameter. 1719b2f0f057SRichard Smith if (PassSizeAndAlign.second) { 1720b2f0f057SRichard Smith QualType AlignValType = *ParamTypeIt++; 1721b2f0f057SRichard Smith CharUnits DeleteTypeAlign = getContext().toCharUnitsFromBits( 1722b2f0f057SRichard Smith getContext().getTypeAlignIfKnown(DeleteTy)); 1723b2f0f057SRichard Smith llvm::Value *Align = llvm::ConstantInt::get(ConvertType(AlignValType), 1724b2f0f057SRichard Smith DeleteTypeAlign.getQuantity()); 1725b2f0f057SRichard Smith DeleteArgs.add(RValue::get(Align), AlignValType); 1726b2f0f057SRichard Smith } 1727b2f0f057SRichard Smith 1728b2f0f057SRichard Smith assert(ParamTypeIt == DeleteFTy->param_type_end() && 1729b2f0f057SRichard Smith "unknown parameter to usual delete function"); 173059486a2dSAnders Carlsson 173159486a2dSAnders Carlsson // Emit the call to delete. 17328d0dc31dSRichard Smith EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs); 173359486a2dSAnders Carlsson } 173459486a2dSAnders Carlsson 17358ed55a54SJohn McCall namespace { 17368ed55a54SJohn McCall /// Calls the given 'operator delete' on a single object. 17377e70d680SDavid Blaikie struct CallObjectDelete final : EHScopeStack::Cleanup { 17388ed55a54SJohn McCall llvm::Value *Ptr; 17398ed55a54SJohn McCall const FunctionDecl *OperatorDelete; 17408ed55a54SJohn McCall QualType ElementType; 17418ed55a54SJohn McCall 17428ed55a54SJohn McCall CallObjectDelete(llvm::Value *Ptr, 17438ed55a54SJohn McCall const FunctionDecl *OperatorDelete, 17448ed55a54SJohn McCall QualType ElementType) 17458ed55a54SJohn McCall : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {} 17468ed55a54SJohn McCall 17474f12f10dSCraig Topper void Emit(CodeGenFunction &CGF, Flags flags) override { 17488ed55a54SJohn McCall CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType); 17498ed55a54SJohn McCall } 17508ed55a54SJohn McCall }; 1751ab9db510SAlexander Kornienko } 17528ed55a54SJohn McCall 17530c0b6d9aSDavid Majnemer void 17540c0b6d9aSDavid Majnemer CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete, 17550c0b6d9aSDavid Majnemer llvm::Value *CompletePtr, 17560c0b6d9aSDavid Majnemer QualType ElementType) { 17570c0b6d9aSDavid Majnemer EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr, 17580c0b6d9aSDavid Majnemer OperatorDelete, ElementType); 17590c0b6d9aSDavid Majnemer } 17600c0b6d9aSDavid Majnemer 17618ed55a54SJohn McCall /// Emit the code for deleting a single object. 17628ed55a54SJohn McCall static void EmitObjectDelete(CodeGenFunction &CGF, 17630868137aSDavid Majnemer const CXXDeleteExpr *DE, 17647f416cc4SJohn McCall Address Ptr, 17650868137aSDavid Majnemer QualType ElementType) { 17668ed55a54SJohn McCall // Find the destructor for the type, if applicable. If the 17678ed55a54SJohn McCall // destructor is virtual, we'll just emit the vcall and return. 17688a13c418SCraig Topper const CXXDestructorDecl *Dtor = nullptr; 17698ed55a54SJohn McCall if (const RecordType *RT = ElementType->getAs<RecordType>()) { 17708ed55a54SJohn McCall CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 1771b23533dbSEli Friedman if (RD->hasDefinition() && !RD->hasTrivialDestructor()) { 17728ed55a54SJohn McCall Dtor = RD->getDestructor(); 17738ed55a54SJohn McCall 17748ed55a54SJohn McCall if (Dtor->isVirtual()) { 17750868137aSDavid Majnemer CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType, 17760868137aSDavid Majnemer Dtor); 17778ed55a54SJohn McCall return; 17788ed55a54SJohn McCall } 17798ed55a54SJohn McCall } 17808ed55a54SJohn McCall } 17818ed55a54SJohn McCall 17828ed55a54SJohn McCall // Make sure that we call delete even if the dtor throws. 1783e4df6c8dSJohn McCall // This doesn't have to a conditional cleanup because we're going 1784e4df6c8dSJohn McCall // to pop it off in a second. 17850868137aSDavid Majnemer const FunctionDecl *OperatorDelete = DE->getOperatorDelete(); 17868ed55a54SJohn McCall CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, 17877f416cc4SJohn McCall Ptr.getPointer(), 17887f416cc4SJohn McCall OperatorDelete, ElementType); 17898ed55a54SJohn McCall 17908ed55a54SJohn McCall if (Dtor) 17918ed55a54SJohn McCall CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, 179261535005SDouglas Gregor /*ForVirtualBase=*/false, 179361535005SDouglas Gregor /*Delegating=*/false, 179461535005SDouglas Gregor Ptr); 1795460ce58fSJohn McCall else if (auto Lifetime = ElementType.getObjCLifetime()) { 1796460ce58fSJohn McCall switch (Lifetime) { 179731168b07SJohn McCall case Qualifiers::OCL_None: 179831168b07SJohn McCall case Qualifiers::OCL_ExplicitNone: 179931168b07SJohn McCall case Qualifiers::OCL_Autoreleasing: 180031168b07SJohn McCall break; 180131168b07SJohn McCall 18027f416cc4SJohn McCall case Qualifiers::OCL_Strong: 18037f416cc4SJohn McCall CGF.EmitARCDestroyStrong(Ptr, ARCPreciseLifetime); 180431168b07SJohn McCall break; 180531168b07SJohn McCall 180631168b07SJohn McCall case Qualifiers::OCL_Weak: 180731168b07SJohn McCall CGF.EmitARCDestroyWeak(Ptr); 180831168b07SJohn McCall break; 180931168b07SJohn McCall } 181031168b07SJohn McCall } 18118ed55a54SJohn McCall 18128ed55a54SJohn McCall CGF.PopCleanupBlock(); 18138ed55a54SJohn McCall } 18148ed55a54SJohn McCall 18158ed55a54SJohn McCall namespace { 18168ed55a54SJohn McCall /// Calls the given 'operator delete' on an array of objects. 18177e70d680SDavid Blaikie struct CallArrayDelete final : EHScopeStack::Cleanup { 18188ed55a54SJohn McCall llvm::Value *Ptr; 18198ed55a54SJohn McCall const FunctionDecl *OperatorDelete; 18208ed55a54SJohn McCall llvm::Value *NumElements; 18218ed55a54SJohn McCall QualType ElementType; 18228ed55a54SJohn McCall CharUnits CookieSize; 18238ed55a54SJohn McCall 18248ed55a54SJohn McCall CallArrayDelete(llvm::Value *Ptr, 18258ed55a54SJohn McCall const FunctionDecl *OperatorDelete, 18268ed55a54SJohn McCall llvm::Value *NumElements, 18278ed55a54SJohn McCall QualType ElementType, 18288ed55a54SJohn McCall CharUnits CookieSize) 18298ed55a54SJohn McCall : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements), 18308ed55a54SJohn McCall ElementType(ElementType), CookieSize(CookieSize) {} 18318ed55a54SJohn McCall 18324f12f10dSCraig Topper void Emit(CodeGenFunction &CGF, Flags flags) override { 1833b2f0f057SRichard Smith CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType, NumElements, 1834b2f0f057SRichard Smith CookieSize); 18358ed55a54SJohn McCall } 18368ed55a54SJohn McCall }; 1837ab9db510SAlexander Kornienko } 18388ed55a54SJohn McCall 18398ed55a54SJohn McCall /// Emit the code for deleting an array of objects. 18408ed55a54SJohn McCall static void EmitArrayDelete(CodeGenFunction &CGF, 1841284c48ffSJohn McCall const CXXDeleteExpr *E, 18427f416cc4SJohn McCall Address deletedPtr, 1843ca2c56f2SJohn McCall QualType elementType) { 18448a13c418SCraig Topper llvm::Value *numElements = nullptr; 18458a13c418SCraig Topper llvm::Value *allocatedPtr = nullptr; 1846ca2c56f2SJohn McCall CharUnits cookieSize; 1847ca2c56f2SJohn McCall CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType, 1848ca2c56f2SJohn McCall numElements, allocatedPtr, cookieSize); 18498ed55a54SJohn McCall 1850ca2c56f2SJohn McCall assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer"); 18518ed55a54SJohn McCall 18528ed55a54SJohn McCall // Make sure that we call delete even if one of the dtors throws. 1853ca2c56f2SJohn McCall const FunctionDecl *operatorDelete = E->getOperatorDelete(); 18548ed55a54SJohn McCall CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup, 1855ca2c56f2SJohn McCall allocatedPtr, operatorDelete, 1856ca2c56f2SJohn McCall numElements, elementType, 1857ca2c56f2SJohn McCall cookieSize); 18588ed55a54SJohn McCall 1859ca2c56f2SJohn McCall // Destroy the elements. 1860ca2c56f2SJohn McCall if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) { 1861ca2c56f2SJohn McCall assert(numElements && "no element count for a type with a destructor!"); 186231168b07SJohn McCall 18637f416cc4SJohn McCall CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType); 18647f416cc4SJohn McCall CharUnits elementAlign = 18657f416cc4SJohn McCall deletedPtr.getAlignment().alignmentOfArrayElement(elementSize); 18667f416cc4SJohn McCall 18677f416cc4SJohn McCall llvm::Value *arrayBegin = deletedPtr.getPointer(); 1868ca2c56f2SJohn McCall llvm::Value *arrayEnd = 18697f416cc4SJohn McCall CGF.Builder.CreateInBoundsGEP(arrayBegin, numElements, "delete.end"); 187097eab0a2SJohn McCall 187197eab0a2SJohn McCall // Note that it is legal to allocate a zero-length array, and we 187297eab0a2SJohn McCall // can never fold the check away because the length should always 187397eab0a2SJohn McCall // come from a cookie. 18747f416cc4SJohn McCall CGF.emitArrayDestroy(arrayBegin, arrayEnd, elementType, elementAlign, 1875ca2c56f2SJohn McCall CGF.getDestroyer(dtorKind), 187697eab0a2SJohn McCall /*checkZeroLength*/ true, 1877ca2c56f2SJohn McCall CGF.needsEHCleanup(dtorKind)); 18788ed55a54SJohn McCall } 18798ed55a54SJohn McCall 1880ca2c56f2SJohn McCall // Pop the cleanup block. 18818ed55a54SJohn McCall CGF.PopCleanupBlock(); 18828ed55a54SJohn McCall } 18838ed55a54SJohn McCall 188459486a2dSAnders Carlsson void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) { 188559486a2dSAnders Carlsson const Expr *Arg = E->getArgument(); 18867f416cc4SJohn McCall Address Ptr = EmitPointerWithAlignment(Arg); 188759486a2dSAnders Carlsson 188859486a2dSAnders Carlsson // Null check the pointer. 188959486a2dSAnders Carlsson llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull"); 189059486a2dSAnders Carlsson llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end"); 189159486a2dSAnders Carlsson 18927f416cc4SJohn McCall llvm::Value *IsNull = Builder.CreateIsNull(Ptr.getPointer(), "isnull"); 189359486a2dSAnders Carlsson 189459486a2dSAnders Carlsson Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull); 189559486a2dSAnders Carlsson EmitBlock(DeleteNotNull); 189659486a2dSAnders Carlsson 18978ed55a54SJohn McCall // We might be deleting a pointer to array. If so, GEP down to the 18988ed55a54SJohn McCall // first non-array element. 18998ed55a54SJohn McCall // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*) 19008ed55a54SJohn McCall QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType(); 19018ed55a54SJohn McCall if (DeleteTy->isConstantArrayType()) { 19028ed55a54SJohn McCall llvm::Value *Zero = Builder.getInt32(0); 19030e62c1ccSChris Lattner SmallVector<llvm::Value*,8> GEP; 190459486a2dSAnders Carlsson 19058ed55a54SJohn McCall GEP.push_back(Zero); // point at the outermost array 19068ed55a54SJohn McCall 19078ed55a54SJohn McCall // For each layer of array type we're pointing at: 19088ed55a54SJohn McCall while (const ConstantArrayType *Arr 19098ed55a54SJohn McCall = getContext().getAsConstantArrayType(DeleteTy)) { 19108ed55a54SJohn McCall // 1. Unpeel the array type. 19118ed55a54SJohn McCall DeleteTy = Arr->getElementType(); 19128ed55a54SJohn McCall 19138ed55a54SJohn McCall // 2. GEP to the first element of the array. 19148ed55a54SJohn McCall GEP.push_back(Zero); 19158ed55a54SJohn McCall } 19168ed55a54SJohn McCall 19177f416cc4SJohn McCall Ptr = Address(Builder.CreateInBoundsGEP(Ptr.getPointer(), GEP, "del.first"), 19187f416cc4SJohn McCall Ptr.getAlignment()); 19198ed55a54SJohn McCall } 19208ed55a54SJohn McCall 19217f416cc4SJohn McCall assert(ConvertTypeForMem(DeleteTy) == Ptr.getElementType()); 19228ed55a54SJohn McCall 19237270ef57SReid Kleckner if (E->isArrayForm()) { 19247270ef57SReid Kleckner EmitArrayDelete(*this, E, Ptr, DeleteTy); 19257270ef57SReid Kleckner } else { 19267270ef57SReid Kleckner EmitObjectDelete(*this, E, Ptr, DeleteTy); 19277270ef57SReid Kleckner } 192859486a2dSAnders Carlsson 192959486a2dSAnders Carlsson EmitBlock(DeleteEnd); 193059486a2dSAnders Carlsson } 193159486a2dSAnders Carlsson 19321c3d95ebSDavid Majnemer static bool isGLValueFromPointerDeref(const Expr *E) { 19331c3d95ebSDavid Majnemer E = E->IgnoreParens(); 19341c3d95ebSDavid Majnemer 19351c3d95ebSDavid Majnemer if (const auto *CE = dyn_cast<CastExpr>(E)) { 19361c3d95ebSDavid Majnemer if (!CE->getSubExpr()->isGLValue()) 19371c3d95ebSDavid Majnemer return false; 19381c3d95ebSDavid Majnemer return isGLValueFromPointerDeref(CE->getSubExpr()); 19391c3d95ebSDavid Majnemer } 19401c3d95ebSDavid Majnemer 19411c3d95ebSDavid Majnemer if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 19421c3d95ebSDavid Majnemer return isGLValueFromPointerDeref(OVE->getSourceExpr()); 19431c3d95ebSDavid Majnemer 19441c3d95ebSDavid Majnemer if (const auto *BO = dyn_cast<BinaryOperator>(E)) 19451c3d95ebSDavid Majnemer if (BO->getOpcode() == BO_Comma) 19461c3d95ebSDavid Majnemer return isGLValueFromPointerDeref(BO->getRHS()); 19471c3d95ebSDavid Majnemer 19481c3d95ebSDavid Majnemer if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E)) 19491c3d95ebSDavid Majnemer return isGLValueFromPointerDeref(ACO->getTrueExpr()) || 19501c3d95ebSDavid Majnemer isGLValueFromPointerDeref(ACO->getFalseExpr()); 19511c3d95ebSDavid Majnemer 19521c3d95ebSDavid Majnemer // C++11 [expr.sub]p1: 19531c3d95ebSDavid Majnemer // The expression E1[E2] is identical (by definition) to *((E1)+(E2)) 19541c3d95ebSDavid Majnemer if (isa<ArraySubscriptExpr>(E)) 19551c3d95ebSDavid Majnemer return true; 19561c3d95ebSDavid Majnemer 19571c3d95ebSDavid Majnemer if (const auto *UO = dyn_cast<UnaryOperator>(E)) 19581c3d95ebSDavid Majnemer if (UO->getOpcode() == UO_Deref) 19591c3d95ebSDavid Majnemer return true; 19601c3d95ebSDavid Majnemer 19611c3d95ebSDavid Majnemer return false; 19621c3d95ebSDavid Majnemer } 19631c3d95ebSDavid Majnemer 1964747e301eSWarren Hunt static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E, 19652192fe50SChris Lattner llvm::Type *StdTypeInfoPtrTy) { 1966940f02d2SAnders Carlsson // Get the vtable pointer. 19677f416cc4SJohn McCall Address ThisPtr = CGF.EmitLValue(E).getAddress(); 1968940f02d2SAnders Carlsson 1969940f02d2SAnders Carlsson // C++ [expr.typeid]p2: 1970940f02d2SAnders Carlsson // If the glvalue expression is obtained by applying the unary * operator to 1971940f02d2SAnders Carlsson // a pointer and the pointer is a null pointer value, the typeid expression 1972940f02d2SAnders Carlsson // throws the std::bad_typeid exception. 19731c3d95ebSDavid Majnemer // 19741c3d95ebSDavid Majnemer // However, this paragraph's intent is not clear. We choose a very generous 19751c3d95ebSDavid Majnemer // interpretation which implores us to consider comma operators, conditional 19761c3d95ebSDavid Majnemer // operators, parentheses and other such constructs. 19771162d25cSDavid Majnemer QualType SrcRecordTy = E->getType(); 19781c3d95ebSDavid Majnemer if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked( 19791c3d95ebSDavid Majnemer isGLValueFromPointerDeref(E), SrcRecordTy)) { 1980940f02d2SAnders Carlsson llvm::BasicBlock *BadTypeidBlock = 1981940f02d2SAnders Carlsson CGF.createBasicBlock("typeid.bad_typeid"); 19821162d25cSDavid Majnemer llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end"); 1983940f02d2SAnders Carlsson 19847f416cc4SJohn McCall llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr.getPointer()); 1985940f02d2SAnders Carlsson CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock); 1986940f02d2SAnders Carlsson 1987940f02d2SAnders Carlsson CGF.EmitBlock(BadTypeidBlock); 19881162d25cSDavid Majnemer CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF); 1989940f02d2SAnders Carlsson CGF.EmitBlock(EndBlock); 1990940f02d2SAnders Carlsson } 1991940f02d2SAnders Carlsson 19921162d25cSDavid Majnemer return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr, 19931162d25cSDavid Majnemer StdTypeInfoPtrTy); 1994940f02d2SAnders Carlsson } 1995940f02d2SAnders Carlsson 199659486a2dSAnders Carlsson llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) { 19972192fe50SChris Lattner llvm::Type *StdTypeInfoPtrTy = 1998940f02d2SAnders Carlsson ConvertType(E->getType())->getPointerTo(); 1999fd7dfeb7SAnders Carlsson 20003f4336cbSAnders Carlsson if (E->isTypeOperand()) { 20013f4336cbSAnders Carlsson llvm::Constant *TypeInfo = 2002143c55eaSDavid Majnemer CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext())); 2003940f02d2SAnders Carlsson return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy); 20043f4336cbSAnders Carlsson } 2005fd7dfeb7SAnders Carlsson 2006940f02d2SAnders Carlsson // C++ [expr.typeid]p2: 2007940f02d2SAnders Carlsson // When typeid is applied to a glvalue expression whose type is a 2008940f02d2SAnders Carlsson // polymorphic class type, the result refers to a std::type_info object 2009940f02d2SAnders Carlsson // representing the type of the most derived object (that is, the dynamic 2010940f02d2SAnders Carlsson // type) to which the glvalue refers. 2011ef8bf436SRichard Smith if (E->isPotentiallyEvaluated()) 2012940f02d2SAnders Carlsson return EmitTypeidFromVTable(*this, E->getExprOperand(), 2013940f02d2SAnders Carlsson StdTypeInfoPtrTy); 2014940f02d2SAnders Carlsson 2015940f02d2SAnders Carlsson QualType OperandTy = E->getExprOperand()->getType(); 2016940f02d2SAnders Carlsson return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy), 2017940f02d2SAnders Carlsson StdTypeInfoPtrTy); 201859486a2dSAnders Carlsson } 201959486a2dSAnders Carlsson 2020c1c9971cSAnders Carlsson static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF, 2021c1c9971cSAnders Carlsson QualType DestTy) { 20222192fe50SChris Lattner llvm::Type *DestLTy = CGF.ConvertType(DestTy); 2023c1c9971cSAnders Carlsson if (DestTy->isPointerType()) 2024c1c9971cSAnders Carlsson return llvm::Constant::getNullValue(DestLTy); 2025c1c9971cSAnders Carlsson 2026c1c9971cSAnders Carlsson /// C++ [expr.dynamic.cast]p9: 2027c1c9971cSAnders Carlsson /// A failed cast to reference type throws std::bad_cast 20281162d25cSDavid Majnemer if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF)) 20291162d25cSDavid Majnemer return nullptr; 2030c1c9971cSAnders Carlsson 2031c1c9971cSAnders Carlsson CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end")); 2032c1c9971cSAnders Carlsson return llvm::UndefValue::get(DestLTy); 2033c1c9971cSAnders Carlsson } 2034c1c9971cSAnders Carlsson 20357f416cc4SJohn McCall llvm::Value *CodeGenFunction::EmitDynamicCast(Address ThisAddr, 203659486a2dSAnders Carlsson const CXXDynamicCastExpr *DCE) { 20372bf9b4c0SAlexey Bataev CGM.EmitExplicitCastExprType(DCE, this); 20383f4336cbSAnders Carlsson QualType DestTy = DCE->getTypeAsWritten(); 20393f4336cbSAnders Carlsson 2040c1c9971cSAnders Carlsson if (DCE->isAlwaysNull()) 20411162d25cSDavid Majnemer if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy)) 20421162d25cSDavid Majnemer return T; 2043c1c9971cSAnders Carlsson 2044c1c9971cSAnders Carlsson QualType SrcTy = DCE->getSubExpr()->getType(); 2045c1c9971cSAnders Carlsson 20461162d25cSDavid Majnemer // C++ [expr.dynamic.cast]p7: 20471162d25cSDavid Majnemer // If T is "pointer to cv void," then the result is a pointer to the most 20481162d25cSDavid Majnemer // derived object pointed to by v. 20491162d25cSDavid Majnemer const PointerType *DestPTy = DestTy->getAs<PointerType>(); 20501162d25cSDavid Majnemer 20511162d25cSDavid Majnemer bool isDynamicCastToVoid; 20521162d25cSDavid Majnemer QualType SrcRecordTy; 20531162d25cSDavid Majnemer QualType DestRecordTy; 20541162d25cSDavid Majnemer if (DestPTy) { 20551162d25cSDavid Majnemer isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType(); 20561162d25cSDavid Majnemer SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType(); 20571162d25cSDavid Majnemer DestRecordTy = DestPTy->getPointeeType(); 20581162d25cSDavid Majnemer } else { 20591162d25cSDavid Majnemer isDynamicCastToVoid = false; 20601162d25cSDavid Majnemer SrcRecordTy = SrcTy; 20611162d25cSDavid Majnemer DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType(); 20621162d25cSDavid Majnemer } 20631162d25cSDavid Majnemer 20641162d25cSDavid Majnemer assert(SrcRecordTy->isRecordType() && "source type must be a record type!"); 20651162d25cSDavid Majnemer 2066882d790fSAnders Carlsson // C++ [expr.dynamic.cast]p4: 2067882d790fSAnders Carlsson // If the value of v is a null pointer value in the pointer case, the result 2068882d790fSAnders Carlsson // is the null pointer value of type T. 20691162d25cSDavid Majnemer bool ShouldNullCheckSrcValue = 20701162d25cSDavid Majnemer CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(), 20711162d25cSDavid Majnemer SrcRecordTy); 207259486a2dSAnders Carlsson 20738a13c418SCraig Topper llvm::BasicBlock *CastNull = nullptr; 20748a13c418SCraig Topper llvm::BasicBlock *CastNotNull = nullptr; 2075882d790fSAnders Carlsson llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end"); 2076fa8b4955SDouglas Gregor 2077882d790fSAnders Carlsson if (ShouldNullCheckSrcValue) { 2078882d790fSAnders Carlsson CastNull = createBasicBlock("dynamic_cast.null"); 2079882d790fSAnders Carlsson CastNotNull = createBasicBlock("dynamic_cast.notnull"); 2080882d790fSAnders Carlsson 20817f416cc4SJohn McCall llvm::Value *IsNull = Builder.CreateIsNull(ThisAddr.getPointer()); 2082882d790fSAnders Carlsson Builder.CreateCondBr(IsNull, CastNull, CastNotNull); 2083882d790fSAnders Carlsson EmitBlock(CastNotNull); 208459486a2dSAnders Carlsson } 208559486a2dSAnders Carlsson 20867f416cc4SJohn McCall llvm::Value *Value; 20871162d25cSDavid Majnemer if (isDynamicCastToVoid) { 20887f416cc4SJohn McCall Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, ThisAddr, SrcRecordTy, 20891162d25cSDavid Majnemer DestTy); 20901162d25cSDavid Majnemer } else { 20911162d25cSDavid Majnemer assert(DestRecordTy->isRecordType() && 20921162d25cSDavid Majnemer "destination type must be a record type!"); 20937f416cc4SJohn McCall Value = CGM.getCXXABI().EmitDynamicCastCall(*this, ThisAddr, SrcRecordTy, 20941162d25cSDavid Majnemer DestTy, DestRecordTy, CastEnd); 209567528eaaSDavid Majnemer CastNotNull = Builder.GetInsertBlock(); 20961162d25cSDavid Majnemer } 20973f4336cbSAnders Carlsson 2098882d790fSAnders Carlsson if (ShouldNullCheckSrcValue) { 2099882d790fSAnders Carlsson EmitBranch(CastEnd); 210059486a2dSAnders Carlsson 2101882d790fSAnders Carlsson EmitBlock(CastNull); 2102882d790fSAnders Carlsson EmitBranch(CastEnd); 210359486a2dSAnders Carlsson } 210459486a2dSAnders Carlsson 2105882d790fSAnders Carlsson EmitBlock(CastEnd); 210659486a2dSAnders Carlsson 2107882d790fSAnders Carlsson if (ShouldNullCheckSrcValue) { 2108882d790fSAnders Carlsson llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2); 2109882d790fSAnders Carlsson PHI->addIncoming(Value, CastNotNull); 2110882d790fSAnders Carlsson PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull); 211159486a2dSAnders Carlsson 2112882d790fSAnders Carlsson Value = PHI; 211359486a2dSAnders Carlsson } 211459486a2dSAnders Carlsson 2115882d790fSAnders Carlsson return Value; 211659486a2dSAnders Carlsson } 2117c370a7eeSEli Friedman 2118c370a7eeSEli Friedman void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) { 21198631f3e8SEli Friedman RunCleanupsScope Scope(*this); 21207f416cc4SJohn McCall LValue SlotLV = MakeAddrLValue(Slot.getAddress(), E->getType()); 21218631f3e8SEli Friedman 2122c370a7eeSEli Friedman CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin(); 212353c7616eSJames Y Knight for (LambdaExpr::const_capture_init_iterator i = E->capture_init_begin(), 2124c370a7eeSEli Friedman e = E->capture_init_end(); 2125c370a7eeSEli Friedman i != e; ++i, ++CurField) { 2126c370a7eeSEli Friedman // Emit initialization 212740ed2973SDavid Blaikie LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField); 212839c81e28SAlexey Bataev if (CurField->hasCapturedVLAType()) { 212939c81e28SAlexey Bataev auto VAT = CurField->getCapturedVLAType(); 213039c81e28SAlexey Bataev EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV); 213139c81e28SAlexey Bataev } else { 21325f1a04ffSEli Friedman ArrayRef<VarDecl *> ArrayIndexes; 21335f1a04ffSEli Friedman if (CurField->getType()->isArrayType()) 21345f1a04ffSEli Friedman ArrayIndexes = E->getCaptureInitIndexVars(i); 213540ed2973SDavid Blaikie EmitInitializerForField(*CurField, LV, *i, ArrayIndexes); 2136c370a7eeSEli Friedman } 2137c370a7eeSEli Friedman } 213839c81e28SAlexey Bataev } 2139