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( 830c0b6d9aSDavid Majnemer const CXXMethodDecl *MD, llvm::Value *Callee, ReturnValueSlot ReturnValue, 840c0b6d9aSDavid Majnemer llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy, 85762672a7SRichard Smith const CallExpr *CE, CallArgList *RtlArgs) { 860c0b6d9aSDavid Majnemer const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 870c0b6d9aSDavid Majnemer CallArgList Args; 880c0b6d9aSDavid Majnemer RequiredArgs required = commonEmitCXXMemberOrOperatorCall( 89762672a7SRichard Smith *this, MD, This, ImplicitParam, ImplicitParamTy, CE, Args, RtlArgs); 908dda7b27SJohn McCall return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required), 91c50c27ccSRafael Espindola Callee, ReturnValue, Args, MD); 9227da15baSAnders Carlsson } 9327da15baSAnders Carlsson 94ae81bbb4SAlexey Samsonov RValue CodeGenFunction::EmitCXXDestructorCall( 95ae81bbb4SAlexey Samsonov const CXXDestructorDecl *DD, llvm::Value *Callee, llvm::Value *This, 96ae81bbb4SAlexey Samsonov llvm::Value *ImplicitParam, QualType ImplicitParamTy, const CallExpr *CE, 97ae81bbb4SAlexey Samsonov StructorType Type) { 980c0b6d9aSDavid Majnemer CallArgList Args; 99ae81bbb4SAlexey Samsonov commonEmitCXXMemberOrOperatorCall(*this, DD, This, ImplicitParam, 100762672a7SRichard Smith ImplicitParamTy, CE, Args, nullptr); 101ae81bbb4SAlexey Samsonov return EmitCall(CGM.getTypes().arrangeCXXStructorDeclaration(DD, Type), 102ae81bbb4SAlexey Samsonov Callee, ReturnValueSlot(), Args, DD); 1030c0b6d9aSDavid Majnemer } 1040c0b6d9aSDavid Majnemer 1053b33c4ecSRafael Espindola static CXXRecordDecl *getCXXRecord(const Expr *E) { 1063b33c4ecSRafael Espindola QualType T = E->getType(); 1073b33c4ecSRafael Espindola if (const PointerType *PTy = T->getAs<PointerType>()) 1083b33c4ecSRafael Espindola T = PTy->getPointeeType(); 1093b33c4ecSRafael Espindola const RecordType *Ty = T->castAs<RecordType>(); 1103b33c4ecSRafael Espindola return cast<CXXRecordDecl>(Ty->getDecl()); 1113b33c4ecSRafael Espindola } 1123b33c4ecSRafael Espindola 11364225794SFrancois Pichet // Note: This function also emit constructor calls to support a MSVC 11464225794SFrancois Pichet // extensions allowing explicit constructor function call. 11527da15baSAnders Carlsson RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE, 11627da15baSAnders Carlsson ReturnValueSlot ReturnValue) { 1172d2e8707SJohn McCall const Expr *callee = CE->getCallee()->IgnoreParens(); 1182d2e8707SJohn McCall 1192d2e8707SJohn McCall if (isa<BinaryOperator>(callee)) 12027da15baSAnders Carlsson return EmitCXXMemberPointerCallExpr(CE, ReturnValue); 12127da15baSAnders Carlsson 1222d2e8707SJohn McCall const MemberExpr *ME = cast<MemberExpr>(callee); 12327da15baSAnders Carlsson const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl()); 12427da15baSAnders Carlsson 12527da15baSAnders Carlsson if (MD->isStatic()) { 12627da15baSAnders Carlsson // The method is static, emit it as we would a regular call. 12727da15baSAnders Carlsson llvm::Value *Callee = CGM.GetAddrOfFunction(MD); 12870b9c01bSAlexey Samsonov return EmitCall(getContext().getPointerType(MD->getType()), Callee, CE, 12970b9c01bSAlexey Samsonov ReturnValue); 13027da15baSAnders Carlsson } 13127da15baSAnders Carlsson 132aad4af6dSNico Weber bool HasQualifier = ME->hasQualifier(); 133aad4af6dSNico Weber NestedNameSpecifier *Qualifier = HasQualifier ? ME->getQualifier() : nullptr; 134aad4af6dSNico Weber bool IsArrow = ME->isArrow(); 135ecbe2e97SRafael Espindola const Expr *Base = ME->getBase(); 136aad4af6dSNico Weber 137aad4af6dSNico Weber return EmitCXXMemberOrOperatorMemberCallExpr( 138aad4af6dSNico Weber CE, MD, ReturnValue, HasQualifier, Qualifier, IsArrow, Base); 139aad4af6dSNico Weber } 140aad4af6dSNico Weber 141aad4af6dSNico Weber RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr( 142aad4af6dSNico Weber const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue, 143aad4af6dSNico Weber bool HasQualifier, NestedNameSpecifier *Qualifier, bool IsArrow, 144aad4af6dSNico Weber const Expr *Base) { 145aad4af6dSNico Weber assert(isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE)); 146aad4af6dSNico Weber 147aad4af6dSNico Weber // Compute the object pointer. 148aad4af6dSNico Weber bool CanUseVirtualCall = MD->isVirtual() && !HasQualifier; 149ecbe2e97SRafael Espindola 1508a13c418SCraig Topper const CXXMethodDecl *DevirtualizedMethod = nullptr; 1517463ed7cSBenjamin Kramer if (CanUseVirtualCall && CanDevirtualizeMemberFunctionCall(Base, MD)) { 1523b33c4ecSRafael Espindola const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType(); 1533b33c4ecSRafael Espindola DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl); 1543b33c4ecSRafael Espindola assert(DevirtualizedMethod); 1553b33c4ecSRafael Espindola const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent(); 1563b33c4ecSRafael Espindola const Expr *Inner = Base->ignoreParenBaseCasts(); 1575bd68794SAlexey Bataev if (DevirtualizedMethod->getReturnType().getCanonicalType() != 1585bd68794SAlexey Bataev MD->getReturnType().getCanonicalType()) 1595bd68794SAlexey Bataev // If the return types are not the same, this might be a case where more 1605bd68794SAlexey Bataev // code needs to run to compensate for it. For example, the derived 1615bd68794SAlexey Bataev // method might return a type that inherits form from the return 1625bd68794SAlexey Bataev // type of MD and has a prefix. 1635bd68794SAlexey Bataev // For now we just avoid devirtualizing these covariant cases. 1645bd68794SAlexey Bataev DevirtualizedMethod = nullptr; 1655bd68794SAlexey Bataev else if (getCXXRecord(Inner) == DevirtualizedClass) 1663b33c4ecSRafael Espindola // If the class of the Inner expression is where the dynamic method 1673b33c4ecSRafael Espindola // is defined, build the this pointer from it. 1683b33c4ecSRafael Espindola Base = Inner; 1693b33c4ecSRafael Espindola else if (getCXXRecord(Base) != DevirtualizedClass) { 1703b33c4ecSRafael Espindola // If the method is defined in a class that is not the best dynamic 1713b33c4ecSRafael Espindola // one or the one of the full expression, we would have to build 1723b33c4ecSRafael Espindola // a derived-to-base cast to compute the correct this pointer, but 1733b33c4ecSRafael Espindola // we don't have support for that yet, so do a virtual call. 1748a13c418SCraig Topper DevirtualizedMethod = nullptr; 1753b33c4ecSRafael Espindola } 1763b33c4ecSRafael Espindola } 177ecbe2e97SRafael Espindola 178762672a7SRichard Smith // C++17 demands that we evaluate the RHS of a (possibly-compound) assignment 179762672a7SRichard Smith // operator before the LHS. 180762672a7SRichard Smith CallArgList RtlArgStorage; 181762672a7SRichard Smith CallArgList *RtlArgs = nullptr; 182762672a7SRichard Smith if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(CE)) { 183762672a7SRichard Smith if (OCE->isAssignmentOp()) { 184762672a7SRichard Smith RtlArgs = &RtlArgStorage; 185762672a7SRichard Smith EmitCallArgs(*RtlArgs, MD->getType()->castAs<FunctionProtoType>(), 186762672a7SRichard Smith drop_begin(CE->arguments(), 1), CE->getDirectCallee(), 187a560ccf2SRichard Smith /*ParamsToSkip*/0, EvaluationOrder::ForceRightToLeft); 188762672a7SRichard Smith } 189762672a7SRichard Smith } 190762672a7SRichard Smith 1917f416cc4SJohn McCall Address This = Address::invalid(); 192aad4af6dSNico Weber if (IsArrow) 1937f416cc4SJohn McCall This = EmitPointerWithAlignment(Base); 194f93ac894SFariborz Jahanian else 1953b33c4ecSRafael Espindola This = EmitLValue(Base).getAddress(); 196ecbe2e97SRafael Espindola 19727da15baSAnders Carlsson 198419bd094SRichard Smith if (MD->isTrivial() || (MD->isDefaulted() && MD->getParent()->isUnion())) { 1998a13c418SCraig Topper if (isa<CXXDestructorDecl>(MD)) return RValue::get(nullptr); 20064225794SFrancois Pichet if (isa<CXXConstructorDecl>(MD) && 20164225794SFrancois Pichet cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) 2028a13c418SCraig Topper return RValue::get(nullptr); 2030d635f53SJohn McCall 204aad4af6dSNico Weber if (!MD->getParent()->mayInsertExtraPadding()) { 20522653bacSSebastian Redl if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) { 20622653bacSSebastian Redl // We don't like to generate the trivial copy/move assignment operator 20722653bacSSebastian Redl // when it isn't necessary; just produce the proper effect here. 208762672a7SRichard Smith LValue RHS = isa<CXXOperatorCallExpr>(CE) 209762672a7SRichard Smith ? MakeNaturalAlignAddrLValue( 210762672a7SRichard Smith (*RtlArgs)[0].RV.getScalarVal(), 211762672a7SRichard Smith (*(CE->arg_begin() + 1))->getType()) 212762672a7SRichard Smith : EmitLValue(*CE->arg_begin()); 213762672a7SRichard Smith EmitAggregateAssign(This, RHS.getAddress(), CE->getType()); 2147f416cc4SJohn McCall return RValue::get(This.getPointer()); 21527da15baSAnders Carlsson } 21627da15baSAnders Carlsson 21764225794SFrancois Pichet if (isa<CXXConstructorDecl>(MD) && 21822653bacSSebastian Redl cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) { 21922653bacSSebastian Redl // Trivial move and copy ctor are the same. 220525bf650SAlexey Samsonov assert(CE->getNumArgs() == 1 && "unexpected argcount for trivial ctor"); 2217f416cc4SJohn McCall Address RHS = EmitLValue(*CE->arg_begin()).getAddress(); 222f48ee448SBenjamin Kramer EmitAggregateCopy(This, RHS, (*CE->arg_begin())->getType()); 2237f416cc4SJohn McCall return RValue::get(This.getPointer()); 22464225794SFrancois Pichet } 22564225794SFrancois Pichet llvm_unreachable("unknown trivial member function"); 22664225794SFrancois Pichet } 227aad4af6dSNico Weber } 22864225794SFrancois Pichet 2290d635f53SJohn McCall // Compute the function type we're calling. 2303abfe958SNico Weber const CXXMethodDecl *CalleeDecl = 2313abfe958SNico Weber DevirtualizedMethod ? DevirtualizedMethod : MD; 2328a13c418SCraig Topper const CGFunctionInfo *FInfo = nullptr; 2333abfe958SNico Weber if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl)) 2348d2a19b4SRafael Espindola FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration( 2358d2a19b4SRafael Espindola Dtor, StructorType::Complete); 2363abfe958SNico Weber else if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(CalleeDecl)) 2378d2a19b4SRafael Espindola FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration( 2388d2a19b4SRafael Espindola Ctor, StructorType::Complete); 23964225794SFrancois Pichet else 240ade60977SEli Friedman FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl); 2410d635f53SJohn McCall 242e7de47efSReid Kleckner llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo); 2430d635f53SJohn McCall 24427da15baSAnders Carlsson // C++ [class.virtual]p12: 24527da15baSAnders Carlsson // Explicit qualification with the scope operator (5.1) suppresses the 24627da15baSAnders Carlsson // virtual call mechanism. 24727da15baSAnders Carlsson // 24827da15baSAnders Carlsson // We also don't emit a virtual call if the base expression has a record type 24927da15baSAnders Carlsson // because then we know what the type is. 2503b33c4ecSRafael Espindola bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod; 25119cee187SStephen Lin llvm::Value *Callee; 2529dc6eef7SStephen Lin 2530d635f53SJohn McCall if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) { 25419cee187SStephen Lin assert(CE->arg_begin() == CE->arg_end() && 2559dc6eef7SStephen Lin "Destructor shouldn't have explicit parameters"); 2569dc6eef7SStephen Lin assert(ReturnValue.isNull() && "Destructor shouldn't have return value"); 2579dc6eef7SStephen Lin if (UseVirtualCall) { 258aad4af6dSNico Weber CGM.getCXXABI().EmitVirtualDestructorCall( 259aad4af6dSNico Weber *this, Dtor, Dtor_Complete, This, cast<CXXMemberCallExpr>(CE)); 26027da15baSAnders Carlsson } else { 261aad4af6dSNico Weber if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier) 262aad4af6dSNico Weber Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty); 2633b33c4ecSRafael Espindola else if (!DevirtualizedMethod) 2641ac0ec86SRafael Espindola Callee = 2651ac0ec86SRafael Espindola CGM.getAddrOfCXXStructor(Dtor, StructorType::Complete, FInfo, Ty); 26649e860b2SRafael Espindola else { 2673b33c4ecSRafael Espindola const CXXDestructorDecl *DDtor = 2683b33c4ecSRafael Espindola cast<CXXDestructorDecl>(DevirtualizedMethod); 26949e860b2SRafael Espindola Callee = CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty); 27049e860b2SRafael Espindola } 2717f416cc4SJohn McCall EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This.getPointer(), 272762672a7SRichard Smith /*ImplicitParam=*/nullptr, QualType(), CE, 273762672a7SRichard Smith nullptr); 27427da15baSAnders Carlsson } 2758a13c418SCraig Topper return RValue::get(nullptr); 2769dc6eef7SStephen Lin } 2779dc6eef7SStephen Lin 2789dc6eef7SStephen Lin if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 27964225794SFrancois Pichet Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty); 2800d635f53SJohn McCall } else if (UseVirtualCall) { 2816708c4a1SPeter Collingbourne Callee = CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, Ty, 2826708c4a1SPeter Collingbourne CE->getLocStart()); 28327da15baSAnders Carlsson } else { 2841a7488afSPeter Collingbourne if (SanOpts.has(SanitizerKind::CFINVCall) && 2851a7488afSPeter Collingbourne MD->getParent()->isDynamicClass()) { 2864b1ac72cSPiotr Padlewski llvm::Value *VTable = GetVTablePtr(This, Int8PtrTy, MD->getParent()); 287fb532b9aSPeter Collingbourne EmitVTablePtrCheckForCall(MD->getParent(), VTable, CFITCK_NVCall, 288fb532b9aSPeter Collingbourne CE->getLocStart()); 2891a7488afSPeter Collingbourne } 2901a7488afSPeter Collingbourne 291aad4af6dSNico Weber if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier) 292aad4af6dSNico Weber Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty); 2933b33c4ecSRafael Espindola else if (!DevirtualizedMethod) 294727a771aSRafael Espindola Callee = CGM.GetAddrOfFunction(MD, Ty); 29549e860b2SRafael Espindola else { 2963b33c4ecSRafael Espindola Callee = CGM.GetAddrOfFunction(DevirtualizedMethod, Ty); 29749e860b2SRafael Espindola } 29827da15baSAnders Carlsson } 29927da15baSAnders Carlsson 300f1749427STimur Iskhodzhanov if (MD->isVirtual()) { 301f1749427STimur Iskhodzhanov This = CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall( 3024b60f30aSReid Kleckner *this, CalleeDecl, This, UseVirtualCall); 303f1749427STimur Iskhodzhanov } 30488fd439aSTimur Iskhodzhanov 3057f416cc4SJohn McCall return EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This.getPointer(), 306762672a7SRichard Smith /*ImplicitParam=*/nullptr, QualType(), CE, 307762672a7SRichard Smith RtlArgs); 30827da15baSAnders Carlsson } 30927da15baSAnders Carlsson 31027da15baSAnders Carlsson RValue 31127da15baSAnders Carlsson CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E, 31227da15baSAnders Carlsson ReturnValueSlot ReturnValue) { 31327da15baSAnders Carlsson const BinaryOperator *BO = 31427da15baSAnders Carlsson cast<BinaryOperator>(E->getCallee()->IgnoreParens()); 31527da15baSAnders Carlsson const Expr *BaseExpr = BO->getLHS(); 31627da15baSAnders Carlsson const Expr *MemFnExpr = BO->getRHS(); 31727da15baSAnders Carlsson 31827da15baSAnders Carlsson const MemberPointerType *MPT = 3190009fcc3SJohn McCall MemFnExpr->getType()->castAs<MemberPointerType>(); 320475999dcSJohn McCall 32127da15baSAnders Carlsson const FunctionProtoType *FPT = 3220009fcc3SJohn McCall MPT->getPointeeType()->castAs<FunctionProtoType>(); 32327da15baSAnders Carlsson const CXXRecordDecl *RD = 32427da15baSAnders Carlsson cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl()); 32527da15baSAnders Carlsson 32627da15baSAnders Carlsson // Emit the 'this' pointer. 3277f416cc4SJohn McCall Address This = Address::invalid(); 328e302792bSJohn McCall if (BO->getOpcode() == BO_PtrMemI) 3297f416cc4SJohn McCall This = EmitPointerWithAlignment(BaseExpr); 33027da15baSAnders Carlsson else 33127da15baSAnders Carlsson This = EmitLValue(BaseExpr).getAddress(); 33227da15baSAnders Carlsson 3337f416cc4SJohn McCall EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This.getPointer(), 334e30752c9SRichard Smith QualType(MPT->getClass(), 0)); 33569d0d262SRichard Smith 336bde62d78SRichard Smith // Get the member function pointer. 337bde62d78SRichard Smith llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr); 338bde62d78SRichard Smith 339475999dcSJohn McCall // Ask the ABI to load the callee. Note that This is modified. 3407f416cc4SJohn McCall llvm::Value *ThisPtrForCall = nullptr; 341475999dcSJohn McCall llvm::Value *Callee = 3427f416cc4SJohn McCall CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This, 3437f416cc4SJohn McCall ThisPtrForCall, MemFnPtr, MPT); 34427da15baSAnders Carlsson 34527da15baSAnders Carlsson CallArgList Args; 34627da15baSAnders Carlsson 34727da15baSAnders Carlsson QualType ThisType = 34827da15baSAnders Carlsson getContext().getPointerType(getContext().getTagDeclType(RD)); 34927da15baSAnders Carlsson 35027da15baSAnders Carlsson // Push the this ptr. 3517f416cc4SJohn McCall Args.add(RValue::get(ThisPtrForCall), ThisType); 35227da15baSAnders Carlsson 353419996ccSGeorge Burgess IV RequiredArgs required = 354419996ccSGeorge Burgess IV RequiredArgs::forPrototypePlus(FPT, 1, /*FD=*/nullptr); 3558dda7b27SJohn McCall 35627da15baSAnders Carlsson // And the rest of the call args 357419996ccSGeorge Burgess IV EmitCallArgs(Args, FPT, E->arguments()); 3585fa40c3bSNick Lewycky return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required), 3595fa40c3bSNick Lewycky Callee, ReturnValue, Args); 36027da15baSAnders Carlsson } 36127da15baSAnders Carlsson 36227da15baSAnders Carlsson RValue 36327da15baSAnders Carlsson CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E, 36427da15baSAnders Carlsson const CXXMethodDecl *MD, 36527da15baSAnders Carlsson ReturnValueSlot ReturnValue) { 36627da15baSAnders Carlsson assert(MD->isInstance() && 36727da15baSAnders Carlsson "Trying to emit a member call expr on a static method!"); 368aad4af6dSNico Weber return EmitCXXMemberOrOperatorMemberCallExpr( 369aad4af6dSNico Weber E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr, 370aad4af6dSNico Weber /*IsArrow=*/false, E->getArg(0)); 37127da15baSAnders Carlsson } 37227da15baSAnders Carlsson 373fe883422SPeter Collingbourne RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E, 374fe883422SPeter Collingbourne ReturnValueSlot ReturnValue) { 375fe883422SPeter Collingbourne return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue); 376fe883422SPeter Collingbourne } 377fe883422SPeter Collingbourne 378fde961dbSEli Friedman static void EmitNullBaseClassInitialization(CodeGenFunction &CGF, 3797f416cc4SJohn McCall Address DestPtr, 380fde961dbSEli Friedman const CXXRecordDecl *Base) { 381fde961dbSEli Friedman if (Base->isEmpty()) 382fde961dbSEli Friedman return; 383fde961dbSEli Friedman 3847f416cc4SJohn McCall DestPtr = CGF.Builder.CreateElementBitCast(DestPtr, CGF.Int8Ty); 385fde961dbSEli Friedman 386fde961dbSEli Friedman const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base); 3878671c6e0SDavid Majnemer CharUnits NVSize = Layout.getNonVirtualSize(); 3888671c6e0SDavid Majnemer 3898671c6e0SDavid Majnemer // We cannot simply zero-initialize the entire base sub-object if vbptrs are 3908671c6e0SDavid Majnemer // present, they are initialized by the most derived class before calling the 3918671c6e0SDavid Majnemer // constructor. 3928671c6e0SDavid Majnemer SmallVector<std::pair<CharUnits, CharUnits>, 1> Stores; 3938671c6e0SDavid Majnemer Stores.emplace_back(CharUnits::Zero(), NVSize); 3948671c6e0SDavid Majnemer 3958671c6e0SDavid Majnemer // Each store is split by the existence of a vbptr. 3968671c6e0SDavid Majnemer CharUnits VBPtrWidth = CGF.getPointerSize(); 3978671c6e0SDavid Majnemer std::vector<CharUnits> VBPtrOffsets = 3988671c6e0SDavid Majnemer CGF.CGM.getCXXABI().getVBPtrOffsets(Base); 3998671c6e0SDavid Majnemer for (CharUnits VBPtrOffset : VBPtrOffsets) { 4007f980d84SDavid Majnemer // Stop before we hit any virtual base pointers located in virtual bases. 4017f980d84SDavid Majnemer if (VBPtrOffset >= NVSize) 4027f980d84SDavid Majnemer break; 4038671c6e0SDavid Majnemer std::pair<CharUnits, CharUnits> LastStore = Stores.pop_back_val(); 4048671c6e0SDavid Majnemer CharUnits LastStoreOffset = LastStore.first; 4058671c6e0SDavid Majnemer CharUnits LastStoreSize = LastStore.second; 4068671c6e0SDavid Majnemer 4078671c6e0SDavid Majnemer CharUnits SplitBeforeOffset = LastStoreOffset; 4088671c6e0SDavid Majnemer CharUnits SplitBeforeSize = VBPtrOffset - SplitBeforeOffset; 4098671c6e0SDavid Majnemer assert(!SplitBeforeSize.isNegative() && "negative store size!"); 4108671c6e0SDavid Majnemer if (!SplitBeforeSize.isZero()) 4118671c6e0SDavid Majnemer Stores.emplace_back(SplitBeforeOffset, SplitBeforeSize); 4128671c6e0SDavid Majnemer 4138671c6e0SDavid Majnemer CharUnits SplitAfterOffset = VBPtrOffset + VBPtrWidth; 4148671c6e0SDavid Majnemer CharUnits SplitAfterSize = LastStoreSize - SplitAfterOffset; 4158671c6e0SDavid Majnemer assert(!SplitAfterSize.isNegative() && "negative store size!"); 4168671c6e0SDavid Majnemer if (!SplitAfterSize.isZero()) 4178671c6e0SDavid Majnemer Stores.emplace_back(SplitAfterOffset, SplitAfterSize); 4188671c6e0SDavid Majnemer } 419fde961dbSEli Friedman 420fde961dbSEli Friedman // If the type contains a pointer to data member we can't memset it to zero. 421fde961dbSEli Friedman // Instead, create a null constant and copy it to the destination. 422fde961dbSEli Friedman // TODO: there are other patterns besides zero that we can usefully memset, 423fde961dbSEli Friedman // like -1, which happens to be the pattern used by member-pointers. 424fde961dbSEli Friedman // TODO: isZeroInitializable can be over-conservative in the case where a 425fde961dbSEli Friedman // virtual base contains a member pointer. 4268671c6e0SDavid Majnemer llvm::Constant *NullConstantForBase = CGF.CGM.EmitNullConstantForBase(Base); 4278671c6e0SDavid Majnemer if (!NullConstantForBase->isNullValue()) { 4288671c6e0SDavid Majnemer llvm::GlobalVariable *NullVariable = new llvm::GlobalVariable( 4298671c6e0SDavid Majnemer CGF.CGM.getModule(), NullConstantForBase->getType(), 4308671c6e0SDavid Majnemer /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, 4318671c6e0SDavid Majnemer NullConstantForBase, Twine()); 4327f416cc4SJohn McCall 4337f416cc4SJohn McCall CharUnits Align = std::max(Layout.getNonVirtualAlignment(), 4347f416cc4SJohn McCall DestPtr.getAlignment()); 435fde961dbSEli Friedman NullVariable->setAlignment(Align.getQuantity()); 4367f416cc4SJohn McCall 4377f416cc4SJohn McCall Address SrcPtr = Address(CGF.EmitCastToVoidPtr(NullVariable), Align); 438fde961dbSEli Friedman 439fde961dbSEli Friedman // Get and call the appropriate llvm.memcpy overload. 4408671c6e0SDavid Majnemer for (std::pair<CharUnits, CharUnits> Store : Stores) { 4418671c6e0SDavid Majnemer CharUnits StoreOffset = Store.first; 4428671c6e0SDavid Majnemer CharUnits StoreSize = Store.second; 4438671c6e0SDavid Majnemer llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize); 4448671c6e0SDavid Majnemer CGF.Builder.CreateMemCpy( 4458671c6e0SDavid Majnemer CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset), 4468671c6e0SDavid Majnemer CGF.Builder.CreateConstInBoundsByteGEP(SrcPtr, StoreOffset), 4478671c6e0SDavid Majnemer StoreSizeVal); 448fde961dbSEli Friedman } 449fde961dbSEli Friedman 450fde961dbSEli Friedman // Otherwise, just memset the whole thing to zero. This is legal 451fde961dbSEli Friedman // because in LLVM, all default initializers (other than the ones we just 452fde961dbSEli Friedman // handled above) are guaranteed to have a bit pattern of all zeros. 4538671c6e0SDavid Majnemer } else { 4548671c6e0SDavid Majnemer for (std::pair<CharUnits, CharUnits> Store : Stores) { 4558671c6e0SDavid Majnemer CharUnits StoreOffset = Store.first; 4568671c6e0SDavid Majnemer CharUnits StoreSize = Store.second; 4578671c6e0SDavid Majnemer llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize); 4588671c6e0SDavid Majnemer CGF.Builder.CreateMemSet( 4598671c6e0SDavid Majnemer CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset), 4608671c6e0SDavid Majnemer CGF.Builder.getInt8(0), StoreSizeVal); 4618671c6e0SDavid Majnemer } 4628671c6e0SDavid Majnemer } 463fde961dbSEli Friedman } 464fde961dbSEli Friedman 46527da15baSAnders Carlsson void 4667a626f63SJohn McCall CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E, 4677a626f63SJohn McCall AggValueSlot Dest) { 4687a626f63SJohn McCall assert(!Dest.isIgnored() && "Must have a destination!"); 46927da15baSAnders Carlsson const CXXConstructorDecl *CD = E->getConstructor(); 470630c76efSDouglas Gregor 471630c76efSDouglas Gregor // If we require zero initialization before (or instead of) calling the 472630c76efSDouglas Gregor // constructor, as can be the case with a non-user-provided default 47303535265SArgyrios Kyrtzidis // constructor, emit the zero initialization now, unless destination is 47403535265SArgyrios Kyrtzidis // already zeroed. 475fde961dbSEli Friedman if (E->requiresZeroInitialization() && !Dest.isZeroed()) { 476fde961dbSEli Friedman switch (E->getConstructionKind()) { 477fde961dbSEli Friedman case CXXConstructExpr::CK_Delegating: 478fde961dbSEli Friedman case CXXConstructExpr::CK_Complete: 4797f416cc4SJohn McCall EmitNullInitialization(Dest.getAddress(), E->getType()); 480fde961dbSEli Friedman break; 481fde961dbSEli Friedman case CXXConstructExpr::CK_VirtualBase: 482fde961dbSEli Friedman case CXXConstructExpr::CK_NonVirtualBase: 4837f416cc4SJohn McCall EmitNullBaseClassInitialization(*this, Dest.getAddress(), 4847f416cc4SJohn McCall CD->getParent()); 485fde961dbSEli Friedman break; 486fde961dbSEli Friedman } 487fde961dbSEli Friedman } 488630c76efSDouglas Gregor 489630c76efSDouglas Gregor // If this is a call to a trivial default constructor, do nothing. 490630c76efSDouglas Gregor if (CD->isTrivial() && CD->isDefaultConstructor()) 49127da15baSAnders Carlsson return; 492630c76efSDouglas Gregor 4938ea46b66SJohn McCall // Elide the constructor if we're constructing from a temporary. 4948ea46b66SJohn McCall // The temporary check is required because Sema sets this on NRVO 4958ea46b66SJohn McCall // returns. 4969c6890a7SRichard Smith if (getLangOpts().ElideConstructors && E->isElidable()) { 4978ea46b66SJohn McCall assert(getContext().hasSameUnqualifiedType(E->getType(), 4988ea46b66SJohn McCall E->getArg(0)->getType())); 4997a626f63SJohn McCall if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) { 5007a626f63SJohn McCall EmitAggExpr(E->getArg(0), Dest); 50127da15baSAnders Carlsson return; 50227da15baSAnders Carlsson } 503222cf0efSDouglas Gregor } 504630c76efSDouglas Gregor 505e7545b33SAlexey Bataev if (const ArrayType *arrayType 506e7545b33SAlexey Bataev = getContext().getAsArrayType(E->getType())) { 5077f416cc4SJohn McCall EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddress(), E); 508f677a8e9SJohn McCall } else { 509bceca20aSCameron Esfahani CXXCtorType Type = Ctor_Complete; 510271c3681SAlexis Hunt bool ForVirtualBase = false; 51161535005SDouglas Gregor bool Delegating = false; 512271c3681SAlexis Hunt 513271c3681SAlexis Hunt switch (E->getConstructionKind()) { 514271c3681SAlexis Hunt case CXXConstructExpr::CK_Delegating: 51561bc1737SAlexis Hunt // We should be emitting a constructor; GlobalDecl will assert this 51661bc1737SAlexis Hunt Type = CurGD.getCtorType(); 51761535005SDouglas Gregor Delegating = true; 518271c3681SAlexis Hunt break; 51961bc1737SAlexis Hunt 520271c3681SAlexis Hunt case CXXConstructExpr::CK_Complete: 521271c3681SAlexis Hunt Type = Ctor_Complete; 522271c3681SAlexis Hunt break; 523271c3681SAlexis Hunt 524271c3681SAlexis Hunt case CXXConstructExpr::CK_VirtualBase: 525271c3681SAlexis Hunt ForVirtualBase = true; 526271c3681SAlexis Hunt // fall-through 527271c3681SAlexis Hunt 528271c3681SAlexis Hunt case CXXConstructExpr::CK_NonVirtualBase: 529271c3681SAlexis Hunt Type = Ctor_Base; 530271c3681SAlexis Hunt } 531e11f9ce9SAnders Carlsson 53227da15baSAnders Carlsson // Call the constructor. 5337f416cc4SJohn McCall EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating, 5347f416cc4SJohn McCall Dest.getAddress(), E); 53527da15baSAnders Carlsson } 536e11f9ce9SAnders Carlsson } 53727da15baSAnders Carlsson 5387f416cc4SJohn McCall void CodeGenFunction::EmitSynthesizedCXXCopyCtor(Address Dest, Address Src, 53950198098SFariborz Jahanian const Expr *Exp) { 5405d413781SJohn McCall if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp)) 541e988bdacSFariborz Jahanian Exp = E->getSubExpr(); 542e988bdacSFariborz Jahanian assert(isa<CXXConstructExpr>(Exp) && 543e988bdacSFariborz Jahanian "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr"); 544e988bdacSFariborz Jahanian const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp); 545e988bdacSFariborz Jahanian const CXXConstructorDecl *CD = E->getConstructor(); 546e988bdacSFariborz Jahanian RunCleanupsScope Scope(*this); 547e988bdacSFariborz Jahanian 548e988bdacSFariborz Jahanian // If we require zero initialization before (or instead of) calling the 549e988bdacSFariborz Jahanian // constructor, as can be the case with a non-user-provided default 550e988bdacSFariborz Jahanian // constructor, emit the zero initialization now. 551e988bdacSFariborz Jahanian // FIXME. Do I still need this for a copy ctor synthesis? 552e988bdacSFariborz Jahanian if (E->requiresZeroInitialization()) 553e988bdacSFariborz Jahanian EmitNullInitialization(Dest, E->getType()); 554e988bdacSFariborz Jahanian 55599da11cfSChandler Carruth assert(!getContext().getAsConstantArrayType(E->getType()) 55699da11cfSChandler Carruth && "EmitSynthesizedCXXCopyCtor - Copied-in Array"); 557525bf650SAlexey Samsonov EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E); 558e988bdacSFariborz Jahanian } 559e988bdacSFariborz Jahanian 5608ed55a54SJohn McCall static CharUnits CalculateCookiePadding(CodeGenFunction &CGF, 5618ed55a54SJohn McCall const CXXNewExpr *E) { 56221122cf6SAnders Carlsson if (!E->isArray()) 5633eb55cfeSKen Dyck return CharUnits::Zero(); 56421122cf6SAnders Carlsson 5657ec4b434SJohn McCall // No cookie is required if the operator new[] being used is the 5667ec4b434SJohn McCall // reserved placement operator new[]. 5677ec4b434SJohn McCall if (E->getOperatorNew()->isReservedGlobalPlacementOperator()) 5683eb55cfeSKen Dyck return CharUnits::Zero(); 569399f499fSAnders Carlsson 570284c48ffSJohn McCall return CGF.CGM.getCXXABI().GetArrayCookieSize(E); 57159486a2dSAnders Carlsson } 57259486a2dSAnders Carlsson 573036f2f6bSJohn McCall static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF, 574036f2f6bSJohn McCall const CXXNewExpr *e, 575f862eb6aSSebastian Redl unsigned minElements, 576036f2f6bSJohn McCall llvm::Value *&numElements, 577036f2f6bSJohn McCall llvm::Value *&sizeWithoutCookie) { 578036f2f6bSJohn McCall QualType type = e->getAllocatedType(); 57959486a2dSAnders Carlsson 580036f2f6bSJohn McCall if (!e->isArray()) { 581036f2f6bSJohn McCall CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type); 582036f2f6bSJohn McCall sizeWithoutCookie 583036f2f6bSJohn McCall = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity()); 584036f2f6bSJohn McCall return sizeWithoutCookie; 58505fc5be3SDouglas Gregor } 58659486a2dSAnders Carlsson 587036f2f6bSJohn McCall // The width of size_t. 588036f2f6bSJohn McCall unsigned sizeWidth = CGF.SizeTy->getBitWidth(); 589036f2f6bSJohn McCall 5908ed55a54SJohn McCall // Figure out the cookie size. 591036f2f6bSJohn McCall llvm::APInt cookieSize(sizeWidth, 592036f2f6bSJohn McCall CalculateCookiePadding(CGF, e).getQuantity()); 5938ed55a54SJohn McCall 59459486a2dSAnders Carlsson // Emit the array size expression. 5957648fb46SArgyrios Kyrtzidis // We multiply the size of all dimensions for NumElements. 5967648fb46SArgyrios Kyrtzidis // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6. 597036f2f6bSJohn McCall numElements = CGF.EmitScalarExpr(e->getArraySize()); 598036f2f6bSJohn McCall assert(isa<llvm::IntegerType>(numElements->getType())); 5998ed55a54SJohn McCall 600036f2f6bSJohn McCall // The number of elements can be have an arbitrary integer type; 601036f2f6bSJohn McCall // essentially, we need to multiply it by a constant factor, add a 602036f2f6bSJohn McCall // cookie size, and verify that the result is representable as a 603036f2f6bSJohn McCall // size_t. That's just a gloss, though, and it's wrong in one 604036f2f6bSJohn McCall // important way: if the count is negative, it's an error even if 605036f2f6bSJohn McCall // the cookie size would bring the total size >= 0. 6066ab2fa8fSDouglas Gregor bool isSigned 6076ab2fa8fSDouglas Gregor = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType(); 6082192fe50SChris Lattner llvm::IntegerType *numElementsType 609036f2f6bSJohn McCall = cast<llvm::IntegerType>(numElements->getType()); 610036f2f6bSJohn McCall unsigned numElementsWidth = numElementsType->getBitWidth(); 611036f2f6bSJohn McCall 612036f2f6bSJohn McCall // Compute the constant factor. 613036f2f6bSJohn McCall llvm::APInt arraySizeMultiplier(sizeWidth, 1); 6147648fb46SArgyrios Kyrtzidis while (const ConstantArrayType *CAT 615036f2f6bSJohn McCall = CGF.getContext().getAsConstantArrayType(type)) { 616036f2f6bSJohn McCall type = CAT->getElementType(); 617036f2f6bSJohn McCall arraySizeMultiplier *= CAT->getSize(); 6187648fb46SArgyrios Kyrtzidis } 61959486a2dSAnders Carlsson 620036f2f6bSJohn McCall CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type); 621036f2f6bSJohn McCall llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity()); 622036f2f6bSJohn McCall typeSizeMultiplier *= arraySizeMultiplier; 623036f2f6bSJohn McCall 624036f2f6bSJohn McCall // This will be a size_t. 625036f2f6bSJohn McCall llvm::Value *size; 62632ac583dSChris Lattner 62732ac583dSChris Lattner // If someone is doing 'new int[42]' there is no need to do a dynamic check. 62832ac583dSChris Lattner // Don't bloat the -O0 code. 629036f2f6bSJohn McCall if (llvm::ConstantInt *numElementsC = 630036f2f6bSJohn McCall dyn_cast<llvm::ConstantInt>(numElements)) { 631036f2f6bSJohn McCall const llvm::APInt &count = numElementsC->getValue(); 63232ac583dSChris Lattner 633036f2f6bSJohn McCall bool hasAnyOverflow = false; 63432ac583dSChris Lattner 635036f2f6bSJohn McCall // If 'count' was a negative number, it's an overflow. 636036f2f6bSJohn McCall if (isSigned && count.isNegative()) 637036f2f6bSJohn McCall hasAnyOverflow = true; 6388ed55a54SJohn McCall 639036f2f6bSJohn McCall // We want to do all this arithmetic in size_t. If numElements is 640036f2f6bSJohn McCall // wider than that, check whether it's already too big, and if so, 641036f2f6bSJohn McCall // overflow. 642036f2f6bSJohn McCall else if (numElementsWidth > sizeWidth && 643036f2f6bSJohn McCall numElementsWidth - sizeWidth > count.countLeadingZeros()) 644036f2f6bSJohn McCall hasAnyOverflow = true; 645036f2f6bSJohn McCall 646036f2f6bSJohn McCall // Okay, compute a count at the right width. 647036f2f6bSJohn McCall llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth); 648036f2f6bSJohn McCall 649f862eb6aSSebastian Redl // If there is a brace-initializer, we cannot allocate fewer elements than 650f862eb6aSSebastian Redl // there are initializers. If we do, that's treated like an overflow. 651f862eb6aSSebastian Redl if (adjustedCount.ult(minElements)) 652f862eb6aSSebastian Redl hasAnyOverflow = true; 653f862eb6aSSebastian Redl 654036f2f6bSJohn McCall // Scale numElements by that. This might overflow, but we don't 655036f2f6bSJohn McCall // care because it only overflows if allocationSize does, too, and 656036f2f6bSJohn McCall // if that overflows then we shouldn't use this. 657036f2f6bSJohn McCall numElements = llvm::ConstantInt::get(CGF.SizeTy, 658036f2f6bSJohn McCall adjustedCount * arraySizeMultiplier); 659036f2f6bSJohn McCall 660036f2f6bSJohn McCall // Compute the size before cookie, and track whether it overflowed. 661036f2f6bSJohn McCall bool overflow; 662036f2f6bSJohn McCall llvm::APInt allocationSize 663036f2f6bSJohn McCall = adjustedCount.umul_ov(typeSizeMultiplier, overflow); 664036f2f6bSJohn McCall hasAnyOverflow |= overflow; 665036f2f6bSJohn McCall 666036f2f6bSJohn McCall // Add in the cookie, and check whether it's overflowed. 667036f2f6bSJohn McCall if (cookieSize != 0) { 668036f2f6bSJohn McCall // Save the current size without a cookie. This shouldn't be 669036f2f6bSJohn McCall // used if there was overflow. 670036f2f6bSJohn McCall sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize); 671036f2f6bSJohn McCall 672036f2f6bSJohn McCall allocationSize = allocationSize.uadd_ov(cookieSize, overflow); 673036f2f6bSJohn McCall hasAnyOverflow |= overflow; 6748ed55a54SJohn McCall } 6758ed55a54SJohn McCall 676036f2f6bSJohn McCall // On overflow, produce a -1 so operator new will fail. 677455f42c9SAaron Ballman if (hasAnyOverflow) { 678455f42c9SAaron Ballman size = llvm::Constant::getAllOnesValue(CGF.SizeTy); 679455f42c9SAaron Ballman } else { 680036f2f6bSJohn McCall size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize); 681455f42c9SAaron Ballman } 68232ac583dSChris Lattner 683036f2f6bSJohn McCall // Otherwise, we might need to use the overflow intrinsics. 6848ed55a54SJohn McCall } else { 685f862eb6aSSebastian Redl // There are up to five conditions we need to test for: 686036f2f6bSJohn McCall // 1) if isSigned, we need to check whether numElements is negative; 687036f2f6bSJohn McCall // 2) if numElementsWidth > sizeWidth, we need to check whether 688036f2f6bSJohn McCall // numElements is larger than something representable in size_t; 689f862eb6aSSebastian Redl // 3) if minElements > 0, we need to check whether numElements is smaller 690f862eb6aSSebastian Redl // than that. 691f862eb6aSSebastian Redl // 4) we need to compute 692036f2f6bSJohn McCall // sizeWithoutCookie := numElements * typeSizeMultiplier 693036f2f6bSJohn McCall // and check whether it overflows; and 694f862eb6aSSebastian Redl // 5) if we need a cookie, we need to compute 695036f2f6bSJohn McCall // size := sizeWithoutCookie + cookieSize 696036f2f6bSJohn McCall // and check whether it overflows. 6978ed55a54SJohn McCall 6988a13c418SCraig Topper llvm::Value *hasOverflow = nullptr; 6998ed55a54SJohn McCall 700036f2f6bSJohn McCall // If numElementsWidth > sizeWidth, then one way or another, we're 701036f2f6bSJohn McCall // going to have to do a comparison for (2), and this happens to 702036f2f6bSJohn McCall // take care of (1), too. 703036f2f6bSJohn McCall if (numElementsWidth > sizeWidth) { 704036f2f6bSJohn McCall llvm::APInt threshold(numElementsWidth, 1); 705036f2f6bSJohn McCall threshold <<= sizeWidth; 7068ed55a54SJohn McCall 707036f2f6bSJohn McCall llvm::Value *thresholdV 708036f2f6bSJohn McCall = llvm::ConstantInt::get(numElementsType, threshold); 709036f2f6bSJohn McCall 710036f2f6bSJohn McCall hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV); 711036f2f6bSJohn McCall numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy); 712036f2f6bSJohn McCall 713036f2f6bSJohn McCall // Otherwise, if we're signed, we want to sext up to size_t. 714036f2f6bSJohn McCall } else if (isSigned) { 715036f2f6bSJohn McCall if (numElementsWidth < sizeWidth) 716036f2f6bSJohn McCall numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy); 717036f2f6bSJohn McCall 718036f2f6bSJohn McCall // If there's a non-1 type size multiplier, then we can do the 719036f2f6bSJohn McCall // signedness check at the same time as we do the multiply 720036f2f6bSJohn McCall // because a negative number times anything will cause an 721f862eb6aSSebastian Redl // unsigned overflow. Otherwise, we have to do it here. But at least 722f862eb6aSSebastian Redl // in this case, we can subsume the >= minElements check. 723036f2f6bSJohn McCall if (typeSizeMultiplier == 1) 724036f2f6bSJohn McCall hasOverflow = CGF.Builder.CreateICmpSLT(numElements, 725f862eb6aSSebastian Redl llvm::ConstantInt::get(CGF.SizeTy, minElements)); 726036f2f6bSJohn McCall 727036f2f6bSJohn McCall // Otherwise, zext up to size_t if necessary. 728036f2f6bSJohn McCall } else if (numElementsWidth < sizeWidth) { 729036f2f6bSJohn McCall numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy); 730036f2f6bSJohn McCall } 731036f2f6bSJohn McCall 732036f2f6bSJohn McCall assert(numElements->getType() == CGF.SizeTy); 733036f2f6bSJohn McCall 734f862eb6aSSebastian Redl if (minElements) { 735f862eb6aSSebastian Redl // Don't allow allocation of fewer elements than we have initializers. 736f862eb6aSSebastian Redl if (!hasOverflow) { 737f862eb6aSSebastian Redl hasOverflow = CGF.Builder.CreateICmpULT(numElements, 738f862eb6aSSebastian Redl llvm::ConstantInt::get(CGF.SizeTy, minElements)); 739f862eb6aSSebastian Redl } else if (numElementsWidth > sizeWidth) { 740f862eb6aSSebastian Redl // The other existing overflow subsumes this check. 741f862eb6aSSebastian Redl // We do an unsigned comparison, since any signed value < -1 is 742f862eb6aSSebastian Redl // taken care of either above or below. 743f862eb6aSSebastian Redl hasOverflow = CGF.Builder.CreateOr(hasOverflow, 744f862eb6aSSebastian Redl CGF.Builder.CreateICmpULT(numElements, 745f862eb6aSSebastian Redl llvm::ConstantInt::get(CGF.SizeTy, minElements))); 746f862eb6aSSebastian Redl } 747f862eb6aSSebastian Redl } 748f862eb6aSSebastian Redl 749036f2f6bSJohn McCall size = numElements; 750036f2f6bSJohn McCall 751036f2f6bSJohn McCall // Multiply by the type size if necessary. This multiplier 752036f2f6bSJohn McCall // includes all the factors for nested arrays. 7538ed55a54SJohn McCall // 754036f2f6bSJohn McCall // This step also causes numElements to be scaled up by the 755036f2f6bSJohn McCall // nested-array factor if necessary. Overflow on this computation 756036f2f6bSJohn McCall // can be ignored because the result shouldn't be used if 757036f2f6bSJohn McCall // allocation fails. 758036f2f6bSJohn McCall if (typeSizeMultiplier != 1) { 759036f2f6bSJohn McCall llvm::Value *umul_with_overflow 7608d375cefSBenjamin Kramer = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy); 7618ed55a54SJohn McCall 762036f2f6bSJohn McCall llvm::Value *tsmV = 763036f2f6bSJohn McCall llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier); 764036f2f6bSJohn McCall llvm::Value *result = 76543f9bb73SDavid Blaikie CGF.Builder.CreateCall(umul_with_overflow, {size, tsmV}); 7668ed55a54SJohn McCall 767036f2f6bSJohn McCall llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1); 768036f2f6bSJohn McCall if (hasOverflow) 769036f2f6bSJohn McCall hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed); 7708ed55a54SJohn McCall else 771036f2f6bSJohn McCall hasOverflow = overflowed; 77259486a2dSAnders Carlsson 773036f2f6bSJohn McCall size = CGF.Builder.CreateExtractValue(result, 0); 774036f2f6bSJohn McCall 775036f2f6bSJohn McCall // Also scale up numElements by the array size multiplier. 776036f2f6bSJohn McCall if (arraySizeMultiplier != 1) { 777036f2f6bSJohn McCall // If the base element type size is 1, then we can re-use the 778036f2f6bSJohn McCall // multiply we just did. 779036f2f6bSJohn McCall if (typeSize.isOne()) { 780036f2f6bSJohn McCall assert(arraySizeMultiplier == typeSizeMultiplier); 781036f2f6bSJohn McCall numElements = size; 782036f2f6bSJohn McCall 783036f2f6bSJohn McCall // Otherwise we need a separate multiply. 784036f2f6bSJohn McCall } else { 785036f2f6bSJohn McCall llvm::Value *asmV = 786036f2f6bSJohn McCall llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier); 787036f2f6bSJohn McCall numElements = CGF.Builder.CreateMul(numElements, asmV); 788036f2f6bSJohn McCall } 789036f2f6bSJohn McCall } 790036f2f6bSJohn McCall } else { 791036f2f6bSJohn McCall // numElements doesn't need to be scaled. 792036f2f6bSJohn McCall assert(arraySizeMultiplier == 1); 793036f2f6bSJohn McCall } 794036f2f6bSJohn McCall 795036f2f6bSJohn McCall // Add in the cookie size if necessary. 796036f2f6bSJohn McCall if (cookieSize != 0) { 797036f2f6bSJohn McCall sizeWithoutCookie = size; 798036f2f6bSJohn McCall 799036f2f6bSJohn McCall llvm::Value *uadd_with_overflow 8008d375cefSBenjamin Kramer = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy); 801036f2f6bSJohn McCall 802036f2f6bSJohn McCall llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize); 803036f2f6bSJohn McCall llvm::Value *result = 80443f9bb73SDavid Blaikie CGF.Builder.CreateCall(uadd_with_overflow, {size, cookieSizeV}); 805036f2f6bSJohn McCall 806036f2f6bSJohn McCall llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1); 807036f2f6bSJohn McCall if (hasOverflow) 808036f2f6bSJohn McCall hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed); 809036f2f6bSJohn McCall else 810036f2f6bSJohn McCall hasOverflow = overflowed; 811036f2f6bSJohn McCall 812036f2f6bSJohn McCall size = CGF.Builder.CreateExtractValue(result, 0); 813036f2f6bSJohn McCall } 814036f2f6bSJohn McCall 815036f2f6bSJohn McCall // If we had any possibility of dynamic overflow, make a select to 816036f2f6bSJohn McCall // overwrite 'size' with an all-ones value, which should cause 817036f2f6bSJohn McCall // operator new to throw. 818036f2f6bSJohn McCall if (hasOverflow) 819455f42c9SAaron Ballman size = CGF.Builder.CreateSelect(hasOverflow, 820455f42c9SAaron Ballman llvm::Constant::getAllOnesValue(CGF.SizeTy), 821036f2f6bSJohn McCall size); 822036f2f6bSJohn McCall } 823036f2f6bSJohn McCall 824036f2f6bSJohn McCall if (cookieSize == 0) 825036f2f6bSJohn McCall sizeWithoutCookie = size; 826036f2f6bSJohn McCall else 827036f2f6bSJohn McCall assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?"); 828036f2f6bSJohn McCall 829036f2f6bSJohn McCall return size; 83059486a2dSAnders Carlsson } 83159486a2dSAnders Carlsson 832f862eb6aSSebastian Redl static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init, 8337f416cc4SJohn McCall QualType AllocType, Address NewPtr) { 8341c96bc5dSRichard Smith // FIXME: Refactor with EmitExprAsInit. 83547fb9508SJohn McCall switch (CGF.getEvaluationKind(AllocType)) { 83647fb9508SJohn McCall case TEK_Scalar: 837a2c1124fSDavid Blaikie CGF.EmitScalarInit(Init, nullptr, 8387f416cc4SJohn McCall CGF.MakeAddrLValue(NewPtr, AllocType), false); 83947fb9508SJohn McCall return; 84047fb9508SJohn McCall case TEK_Complex: 8417f416cc4SJohn McCall CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType), 84247fb9508SJohn McCall /*isInit*/ true); 84347fb9508SJohn McCall return; 84447fb9508SJohn McCall case TEK_Aggregate: { 8457a626f63SJohn McCall AggValueSlot Slot 8467f416cc4SJohn McCall = AggValueSlot::forAddr(NewPtr, AllocType.getQualifiers(), 8478d6fc958SJohn McCall AggValueSlot::IsDestructed, 84846759f4fSJohn McCall AggValueSlot::DoesNotNeedGCBarriers, 849615ed1a3SChad Rosier AggValueSlot::IsNotAliased); 8507a626f63SJohn McCall CGF.EmitAggExpr(Init, Slot); 85147fb9508SJohn McCall return; 8527a626f63SJohn McCall } 853d5202e09SFariborz Jahanian } 85447fb9508SJohn McCall llvm_unreachable("bad evaluation kind"); 85547fb9508SJohn McCall } 856d5202e09SFariborz Jahanian 857fb901c7aSDavid Blaikie void CodeGenFunction::EmitNewArrayInitializer( 858fb901c7aSDavid Blaikie const CXXNewExpr *E, QualType ElementType, llvm::Type *ElementTy, 8597f416cc4SJohn McCall Address BeginPtr, llvm::Value *NumElements, 86006a67e2cSRichard Smith llvm::Value *AllocSizeWithoutCookie) { 86106a67e2cSRichard Smith // If we have a type with trivial initialization and no initializer, 86206a67e2cSRichard Smith // there's nothing to do. 8636047f07eSSebastian Redl if (!E->hasInitializer()) 86406a67e2cSRichard Smith return; 865b66b08efSFariborz Jahanian 8667f416cc4SJohn McCall Address CurPtr = BeginPtr; 867d5202e09SFariborz Jahanian 86806a67e2cSRichard Smith unsigned InitListElements = 0; 869f862eb6aSSebastian Redl 870f862eb6aSSebastian Redl const Expr *Init = E->getInitializer(); 8717f416cc4SJohn McCall Address EndOfInit = Address::invalid(); 87206a67e2cSRichard Smith QualType::DestructionKind DtorKind = ElementType.isDestructedType(); 87306a67e2cSRichard Smith EHScopeStack::stable_iterator Cleanup; 87406a67e2cSRichard Smith llvm::Instruction *CleanupDominator = nullptr; 8751c96bc5dSRichard Smith 8767f416cc4SJohn McCall CharUnits ElementSize = getContext().getTypeSizeInChars(ElementType); 8777f416cc4SJohn McCall CharUnits ElementAlign = 8787f416cc4SJohn McCall BeginPtr.getAlignment().alignmentOfArrayElement(ElementSize); 8797f416cc4SJohn McCall 8800511d23aSRichard Smith // Attempt to perform zero-initialization using memset. 8810511d23aSRichard Smith auto TryMemsetInitialization = [&]() -> bool { 8820511d23aSRichard Smith // FIXME: If the type is a pointer-to-data-member under the Itanium ABI, 8830511d23aSRichard Smith // we can initialize with a memset to -1. 8840511d23aSRichard Smith if (!CGM.getTypes().isZeroInitializable(ElementType)) 8850511d23aSRichard Smith return false; 8860511d23aSRichard Smith 8870511d23aSRichard Smith // Optimization: since zero initialization will just set the memory 8880511d23aSRichard Smith // to all zeroes, generate a single memset to do it in one shot. 8890511d23aSRichard Smith 8900511d23aSRichard Smith // Subtract out the size of any elements we've already initialized. 8910511d23aSRichard Smith auto *RemainingSize = AllocSizeWithoutCookie; 8920511d23aSRichard Smith if (InitListElements) { 8930511d23aSRichard Smith // We know this can't overflow; we check this when doing the allocation. 8940511d23aSRichard Smith auto *InitializedSize = llvm::ConstantInt::get( 8950511d23aSRichard Smith RemainingSize->getType(), 8960511d23aSRichard Smith getContext().getTypeSizeInChars(ElementType).getQuantity() * 8970511d23aSRichard Smith InitListElements); 8980511d23aSRichard Smith RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize); 8990511d23aSRichard Smith } 9000511d23aSRichard Smith 9010511d23aSRichard Smith // Create the memset. 9020511d23aSRichard Smith Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize, false); 9030511d23aSRichard Smith return true; 9040511d23aSRichard Smith }; 9050511d23aSRichard Smith 906f862eb6aSSebastian Redl // If the initializer is an initializer list, first do the explicit elements. 907f862eb6aSSebastian Redl if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) { 9080511d23aSRichard Smith // Initializing from a (braced) string literal is a special case; the init 9090511d23aSRichard Smith // list element does not initialize a (single) array element. 9100511d23aSRichard Smith if (ILE->isStringLiteralInit()) { 9110511d23aSRichard Smith // Initialize the initial portion of length equal to that of the string 9120511d23aSRichard Smith // literal. The allocation must be for at least this much; we emitted a 9130511d23aSRichard Smith // check for that earlier. 9140511d23aSRichard Smith AggValueSlot Slot = 9150511d23aSRichard Smith AggValueSlot::forAddr(CurPtr, ElementType.getQualifiers(), 9160511d23aSRichard Smith AggValueSlot::IsDestructed, 9170511d23aSRichard Smith AggValueSlot::DoesNotNeedGCBarriers, 9180511d23aSRichard Smith AggValueSlot::IsNotAliased); 9190511d23aSRichard Smith EmitAggExpr(ILE->getInit(0), Slot); 9200511d23aSRichard Smith 9210511d23aSRichard Smith // Move past these elements. 9220511d23aSRichard Smith InitListElements = 9230511d23aSRichard Smith cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe()) 9240511d23aSRichard Smith ->getSize().getZExtValue(); 9250511d23aSRichard Smith CurPtr = 9260511d23aSRichard Smith Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(), 9270511d23aSRichard Smith Builder.getSize(InitListElements), 9280511d23aSRichard Smith "string.init.end"), 9290511d23aSRichard Smith CurPtr.getAlignment().alignmentAtOffset(InitListElements * 9300511d23aSRichard Smith ElementSize)); 9310511d23aSRichard Smith 9320511d23aSRichard Smith // Zero out the rest, if any remain. 9330511d23aSRichard Smith llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements); 9340511d23aSRichard Smith if (!ConstNum || !ConstNum->equalsInt(InitListElements)) { 9350511d23aSRichard Smith bool OK = TryMemsetInitialization(); 9360511d23aSRichard Smith (void)OK; 9370511d23aSRichard Smith assert(OK && "couldn't memset character type?"); 9380511d23aSRichard Smith } 9390511d23aSRichard Smith return; 9400511d23aSRichard Smith } 9410511d23aSRichard Smith 94206a67e2cSRichard Smith InitListElements = ILE->getNumInits(); 943f62290a1SChad Rosier 9441c96bc5dSRichard Smith // If this is a multi-dimensional array new, we will initialize multiple 9451c96bc5dSRichard Smith // elements with each init list element. 9461c96bc5dSRichard Smith QualType AllocType = E->getAllocatedType(); 9471c96bc5dSRichard Smith if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>( 9481c96bc5dSRichard Smith AllocType->getAsArrayTypeUnsafe())) { 949fb901c7aSDavid Blaikie ElementTy = ConvertTypeForMem(AllocType); 9507f416cc4SJohn McCall CurPtr = Builder.CreateElementBitCast(CurPtr, ElementTy); 95106a67e2cSRichard Smith InitListElements *= getContext().getConstantArrayElementCount(CAT); 9521c96bc5dSRichard Smith } 9531c96bc5dSRichard Smith 95406a67e2cSRichard Smith // Enter a partial-destruction Cleanup if necessary. 95506a67e2cSRichard Smith if (needsEHCleanup(DtorKind)) { 95606a67e2cSRichard Smith // In principle we could tell the Cleanup where we are more 957f62290a1SChad Rosier // directly, but the control flow can get so varied here that it 958f62290a1SChad Rosier // would actually be quite complex. Therefore we go through an 959f62290a1SChad Rosier // alloca. 9607f416cc4SJohn McCall EndOfInit = CreateTempAlloca(BeginPtr.getType(), getPointerAlign(), 9617f416cc4SJohn McCall "array.init.end"); 9627f416cc4SJohn McCall CleanupDominator = Builder.CreateStore(BeginPtr.getPointer(), EndOfInit); 9637f416cc4SJohn McCall pushIrregularPartialArrayCleanup(BeginPtr.getPointer(), EndOfInit, 9647f416cc4SJohn McCall ElementType, ElementAlign, 96506a67e2cSRichard Smith getDestroyer(DtorKind)); 96606a67e2cSRichard Smith Cleanup = EHStack.stable_begin(); 967f62290a1SChad Rosier } 968f62290a1SChad Rosier 9697f416cc4SJohn McCall CharUnits StartAlign = CurPtr.getAlignment(); 970f862eb6aSSebastian Redl for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) { 971f62290a1SChad Rosier // Tell the cleanup that it needs to destroy up to this 972f62290a1SChad Rosier // element. TODO: some of these stores can be trivially 973f62290a1SChad Rosier // observed to be unnecessary. 9747f416cc4SJohn McCall if (EndOfInit.isValid()) { 9757f416cc4SJohn McCall auto FinishedPtr = 9767f416cc4SJohn McCall Builder.CreateBitCast(CurPtr.getPointer(), BeginPtr.getType()); 9777f416cc4SJohn McCall Builder.CreateStore(FinishedPtr, EndOfInit); 9787f416cc4SJohn McCall } 97906a67e2cSRichard Smith // FIXME: If the last initializer is an incomplete initializer list for 98006a67e2cSRichard Smith // an array, and we have an array filler, we can fold together the two 98106a67e2cSRichard Smith // initialization loops. 9821c96bc5dSRichard Smith StoreAnyExprIntoOneUnit(*this, ILE->getInit(i), 98306a67e2cSRichard Smith ILE->getInit(i)->getType(), CurPtr); 9847f416cc4SJohn McCall CurPtr = Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(), 9857f416cc4SJohn McCall Builder.getSize(1), 9867f416cc4SJohn McCall "array.exp.next"), 9877f416cc4SJohn McCall StartAlign.alignmentAtOffset((i + 1) * ElementSize)); 988f862eb6aSSebastian Redl } 989f862eb6aSSebastian Redl 990f862eb6aSSebastian Redl // The remaining elements are filled with the array filler expression. 991f862eb6aSSebastian Redl Init = ILE->getArrayFiller(); 9921c96bc5dSRichard Smith 99306a67e2cSRichard Smith // Extract the initializer for the individual array elements by pulling 99406a67e2cSRichard Smith // out the array filler from all the nested initializer lists. This avoids 99506a67e2cSRichard Smith // generating a nested loop for the initialization. 99606a67e2cSRichard Smith while (Init && Init->getType()->isConstantArrayType()) { 99706a67e2cSRichard Smith auto *SubILE = dyn_cast<InitListExpr>(Init); 99806a67e2cSRichard Smith if (!SubILE) 99906a67e2cSRichard Smith break; 100006a67e2cSRichard Smith assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?"); 100106a67e2cSRichard Smith Init = SubILE->getArrayFiller(); 1002f862eb6aSSebastian Redl } 1003f862eb6aSSebastian Redl 100406a67e2cSRichard Smith // Switch back to initializing one base element at a time. 10057f416cc4SJohn McCall CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr.getType()); 1006f62290a1SChad Rosier } 1007e6c980c4SChandler Carruth 1008454a7cdfSRichard Smith // If all elements have already been initialized, skip any further 1009454a7cdfSRichard Smith // initialization. 1010454a7cdfSRichard Smith llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements); 1011454a7cdfSRichard Smith if (ConstNum && ConstNum->getZExtValue() <= InitListElements) { 1012454a7cdfSRichard Smith // If there was a Cleanup, deactivate it. 1013454a7cdfSRichard Smith if (CleanupDominator) 1014454a7cdfSRichard Smith DeactivateCleanupBlock(Cleanup, CleanupDominator); 1015454a7cdfSRichard Smith return; 1016454a7cdfSRichard Smith } 1017454a7cdfSRichard Smith 1018454a7cdfSRichard Smith assert(Init && "have trailing elements to initialize but no initializer"); 1019454a7cdfSRichard Smith 102006a67e2cSRichard Smith // If this is a constructor call, try to optimize it out, and failing that 102106a67e2cSRichard Smith // emit a single loop to initialize all remaining elements. 1022454a7cdfSRichard Smith if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) { 10236047f07eSSebastian Redl CXXConstructorDecl *Ctor = CCE->getConstructor(); 1024d153103cSDouglas Gregor if (Ctor->isTrivial()) { 102505fc5be3SDouglas Gregor // If new expression did not specify value-initialization, then there 102605fc5be3SDouglas Gregor // is no initialization. 10276047f07eSSebastian Redl if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty()) 102805fc5be3SDouglas Gregor return; 102905fc5be3SDouglas Gregor 103006a67e2cSRichard Smith if (TryMemsetInitialization()) 10313a202f60SAnders Carlsson return; 10323a202f60SAnders Carlsson } 103305fc5be3SDouglas Gregor 103406a67e2cSRichard Smith // Store the new Cleanup position for irregular Cleanups. 103506a67e2cSRichard Smith // 103606a67e2cSRichard Smith // FIXME: Share this cleanup with the constructor call emission rather than 103706a67e2cSRichard Smith // having it create a cleanup of its own. 10387f416cc4SJohn McCall if (EndOfInit.isValid()) 10397f416cc4SJohn McCall Builder.CreateStore(CurPtr.getPointer(), EndOfInit); 104006a67e2cSRichard Smith 104106a67e2cSRichard Smith // Emit a constructor call loop to initialize the remaining elements. 104206a67e2cSRichard Smith if (InitListElements) 104306a67e2cSRichard Smith NumElements = Builder.CreateSub( 104406a67e2cSRichard Smith NumElements, 104506a67e2cSRichard Smith llvm::ConstantInt::get(NumElements->getType(), InitListElements)); 104670b9c01bSAlexey Samsonov EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE, 104748ddcf2cSEli Friedman CCE->requiresZeroInitialization()); 104805fc5be3SDouglas Gregor return; 10496047f07eSSebastian Redl } 105006a67e2cSRichard Smith 105106a67e2cSRichard Smith // If this is value-initialization, we can usually use memset. 105206a67e2cSRichard Smith ImplicitValueInitExpr IVIE(ElementType); 1053454a7cdfSRichard Smith if (isa<ImplicitValueInitExpr>(Init)) { 105406a67e2cSRichard Smith if (TryMemsetInitialization()) 105506a67e2cSRichard Smith return; 105606a67e2cSRichard Smith 105706a67e2cSRichard Smith // Switch to an ImplicitValueInitExpr for the element type. This handles 105806a67e2cSRichard Smith // only one case: multidimensional array new of pointers to members. In 105906a67e2cSRichard Smith // all other cases, we already have an initializer for the array element. 106006a67e2cSRichard Smith Init = &IVIE; 106106a67e2cSRichard Smith } 106206a67e2cSRichard Smith 106306a67e2cSRichard Smith // At this point we should have found an initializer for the individual 106406a67e2cSRichard Smith // elements of the array. 106506a67e2cSRichard Smith assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) && 106606a67e2cSRichard Smith "got wrong type of element to initialize"); 106706a67e2cSRichard Smith 1068454a7cdfSRichard Smith // If we have an empty initializer list, we can usually use memset. 1069454a7cdfSRichard Smith if (auto *ILE = dyn_cast<InitListExpr>(Init)) 1070454a7cdfSRichard Smith if (ILE->getNumInits() == 0 && TryMemsetInitialization()) 1071d5202e09SFariborz Jahanian return; 107259486a2dSAnders Carlsson 1073cb77930dSYunzhong Gao // If we have a struct whose every field is value-initialized, we can 1074cb77930dSYunzhong Gao // usually use memset. 1075cb77930dSYunzhong Gao if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 1076cb77930dSYunzhong Gao if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) { 1077cb77930dSYunzhong Gao if (RType->getDecl()->isStruct()) { 1078872307e2SRichard Smith unsigned NumElements = 0; 1079872307e2SRichard Smith if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RType->getDecl())) 1080872307e2SRichard Smith NumElements = CXXRD->getNumBases(); 1081cb77930dSYunzhong Gao for (auto *Field : RType->getDecl()->fields()) 1082cb77930dSYunzhong Gao if (!Field->isUnnamedBitfield()) 1083872307e2SRichard Smith ++NumElements; 1084872307e2SRichard Smith // FIXME: Recurse into nested InitListExprs. 1085872307e2SRichard Smith if (ILE->getNumInits() == NumElements) 1086cb77930dSYunzhong Gao for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) 1087cb77930dSYunzhong Gao if (!isa<ImplicitValueInitExpr>(ILE->getInit(i))) 1088872307e2SRichard Smith --NumElements; 1089872307e2SRichard Smith if (ILE->getNumInits() == NumElements && TryMemsetInitialization()) 1090cb77930dSYunzhong Gao return; 1091cb77930dSYunzhong Gao } 1092cb77930dSYunzhong Gao } 1093cb77930dSYunzhong Gao } 1094cb77930dSYunzhong Gao 109506a67e2cSRichard Smith // Create the loop blocks. 109606a67e2cSRichard Smith llvm::BasicBlock *EntryBB = Builder.GetInsertBlock(); 109706a67e2cSRichard Smith llvm::BasicBlock *LoopBB = createBasicBlock("new.loop"); 109806a67e2cSRichard Smith llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end"); 109959486a2dSAnders Carlsson 110006a67e2cSRichard Smith // Find the end of the array, hoisted out of the loop. 110106a67e2cSRichard Smith llvm::Value *EndPtr = 11027f416cc4SJohn McCall Builder.CreateInBoundsGEP(BeginPtr.getPointer(), NumElements, "array.end"); 110306a67e2cSRichard Smith 110406a67e2cSRichard Smith // If the number of elements isn't constant, we have to now check if there is 110506a67e2cSRichard Smith // anything left to initialize. 110606a67e2cSRichard Smith if (!ConstNum) { 11077f416cc4SJohn McCall llvm::Value *IsEmpty = 11087f416cc4SJohn McCall Builder.CreateICmpEQ(CurPtr.getPointer(), EndPtr, "array.isempty"); 110906a67e2cSRichard Smith Builder.CreateCondBr(IsEmpty, ContBB, LoopBB); 111006a67e2cSRichard Smith } 111106a67e2cSRichard Smith 111206a67e2cSRichard Smith // Enter the loop. 111306a67e2cSRichard Smith EmitBlock(LoopBB); 111406a67e2cSRichard Smith 111506a67e2cSRichard Smith // Set up the current-element phi. 111606a67e2cSRichard Smith llvm::PHINode *CurPtrPhi = 11177f416cc4SJohn McCall Builder.CreatePHI(CurPtr.getType(), 2, "array.cur"); 11187f416cc4SJohn McCall CurPtrPhi->addIncoming(CurPtr.getPointer(), EntryBB); 11197f416cc4SJohn McCall 11207f416cc4SJohn McCall CurPtr = Address(CurPtrPhi, ElementAlign); 112106a67e2cSRichard Smith 112206a67e2cSRichard Smith // Store the new Cleanup position for irregular Cleanups. 11237f416cc4SJohn McCall if (EndOfInit.isValid()) 11247f416cc4SJohn McCall Builder.CreateStore(CurPtr.getPointer(), EndOfInit); 112506a67e2cSRichard Smith 112606a67e2cSRichard Smith // Enter a partial-destruction Cleanup if necessary. 112706a67e2cSRichard Smith if (!CleanupDominator && needsEHCleanup(DtorKind)) { 11287f416cc4SJohn McCall pushRegularPartialArrayCleanup(BeginPtr.getPointer(), CurPtr.getPointer(), 11297f416cc4SJohn McCall ElementType, ElementAlign, 113006a67e2cSRichard Smith getDestroyer(DtorKind)); 113106a67e2cSRichard Smith Cleanup = EHStack.stable_begin(); 113206a67e2cSRichard Smith CleanupDominator = Builder.CreateUnreachable(); 113306a67e2cSRichard Smith } 113406a67e2cSRichard Smith 113506a67e2cSRichard Smith // Emit the initializer into this element. 113606a67e2cSRichard Smith StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr); 113706a67e2cSRichard Smith 113806a67e2cSRichard Smith // Leave the Cleanup if we entered one. 113906a67e2cSRichard Smith if (CleanupDominator) { 114006a67e2cSRichard Smith DeactivateCleanupBlock(Cleanup, CleanupDominator); 114106a67e2cSRichard Smith CleanupDominator->eraseFromParent(); 114206a67e2cSRichard Smith } 114306a67e2cSRichard Smith 114406a67e2cSRichard Smith // Advance to the next element by adjusting the pointer type as necessary. 114506a67e2cSRichard Smith llvm::Value *NextPtr = 11467f416cc4SJohn McCall Builder.CreateConstInBoundsGEP1_32(ElementTy, CurPtr.getPointer(), 1, 11477f416cc4SJohn McCall "array.next"); 114806a67e2cSRichard Smith 114906a67e2cSRichard Smith // Check whether we've gotten to the end of the array and, if so, 115006a67e2cSRichard Smith // exit the loop. 115106a67e2cSRichard Smith llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend"); 115206a67e2cSRichard Smith Builder.CreateCondBr(IsEnd, ContBB, LoopBB); 115306a67e2cSRichard Smith CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock()); 115406a67e2cSRichard Smith 115506a67e2cSRichard Smith EmitBlock(ContBB); 115606a67e2cSRichard Smith } 115706a67e2cSRichard Smith 115806a67e2cSRichard Smith static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E, 1159fb901c7aSDavid Blaikie QualType ElementType, llvm::Type *ElementTy, 11607f416cc4SJohn McCall Address NewPtr, llvm::Value *NumElements, 116106a67e2cSRichard Smith llvm::Value *AllocSizeWithoutCookie) { 11629b479666SDavid Blaikie ApplyDebugLocation DL(CGF, E); 116306a67e2cSRichard Smith if (E->isArray()) 1164fb901c7aSDavid Blaikie CGF.EmitNewArrayInitializer(E, ElementType, ElementTy, NewPtr, NumElements, 116506a67e2cSRichard Smith AllocSizeWithoutCookie); 116606a67e2cSRichard Smith else if (const Expr *Init = E->getInitializer()) 116766e4197fSDavid Blaikie StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr); 116859486a2dSAnders Carlsson } 116959486a2dSAnders Carlsson 11708d0dc31dSRichard Smith /// Emit a call to an operator new or operator delete function, as implicitly 11718d0dc31dSRichard Smith /// created by new-expressions and delete-expressions. 11728d0dc31dSRichard Smith static RValue EmitNewDeleteCall(CodeGenFunction &CGF, 11738d0dc31dSRichard Smith const FunctionDecl *Callee, 11748d0dc31dSRichard Smith const FunctionProtoType *CalleeType, 11758d0dc31dSRichard Smith const CallArgList &Args) { 11768d0dc31dSRichard Smith llvm::Instruction *CallOrInvoke; 11771235a8daSRichard Smith llvm::Value *CalleeAddr = CGF.CGM.GetAddrOfFunction(Callee); 11788d0dc31dSRichard Smith RValue RV = 1179f770683fSPeter Collingbourne CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall( 1180f770683fSPeter Collingbourne Args, CalleeType, /*chainCall=*/false), 1181f770683fSPeter Collingbourne CalleeAddr, ReturnValueSlot(), Args, Callee, &CallOrInvoke); 11828d0dc31dSRichard Smith 11838d0dc31dSRichard Smith /// C++1y [expr.new]p10: 11848d0dc31dSRichard Smith /// [In a new-expression,] an implementation is allowed to omit a call 11858d0dc31dSRichard Smith /// to a replaceable global allocation function. 11868d0dc31dSRichard Smith /// 11878d0dc31dSRichard Smith /// We model such elidable calls with the 'builtin' attribute. 11886956d587SRafael Espindola llvm::Function *Fn = dyn_cast<llvm::Function>(CalleeAddr); 11891235a8daSRichard Smith if (Callee->isReplaceableGlobalAllocationFunction() && 11906956d587SRafael Espindola Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) { 11918d0dc31dSRichard Smith // FIXME: Add addAttribute to CallSite. 11928d0dc31dSRichard Smith if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(CallOrInvoke)) 11938d0dc31dSRichard Smith CI->addAttribute(llvm::AttributeSet::FunctionIndex, 11948d0dc31dSRichard Smith llvm::Attribute::Builtin); 11958d0dc31dSRichard Smith else if (llvm::InvokeInst *II = dyn_cast<llvm::InvokeInst>(CallOrInvoke)) 11968d0dc31dSRichard Smith II->addAttribute(llvm::AttributeSet::FunctionIndex, 11978d0dc31dSRichard Smith llvm::Attribute::Builtin); 11988d0dc31dSRichard Smith else 11998d0dc31dSRichard Smith llvm_unreachable("unexpected kind of call instruction"); 12008d0dc31dSRichard Smith } 12018d0dc31dSRichard Smith 12028d0dc31dSRichard Smith return RV; 12038d0dc31dSRichard Smith } 12048d0dc31dSRichard Smith 1205760520bcSRichard Smith RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type, 1206760520bcSRichard Smith const Expr *Arg, 1207760520bcSRichard Smith bool IsDelete) { 1208760520bcSRichard Smith CallArgList Args; 1209760520bcSRichard Smith const Stmt *ArgS = Arg; 1210f05779e2SDavid Blaikie EmitCallArgs(Args, *Type->param_type_begin(), llvm::makeArrayRef(ArgS)); 1211760520bcSRichard Smith // Find the allocation or deallocation function that we're calling. 1212760520bcSRichard Smith ASTContext &Ctx = getContext(); 1213760520bcSRichard Smith DeclarationName Name = Ctx.DeclarationNames 1214760520bcSRichard Smith .getCXXOperatorName(IsDelete ? OO_Delete : OO_New); 1215760520bcSRichard Smith for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name)) 1216599bed75SRichard Smith if (auto *FD = dyn_cast<FunctionDecl>(Decl)) 1217599bed75SRichard Smith if (Ctx.hasSameType(FD->getType(), QualType(Type, 0))) 1218760520bcSRichard Smith return EmitNewDeleteCall(*this, cast<FunctionDecl>(Decl), Type, Args); 1219760520bcSRichard Smith llvm_unreachable("predeclared global operator new/delete is missing"); 1220760520bcSRichard Smith } 1221760520bcSRichard Smith 1222*189e52fcSRichard Smith static std::pair<bool, bool> 1223*189e52fcSRichard Smith shouldPassSizeAndAlignToUsualDelete(const FunctionProtoType *FPT) { 1224*189e52fcSRichard Smith auto AI = FPT->param_type_begin(), AE = FPT->param_type_end(); 1225824c2f53SJohn McCall 1226*189e52fcSRichard Smith // The first argument is always a void*. 1227*189e52fcSRichard Smith ++AI; 1228*189e52fcSRichard Smith 1229*189e52fcSRichard Smith // Figure out what other parameters we should be implicitly passing. 1230*189e52fcSRichard Smith bool PassSize = false; 1231*189e52fcSRichard Smith bool PassAlignment = false; 1232*189e52fcSRichard Smith 1233*189e52fcSRichard Smith if (AI != AE && (*AI)->isIntegerType()) { 1234*189e52fcSRichard Smith PassSize = true; 1235*189e52fcSRichard Smith ++AI; 1236*189e52fcSRichard Smith } 1237*189e52fcSRichard Smith 1238*189e52fcSRichard Smith if (AI != AE && (*AI)->isAlignValT()) { 1239*189e52fcSRichard Smith PassAlignment = true; 1240*189e52fcSRichard Smith ++AI; 1241*189e52fcSRichard Smith } 1242*189e52fcSRichard Smith 1243*189e52fcSRichard Smith assert(AI == AE && "unexpected usual deallocation function parameter"); 1244*189e52fcSRichard Smith return {PassSize, PassAlignment}; 1245*189e52fcSRichard Smith } 1246*189e52fcSRichard Smith 1247*189e52fcSRichard Smith namespace { 1248*189e52fcSRichard Smith /// A cleanup to call the given 'operator delete' function upon abnormal 1249*189e52fcSRichard Smith /// exit from a new expression. Templated on a traits type that deals with 1250*189e52fcSRichard Smith /// ensuring that the arguments dominate the cleanup if necessary. 1251*189e52fcSRichard Smith template<typename Traits> 1252*189e52fcSRichard Smith class CallDeleteDuringNew final : public EHScopeStack::Cleanup { 1253*189e52fcSRichard Smith /// Type used to hold llvm::Value*s. 1254*189e52fcSRichard Smith typedef typename Traits::ValueTy ValueTy; 1255*189e52fcSRichard Smith /// Type used to hold RValues. 1256*189e52fcSRichard Smith typedef typename Traits::RValueTy RValueTy; 1257*189e52fcSRichard Smith struct PlacementArg { 1258*189e52fcSRichard Smith RValueTy ArgValue; 1259*189e52fcSRichard Smith QualType ArgType; 1260*189e52fcSRichard Smith }; 1261*189e52fcSRichard Smith 1262*189e52fcSRichard Smith unsigned NumPlacementArgs : 31; 1263*189e52fcSRichard Smith unsigned PassAlignmentToPlacementDelete : 1; 1264*189e52fcSRichard Smith const FunctionDecl *OperatorDelete; 1265*189e52fcSRichard Smith ValueTy Ptr; 1266*189e52fcSRichard Smith ValueTy AllocSize; 1267*189e52fcSRichard Smith CharUnits AllocAlign; 1268*189e52fcSRichard Smith 1269*189e52fcSRichard Smith PlacementArg *getPlacementArgs() { 1270*189e52fcSRichard Smith return reinterpret_cast<PlacementArg *>(this + 1); 1271*189e52fcSRichard Smith } 1272824c2f53SJohn McCall 1273824c2f53SJohn McCall public: 1274824c2f53SJohn McCall static size_t getExtraSize(size_t NumPlacementArgs) { 1275*189e52fcSRichard Smith return NumPlacementArgs * sizeof(PlacementArg); 1276824c2f53SJohn McCall } 1277824c2f53SJohn McCall 1278824c2f53SJohn McCall CallDeleteDuringNew(size_t NumPlacementArgs, 1279*189e52fcSRichard Smith const FunctionDecl *OperatorDelete, ValueTy Ptr, 1280*189e52fcSRichard Smith ValueTy AllocSize, bool PassAlignmentToPlacementDelete, 1281*189e52fcSRichard Smith CharUnits AllocAlign) 1282*189e52fcSRichard Smith : NumPlacementArgs(NumPlacementArgs), 1283*189e52fcSRichard Smith PassAlignmentToPlacementDelete(PassAlignmentToPlacementDelete), 1284*189e52fcSRichard Smith OperatorDelete(OperatorDelete), Ptr(Ptr), AllocSize(AllocSize), 1285*189e52fcSRichard Smith AllocAlign(AllocAlign) {} 1286824c2f53SJohn McCall 1287*189e52fcSRichard Smith void setPlacementArg(unsigned I, RValueTy Arg, QualType Type) { 1288824c2f53SJohn McCall assert(I < NumPlacementArgs && "index out of range"); 1289*189e52fcSRichard Smith getPlacementArgs()[I] = {Arg, Type}; 1290824c2f53SJohn McCall } 1291824c2f53SJohn McCall 12924f12f10dSCraig Topper void Emit(CodeGenFunction &CGF, Flags flags) override { 1293*189e52fcSRichard Smith const FunctionProtoType *FPT = 1294*189e52fcSRichard Smith OperatorDelete->getType()->getAs<FunctionProtoType>(); 1295824c2f53SJohn McCall CallArgList DeleteArgs; 1296824c2f53SJohn McCall 1297824c2f53SJohn McCall // The first argument is always a void*. 1298*189e52fcSRichard Smith DeleteArgs.add(Traits::get(CGF, Ptr), FPT->getParamType(0)); 1299824c2f53SJohn McCall 1300*189e52fcSRichard Smith // Figure out what other parameters we should be implicitly passing. 1301*189e52fcSRichard Smith bool PassSize = false; 1302*189e52fcSRichard Smith bool PassAlignment = false; 1303*189e52fcSRichard Smith if (NumPlacementArgs) { 1304*189e52fcSRichard Smith // A placement deallocation function is implicitly passed an alignment 1305*189e52fcSRichard Smith // if the placement allocation function was, but is never passed a size. 1306*189e52fcSRichard Smith PassAlignment = PassAlignmentToPlacementDelete; 1307*189e52fcSRichard Smith } else { 1308*189e52fcSRichard Smith // For a non-placement new-expression, 'operator delete' can take a 1309*189e52fcSRichard Smith // size and/or an alignment if it has the right parameters. 1310*189e52fcSRichard Smith std::tie(PassSize, PassAlignment) = 1311*189e52fcSRichard Smith shouldPassSizeAndAlignToUsualDelete(FPT); 13127f9c92a9SJohn McCall } 13137f9c92a9SJohn McCall 1314*189e52fcSRichard Smith // The second argument can be a std::size_t (for non-placement delete). 1315*189e52fcSRichard Smith if (PassSize) 1316*189e52fcSRichard Smith DeleteArgs.add(Traits::get(CGF, AllocSize), 1317*189e52fcSRichard Smith CGF.getContext().getSizeType()); 13187f9c92a9SJohn McCall 1319*189e52fcSRichard Smith // The next (second or third) argument can be a std::align_val_t, which 1320*189e52fcSRichard Smith // is an enum whose underlying type is std::size_t. 1321*189e52fcSRichard Smith // FIXME: Use the right type as the parameter type. Note that in a call 1322*189e52fcSRichard Smith // to operator delete(size_t, ...), we may not have it available. 1323*189e52fcSRichard Smith if (PassAlignment) 1324*189e52fcSRichard Smith DeleteArgs.add(RValue::get(llvm::ConstantInt::get( 1325*189e52fcSRichard Smith CGF.SizeTy, AllocAlign.getQuantity())), 1326*189e52fcSRichard Smith CGF.getContext().getSizeType()); 13277f9c92a9SJohn McCall 13287f9c92a9SJohn McCall // Pass the rest of the arguments, which must match exactly. 13297f9c92a9SJohn McCall for (unsigned I = 0; I != NumPlacementArgs; ++I) { 1330*189e52fcSRichard Smith auto Arg = getPlacementArgs()[I]; 1331*189e52fcSRichard Smith DeleteArgs.add(Traits::get(CGF, Arg.ArgValue), Arg.ArgType); 13327f9c92a9SJohn McCall } 13337f9c92a9SJohn McCall 13347f9c92a9SJohn McCall // Call 'operator delete'. 13358d0dc31dSRichard Smith EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs); 13367f9c92a9SJohn McCall } 13377f9c92a9SJohn McCall }; 1338ab9db510SAlexander Kornienko } 13397f9c92a9SJohn McCall 13407f9c92a9SJohn McCall /// Enter a cleanup to call 'operator delete' if the initializer in a 13417f9c92a9SJohn McCall /// new-expression throws. 13427f9c92a9SJohn McCall static void EnterNewDeleteCleanup(CodeGenFunction &CGF, 13437f9c92a9SJohn McCall const CXXNewExpr *E, 13447f416cc4SJohn McCall Address NewPtr, 13457f9c92a9SJohn McCall llvm::Value *AllocSize, 1346*189e52fcSRichard Smith CharUnits AllocAlign, 13477f9c92a9SJohn McCall const CallArgList &NewArgs) { 1348*189e52fcSRichard Smith unsigned NumNonPlacementArgs = E->passAlignment() ? 2 : 1; 1349*189e52fcSRichard Smith 13507f9c92a9SJohn McCall // If we're not inside a conditional branch, then the cleanup will 13517f9c92a9SJohn McCall // dominate and we can do the easier (and more efficient) thing. 13527f9c92a9SJohn McCall if (!CGF.isInConditionalBranch()) { 1353*189e52fcSRichard Smith struct DirectCleanupTraits { 1354*189e52fcSRichard Smith typedef llvm::Value *ValueTy; 1355*189e52fcSRichard Smith typedef RValue RValueTy; 1356*189e52fcSRichard Smith static RValue get(CodeGenFunction &, ValueTy V) { return RValue::get(V); } 1357*189e52fcSRichard Smith static RValue get(CodeGenFunction &, RValueTy V) { return V; } 1358*189e52fcSRichard Smith }; 1359*189e52fcSRichard Smith 1360*189e52fcSRichard Smith typedef CallDeleteDuringNew<DirectCleanupTraits> DirectCleanup; 1361*189e52fcSRichard Smith 1362*189e52fcSRichard Smith DirectCleanup *Cleanup = CGF.EHStack 1363*189e52fcSRichard Smith .pushCleanupWithExtra<DirectCleanup>(EHCleanup, 13647f9c92a9SJohn McCall E->getNumPlacementArgs(), 13657f9c92a9SJohn McCall E->getOperatorDelete(), 13667f416cc4SJohn McCall NewPtr.getPointer(), 1367*189e52fcSRichard Smith AllocSize, 1368*189e52fcSRichard Smith E->passAlignment(), 1369*189e52fcSRichard Smith AllocAlign); 1370*189e52fcSRichard Smith for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) { 1371*189e52fcSRichard Smith auto &Arg = NewArgs[I + NumNonPlacementArgs]; 1372*189e52fcSRichard Smith Cleanup->setPlacementArg(I, Arg.RV, Arg.Ty); 1373*189e52fcSRichard Smith } 13747f9c92a9SJohn McCall 13757f9c92a9SJohn McCall return; 13767f9c92a9SJohn McCall } 13777f9c92a9SJohn McCall 13787f9c92a9SJohn McCall // Otherwise, we need to save all this stuff. 1379cb5f77f0SJohn McCall DominatingValue<RValue>::saved_type SavedNewPtr = 13807f416cc4SJohn McCall DominatingValue<RValue>::save(CGF, RValue::get(NewPtr.getPointer())); 1381cb5f77f0SJohn McCall DominatingValue<RValue>::saved_type SavedAllocSize = 1382cb5f77f0SJohn McCall DominatingValue<RValue>::save(CGF, RValue::get(AllocSize)); 13837f9c92a9SJohn McCall 1384*189e52fcSRichard Smith struct ConditionalCleanupTraits { 1385*189e52fcSRichard Smith typedef DominatingValue<RValue>::saved_type ValueTy; 1386*189e52fcSRichard Smith typedef DominatingValue<RValue>::saved_type RValueTy; 1387*189e52fcSRichard Smith static RValue get(CodeGenFunction &CGF, ValueTy V) { 1388*189e52fcSRichard Smith return V.restore(CGF); 1389*189e52fcSRichard Smith } 1390*189e52fcSRichard Smith }; 1391*189e52fcSRichard Smith typedef CallDeleteDuringNew<ConditionalCleanupTraits> ConditionalCleanup; 1392*189e52fcSRichard Smith 1393*189e52fcSRichard Smith ConditionalCleanup *Cleanup = CGF.EHStack 1394*189e52fcSRichard Smith .pushCleanupWithExtra<ConditionalCleanup>(EHCleanup, 13957f9c92a9SJohn McCall E->getNumPlacementArgs(), 13967f9c92a9SJohn McCall E->getOperatorDelete(), 13977f9c92a9SJohn McCall SavedNewPtr, 1398*189e52fcSRichard Smith SavedAllocSize, 1399*189e52fcSRichard Smith E->passAlignment(), 1400*189e52fcSRichard Smith AllocAlign); 1401*189e52fcSRichard Smith for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) { 1402*189e52fcSRichard Smith auto &Arg = NewArgs[I + NumNonPlacementArgs]; 1403*189e52fcSRichard Smith Cleanup->setPlacementArg(I, DominatingValue<RValue>::save(CGF, Arg.RV), 1404*189e52fcSRichard Smith Arg.Ty); 1405*189e52fcSRichard Smith } 14067f9c92a9SJohn McCall 1407f4beacd0SJohn McCall CGF.initFullExprCleanup(); 1408824c2f53SJohn McCall } 1409824c2f53SJohn McCall 141059486a2dSAnders Carlsson llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) { 141175f9498aSJohn McCall // The element type being allocated. 141275f9498aSJohn McCall QualType allocType = getContext().getBaseElementType(E->getAllocatedType()); 14138ed55a54SJohn McCall 141475f9498aSJohn McCall // 1. Build a call to the allocation function. 141575f9498aSJohn McCall FunctionDecl *allocator = E->getOperatorNew(); 141659486a2dSAnders Carlsson 1417f862eb6aSSebastian Redl // If there is a brace-initializer, cannot allocate fewer elements than inits. 1418f862eb6aSSebastian Redl unsigned minElements = 0; 1419f862eb6aSSebastian Redl if (E->isArray() && E->hasInitializer()) { 14200511d23aSRichard Smith const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer()); 14210511d23aSRichard Smith if (ILE && ILE->isStringLiteralInit()) 14220511d23aSRichard Smith minElements = 14230511d23aSRichard Smith cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe()) 14240511d23aSRichard Smith ->getSize().getZExtValue(); 14250511d23aSRichard Smith else if (ILE) 1426f862eb6aSSebastian Redl minElements = ILE->getNumInits(); 1427f862eb6aSSebastian Redl } 1428f862eb6aSSebastian Redl 14298a13c418SCraig Topper llvm::Value *numElements = nullptr; 14308a13c418SCraig Topper llvm::Value *allocSizeWithoutCookie = nullptr; 143175f9498aSJohn McCall llvm::Value *allocSize = 1432f862eb6aSSebastian Redl EmitCXXNewAllocSize(*this, E, minElements, numElements, 1433f862eb6aSSebastian Redl allocSizeWithoutCookie); 1434*189e52fcSRichard Smith CharUnits allocAlign = getContext().getTypeAlignInChars(allocType); 143559486a2dSAnders Carlsson 14367f416cc4SJohn McCall // Emit the allocation call. If the allocator is a global placement 14377f416cc4SJohn McCall // operator, just "inline" it directly. 14387f416cc4SJohn McCall Address allocation = Address::invalid(); 14397f416cc4SJohn McCall CallArgList allocatorArgs; 14407f416cc4SJohn McCall if (allocator->isReservedGlobalPlacementOperator()) { 144153dcf94dSJohn McCall assert(E->getNumPlacementArgs() == 1); 144253dcf94dSJohn McCall const Expr *arg = *E->placement_arguments().begin(); 144353dcf94dSJohn McCall 14447f416cc4SJohn McCall AlignmentSource alignSource; 144553dcf94dSJohn McCall allocation = EmitPointerWithAlignment(arg, &alignSource); 14467f416cc4SJohn McCall 14477f416cc4SJohn McCall // The pointer expression will, in many cases, be an opaque void*. 14487f416cc4SJohn McCall // In these cases, discard the computed alignment and use the 14497f416cc4SJohn McCall // formal alignment of the allocated type. 1450*189e52fcSRichard Smith if (alignSource != AlignmentSource::Decl) 1451*189e52fcSRichard Smith allocation = Address(allocation.getPointer(), allocAlign); 14527f416cc4SJohn McCall 145353dcf94dSJohn McCall // Set up allocatorArgs for the call to operator delete if it's not 145453dcf94dSJohn McCall // the reserved global operator. 145553dcf94dSJohn McCall if (E->getOperatorDelete() && 145653dcf94dSJohn McCall !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) { 145753dcf94dSJohn McCall allocatorArgs.add(RValue::get(allocSize), getContext().getSizeType()); 145853dcf94dSJohn McCall allocatorArgs.add(RValue::get(allocation.getPointer()), arg->getType()); 145953dcf94dSJohn McCall } 146053dcf94dSJohn McCall 14617f416cc4SJohn McCall } else { 14627f416cc4SJohn McCall const FunctionProtoType *allocatorType = 14637f416cc4SJohn McCall allocator->getType()->castAs<FunctionProtoType>(); 1464*189e52fcSRichard Smith unsigned ParamsToSkip = 0; 14657f416cc4SJohn McCall 14667f416cc4SJohn McCall // The allocation size is the first argument. 14677f416cc4SJohn McCall QualType sizeType = getContext().getSizeType(); 146843dca6a8SEli Friedman allocatorArgs.add(RValue::get(allocSize), sizeType); 1469*189e52fcSRichard Smith ++ParamsToSkip; 147059486a2dSAnders Carlsson 1471*189e52fcSRichard Smith if (allocSize != allocSizeWithoutCookie) { 1472*189e52fcSRichard Smith CharUnits cookieAlign = getSizeAlign(); // FIXME: Ask the ABI. 1473*189e52fcSRichard Smith allocAlign = std::max(allocAlign, cookieAlign); 1474*189e52fcSRichard Smith } 1475*189e52fcSRichard Smith 1476*189e52fcSRichard Smith // The allocation alignment may be passed as the second argument. 1477*189e52fcSRichard Smith if (E->passAlignment()) { 1478*189e52fcSRichard Smith QualType AlignValT = sizeType; 1479*189e52fcSRichard Smith if (allocatorType->getNumParams() > 1) { 1480*189e52fcSRichard Smith AlignValT = allocatorType->getParamType(1); 1481*189e52fcSRichard Smith assert(getContext().hasSameUnqualifiedType( 1482*189e52fcSRichard Smith AlignValT->castAs<EnumType>()->getDecl()->getIntegerType(), 1483*189e52fcSRichard Smith sizeType) && 1484*189e52fcSRichard Smith "wrong type for alignment parameter"); 1485*189e52fcSRichard Smith ++ParamsToSkip; 1486*189e52fcSRichard Smith } else { 1487*189e52fcSRichard Smith // Corner case, passing alignment to 'operator new(size_t, ...)'. 1488*189e52fcSRichard Smith assert(allocator->isVariadic() && "can't pass alignment to allocator"); 1489*189e52fcSRichard Smith } 1490*189e52fcSRichard Smith allocatorArgs.add( 1491*189e52fcSRichard Smith RValue::get(llvm::ConstantInt::get(SizeTy, allocAlign.getQuantity())), 1492*189e52fcSRichard Smith AlignValT); 1493*189e52fcSRichard Smith } 1494*189e52fcSRichard Smith 1495*189e52fcSRichard Smith // FIXME: Why do we not pass a CalleeDecl here? 1496f05779e2SDavid Blaikie EmitCallArgs(allocatorArgs, allocatorType, E->placement_arguments(), 1497*189e52fcSRichard Smith /*CalleeDecl*/nullptr, /*ParamsToSkip*/ParamsToSkip); 149859486a2dSAnders Carlsson 14997f416cc4SJohn McCall RValue RV = 15007f416cc4SJohn McCall EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs); 15017f416cc4SJohn McCall 1502*189e52fcSRichard Smith // If this was a call to a global replaceable allocation function that does 1503*189e52fcSRichard Smith // not take an alignment argument, the allocator is known to produce 1504*189e52fcSRichard Smith // storage that's suitably aligned for any object that fits, up to a known 1505*189e52fcSRichard Smith // threshold. Otherwise assume it's suitably aligned for the allocated type. 1506*189e52fcSRichard Smith CharUnits allocationAlign = allocAlign; 1507*189e52fcSRichard Smith if (!E->passAlignment() && 1508*189e52fcSRichard Smith allocator->isReplaceableGlobalAllocationFunction()) { 1509*189e52fcSRichard Smith unsigned AllocatorAlign = llvm::PowerOf2Floor(std::min<uint64_t>( 1510*189e52fcSRichard Smith Target.getNewAlign(), getContext().getTypeSize(allocType))); 1511*189e52fcSRichard Smith allocationAlign = std::max( 1512*189e52fcSRichard Smith allocationAlign, getContext().toCharUnitsFromBits(AllocatorAlign)); 15137f416cc4SJohn McCall } 15147f416cc4SJohn McCall 15157f416cc4SJohn McCall allocation = Address(RV.getScalarVal(), allocationAlign); 15167ec4b434SJohn McCall } 151759486a2dSAnders Carlsson 151875f9498aSJohn McCall // Emit a null check on the allocation result if the allocation 151975f9498aSJohn McCall // function is allowed to return null (because it has a non-throwing 1520902a0238SRichard Smith // exception spec or is the reserved placement new) and we have an 152175f9498aSJohn McCall // interesting initializer. 1522902a0238SRichard Smith bool nullCheck = E->shouldNullCheckAllocation(getContext()) && 15236047f07eSSebastian Redl (!allocType.isPODType(getContext()) || E->hasInitializer()); 152459486a2dSAnders Carlsson 15258a13c418SCraig Topper llvm::BasicBlock *nullCheckBB = nullptr; 15268a13c418SCraig Topper llvm::BasicBlock *contBB = nullptr; 152759486a2dSAnders Carlsson 1528f7dcf320SJohn McCall // The null-check means that the initializer is conditionally 1529f7dcf320SJohn McCall // evaluated. 1530f7dcf320SJohn McCall ConditionalEvaluation conditional(*this); 1531f7dcf320SJohn McCall 153275f9498aSJohn McCall if (nullCheck) { 1533f7dcf320SJohn McCall conditional.begin(*this); 153475f9498aSJohn McCall 153575f9498aSJohn McCall nullCheckBB = Builder.GetInsertBlock(); 153675f9498aSJohn McCall llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull"); 153775f9498aSJohn McCall contBB = createBasicBlock("new.cont"); 153875f9498aSJohn McCall 15397f416cc4SJohn McCall llvm::Value *isNull = 15407f416cc4SJohn McCall Builder.CreateIsNull(allocation.getPointer(), "new.isnull"); 154175f9498aSJohn McCall Builder.CreateCondBr(isNull, contBB, notNullBB); 154275f9498aSJohn McCall EmitBlock(notNullBB); 154359486a2dSAnders Carlsson } 154459486a2dSAnders Carlsson 1545824c2f53SJohn McCall // If there's an operator delete, enter a cleanup to call it if an 1546824c2f53SJohn McCall // exception is thrown. 154775f9498aSJohn McCall EHScopeStack::stable_iterator operatorDeleteCleanup; 15488a13c418SCraig Topper llvm::Instruction *cleanupDominator = nullptr; 15497ec4b434SJohn McCall if (E->getOperatorDelete() && 15507ec4b434SJohn McCall !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) { 1551*189e52fcSRichard Smith EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocAlign, 1552*189e52fcSRichard Smith allocatorArgs); 155375f9498aSJohn McCall operatorDeleteCleanup = EHStack.stable_begin(); 1554f4beacd0SJohn McCall cleanupDominator = Builder.CreateUnreachable(); 1555824c2f53SJohn McCall } 1556824c2f53SJohn McCall 1557cf9b1f65SEli Friedman assert((allocSize == allocSizeWithoutCookie) == 1558cf9b1f65SEli Friedman CalculateCookiePadding(*this, E).isZero()); 1559cf9b1f65SEli Friedman if (allocSize != allocSizeWithoutCookie) { 1560cf9b1f65SEli Friedman assert(E->isArray()); 1561cf9b1f65SEli Friedman allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation, 1562cf9b1f65SEli Friedman numElements, 1563cf9b1f65SEli Friedman E, allocType); 1564cf9b1f65SEli Friedman } 1565cf9b1f65SEli Friedman 1566fb901c7aSDavid Blaikie llvm::Type *elementTy = ConvertTypeForMem(allocType); 15677f416cc4SJohn McCall Address result = Builder.CreateElementBitCast(allocation, elementTy); 1568824c2f53SJohn McCall 1569338c9d0aSPiotr Padlewski // Passing pointer through invariant.group.barrier to avoid propagation of 1570338c9d0aSPiotr Padlewski // vptrs information which may be included in previous type. 1571338c9d0aSPiotr Padlewski if (CGM.getCodeGenOpts().StrictVTablePointers && 1572338c9d0aSPiotr Padlewski CGM.getCodeGenOpts().OptimizationLevel > 0 && 1573338c9d0aSPiotr Padlewski allocator->isReservedGlobalPlacementOperator()) 1574338c9d0aSPiotr Padlewski result = Address(Builder.CreateInvariantGroupBarrier(result.getPointer()), 1575338c9d0aSPiotr Padlewski result.getAlignment()); 1576338c9d0aSPiotr Padlewski 1577fb901c7aSDavid Blaikie EmitNewInitializer(*this, E, allocType, elementTy, result, numElements, 157899210dc9SJohn McCall allocSizeWithoutCookie); 15798ed55a54SJohn McCall if (E->isArray()) { 15808ed55a54SJohn McCall // NewPtr is a pointer to the base element type. If we're 15818ed55a54SJohn McCall // allocating an array of arrays, we'll need to cast back to the 15828ed55a54SJohn McCall // array pointer type. 15832192fe50SChris Lattner llvm::Type *resultType = ConvertTypeForMem(E->getType()); 15847f416cc4SJohn McCall if (result.getType() != resultType) 158575f9498aSJohn McCall result = Builder.CreateBitCast(result, resultType); 158647b4629bSFariborz Jahanian } 158759486a2dSAnders Carlsson 1588824c2f53SJohn McCall // Deactivate the 'operator delete' cleanup if we finished 1589824c2f53SJohn McCall // initialization. 1590f4beacd0SJohn McCall if (operatorDeleteCleanup.isValid()) { 1591f4beacd0SJohn McCall DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator); 1592f4beacd0SJohn McCall cleanupDominator->eraseFromParent(); 1593f4beacd0SJohn McCall } 1594824c2f53SJohn McCall 15957f416cc4SJohn McCall llvm::Value *resultPtr = result.getPointer(); 159675f9498aSJohn McCall if (nullCheck) { 1597f7dcf320SJohn McCall conditional.end(*this); 1598f7dcf320SJohn McCall 159975f9498aSJohn McCall llvm::BasicBlock *notNullBB = Builder.GetInsertBlock(); 160075f9498aSJohn McCall EmitBlock(contBB); 160159486a2dSAnders Carlsson 16027f416cc4SJohn McCall llvm::PHINode *PHI = Builder.CreatePHI(resultPtr->getType(), 2); 16037f416cc4SJohn McCall PHI->addIncoming(resultPtr, notNullBB); 16047f416cc4SJohn McCall PHI->addIncoming(llvm::Constant::getNullValue(resultPtr->getType()), 160575f9498aSJohn McCall nullCheckBB); 160659486a2dSAnders Carlsson 16077f416cc4SJohn McCall resultPtr = PHI; 160859486a2dSAnders Carlsson } 160959486a2dSAnders Carlsson 16107f416cc4SJohn McCall return resultPtr; 161159486a2dSAnders Carlsson } 161259486a2dSAnders Carlsson 161359486a2dSAnders Carlsson void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD, 1614*189e52fcSRichard Smith llvm::Value *Ptr, QualType DeleteTy, 1615*189e52fcSRichard Smith llvm::Value *NumElements, 1616*189e52fcSRichard Smith CharUnits CookieSize) { 1617*189e52fcSRichard Smith assert((!NumElements && CookieSize.isZero()) || 1618*189e52fcSRichard Smith DeleteFD->getOverloadedOperator() == OO_Array_Delete); 16198ed55a54SJohn McCall 162059486a2dSAnders Carlsson const FunctionProtoType *DeleteFTy = 162159486a2dSAnders Carlsson DeleteFD->getType()->getAs<FunctionProtoType>(); 162259486a2dSAnders Carlsson 162359486a2dSAnders Carlsson CallArgList DeleteArgs; 162459486a2dSAnders Carlsson 1625*189e52fcSRichard Smith std::pair<bool, bool> PassSizeAndAlign = 1626*189e52fcSRichard Smith shouldPassSizeAndAlignToUsualDelete(DeleteFTy); 162721122cf6SAnders Carlsson 1628*189e52fcSRichard Smith auto ParamTypeIt = DeleteFTy->param_type_begin(); 1629*189e52fcSRichard Smith 1630*189e52fcSRichard Smith // Pass the pointer itself. 1631*189e52fcSRichard Smith QualType ArgTy = *ParamTypeIt++; 163259486a2dSAnders Carlsson llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy)); 163343dca6a8SEli Friedman DeleteArgs.add(RValue::get(DeletePtr), ArgTy); 163459486a2dSAnders Carlsson 1635*189e52fcSRichard Smith // Pass the size if the delete function has a size_t parameter. 1636*189e52fcSRichard Smith if (PassSizeAndAlign.first) { 1637*189e52fcSRichard Smith QualType SizeType = *ParamTypeIt++; 1638*189e52fcSRichard Smith CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy); 1639*189e52fcSRichard Smith llvm::Value *Size = llvm::ConstantInt::get(ConvertType(SizeType), 1640*189e52fcSRichard Smith DeleteTypeSize.getQuantity()); 1641*189e52fcSRichard Smith 1642*189e52fcSRichard Smith // For array new, multiply by the number of elements. 1643*189e52fcSRichard Smith if (NumElements) 1644*189e52fcSRichard Smith Size = Builder.CreateMul(Size, NumElements); 1645*189e52fcSRichard Smith 1646*189e52fcSRichard Smith // If there is a cookie, add the cookie size. 1647*189e52fcSRichard Smith if (!CookieSize.isZero()) 1648*189e52fcSRichard Smith Size = Builder.CreateAdd( 1649*189e52fcSRichard Smith Size, llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity())); 1650*189e52fcSRichard Smith 1651*189e52fcSRichard Smith DeleteArgs.add(RValue::get(Size), SizeType); 1652*189e52fcSRichard Smith } 1653*189e52fcSRichard Smith 1654*189e52fcSRichard Smith // Pass the alignment if the delete function has an align_val_t parameter. 1655*189e52fcSRichard Smith if (PassSizeAndAlign.second) { 1656*189e52fcSRichard Smith QualType AlignValType = *ParamTypeIt++; 1657*189e52fcSRichard Smith CharUnits DeleteTypeAlign = getContext().toCharUnitsFromBits( 1658*189e52fcSRichard Smith getContext().getTypeAlignIfKnown(DeleteTy)); 1659*189e52fcSRichard Smith llvm::Value *Align = llvm::ConstantInt::get(ConvertType(AlignValType), 1660*189e52fcSRichard Smith DeleteTypeAlign.getQuantity()); 1661*189e52fcSRichard Smith DeleteArgs.add(RValue::get(Align), AlignValType); 1662*189e52fcSRichard Smith } 1663*189e52fcSRichard Smith 1664*189e52fcSRichard Smith assert(ParamTypeIt == DeleteFTy->param_type_end() && 1665*189e52fcSRichard Smith "unknown parameter to usual delete function"); 166659486a2dSAnders Carlsson 166759486a2dSAnders Carlsson // Emit the call to delete. 16688d0dc31dSRichard Smith EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs); 166959486a2dSAnders Carlsson } 167059486a2dSAnders Carlsson 16718ed55a54SJohn McCall namespace { 16728ed55a54SJohn McCall /// Calls the given 'operator delete' on a single object. 16737e70d680SDavid Blaikie struct CallObjectDelete final : EHScopeStack::Cleanup { 16748ed55a54SJohn McCall llvm::Value *Ptr; 16758ed55a54SJohn McCall const FunctionDecl *OperatorDelete; 16768ed55a54SJohn McCall QualType ElementType; 16778ed55a54SJohn McCall 16788ed55a54SJohn McCall CallObjectDelete(llvm::Value *Ptr, 16798ed55a54SJohn McCall const FunctionDecl *OperatorDelete, 16808ed55a54SJohn McCall QualType ElementType) 16818ed55a54SJohn McCall : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {} 16828ed55a54SJohn McCall 16834f12f10dSCraig Topper void Emit(CodeGenFunction &CGF, Flags flags) override { 16848ed55a54SJohn McCall CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType); 16858ed55a54SJohn McCall } 16868ed55a54SJohn McCall }; 1687ab9db510SAlexander Kornienko } 16888ed55a54SJohn McCall 16890c0b6d9aSDavid Majnemer void 16900c0b6d9aSDavid Majnemer CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete, 16910c0b6d9aSDavid Majnemer llvm::Value *CompletePtr, 16920c0b6d9aSDavid Majnemer QualType ElementType) { 16930c0b6d9aSDavid Majnemer EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr, 16940c0b6d9aSDavid Majnemer OperatorDelete, ElementType); 16950c0b6d9aSDavid Majnemer } 16960c0b6d9aSDavid Majnemer 16978ed55a54SJohn McCall /// Emit the code for deleting a single object. 16988ed55a54SJohn McCall static void EmitObjectDelete(CodeGenFunction &CGF, 16990868137aSDavid Majnemer const CXXDeleteExpr *DE, 17007f416cc4SJohn McCall Address Ptr, 17010868137aSDavid Majnemer QualType ElementType) { 17028ed55a54SJohn McCall // Find the destructor for the type, if applicable. If the 17038ed55a54SJohn McCall // destructor is virtual, we'll just emit the vcall and return. 17048a13c418SCraig Topper const CXXDestructorDecl *Dtor = nullptr; 17058ed55a54SJohn McCall if (const RecordType *RT = ElementType->getAs<RecordType>()) { 17068ed55a54SJohn McCall CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 1707b23533dbSEli Friedman if (RD->hasDefinition() && !RD->hasTrivialDestructor()) { 17088ed55a54SJohn McCall Dtor = RD->getDestructor(); 17098ed55a54SJohn McCall 17108ed55a54SJohn McCall if (Dtor->isVirtual()) { 17110868137aSDavid Majnemer CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType, 17120868137aSDavid Majnemer Dtor); 17138ed55a54SJohn McCall return; 17148ed55a54SJohn McCall } 17158ed55a54SJohn McCall } 17168ed55a54SJohn McCall } 17178ed55a54SJohn McCall 17188ed55a54SJohn McCall // Make sure that we call delete even if the dtor throws. 1719e4df6c8dSJohn McCall // This doesn't have to a conditional cleanup because we're going 1720e4df6c8dSJohn McCall // to pop it off in a second. 17210868137aSDavid Majnemer const FunctionDecl *OperatorDelete = DE->getOperatorDelete(); 17228ed55a54SJohn McCall CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, 17237f416cc4SJohn McCall Ptr.getPointer(), 17247f416cc4SJohn McCall OperatorDelete, ElementType); 17258ed55a54SJohn McCall 17268ed55a54SJohn McCall if (Dtor) 17278ed55a54SJohn McCall CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, 172861535005SDouglas Gregor /*ForVirtualBase=*/false, 172961535005SDouglas Gregor /*Delegating=*/false, 173061535005SDouglas Gregor Ptr); 1731460ce58fSJohn McCall else if (auto Lifetime = ElementType.getObjCLifetime()) { 1732460ce58fSJohn McCall switch (Lifetime) { 173331168b07SJohn McCall case Qualifiers::OCL_None: 173431168b07SJohn McCall case Qualifiers::OCL_ExplicitNone: 173531168b07SJohn McCall case Qualifiers::OCL_Autoreleasing: 173631168b07SJohn McCall break; 173731168b07SJohn McCall 17387f416cc4SJohn McCall case Qualifiers::OCL_Strong: 17397f416cc4SJohn McCall CGF.EmitARCDestroyStrong(Ptr, ARCPreciseLifetime); 174031168b07SJohn McCall break; 174131168b07SJohn McCall 174231168b07SJohn McCall case Qualifiers::OCL_Weak: 174331168b07SJohn McCall CGF.EmitARCDestroyWeak(Ptr); 174431168b07SJohn McCall break; 174531168b07SJohn McCall } 174631168b07SJohn McCall } 17478ed55a54SJohn McCall 17488ed55a54SJohn McCall CGF.PopCleanupBlock(); 17498ed55a54SJohn McCall } 17508ed55a54SJohn McCall 17518ed55a54SJohn McCall namespace { 17528ed55a54SJohn McCall /// Calls the given 'operator delete' on an array of objects. 17537e70d680SDavid Blaikie struct CallArrayDelete final : EHScopeStack::Cleanup { 17548ed55a54SJohn McCall llvm::Value *Ptr; 17558ed55a54SJohn McCall const FunctionDecl *OperatorDelete; 17568ed55a54SJohn McCall llvm::Value *NumElements; 17578ed55a54SJohn McCall QualType ElementType; 17588ed55a54SJohn McCall CharUnits CookieSize; 17598ed55a54SJohn McCall 17608ed55a54SJohn McCall CallArrayDelete(llvm::Value *Ptr, 17618ed55a54SJohn McCall const FunctionDecl *OperatorDelete, 17628ed55a54SJohn McCall llvm::Value *NumElements, 17638ed55a54SJohn McCall QualType ElementType, 17648ed55a54SJohn McCall CharUnits CookieSize) 17658ed55a54SJohn McCall : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements), 17668ed55a54SJohn McCall ElementType(ElementType), CookieSize(CookieSize) {} 17678ed55a54SJohn McCall 17684f12f10dSCraig Topper void Emit(CodeGenFunction &CGF, Flags flags) override { 1769*189e52fcSRichard Smith CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType, NumElements, 1770*189e52fcSRichard Smith CookieSize); 17718ed55a54SJohn McCall } 17728ed55a54SJohn McCall }; 1773ab9db510SAlexander Kornienko } 17748ed55a54SJohn McCall 17758ed55a54SJohn McCall /// Emit the code for deleting an array of objects. 17768ed55a54SJohn McCall static void EmitArrayDelete(CodeGenFunction &CGF, 1777284c48ffSJohn McCall const CXXDeleteExpr *E, 17787f416cc4SJohn McCall Address deletedPtr, 1779ca2c56f2SJohn McCall QualType elementType) { 17808a13c418SCraig Topper llvm::Value *numElements = nullptr; 17818a13c418SCraig Topper llvm::Value *allocatedPtr = nullptr; 1782ca2c56f2SJohn McCall CharUnits cookieSize; 1783ca2c56f2SJohn McCall CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType, 1784ca2c56f2SJohn McCall numElements, allocatedPtr, cookieSize); 17858ed55a54SJohn McCall 1786ca2c56f2SJohn McCall assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer"); 17878ed55a54SJohn McCall 17888ed55a54SJohn McCall // Make sure that we call delete even if one of the dtors throws. 1789ca2c56f2SJohn McCall const FunctionDecl *operatorDelete = E->getOperatorDelete(); 17908ed55a54SJohn McCall CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup, 1791ca2c56f2SJohn McCall allocatedPtr, operatorDelete, 1792ca2c56f2SJohn McCall numElements, elementType, 1793ca2c56f2SJohn McCall cookieSize); 17948ed55a54SJohn McCall 1795ca2c56f2SJohn McCall // Destroy the elements. 1796ca2c56f2SJohn McCall if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) { 1797ca2c56f2SJohn McCall assert(numElements && "no element count for a type with a destructor!"); 179831168b07SJohn McCall 17997f416cc4SJohn McCall CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType); 18007f416cc4SJohn McCall CharUnits elementAlign = 18017f416cc4SJohn McCall deletedPtr.getAlignment().alignmentOfArrayElement(elementSize); 18027f416cc4SJohn McCall 18037f416cc4SJohn McCall llvm::Value *arrayBegin = deletedPtr.getPointer(); 1804ca2c56f2SJohn McCall llvm::Value *arrayEnd = 18057f416cc4SJohn McCall CGF.Builder.CreateInBoundsGEP(arrayBegin, numElements, "delete.end"); 180697eab0a2SJohn McCall 180797eab0a2SJohn McCall // Note that it is legal to allocate a zero-length array, and we 180897eab0a2SJohn McCall // can never fold the check away because the length should always 180997eab0a2SJohn McCall // come from a cookie. 18107f416cc4SJohn McCall CGF.emitArrayDestroy(arrayBegin, arrayEnd, elementType, elementAlign, 1811ca2c56f2SJohn McCall CGF.getDestroyer(dtorKind), 181297eab0a2SJohn McCall /*checkZeroLength*/ true, 1813ca2c56f2SJohn McCall CGF.needsEHCleanup(dtorKind)); 18148ed55a54SJohn McCall } 18158ed55a54SJohn McCall 1816ca2c56f2SJohn McCall // Pop the cleanup block. 18178ed55a54SJohn McCall CGF.PopCleanupBlock(); 18188ed55a54SJohn McCall } 18198ed55a54SJohn McCall 182059486a2dSAnders Carlsson void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) { 182159486a2dSAnders Carlsson const Expr *Arg = E->getArgument(); 18227f416cc4SJohn McCall Address Ptr = EmitPointerWithAlignment(Arg); 182359486a2dSAnders Carlsson 182459486a2dSAnders Carlsson // Null check the pointer. 182559486a2dSAnders Carlsson llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull"); 182659486a2dSAnders Carlsson llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end"); 182759486a2dSAnders Carlsson 18287f416cc4SJohn McCall llvm::Value *IsNull = Builder.CreateIsNull(Ptr.getPointer(), "isnull"); 182959486a2dSAnders Carlsson 183059486a2dSAnders Carlsson Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull); 183159486a2dSAnders Carlsson EmitBlock(DeleteNotNull); 183259486a2dSAnders Carlsson 18338ed55a54SJohn McCall // We might be deleting a pointer to array. If so, GEP down to the 18348ed55a54SJohn McCall // first non-array element. 18358ed55a54SJohn McCall // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*) 18368ed55a54SJohn McCall QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType(); 18378ed55a54SJohn McCall if (DeleteTy->isConstantArrayType()) { 18388ed55a54SJohn McCall llvm::Value *Zero = Builder.getInt32(0); 18390e62c1ccSChris Lattner SmallVector<llvm::Value*,8> GEP; 184059486a2dSAnders Carlsson 18418ed55a54SJohn McCall GEP.push_back(Zero); // point at the outermost array 18428ed55a54SJohn McCall 18438ed55a54SJohn McCall // For each layer of array type we're pointing at: 18448ed55a54SJohn McCall while (const ConstantArrayType *Arr 18458ed55a54SJohn McCall = getContext().getAsConstantArrayType(DeleteTy)) { 18468ed55a54SJohn McCall // 1. Unpeel the array type. 18478ed55a54SJohn McCall DeleteTy = Arr->getElementType(); 18488ed55a54SJohn McCall 18498ed55a54SJohn McCall // 2. GEP to the first element of the array. 18508ed55a54SJohn McCall GEP.push_back(Zero); 18518ed55a54SJohn McCall } 18528ed55a54SJohn McCall 18537f416cc4SJohn McCall Ptr = Address(Builder.CreateInBoundsGEP(Ptr.getPointer(), GEP, "del.first"), 18547f416cc4SJohn McCall Ptr.getAlignment()); 18558ed55a54SJohn McCall } 18568ed55a54SJohn McCall 18577f416cc4SJohn McCall assert(ConvertTypeForMem(DeleteTy) == Ptr.getElementType()); 18588ed55a54SJohn McCall 18597270ef57SReid Kleckner if (E->isArrayForm()) { 18607270ef57SReid Kleckner EmitArrayDelete(*this, E, Ptr, DeleteTy); 18617270ef57SReid Kleckner } else { 18627270ef57SReid Kleckner EmitObjectDelete(*this, E, Ptr, DeleteTy); 18637270ef57SReid Kleckner } 186459486a2dSAnders Carlsson 186559486a2dSAnders Carlsson EmitBlock(DeleteEnd); 186659486a2dSAnders Carlsson } 186759486a2dSAnders Carlsson 18681c3d95ebSDavid Majnemer static bool isGLValueFromPointerDeref(const Expr *E) { 18691c3d95ebSDavid Majnemer E = E->IgnoreParens(); 18701c3d95ebSDavid Majnemer 18711c3d95ebSDavid Majnemer if (const auto *CE = dyn_cast<CastExpr>(E)) { 18721c3d95ebSDavid Majnemer if (!CE->getSubExpr()->isGLValue()) 18731c3d95ebSDavid Majnemer return false; 18741c3d95ebSDavid Majnemer return isGLValueFromPointerDeref(CE->getSubExpr()); 18751c3d95ebSDavid Majnemer } 18761c3d95ebSDavid Majnemer 18771c3d95ebSDavid Majnemer if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 18781c3d95ebSDavid Majnemer return isGLValueFromPointerDeref(OVE->getSourceExpr()); 18791c3d95ebSDavid Majnemer 18801c3d95ebSDavid Majnemer if (const auto *BO = dyn_cast<BinaryOperator>(E)) 18811c3d95ebSDavid Majnemer if (BO->getOpcode() == BO_Comma) 18821c3d95ebSDavid Majnemer return isGLValueFromPointerDeref(BO->getRHS()); 18831c3d95ebSDavid Majnemer 18841c3d95ebSDavid Majnemer if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E)) 18851c3d95ebSDavid Majnemer return isGLValueFromPointerDeref(ACO->getTrueExpr()) || 18861c3d95ebSDavid Majnemer isGLValueFromPointerDeref(ACO->getFalseExpr()); 18871c3d95ebSDavid Majnemer 18881c3d95ebSDavid Majnemer // C++11 [expr.sub]p1: 18891c3d95ebSDavid Majnemer // The expression E1[E2] is identical (by definition) to *((E1)+(E2)) 18901c3d95ebSDavid Majnemer if (isa<ArraySubscriptExpr>(E)) 18911c3d95ebSDavid Majnemer return true; 18921c3d95ebSDavid Majnemer 18931c3d95ebSDavid Majnemer if (const auto *UO = dyn_cast<UnaryOperator>(E)) 18941c3d95ebSDavid Majnemer if (UO->getOpcode() == UO_Deref) 18951c3d95ebSDavid Majnemer return true; 18961c3d95ebSDavid Majnemer 18971c3d95ebSDavid Majnemer return false; 18981c3d95ebSDavid Majnemer } 18991c3d95ebSDavid Majnemer 1900747e301eSWarren Hunt static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E, 19012192fe50SChris Lattner llvm::Type *StdTypeInfoPtrTy) { 1902940f02d2SAnders Carlsson // Get the vtable pointer. 19037f416cc4SJohn McCall Address ThisPtr = CGF.EmitLValue(E).getAddress(); 1904940f02d2SAnders Carlsson 1905940f02d2SAnders Carlsson // C++ [expr.typeid]p2: 1906940f02d2SAnders Carlsson // If the glvalue expression is obtained by applying the unary * operator to 1907940f02d2SAnders Carlsson // a pointer and the pointer is a null pointer value, the typeid expression 1908940f02d2SAnders Carlsson // throws the std::bad_typeid exception. 19091c3d95ebSDavid Majnemer // 19101c3d95ebSDavid Majnemer // However, this paragraph's intent is not clear. We choose a very generous 19111c3d95ebSDavid Majnemer // interpretation which implores us to consider comma operators, conditional 19121c3d95ebSDavid Majnemer // operators, parentheses and other such constructs. 19131162d25cSDavid Majnemer QualType SrcRecordTy = E->getType(); 19141c3d95ebSDavid Majnemer if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked( 19151c3d95ebSDavid Majnemer isGLValueFromPointerDeref(E), SrcRecordTy)) { 1916940f02d2SAnders Carlsson llvm::BasicBlock *BadTypeidBlock = 1917940f02d2SAnders Carlsson CGF.createBasicBlock("typeid.bad_typeid"); 19181162d25cSDavid Majnemer llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end"); 1919940f02d2SAnders Carlsson 19207f416cc4SJohn McCall llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr.getPointer()); 1921940f02d2SAnders Carlsson CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock); 1922940f02d2SAnders Carlsson 1923940f02d2SAnders Carlsson CGF.EmitBlock(BadTypeidBlock); 19241162d25cSDavid Majnemer CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF); 1925940f02d2SAnders Carlsson CGF.EmitBlock(EndBlock); 1926940f02d2SAnders Carlsson } 1927940f02d2SAnders Carlsson 19281162d25cSDavid Majnemer return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr, 19291162d25cSDavid Majnemer StdTypeInfoPtrTy); 1930940f02d2SAnders Carlsson } 1931940f02d2SAnders Carlsson 193259486a2dSAnders Carlsson llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) { 19332192fe50SChris Lattner llvm::Type *StdTypeInfoPtrTy = 1934940f02d2SAnders Carlsson ConvertType(E->getType())->getPointerTo(); 1935fd7dfeb7SAnders Carlsson 19363f4336cbSAnders Carlsson if (E->isTypeOperand()) { 19373f4336cbSAnders Carlsson llvm::Constant *TypeInfo = 1938143c55eaSDavid Majnemer CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext())); 1939940f02d2SAnders Carlsson return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy); 19403f4336cbSAnders Carlsson } 1941fd7dfeb7SAnders Carlsson 1942940f02d2SAnders Carlsson // C++ [expr.typeid]p2: 1943940f02d2SAnders Carlsson // When typeid is applied to a glvalue expression whose type is a 1944940f02d2SAnders Carlsson // polymorphic class type, the result refers to a std::type_info object 1945940f02d2SAnders Carlsson // representing the type of the most derived object (that is, the dynamic 1946940f02d2SAnders Carlsson // type) to which the glvalue refers. 1947ef8bf436SRichard Smith if (E->isPotentiallyEvaluated()) 1948940f02d2SAnders Carlsson return EmitTypeidFromVTable(*this, E->getExprOperand(), 1949940f02d2SAnders Carlsson StdTypeInfoPtrTy); 1950940f02d2SAnders Carlsson 1951940f02d2SAnders Carlsson QualType OperandTy = E->getExprOperand()->getType(); 1952940f02d2SAnders Carlsson return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy), 1953940f02d2SAnders Carlsson StdTypeInfoPtrTy); 195459486a2dSAnders Carlsson } 195559486a2dSAnders Carlsson 1956c1c9971cSAnders Carlsson static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF, 1957c1c9971cSAnders Carlsson QualType DestTy) { 19582192fe50SChris Lattner llvm::Type *DestLTy = CGF.ConvertType(DestTy); 1959c1c9971cSAnders Carlsson if (DestTy->isPointerType()) 1960c1c9971cSAnders Carlsson return llvm::Constant::getNullValue(DestLTy); 1961c1c9971cSAnders Carlsson 1962c1c9971cSAnders Carlsson /// C++ [expr.dynamic.cast]p9: 1963c1c9971cSAnders Carlsson /// A failed cast to reference type throws std::bad_cast 19641162d25cSDavid Majnemer if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF)) 19651162d25cSDavid Majnemer return nullptr; 1966c1c9971cSAnders Carlsson 1967c1c9971cSAnders Carlsson CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end")); 1968c1c9971cSAnders Carlsson return llvm::UndefValue::get(DestLTy); 1969c1c9971cSAnders Carlsson } 1970c1c9971cSAnders Carlsson 19717f416cc4SJohn McCall llvm::Value *CodeGenFunction::EmitDynamicCast(Address ThisAddr, 197259486a2dSAnders Carlsson const CXXDynamicCastExpr *DCE) { 19732bf9b4c0SAlexey Bataev CGM.EmitExplicitCastExprType(DCE, this); 19743f4336cbSAnders Carlsson QualType DestTy = DCE->getTypeAsWritten(); 19753f4336cbSAnders Carlsson 1976c1c9971cSAnders Carlsson if (DCE->isAlwaysNull()) 19771162d25cSDavid Majnemer if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy)) 19781162d25cSDavid Majnemer return T; 1979c1c9971cSAnders Carlsson 1980c1c9971cSAnders Carlsson QualType SrcTy = DCE->getSubExpr()->getType(); 1981c1c9971cSAnders Carlsson 19821162d25cSDavid Majnemer // C++ [expr.dynamic.cast]p7: 19831162d25cSDavid Majnemer // If T is "pointer to cv void," then the result is a pointer to the most 19841162d25cSDavid Majnemer // derived object pointed to by v. 19851162d25cSDavid Majnemer const PointerType *DestPTy = DestTy->getAs<PointerType>(); 19861162d25cSDavid Majnemer 19871162d25cSDavid Majnemer bool isDynamicCastToVoid; 19881162d25cSDavid Majnemer QualType SrcRecordTy; 19891162d25cSDavid Majnemer QualType DestRecordTy; 19901162d25cSDavid Majnemer if (DestPTy) { 19911162d25cSDavid Majnemer isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType(); 19921162d25cSDavid Majnemer SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType(); 19931162d25cSDavid Majnemer DestRecordTy = DestPTy->getPointeeType(); 19941162d25cSDavid Majnemer } else { 19951162d25cSDavid Majnemer isDynamicCastToVoid = false; 19961162d25cSDavid Majnemer SrcRecordTy = SrcTy; 19971162d25cSDavid Majnemer DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType(); 19981162d25cSDavid Majnemer } 19991162d25cSDavid Majnemer 20001162d25cSDavid Majnemer assert(SrcRecordTy->isRecordType() && "source type must be a record type!"); 20011162d25cSDavid Majnemer 2002882d790fSAnders Carlsson // C++ [expr.dynamic.cast]p4: 2003882d790fSAnders Carlsson // If the value of v is a null pointer value in the pointer case, the result 2004882d790fSAnders Carlsson // is the null pointer value of type T. 20051162d25cSDavid Majnemer bool ShouldNullCheckSrcValue = 20061162d25cSDavid Majnemer CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(), 20071162d25cSDavid Majnemer SrcRecordTy); 200859486a2dSAnders Carlsson 20098a13c418SCraig Topper llvm::BasicBlock *CastNull = nullptr; 20108a13c418SCraig Topper llvm::BasicBlock *CastNotNull = nullptr; 2011882d790fSAnders Carlsson llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end"); 2012fa8b4955SDouglas Gregor 2013882d790fSAnders Carlsson if (ShouldNullCheckSrcValue) { 2014882d790fSAnders Carlsson CastNull = createBasicBlock("dynamic_cast.null"); 2015882d790fSAnders Carlsson CastNotNull = createBasicBlock("dynamic_cast.notnull"); 2016882d790fSAnders Carlsson 20177f416cc4SJohn McCall llvm::Value *IsNull = Builder.CreateIsNull(ThisAddr.getPointer()); 2018882d790fSAnders Carlsson Builder.CreateCondBr(IsNull, CastNull, CastNotNull); 2019882d790fSAnders Carlsson EmitBlock(CastNotNull); 202059486a2dSAnders Carlsson } 202159486a2dSAnders Carlsson 20227f416cc4SJohn McCall llvm::Value *Value; 20231162d25cSDavid Majnemer if (isDynamicCastToVoid) { 20247f416cc4SJohn McCall Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, ThisAddr, SrcRecordTy, 20251162d25cSDavid Majnemer DestTy); 20261162d25cSDavid Majnemer } else { 20271162d25cSDavid Majnemer assert(DestRecordTy->isRecordType() && 20281162d25cSDavid Majnemer "destination type must be a record type!"); 20297f416cc4SJohn McCall Value = CGM.getCXXABI().EmitDynamicCastCall(*this, ThisAddr, SrcRecordTy, 20301162d25cSDavid Majnemer DestTy, DestRecordTy, CastEnd); 203167528eaaSDavid Majnemer CastNotNull = Builder.GetInsertBlock(); 20321162d25cSDavid Majnemer } 20333f4336cbSAnders Carlsson 2034882d790fSAnders Carlsson if (ShouldNullCheckSrcValue) { 2035882d790fSAnders Carlsson EmitBranch(CastEnd); 203659486a2dSAnders Carlsson 2037882d790fSAnders Carlsson EmitBlock(CastNull); 2038882d790fSAnders Carlsson EmitBranch(CastEnd); 203959486a2dSAnders Carlsson } 204059486a2dSAnders Carlsson 2041882d790fSAnders Carlsson EmitBlock(CastEnd); 204259486a2dSAnders Carlsson 2043882d790fSAnders Carlsson if (ShouldNullCheckSrcValue) { 2044882d790fSAnders Carlsson llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2); 2045882d790fSAnders Carlsson PHI->addIncoming(Value, CastNotNull); 2046882d790fSAnders Carlsson PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull); 204759486a2dSAnders Carlsson 2048882d790fSAnders Carlsson Value = PHI; 204959486a2dSAnders Carlsson } 205059486a2dSAnders Carlsson 2051882d790fSAnders Carlsson return Value; 205259486a2dSAnders Carlsson } 2053c370a7eeSEli Friedman 2054c370a7eeSEli Friedman void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) { 20558631f3e8SEli Friedman RunCleanupsScope Scope(*this); 20567f416cc4SJohn McCall LValue SlotLV = MakeAddrLValue(Slot.getAddress(), E->getType()); 20578631f3e8SEli Friedman 2058c370a7eeSEli Friedman CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin(); 205953c7616eSJames Y Knight for (LambdaExpr::const_capture_init_iterator i = E->capture_init_begin(), 2060c370a7eeSEli Friedman e = E->capture_init_end(); 2061c370a7eeSEli Friedman i != e; ++i, ++CurField) { 2062c370a7eeSEli Friedman // Emit initialization 206340ed2973SDavid Blaikie LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField); 206439c81e28SAlexey Bataev if (CurField->hasCapturedVLAType()) { 206539c81e28SAlexey Bataev auto VAT = CurField->getCapturedVLAType(); 206639c81e28SAlexey Bataev EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV); 206739c81e28SAlexey Bataev } else { 20685f1a04ffSEli Friedman ArrayRef<VarDecl *> ArrayIndexes; 20695f1a04ffSEli Friedman if (CurField->getType()->isArrayType()) 20705f1a04ffSEli Friedman ArrayIndexes = E->getCaptureInitIndexVars(i); 207140ed2973SDavid Blaikie EmitInitializerForField(*CurField, LV, *i, ArrayIndexes); 2072c370a7eeSEli Friedman } 2073c370a7eeSEli Friedman } 207439c81e28SAlexey Bataev } 2075