Path: blob/main/contrib/llvm-project/clang/lib/CodeGen/CGExprCXX.cpp
35233 views
//===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This contains code dealing with code generation of C++ expressions9//10//===----------------------------------------------------------------------===//1112#include "CGCUDARuntime.h"13#include "CGCXXABI.h"14#include "CGDebugInfo.h"15#include "CGObjCRuntime.h"16#include "CodeGenFunction.h"17#include "ConstantEmitter.h"18#include "TargetInfo.h"19#include "clang/Basic/CodeGenOptions.h"20#include "clang/CodeGen/CGFunctionInfo.h"21#include "llvm/IR/Intrinsics.h"2223using namespace clang;24using namespace CodeGen;2526namespace {27struct MemberCallInfo {28RequiredArgs ReqArgs;29// Number of prefix arguments for the call. Ignores the `this` pointer.30unsigned PrefixSize;31};32}3334static MemberCallInfo35commonEmitCXXMemberOrOperatorCall(CodeGenFunction &CGF, GlobalDecl GD,36llvm::Value *This, llvm::Value *ImplicitParam,37QualType ImplicitParamTy, const CallExpr *CE,38CallArgList &Args, CallArgList *RtlArgs) {39auto *MD = cast<CXXMethodDecl>(GD.getDecl());4041assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) ||42isa<CXXOperatorCallExpr>(CE));43assert(MD->isImplicitObjectMemberFunction() &&44"Trying to emit a member or operator call expr on a static method!");4546// Push the this ptr.47const CXXRecordDecl *RD =48CGF.CGM.getCXXABI().getThisArgumentTypeForMethod(GD);49Args.add(RValue::get(This), CGF.getTypes().DeriveThisType(RD, MD));5051// If there is an implicit parameter (e.g. VTT), emit it.52if (ImplicitParam) {53Args.add(RValue::get(ImplicitParam), ImplicitParamTy);54}5556const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();57RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size());58unsigned PrefixSize = Args.size() - 1;5960// And the rest of the call args.61if (RtlArgs) {62// Special case: if the caller emitted the arguments right-to-left already63// (prior to emitting the *this argument), we're done. This happens for64// assignment operators.65Args.addFrom(*RtlArgs);66} else if (CE) {67// Special case: skip first argument of CXXOperatorCall (it is "this").68unsigned ArgsToSkip = 0;69if (const auto *Op = dyn_cast<CXXOperatorCallExpr>(CE)) {70if (const auto *M = dyn_cast<CXXMethodDecl>(Op->getCalleeDecl()))71ArgsToSkip =72static_cast<unsigned>(!M->isExplicitObjectMemberFunction());73}74CGF.EmitCallArgs(Args, FPT, drop_begin(CE->arguments(), ArgsToSkip),75CE->getDirectCallee());76} else {77assert(78FPT->getNumParams() == 0 &&79"No CallExpr specified for function with non-zero number of arguments");80}81return {required, PrefixSize};82}8384RValue CodeGenFunction::EmitCXXMemberOrOperatorCall(85const CXXMethodDecl *MD, const CGCallee &Callee,86ReturnValueSlot ReturnValue,87llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,88const CallExpr *CE, CallArgList *RtlArgs) {89const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();90CallArgList Args;91MemberCallInfo CallInfo = commonEmitCXXMemberOrOperatorCall(92*this, MD, This, ImplicitParam, ImplicitParamTy, CE, Args, RtlArgs);93auto &FnInfo = CGM.getTypes().arrangeCXXMethodCall(94Args, FPT, CallInfo.ReqArgs, CallInfo.PrefixSize);95return EmitCall(FnInfo, Callee, ReturnValue, Args, nullptr,96CE && CE == MustTailCall,97CE ? CE->getExprLoc() : SourceLocation());98}99100RValue CodeGenFunction::EmitCXXDestructorCall(101GlobalDecl Dtor, const CGCallee &Callee, llvm::Value *This, QualType ThisTy,102llvm::Value *ImplicitParam, QualType ImplicitParamTy, const CallExpr *CE) {103const CXXMethodDecl *DtorDecl = cast<CXXMethodDecl>(Dtor.getDecl());104105assert(!ThisTy.isNull());106assert(ThisTy->getAsCXXRecordDecl() == DtorDecl->getParent() &&107"Pointer/Object mixup");108109LangAS SrcAS = ThisTy.getAddressSpace();110LangAS DstAS = DtorDecl->getMethodQualifiers().getAddressSpace();111if (SrcAS != DstAS) {112QualType DstTy = DtorDecl->getThisType();113llvm::Type *NewType = CGM.getTypes().ConvertType(DstTy);114This = getTargetHooks().performAddrSpaceCast(*this, This, SrcAS, DstAS,115NewType);116}117118CallArgList Args;119commonEmitCXXMemberOrOperatorCall(*this, Dtor, This, ImplicitParam,120ImplicitParamTy, CE, Args, nullptr);121return EmitCall(CGM.getTypes().arrangeCXXStructorDeclaration(Dtor), Callee,122ReturnValueSlot(), Args, nullptr, CE && CE == MustTailCall,123CE ? CE->getExprLoc() : SourceLocation{});124}125126RValue CodeGenFunction::EmitCXXPseudoDestructorExpr(127const CXXPseudoDestructorExpr *E) {128QualType DestroyedType = E->getDestroyedType();129if (DestroyedType.hasStrongOrWeakObjCLifetime()) {130// Automatic Reference Counting:131// If the pseudo-expression names a retainable object with weak or132// strong lifetime, the object shall be released.133Expr *BaseExpr = E->getBase();134Address BaseValue = Address::invalid();135Qualifiers BaseQuals;136137// If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.138if (E->isArrow()) {139BaseValue = EmitPointerWithAlignment(BaseExpr);140const auto *PTy = BaseExpr->getType()->castAs<PointerType>();141BaseQuals = PTy->getPointeeType().getQualifiers();142} else {143LValue BaseLV = EmitLValue(BaseExpr);144BaseValue = BaseLV.getAddress();145QualType BaseTy = BaseExpr->getType();146BaseQuals = BaseTy.getQualifiers();147}148149switch (DestroyedType.getObjCLifetime()) {150case Qualifiers::OCL_None:151case Qualifiers::OCL_ExplicitNone:152case Qualifiers::OCL_Autoreleasing:153break;154155case Qualifiers::OCL_Strong:156EmitARCRelease(Builder.CreateLoad(BaseValue,157DestroyedType.isVolatileQualified()),158ARCPreciseLifetime);159break;160161case Qualifiers::OCL_Weak:162EmitARCDestroyWeak(BaseValue);163break;164}165} else {166// C++ [expr.pseudo]p1:167// The result shall only be used as the operand for the function call168// operator (), and the result of such a call has type void. The only169// effect is the evaluation of the postfix-expression before the dot or170// arrow.171EmitIgnoredExpr(E->getBase());172}173174return RValue::get(nullptr);175}176177static CXXRecordDecl *getCXXRecord(const Expr *E) {178QualType T = E->getType();179if (const PointerType *PTy = T->getAs<PointerType>())180T = PTy->getPointeeType();181const RecordType *Ty = T->castAs<RecordType>();182return cast<CXXRecordDecl>(Ty->getDecl());183}184185// Note: This function also emit constructor calls to support a MSVC186// extensions allowing explicit constructor function call.187RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,188ReturnValueSlot ReturnValue) {189const Expr *callee = CE->getCallee()->IgnoreParens();190191if (isa<BinaryOperator>(callee))192return EmitCXXMemberPointerCallExpr(CE, ReturnValue);193194const MemberExpr *ME = cast<MemberExpr>(callee);195const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());196197if (MD->isStatic()) {198// The method is static, emit it as we would a regular call.199CGCallee callee =200CGCallee::forDirect(CGM.GetAddrOfFunction(MD), GlobalDecl(MD));201return EmitCall(getContext().getPointerType(MD->getType()), callee, CE,202ReturnValue);203}204205bool HasQualifier = ME->hasQualifier();206NestedNameSpecifier *Qualifier = HasQualifier ? ME->getQualifier() : nullptr;207bool IsArrow = ME->isArrow();208const Expr *Base = ME->getBase();209210return EmitCXXMemberOrOperatorMemberCallExpr(211CE, MD, ReturnValue, HasQualifier, Qualifier, IsArrow, Base);212}213214RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr(215const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue,216bool HasQualifier, NestedNameSpecifier *Qualifier, bool IsArrow,217const Expr *Base) {218assert(isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE));219220// Compute the object pointer.221bool CanUseVirtualCall = MD->isVirtual() && !HasQualifier;222223const CXXMethodDecl *DevirtualizedMethod = nullptr;224if (CanUseVirtualCall &&225MD->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) {226const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();227DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);228assert(DevirtualizedMethod);229const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();230const Expr *Inner = Base->IgnoreParenBaseCasts();231if (DevirtualizedMethod->getReturnType().getCanonicalType() !=232MD->getReturnType().getCanonicalType())233// If the return types are not the same, this might be a case where more234// code needs to run to compensate for it. For example, the derived235// method might return a type that inherits form from the return236// type of MD and has a prefix.237// For now we just avoid devirtualizing these covariant cases.238DevirtualizedMethod = nullptr;239else if (getCXXRecord(Inner) == DevirtualizedClass)240// If the class of the Inner expression is where the dynamic method241// is defined, build the this pointer from it.242Base = Inner;243else if (getCXXRecord(Base) != DevirtualizedClass) {244// If the method is defined in a class that is not the best dynamic245// one or the one of the full expression, we would have to build246// a derived-to-base cast to compute the correct this pointer, but247// we don't have support for that yet, so do a virtual call.248DevirtualizedMethod = nullptr;249}250}251252bool TrivialForCodegen =253MD->isTrivial() || (MD->isDefaulted() && MD->getParent()->isUnion());254bool TrivialAssignment =255TrivialForCodegen &&256(MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&257!MD->getParent()->mayInsertExtraPadding();258259// C++17 demands that we evaluate the RHS of a (possibly-compound) assignment260// operator before the LHS.261CallArgList RtlArgStorage;262CallArgList *RtlArgs = nullptr;263LValue TrivialAssignmentRHS;264if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(CE)) {265if (OCE->isAssignmentOp()) {266if (TrivialAssignment) {267TrivialAssignmentRHS = EmitLValue(CE->getArg(1));268} else {269RtlArgs = &RtlArgStorage;270EmitCallArgs(*RtlArgs, MD->getType()->castAs<FunctionProtoType>(),271drop_begin(CE->arguments(), 1), CE->getDirectCallee(),272/*ParamsToSkip*/0, EvaluationOrder::ForceRightToLeft);273}274}275}276277LValue This;278if (IsArrow) {279LValueBaseInfo BaseInfo;280TBAAAccessInfo TBAAInfo;281Address ThisValue = EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo);282This = MakeAddrLValue(ThisValue, Base->getType()->getPointeeType(),283BaseInfo, TBAAInfo);284} else {285This = EmitLValue(Base);286}287288if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {289// This is the MSVC p->Ctor::Ctor(...) extension. We assume that's290// constructing a new complete object of type Ctor.291assert(!RtlArgs);292assert(ReturnValue.isNull() && "Constructor shouldn't have return value");293CallArgList Args;294commonEmitCXXMemberOrOperatorCall(295*this, {Ctor, Ctor_Complete}, This.getPointer(*this),296/*ImplicitParam=*/nullptr,297/*ImplicitParamTy=*/QualType(), CE, Args, nullptr);298299EmitCXXConstructorCall(Ctor, Ctor_Complete, /*ForVirtualBase=*/false,300/*Delegating=*/false, This.getAddress(), Args,301AggValueSlot::DoesNotOverlap, CE->getExprLoc(),302/*NewPointerIsChecked=*/false);303return RValue::get(nullptr);304}305306if (TrivialForCodegen) {307if (isa<CXXDestructorDecl>(MD))308return RValue::get(nullptr);309310if (TrivialAssignment) {311// We don't like to generate the trivial copy/move assignment operator312// when it isn't necessary; just produce the proper effect here.313// It's important that we use the result of EmitLValue here rather than314// emitting call arguments, in order to preserve TBAA information from315// the RHS.316LValue RHS = isa<CXXOperatorCallExpr>(CE)317? TrivialAssignmentRHS318: EmitLValue(*CE->arg_begin());319EmitAggregateAssign(This, RHS, CE->getType());320return RValue::get(This.getPointer(*this));321}322323assert(MD->getParent()->mayInsertExtraPadding() &&324"unknown trivial member function");325}326327// Compute the function type we're calling.328const CXXMethodDecl *CalleeDecl =329DevirtualizedMethod ? DevirtualizedMethod : MD;330const CGFunctionInfo *FInfo = nullptr;331if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))332FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(333GlobalDecl(Dtor, Dtor_Complete));334else335FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);336337llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);338339// C++11 [class.mfct.non-static]p2:340// If a non-static member function of a class X is called for an object that341// is not of type X, or of a type derived from X, the behavior is undefined.342SourceLocation CallLoc;343ASTContext &C = getContext();344if (CE)345CallLoc = CE->getExprLoc();346347SanitizerSet SkippedChecks;348if (const auto *CMCE = dyn_cast<CXXMemberCallExpr>(CE)) {349auto *IOA = CMCE->getImplicitObjectArgument();350bool IsImplicitObjectCXXThis = IsWrappedCXXThis(IOA);351if (IsImplicitObjectCXXThis)352SkippedChecks.set(SanitizerKind::Alignment, true);353if (IsImplicitObjectCXXThis || isa<DeclRefExpr>(IOA))354SkippedChecks.set(SanitizerKind::Null, true);355}356357if (sanitizePerformTypeCheck())358EmitTypeCheck(CodeGenFunction::TCK_MemberCall, CallLoc,359This.emitRawPointer(*this),360C.getRecordType(CalleeDecl->getParent()),361/*Alignment=*/CharUnits::Zero(), SkippedChecks);362363// C++ [class.virtual]p12:364// Explicit qualification with the scope operator (5.1) suppresses the365// virtual call mechanism.366//367// We also don't emit a virtual call if the base expression has a record type368// because then we know what the type is.369bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;370371if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl)) {372assert(CE->arg_begin() == CE->arg_end() &&373"Destructor shouldn't have explicit parameters");374assert(ReturnValue.isNull() && "Destructor shouldn't have return value");375if (UseVirtualCall) {376CGM.getCXXABI().EmitVirtualDestructorCall(*this, Dtor, Dtor_Complete,377This.getAddress(),378cast<CXXMemberCallExpr>(CE));379} else {380GlobalDecl GD(Dtor, Dtor_Complete);381CGCallee Callee;382if (getLangOpts().AppleKext && Dtor->isVirtual() && HasQualifier)383Callee = BuildAppleKextVirtualCall(Dtor, Qualifier, Ty);384else if (!DevirtualizedMethod)385Callee =386CGCallee::forDirect(CGM.getAddrOfCXXStructor(GD, FInfo, Ty), GD);387else {388Callee = CGCallee::forDirect(CGM.GetAddrOfFunction(GD, Ty), GD);389}390391QualType ThisTy =392IsArrow ? Base->getType()->getPointeeType() : Base->getType();393EmitCXXDestructorCall(GD, Callee, This.getPointer(*this), ThisTy,394/*ImplicitParam=*/nullptr,395/*ImplicitParamTy=*/QualType(), CE);396}397return RValue::get(nullptr);398}399400// FIXME: Uses of 'MD' past this point need to be audited. We may need to use401// 'CalleeDecl' instead.402403CGCallee Callee;404if (UseVirtualCall) {405Callee = CGCallee::forVirtual(CE, MD, This.getAddress(), Ty);406} else {407if (SanOpts.has(SanitizerKind::CFINVCall) &&408MD->getParent()->isDynamicClass()) {409llvm::Value *VTable;410const CXXRecordDecl *RD;411std::tie(VTable, RD) = CGM.getCXXABI().LoadVTablePtr(412*this, This.getAddress(), CalleeDecl->getParent());413EmitVTablePtrCheckForCall(RD, VTable, CFITCK_NVCall, CE->getBeginLoc());414}415416if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)417Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);418else if (!DevirtualizedMethod)419Callee =420CGCallee::forDirect(CGM.GetAddrOfFunction(MD, Ty), GlobalDecl(MD));421else {422Callee =423CGCallee::forDirect(CGM.GetAddrOfFunction(DevirtualizedMethod, Ty),424GlobalDecl(DevirtualizedMethod));425}426}427428if (MD->isVirtual()) {429Address NewThisAddr =430CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(431*this, CalleeDecl, This.getAddress(), UseVirtualCall);432This.setAddress(NewThisAddr);433}434435return EmitCXXMemberOrOperatorCall(436CalleeDecl, Callee, ReturnValue, This.getPointer(*this),437/*ImplicitParam=*/nullptr, QualType(), CE, RtlArgs);438}439440RValue441CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,442ReturnValueSlot ReturnValue) {443const BinaryOperator *BO =444cast<BinaryOperator>(E->getCallee()->IgnoreParens());445const Expr *BaseExpr = BO->getLHS();446const Expr *MemFnExpr = BO->getRHS();447448const auto *MPT = MemFnExpr->getType()->castAs<MemberPointerType>();449const auto *FPT = MPT->getPointeeType()->castAs<FunctionProtoType>();450const auto *RD =451cast<CXXRecordDecl>(MPT->getClass()->castAs<RecordType>()->getDecl());452453// Emit the 'this' pointer.454Address This = Address::invalid();455if (BO->getOpcode() == BO_PtrMemI)456This = EmitPointerWithAlignment(BaseExpr, nullptr, nullptr, KnownNonNull);457else458This = EmitLValue(BaseExpr, KnownNonNull).getAddress();459460EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This.emitRawPointer(*this),461QualType(MPT->getClass(), 0));462463// Get the member function pointer.464llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);465466// Ask the ABI to load the callee. Note that This is modified.467llvm::Value *ThisPtrForCall = nullptr;468CGCallee Callee =469CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This,470ThisPtrForCall, MemFnPtr, MPT);471472CallArgList Args;473474QualType ThisType =475getContext().getPointerType(getContext().getTagDeclType(RD));476477// Push the this ptr.478Args.add(RValue::get(ThisPtrForCall), ThisType);479480RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1);481482// And the rest of the call args483EmitCallArgs(Args, FPT, E->arguments());484return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required,485/*PrefixSize=*/0),486Callee, ReturnValue, Args, nullptr, E == MustTailCall,487E->getExprLoc());488}489490RValue491CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,492const CXXMethodDecl *MD,493ReturnValueSlot ReturnValue) {494assert(MD->isImplicitObjectMemberFunction() &&495"Trying to emit a member call expr on a static method!");496return EmitCXXMemberOrOperatorMemberCallExpr(497E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr,498/*IsArrow=*/false, E->getArg(0));499}500501RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,502ReturnValueSlot ReturnValue) {503return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);504}505506static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,507Address DestPtr,508const CXXRecordDecl *Base) {509if (Base->isEmpty())510return;511512DestPtr = DestPtr.withElementType(CGF.Int8Ty);513514const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);515CharUnits NVSize = Layout.getNonVirtualSize();516517// We cannot simply zero-initialize the entire base sub-object if vbptrs are518// present, they are initialized by the most derived class before calling the519// constructor.520SmallVector<std::pair<CharUnits, CharUnits>, 1> Stores;521Stores.emplace_back(CharUnits::Zero(), NVSize);522523// Each store is split by the existence of a vbptr.524CharUnits VBPtrWidth = CGF.getPointerSize();525std::vector<CharUnits> VBPtrOffsets =526CGF.CGM.getCXXABI().getVBPtrOffsets(Base);527for (CharUnits VBPtrOffset : VBPtrOffsets) {528// Stop before we hit any virtual base pointers located in virtual bases.529if (VBPtrOffset >= NVSize)530break;531std::pair<CharUnits, CharUnits> LastStore = Stores.pop_back_val();532CharUnits LastStoreOffset = LastStore.first;533CharUnits LastStoreSize = LastStore.second;534535CharUnits SplitBeforeOffset = LastStoreOffset;536CharUnits SplitBeforeSize = VBPtrOffset - SplitBeforeOffset;537assert(!SplitBeforeSize.isNegative() && "negative store size!");538if (!SplitBeforeSize.isZero())539Stores.emplace_back(SplitBeforeOffset, SplitBeforeSize);540541CharUnits SplitAfterOffset = VBPtrOffset + VBPtrWidth;542CharUnits SplitAfterSize = LastStoreSize - SplitAfterOffset;543assert(!SplitAfterSize.isNegative() && "negative store size!");544if (!SplitAfterSize.isZero())545Stores.emplace_back(SplitAfterOffset, SplitAfterSize);546}547548// If the type contains a pointer to data member we can't memset it to zero.549// Instead, create a null constant and copy it to the destination.550// TODO: there are other patterns besides zero that we can usefully memset,551// like -1, which happens to be the pattern used by member-pointers.552// TODO: isZeroInitializable can be over-conservative in the case where a553// virtual base contains a member pointer.554llvm::Constant *NullConstantForBase = CGF.CGM.EmitNullConstantForBase(Base);555if (!NullConstantForBase->isNullValue()) {556llvm::GlobalVariable *NullVariable = new llvm::GlobalVariable(557CGF.CGM.getModule(), NullConstantForBase->getType(),558/*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage,559NullConstantForBase, Twine());560561CharUnits Align =562std::max(Layout.getNonVirtualAlignment(), DestPtr.getAlignment());563NullVariable->setAlignment(Align.getAsAlign());564565Address SrcPtr(NullVariable, CGF.Int8Ty, Align);566567// Get and call the appropriate llvm.memcpy overload.568for (std::pair<CharUnits, CharUnits> Store : Stores) {569CharUnits StoreOffset = Store.first;570CharUnits StoreSize = Store.second;571llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);572CGF.Builder.CreateMemCpy(573CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),574CGF.Builder.CreateConstInBoundsByteGEP(SrcPtr, StoreOffset),575StoreSizeVal);576}577578// Otherwise, just memset the whole thing to zero. This is legal579// because in LLVM, all default initializers (other than the ones we just580// handled above) are guaranteed to have a bit pattern of all zeros.581} else {582for (std::pair<CharUnits, CharUnits> Store : Stores) {583CharUnits StoreOffset = Store.first;584CharUnits StoreSize = Store.second;585llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);586CGF.Builder.CreateMemSet(587CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),588CGF.Builder.getInt8(0), StoreSizeVal);589}590}591}592593void594CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,595AggValueSlot Dest) {596assert(!Dest.isIgnored() && "Must have a destination!");597const CXXConstructorDecl *CD = E->getConstructor();598599// If we require zero initialization before (or instead of) calling the600// constructor, as can be the case with a non-user-provided default601// constructor, emit the zero initialization now, unless destination is602// already zeroed.603if (E->requiresZeroInitialization() && !Dest.isZeroed()) {604switch (E->getConstructionKind()) {605case CXXConstructionKind::Delegating:606case CXXConstructionKind::Complete:607EmitNullInitialization(Dest.getAddress(), E->getType());608break;609case CXXConstructionKind::VirtualBase:610case CXXConstructionKind::NonVirtualBase:611EmitNullBaseClassInitialization(*this, Dest.getAddress(),612CD->getParent());613break;614}615}616617// If this is a call to a trivial default constructor, do nothing.618if (CD->isTrivial() && CD->isDefaultConstructor())619return;620621// Elide the constructor if we're constructing from a temporary.622if (getLangOpts().ElideConstructors && E->isElidable()) {623// FIXME: This only handles the simplest case, where the source object624// is passed directly as the first argument to the constructor.625// This should also handle stepping though implicit casts and626// conversion sequences which involve two steps, with a627// conversion operator followed by a converting constructor.628const Expr *SrcObj = E->getArg(0);629assert(SrcObj->isTemporaryObject(getContext(), CD->getParent()));630assert(631getContext().hasSameUnqualifiedType(E->getType(), SrcObj->getType()));632EmitAggExpr(SrcObj, Dest);633return;634}635636if (const ArrayType *arrayType637= getContext().getAsArrayType(E->getType())) {638EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddress(), E,639Dest.isSanitizerChecked());640} else {641CXXCtorType Type = Ctor_Complete;642bool ForVirtualBase = false;643bool Delegating = false;644645switch (E->getConstructionKind()) {646case CXXConstructionKind::Delegating:647// We should be emitting a constructor; GlobalDecl will assert this648Type = CurGD.getCtorType();649Delegating = true;650break;651652case CXXConstructionKind::Complete:653Type = Ctor_Complete;654break;655656case CXXConstructionKind::VirtualBase:657ForVirtualBase = true;658[[fallthrough]];659660case CXXConstructionKind::NonVirtualBase:661Type = Ctor_Base;662}663664// Call the constructor.665EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating, Dest, E);666}667}668669void CodeGenFunction::EmitSynthesizedCXXCopyCtor(Address Dest, Address Src,670const Expr *Exp) {671if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))672Exp = E->getSubExpr();673assert(isa<CXXConstructExpr>(Exp) &&674"EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");675const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);676const CXXConstructorDecl *CD = E->getConstructor();677RunCleanupsScope Scope(*this);678679// If we require zero initialization before (or instead of) calling the680// constructor, as can be the case with a non-user-provided default681// constructor, emit the zero initialization now.682// FIXME. Do I still need this for a copy ctor synthesis?683if (E->requiresZeroInitialization())684EmitNullInitialization(Dest, E->getType());685686assert(!getContext().getAsConstantArrayType(E->getType())687&& "EmitSynthesizedCXXCopyCtor - Copied-in Array");688EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E);689}690691static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,692const CXXNewExpr *E) {693if (!E->isArray())694return CharUnits::Zero();695696// No cookie is required if the operator new[] being used is the697// reserved placement operator new[].698if (E->getOperatorNew()->isReservedGlobalPlacementOperator())699return CharUnits::Zero();700701return CGF.CGM.getCXXABI().GetArrayCookieSize(E);702}703704static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,705const CXXNewExpr *e,706unsigned minElements,707llvm::Value *&numElements,708llvm::Value *&sizeWithoutCookie) {709QualType type = e->getAllocatedType();710711if (!e->isArray()) {712CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);713sizeWithoutCookie714= llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());715return sizeWithoutCookie;716}717718// The width of size_t.719unsigned sizeWidth = CGF.SizeTy->getBitWidth();720721// Figure out the cookie size.722llvm::APInt cookieSize(sizeWidth,723CalculateCookiePadding(CGF, e).getQuantity());724725// Emit the array size expression.726// We multiply the size of all dimensions for NumElements.727// e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.728numElements =729ConstantEmitter(CGF).tryEmitAbstract(*e->getArraySize(), e->getType());730if (!numElements)731numElements = CGF.EmitScalarExpr(*e->getArraySize());732assert(isa<llvm::IntegerType>(numElements->getType()));733734// The number of elements can be have an arbitrary integer type;735// essentially, we need to multiply it by a constant factor, add a736// cookie size, and verify that the result is representable as a737// size_t. That's just a gloss, though, and it's wrong in one738// important way: if the count is negative, it's an error even if739// the cookie size would bring the total size >= 0.740bool isSigned741= (*e->getArraySize())->getType()->isSignedIntegerOrEnumerationType();742llvm::IntegerType *numElementsType743= cast<llvm::IntegerType>(numElements->getType());744unsigned numElementsWidth = numElementsType->getBitWidth();745746// Compute the constant factor.747llvm::APInt arraySizeMultiplier(sizeWidth, 1);748while (const ConstantArrayType *CAT749= CGF.getContext().getAsConstantArrayType(type)) {750type = CAT->getElementType();751arraySizeMultiplier *= CAT->getSize();752}753754CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);755llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());756typeSizeMultiplier *= arraySizeMultiplier;757758// This will be a size_t.759llvm::Value *size;760761// If someone is doing 'new int[42]' there is no need to do a dynamic check.762// Don't bloat the -O0 code.763if (llvm::ConstantInt *numElementsC =764dyn_cast<llvm::ConstantInt>(numElements)) {765const llvm::APInt &count = numElementsC->getValue();766767bool hasAnyOverflow = false;768769// If 'count' was a negative number, it's an overflow.770if (isSigned && count.isNegative())771hasAnyOverflow = true;772773// We want to do all this arithmetic in size_t. If numElements is774// wider than that, check whether it's already too big, and if so,775// overflow.776else if (numElementsWidth > sizeWidth &&777numElementsWidth - sizeWidth > count.countl_zero())778hasAnyOverflow = true;779780// Okay, compute a count at the right width.781llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);782783// If there is a brace-initializer, we cannot allocate fewer elements than784// there are initializers. If we do, that's treated like an overflow.785if (adjustedCount.ult(minElements))786hasAnyOverflow = true;787788// Scale numElements by that. This might overflow, but we don't789// care because it only overflows if allocationSize does, too, and790// if that overflows then we shouldn't use this.791numElements = llvm::ConstantInt::get(CGF.SizeTy,792adjustedCount * arraySizeMultiplier);793794// Compute the size before cookie, and track whether it overflowed.795bool overflow;796llvm::APInt allocationSize797= adjustedCount.umul_ov(typeSizeMultiplier, overflow);798hasAnyOverflow |= overflow;799800// Add in the cookie, and check whether it's overflowed.801if (cookieSize != 0) {802// Save the current size without a cookie. This shouldn't be803// used if there was overflow.804sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);805806allocationSize = allocationSize.uadd_ov(cookieSize, overflow);807hasAnyOverflow |= overflow;808}809810// On overflow, produce a -1 so operator new will fail.811if (hasAnyOverflow) {812size = llvm::Constant::getAllOnesValue(CGF.SizeTy);813} else {814size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);815}816817// Otherwise, we might need to use the overflow intrinsics.818} else {819// There are up to five conditions we need to test for:820// 1) if isSigned, we need to check whether numElements is negative;821// 2) if numElementsWidth > sizeWidth, we need to check whether822// numElements is larger than something representable in size_t;823// 3) if minElements > 0, we need to check whether numElements is smaller824// than that.825// 4) we need to compute826// sizeWithoutCookie := numElements * typeSizeMultiplier827// and check whether it overflows; and828// 5) if we need a cookie, we need to compute829// size := sizeWithoutCookie + cookieSize830// and check whether it overflows.831832llvm::Value *hasOverflow = nullptr;833834// If numElementsWidth > sizeWidth, then one way or another, we're835// going to have to do a comparison for (2), and this happens to836// take care of (1), too.837if (numElementsWidth > sizeWidth) {838llvm::APInt threshold =839llvm::APInt::getOneBitSet(numElementsWidth, sizeWidth);840841llvm::Value *thresholdV842= llvm::ConstantInt::get(numElementsType, threshold);843844hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);845numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);846847// Otherwise, if we're signed, we want to sext up to size_t.848} else if (isSigned) {849if (numElementsWidth < sizeWidth)850numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);851852// If there's a non-1 type size multiplier, then we can do the853// signedness check at the same time as we do the multiply854// because a negative number times anything will cause an855// unsigned overflow. Otherwise, we have to do it here. But at least856// in this case, we can subsume the >= minElements check.857if (typeSizeMultiplier == 1)858hasOverflow = CGF.Builder.CreateICmpSLT(numElements,859llvm::ConstantInt::get(CGF.SizeTy, minElements));860861// Otherwise, zext up to size_t if necessary.862} else if (numElementsWidth < sizeWidth) {863numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);864}865866assert(numElements->getType() == CGF.SizeTy);867868if (minElements) {869// Don't allow allocation of fewer elements than we have initializers.870if (!hasOverflow) {871hasOverflow = CGF.Builder.CreateICmpULT(numElements,872llvm::ConstantInt::get(CGF.SizeTy, minElements));873} else if (numElementsWidth > sizeWidth) {874// The other existing overflow subsumes this check.875// We do an unsigned comparison, since any signed value < -1 is876// taken care of either above or below.877hasOverflow = CGF.Builder.CreateOr(hasOverflow,878CGF.Builder.CreateICmpULT(numElements,879llvm::ConstantInt::get(CGF.SizeTy, minElements)));880}881}882883size = numElements;884885// Multiply by the type size if necessary. This multiplier886// includes all the factors for nested arrays.887//888// This step also causes numElements to be scaled up by the889// nested-array factor if necessary. Overflow on this computation890// can be ignored because the result shouldn't be used if891// allocation fails.892if (typeSizeMultiplier != 1) {893llvm::Function *umul_with_overflow894= CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);895896llvm::Value *tsmV =897llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);898llvm::Value *result =899CGF.Builder.CreateCall(umul_with_overflow, {size, tsmV});900901llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);902if (hasOverflow)903hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);904else905hasOverflow = overflowed;906907size = CGF.Builder.CreateExtractValue(result, 0);908909// Also scale up numElements by the array size multiplier.910if (arraySizeMultiplier != 1) {911// If the base element type size is 1, then we can re-use the912// multiply we just did.913if (typeSize.isOne()) {914assert(arraySizeMultiplier == typeSizeMultiplier);915numElements = size;916917// Otherwise we need a separate multiply.918} else {919llvm::Value *asmV =920llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);921numElements = CGF.Builder.CreateMul(numElements, asmV);922}923}924} else {925// numElements doesn't need to be scaled.926assert(arraySizeMultiplier == 1);927}928929// Add in the cookie size if necessary.930if (cookieSize != 0) {931sizeWithoutCookie = size;932933llvm::Function *uadd_with_overflow934= CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);935936llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);937llvm::Value *result =938CGF.Builder.CreateCall(uadd_with_overflow, {size, cookieSizeV});939940llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);941if (hasOverflow)942hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);943else944hasOverflow = overflowed;945946size = CGF.Builder.CreateExtractValue(result, 0);947}948949// If we had any possibility of dynamic overflow, make a select to950// overwrite 'size' with an all-ones value, which should cause951// operator new to throw.952if (hasOverflow)953size = CGF.Builder.CreateSelect(hasOverflow,954llvm::Constant::getAllOnesValue(CGF.SizeTy),955size);956}957958if (cookieSize == 0)959sizeWithoutCookie = size;960else961assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");962963return size;964}965966static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,967QualType AllocType, Address NewPtr,968AggValueSlot::Overlap_t MayOverlap) {969// FIXME: Refactor with EmitExprAsInit.970switch (CGF.getEvaluationKind(AllocType)) {971case TEK_Scalar:972CGF.EmitScalarInit(Init, nullptr,973CGF.MakeAddrLValue(NewPtr, AllocType), false);974return;975case TEK_Complex:976CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType),977/*isInit*/ true);978return;979case TEK_Aggregate: {980AggValueSlot Slot981= AggValueSlot::forAddr(NewPtr, AllocType.getQualifiers(),982AggValueSlot::IsDestructed,983AggValueSlot::DoesNotNeedGCBarriers,984AggValueSlot::IsNotAliased,985MayOverlap, AggValueSlot::IsNotZeroed,986AggValueSlot::IsSanitizerChecked);987CGF.EmitAggExpr(Init, Slot);988return;989}990}991llvm_unreachable("bad evaluation kind");992}993994void CodeGenFunction::EmitNewArrayInitializer(995const CXXNewExpr *E, QualType ElementType, llvm::Type *ElementTy,996Address BeginPtr, llvm::Value *NumElements,997llvm::Value *AllocSizeWithoutCookie) {998// If we have a type with trivial initialization and no initializer,999// there's nothing to do.1000if (!E->hasInitializer())1001return;10021003Address CurPtr = BeginPtr;10041005unsigned InitListElements = 0;10061007const Expr *Init = E->getInitializer();1008Address EndOfInit = Address::invalid();1009QualType::DestructionKind DtorKind = ElementType.isDestructedType();1010CleanupDeactivationScope deactivation(*this);1011bool pushedCleanup = false;10121013CharUnits ElementSize = getContext().getTypeSizeInChars(ElementType);1014CharUnits ElementAlign =1015BeginPtr.getAlignment().alignmentOfArrayElement(ElementSize);10161017// Attempt to perform zero-initialization using memset.1018auto TryMemsetInitialization = [&]() -> bool {1019// FIXME: If the type is a pointer-to-data-member under the Itanium ABI,1020// we can initialize with a memset to -1.1021if (!CGM.getTypes().isZeroInitializable(ElementType))1022return false;10231024// Optimization: since zero initialization will just set the memory1025// to all zeroes, generate a single memset to do it in one shot.10261027// Subtract out the size of any elements we've already initialized.1028auto *RemainingSize = AllocSizeWithoutCookie;1029if (InitListElements) {1030// We know this can't overflow; we check this when doing the allocation.1031auto *InitializedSize = llvm::ConstantInt::get(1032RemainingSize->getType(),1033getContext().getTypeSizeInChars(ElementType).getQuantity() *1034InitListElements);1035RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);1036}10371038// Create the memset.1039Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize, false);1040return true;1041};10421043const InitListExpr *ILE = dyn_cast<InitListExpr>(Init);1044const CXXParenListInitExpr *CPLIE = nullptr;1045const StringLiteral *SL = nullptr;1046const ObjCEncodeExpr *OCEE = nullptr;1047const Expr *IgnoreParen = nullptr;1048if (!ILE) {1049IgnoreParen = Init->IgnoreParenImpCasts();1050CPLIE = dyn_cast<CXXParenListInitExpr>(IgnoreParen);1051SL = dyn_cast<StringLiteral>(IgnoreParen);1052OCEE = dyn_cast<ObjCEncodeExpr>(IgnoreParen);1053}10541055// If the initializer is an initializer list, first do the explicit elements.1056if (ILE || CPLIE || SL || OCEE) {1057// Initializing from a (braced) string literal is a special case; the init1058// list element does not initialize a (single) array element.1059if ((ILE && ILE->isStringLiteralInit()) || SL || OCEE) {1060if (!ILE)1061Init = IgnoreParen;1062// Initialize the initial portion of length equal to that of the string1063// literal. The allocation must be for at least this much; we emitted a1064// check for that earlier.1065AggValueSlot Slot =1066AggValueSlot::forAddr(CurPtr, ElementType.getQualifiers(),1067AggValueSlot::IsDestructed,1068AggValueSlot::DoesNotNeedGCBarriers,1069AggValueSlot::IsNotAliased,1070AggValueSlot::DoesNotOverlap,1071AggValueSlot::IsNotZeroed,1072AggValueSlot::IsSanitizerChecked);1073EmitAggExpr(ILE ? ILE->getInit(0) : Init, Slot);10741075// Move past these elements.1076InitListElements =1077cast<ConstantArrayType>(Init->getType()->getAsArrayTypeUnsafe())1078->getZExtSize();1079CurPtr = Builder.CreateConstInBoundsGEP(1080CurPtr, InitListElements, "string.init.end");10811082// Zero out the rest, if any remain.1083llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);1084if (!ConstNum || !ConstNum->equalsInt(InitListElements)) {1085bool OK = TryMemsetInitialization();1086(void)OK;1087assert(OK && "couldn't memset character type?");1088}1089return;1090}10911092ArrayRef<const Expr *> InitExprs =1093ILE ? ILE->inits() : CPLIE->getInitExprs();1094InitListElements = InitExprs.size();10951096// If this is a multi-dimensional array new, we will initialize multiple1097// elements with each init list element.1098QualType AllocType = E->getAllocatedType();1099if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(1100AllocType->getAsArrayTypeUnsafe())) {1101ElementTy = ConvertTypeForMem(AllocType);1102CurPtr = CurPtr.withElementType(ElementTy);1103InitListElements *= getContext().getConstantArrayElementCount(CAT);1104}11051106// Enter a partial-destruction Cleanup if necessary.1107if (DtorKind) {1108AllocaTrackerRAII AllocaTracker(*this);1109// In principle we could tell the Cleanup where we are more1110// directly, but the control flow can get so varied here that it1111// would actually be quite complex. Therefore we go through an1112// alloca.1113llvm::Instruction *DominatingIP =1114Builder.CreateFlagLoad(llvm::ConstantInt::getNullValue(Int8PtrTy));1115EndOfInit = CreateTempAlloca(BeginPtr.getType(), getPointerAlign(),1116"array.init.end");1117pushIrregularPartialArrayCleanup(BeginPtr.emitRawPointer(*this),1118EndOfInit, ElementType, ElementAlign,1119getDestroyer(DtorKind));1120cast<EHCleanupScope>(*EHStack.find(EHStack.stable_begin()))1121.AddAuxAllocas(AllocaTracker.Take());1122DeferredDeactivationCleanupStack.push_back(1123{EHStack.stable_begin(), DominatingIP});1124pushedCleanup = true;1125}11261127CharUnits StartAlign = CurPtr.getAlignment();1128unsigned i = 0;1129for (const Expr *IE : InitExprs) {1130// Tell the cleanup that it needs to destroy up to this1131// element. TODO: some of these stores can be trivially1132// observed to be unnecessary.1133if (EndOfInit.isValid()) {1134Builder.CreateStore(CurPtr.emitRawPointer(*this), EndOfInit);1135}1136// FIXME: If the last initializer is an incomplete initializer list for1137// an array, and we have an array filler, we can fold together the two1138// initialization loops.1139StoreAnyExprIntoOneUnit(*this, IE, IE->getType(), CurPtr,1140AggValueSlot::DoesNotOverlap);1141CurPtr = Address(Builder.CreateInBoundsGEP(CurPtr.getElementType(),1142CurPtr.emitRawPointer(*this),1143Builder.getSize(1),1144"array.exp.next"),1145CurPtr.getElementType(),1146StartAlign.alignmentAtOffset((++i) * ElementSize));1147}11481149// The remaining elements are filled with the array filler expression.1150Init = ILE ? ILE->getArrayFiller() : CPLIE->getArrayFiller();11511152// Extract the initializer for the individual array elements by pulling1153// out the array filler from all the nested initializer lists. This avoids1154// generating a nested loop for the initialization.1155while (Init && Init->getType()->isConstantArrayType()) {1156auto *SubILE = dyn_cast<InitListExpr>(Init);1157if (!SubILE)1158break;1159assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");1160Init = SubILE->getArrayFiller();1161}11621163// Switch back to initializing one base element at a time.1164CurPtr = CurPtr.withElementType(BeginPtr.getElementType());1165}11661167// If all elements have already been initialized, skip any further1168// initialization.1169llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);1170if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {1171return;1172}11731174assert(Init && "have trailing elements to initialize but no initializer");11751176// If this is a constructor call, try to optimize it out, and failing that1177// emit a single loop to initialize all remaining elements.1178if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {1179CXXConstructorDecl *Ctor = CCE->getConstructor();1180if (Ctor->isTrivial()) {1181// If new expression did not specify value-initialization, then there1182// is no initialization.1183if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())1184return;11851186if (TryMemsetInitialization())1187return;1188}11891190// Store the new Cleanup position for irregular Cleanups.1191//1192// FIXME: Share this cleanup with the constructor call emission rather than1193// having it create a cleanup of its own.1194if (EndOfInit.isValid())1195Builder.CreateStore(CurPtr.emitRawPointer(*this), EndOfInit);11961197// Emit a constructor call loop to initialize the remaining elements.1198if (InitListElements)1199NumElements = Builder.CreateSub(1200NumElements,1201llvm::ConstantInt::get(NumElements->getType(), InitListElements));1202EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,1203/*NewPointerIsChecked*/true,1204CCE->requiresZeroInitialization());1205return;1206}12071208// If this is value-initialization, we can usually use memset.1209ImplicitValueInitExpr IVIE(ElementType);1210if (isa<ImplicitValueInitExpr>(Init)) {1211if (TryMemsetInitialization())1212return;12131214// Switch to an ImplicitValueInitExpr for the element type. This handles1215// only one case: multidimensional array new of pointers to members. In1216// all other cases, we already have an initializer for the array element.1217Init = &IVIE;1218}12191220// At this point we should have found an initializer for the individual1221// elements of the array.1222assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&1223"got wrong type of element to initialize");12241225// If we have an empty initializer list, we can usually use memset.1226if (auto *ILE = dyn_cast<InitListExpr>(Init))1227if (ILE->getNumInits() == 0 && TryMemsetInitialization())1228return;12291230// If we have a struct whose every field is value-initialized, we can1231// usually use memset.1232if (auto *ILE = dyn_cast<InitListExpr>(Init)) {1233if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {1234if (RType->getDecl()->isStruct()) {1235unsigned NumElements = 0;1236if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RType->getDecl()))1237NumElements = CXXRD->getNumBases();1238for (auto *Field : RType->getDecl()->fields())1239if (!Field->isUnnamedBitField())1240++NumElements;1241// FIXME: Recurse into nested InitListExprs.1242if (ILE->getNumInits() == NumElements)1243for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)1244if (!isa<ImplicitValueInitExpr>(ILE->getInit(i)))1245--NumElements;1246if (ILE->getNumInits() == NumElements && TryMemsetInitialization())1247return;1248}1249}1250}12511252// Create the loop blocks.1253llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();1254llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");1255llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");12561257// Find the end of the array, hoisted out of the loop.1258llvm::Value *EndPtr = Builder.CreateInBoundsGEP(1259BeginPtr.getElementType(), BeginPtr.emitRawPointer(*this), NumElements,1260"array.end");12611262// If the number of elements isn't constant, we have to now check if there is1263// anything left to initialize.1264if (!ConstNum) {1265llvm::Value *IsEmpty = Builder.CreateICmpEQ(CurPtr.emitRawPointer(*this),1266EndPtr, "array.isempty");1267Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);1268}12691270// Enter the loop.1271EmitBlock(LoopBB);12721273// Set up the current-element phi.1274llvm::PHINode *CurPtrPhi =1275Builder.CreatePHI(CurPtr.getType(), 2, "array.cur");1276CurPtrPhi->addIncoming(CurPtr.emitRawPointer(*this), EntryBB);12771278CurPtr = Address(CurPtrPhi, CurPtr.getElementType(), ElementAlign);12791280// Store the new Cleanup position for irregular Cleanups.1281if (EndOfInit.isValid())1282Builder.CreateStore(CurPtr.emitRawPointer(*this), EndOfInit);12831284// Enter a partial-destruction Cleanup if necessary.1285if (!pushedCleanup && needsEHCleanup(DtorKind)) {1286llvm::Instruction *DominatingIP =1287Builder.CreateFlagLoad(llvm::ConstantInt::getNullValue(Int8PtrTy));1288pushRegularPartialArrayCleanup(BeginPtr.emitRawPointer(*this),1289CurPtr.emitRawPointer(*this), ElementType,1290ElementAlign, getDestroyer(DtorKind));1291DeferredDeactivationCleanupStack.push_back(1292{EHStack.stable_begin(), DominatingIP});1293}12941295// Emit the initializer into this element.1296StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr,1297AggValueSlot::DoesNotOverlap);12981299// Leave the Cleanup if we entered one.1300deactivation.ForceDeactivate();13011302// Advance to the next element by adjusting the pointer type as necessary.1303llvm::Value *NextPtr = Builder.CreateConstInBoundsGEP1_32(1304ElementTy, CurPtr.emitRawPointer(*this), 1, "array.next");13051306// Check whether we've gotten to the end of the array and, if so,1307// exit the loop.1308llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");1309Builder.CreateCondBr(IsEnd, ContBB, LoopBB);1310CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());13111312EmitBlock(ContBB);1313}13141315static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,1316QualType ElementType, llvm::Type *ElementTy,1317Address NewPtr, llvm::Value *NumElements,1318llvm::Value *AllocSizeWithoutCookie) {1319ApplyDebugLocation DL(CGF, E);1320if (E->isArray())1321CGF.EmitNewArrayInitializer(E, ElementType, ElementTy, NewPtr, NumElements,1322AllocSizeWithoutCookie);1323else if (const Expr *Init = E->getInitializer())1324StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr,1325AggValueSlot::DoesNotOverlap);1326}13271328/// Emit a call to an operator new or operator delete function, as implicitly1329/// created by new-expressions and delete-expressions.1330static RValue EmitNewDeleteCall(CodeGenFunction &CGF,1331const FunctionDecl *CalleeDecl,1332const FunctionProtoType *CalleeType,1333const CallArgList &Args) {1334llvm::CallBase *CallOrInvoke;1335llvm::Constant *CalleePtr = CGF.CGM.GetAddrOfFunction(CalleeDecl);1336CGCallee Callee = CGCallee::forDirect(CalleePtr, GlobalDecl(CalleeDecl));1337RValue RV =1338CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(1339Args, CalleeType, /*ChainCall=*/false),1340Callee, ReturnValueSlot(), Args, &CallOrInvoke);13411342/// C++1y [expr.new]p10:1343/// [In a new-expression,] an implementation is allowed to omit a call1344/// to a replaceable global allocation function.1345///1346/// We model such elidable calls with the 'builtin' attribute.1347llvm::Function *Fn = dyn_cast<llvm::Function>(CalleePtr);1348if (CalleeDecl->isReplaceableGlobalAllocationFunction() &&1349Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {1350CallOrInvoke->addFnAttr(llvm::Attribute::Builtin);1351}13521353return RV;1354}13551356RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,1357const CallExpr *TheCall,1358bool IsDelete) {1359CallArgList Args;1360EmitCallArgs(Args, Type, TheCall->arguments());1361// Find the allocation or deallocation function that we're calling.1362ASTContext &Ctx = getContext();1363DeclarationName Name = Ctx.DeclarationNames1364.getCXXOperatorName(IsDelete ? OO_Delete : OO_New);13651366for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))1367if (auto *FD = dyn_cast<FunctionDecl>(Decl))1368if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))1369return EmitNewDeleteCall(*this, FD, Type, Args);1370llvm_unreachable("predeclared global operator new/delete is missing");1371}13721373namespace {1374/// The parameters to pass to a usual operator delete.1375struct UsualDeleteParams {1376bool DestroyingDelete = false;1377bool Size = false;1378bool Alignment = false;1379};1380}13811382static UsualDeleteParams getUsualDeleteParams(const FunctionDecl *FD) {1383UsualDeleteParams Params;13841385const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();1386auto AI = FPT->param_type_begin(), AE = FPT->param_type_end();13871388// The first argument is always a void*.1389++AI;13901391// The next parameter may be a std::destroying_delete_t.1392if (FD->isDestroyingOperatorDelete()) {1393Params.DestroyingDelete = true;1394assert(AI != AE);1395++AI;1396}13971398// Figure out what other parameters we should be implicitly passing.1399if (AI != AE && (*AI)->isIntegerType()) {1400Params.Size = true;1401++AI;1402}14031404if (AI != AE && (*AI)->isAlignValT()) {1405Params.Alignment = true;1406++AI;1407}14081409assert(AI == AE && "unexpected usual deallocation function parameter");1410return Params;1411}14121413namespace {1414/// A cleanup to call the given 'operator delete' function upon abnormal1415/// exit from a new expression. Templated on a traits type that deals with1416/// ensuring that the arguments dominate the cleanup if necessary.1417template<typename Traits>1418class CallDeleteDuringNew final : public EHScopeStack::Cleanup {1419/// Type used to hold llvm::Value*s.1420typedef typename Traits::ValueTy ValueTy;1421/// Type used to hold RValues.1422typedef typename Traits::RValueTy RValueTy;1423struct PlacementArg {1424RValueTy ArgValue;1425QualType ArgType;1426};14271428unsigned NumPlacementArgs : 31;1429LLVM_PREFERRED_TYPE(bool)1430unsigned PassAlignmentToPlacementDelete : 1;1431const FunctionDecl *OperatorDelete;1432ValueTy Ptr;1433ValueTy AllocSize;1434CharUnits AllocAlign;14351436PlacementArg *getPlacementArgs() {1437return reinterpret_cast<PlacementArg *>(this + 1);1438}14391440public:1441static size_t getExtraSize(size_t NumPlacementArgs) {1442return NumPlacementArgs * sizeof(PlacementArg);1443}14441445CallDeleteDuringNew(size_t NumPlacementArgs,1446const FunctionDecl *OperatorDelete, ValueTy Ptr,1447ValueTy AllocSize, bool PassAlignmentToPlacementDelete,1448CharUnits AllocAlign)1449: NumPlacementArgs(NumPlacementArgs),1450PassAlignmentToPlacementDelete(PassAlignmentToPlacementDelete),1451OperatorDelete(OperatorDelete), Ptr(Ptr), AllocSize(AllocSize),1452AllocAlign(AllocAlign) {}14531454void setPlacementArg(unsigned I, RValueTy Arg, QualType Type) {1455assert(I < NumPlacementArgs && "index out of range");1456getPlacementArgs()[I] = {Arg, Type};1457}14581459void Emit(CodeGenFunction &CGF, Flags flags) override {1460const auto *FPT = OperatorDelete->getType()->castAs<FunctionProtoType>();1461CallArgList DeleteArgs;14621463// The first argument is always a void* (or C* for a destroying operator1464// delete for class type C).1465DeleteArgs.add(Traits::get(CGF, Ptr), FPT->getParamType(0));14661467// Figure out what other parameters we should be implicitly passing.1468UsualDeleteParams Params;1469if (NumPlacementArgs) {1470// A placement deallocation function is implicitly passed an alignment1471// if the placement allocation function was, but is never passed a size.1472Params.Alignment = PassAlignmentToPlacementDelete;1473} else {1474// For a non-placement new-expression, 'operator delete' can take a1475// size and/or an alignment if it has the right parameters.1476Params = getUsualDeleteParams(OperatorDelete);1477}14781479assert(!Params.DestroyingDelete &&1480"should not call destroying delete in a new-expression");14811482// The second argument can be a std::size_t (for non-placement delete).1483if (Params.Size)1484DeleteArgs.add(Traits::get(CGF, AllocSize),1485CGF.getContext().getSizeType());14861487// The next (second or third) argument can be a std::align_val_t, which1488// is an enum whose underlying type is std::size_t.1489// FIXME: Use the right type as the parameter type. Note that in a call1490// to operator delete(size_t, ...), we may not have it available.1491if (Params.Alignment)1492DeleteArgs.add(RValue::get(llvm::ConstantInt::get(1493CGF.SizeTy, AllocAlign.getQuantity())),1494CGF.getContext().getSizeType());14951496// Pass the rest of the arguments, which must match exactly.1497for (unsigned I = 0; I != NumPlacementArgs; ++I) {1498auto Arg = getPlacementArgs()[I];1499DeleteArgs.add(Traits::get(CGF, Arg.ArgValue), Arg.ArgType);1500}15011502// Call 'operator delete'.1503EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);1504}1505};1506}15071508/// Enter a cleanup to call 'operator delete' if the initializer in a1509/// new-expression throws.1510static void EnterNewDeleteCleanup(CodeGenFunction &CGF,1511const CXXNewExpr *E,1512Address NewPtr,1513llvm::Value *AllocSize,1514CharUnits AllocAlign,1515const CallArgList &NewArgs) {1516unsigned NumNonPlacementArgs = E->passAlignment() ? 2 : 1;15171518// If we're not inside a conditional branch, then the cleanup will1519// dominate and we can do the easier (and more efficient) thing.1520if (!CGF.isInConditionalBranch()) {1521struct DirectCleanupTraits {1522typedef llvm::Value *ValueTy;1523typedef RValue RValueTy;1524static RValue get(CodeGenFunction &, ValueTy V) { return RValue::get(V); }1525static RValue get(CodeGenFunction &, RValueTy V) { return V; }1526};15271528typedef CallDeleteDuringNew<DirectCleanupTraits> DirectCleanup;15291530DirectCleanup *Cleanup = CGF.EHStack.pushCleanupWithExtra<DirectCleanup>(1531EHCleanup, E->getNumPlacementArgs(), E->getOperatorDelete(),1532NewPtr.emitRawPointer(CGF), AllocSize, E->passAlignment(), AllocAlign);1533for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {1534auto &Arg = NewArgs[I + NumNonPlacementArgs];1535Cleanup->setPlacementArg(I, Arg.getRValue(CGF), Arg.Ty);1536}15371538return;1539}15401541// Otherwise, we need to save all this stuff.1542DominatingValue<RValue>::saved_type SavedNewPtr =1543DominatingValue<RValue>::save(CGF, RValue::get(NewPtr, CGF));1544DominatingValue<RValue>::saved_type SavedAllocSize =1545DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));15461547struct ConditionalCleanupTraits {1548typedef DominatingValue<RValue>::saved_type ValueTy;1549typedef DominatingValue<RValue>::saved_type RValueTy;1550static RValue get(CodeGenFunction &CGF, ValueTy V) {1551return V.restore(CGF);1552}1553};1554typedef CallDeleteDuringNew<ConditionalCleanupTraits> ConditionalCleanup;15551556ConditionalCleanup *Cleanup = CGF.EHStack1557.pushCleanupWithExtra<ConditionalCleanup>(EHCleanup,1558E->getNumPlacementArgs(),1559E->getOperatorDelete(),1560SavedNewPtr,1561SavedAllocSize,1562E->passAlignment(),1563AllocAlign);1564for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {1565auto &Arg = NewArgs[I + NumNonPlacementArgs];1566Cleanup->setPlacementArg(1567I, DominatingValue<RValue>::save(CGF, Arg.getRValue(CGF)), Arg.Ty);1568}15691570CGF.initFullExprCleanup();1571}15721573llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {1574// The element type being allocated.1575QualType allocType = getContext().getBaseElementType(E->getAllocatedType());15761577// 1. Build a call to the allocation function.1578FunctionDecl *allocator = E->getOperatorNew();15791580// If there is a brace-initializer or C++20 parenthesized initializer, cannot1581// allocate fewer elements than inits.1582unsigned minElements = 0;1583if (E->isArray() && E->hasInitializer()) {1584const Expr *Init = E->getInitializer();1585const InitListExpr *ILE = dyn_cast<InitListExpr>(Init);1586const CXXParenListInitExpr *CPLIE = dyn_cast<CXXParenListInitExpr>(Init);1587const Expr *IgnoreParen = Init->IgnoreParenImpCasts();1588if ((ILE && ILE->isStringLiteralInit()) ||1589isa<StringLiteral>(IgnoreParen) || isa<ObjCEncodeExpr>(IgnoreParen)) {1590minElements =1591cast<ConstantArrayType>(Init->getType()->getAsArrayTypeUnsafe())1592->getZExtSize();1593} else if (ILE || CPLIE) {1594minElements = ILE ? ILE->getNumInits() : CPLIE->getInitExprs().size();1595}1596}15971598llvm::Value *numElements = nullptr;1599llvm::Value *allocSizeWithoutCookie = nullptr;1600llvm::Value *allocSize =1601EmitCXXNewAllocSize(*this, E, minElements, numElements,1602allocSizeWithoutCookie);1603CharUnits allocAlign = getContext().getTypeAlignInChars(allocType);16041605// Emit the allocation call. If the allocator is a global placement1606// operator, just "inline" it directly.1607Address allocation = Address::invalid();1608CallArgList allocatorArgs;1609if (allocator->isReservedGlobalPlacementOperator()) {1610assert(E->getNumPlacementArgs() == 1);1611const Expr *arg = *E->placement_arguments().begin();16121613LValueBaseInfo BaseInfo;1614allocation = EmitPointerWithAlignment(arg, &BaseInfo);16151616// The pointer expression will, in many cases, be an opaque void*.1617// In these cases, discard the computed alignment and use the1618// formal alignment of the allocated type.1619if (BaseInfo.getAlignmentSource() != AlignmentSource::Decl)1620allocation.setAlignment(allocAlign);16211622// Set up allocatorArgs for the call to operator delete if it's not1623// the reserved global operator.1624if (E->getOperatorDelete() &&1625!E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {1626allocatorArgs.add(RValue::get(allocSize), getContext().getSizeType());1627allocatorArgs.add(RValue::get(allocation, *this), arg->getType());1628}16291630} else {1631const FunctionProtoType *allocatorType =1632allocator->getType()->castAs<FunctionProtoType>();1633unsigned ParamsToSkip = 0;16341635// The allocation size is the first argument.1636QualType sizeType = getContext().getSizeType();1637allocatorArgs.add(RValue::get(allocSize), sizeType);1638++ParamsToSkip;16391640if (allocSize != allocSizeWithoutCookie) {1641CharUnits cookieAlign = getSizeAlign(); // FIXME: Ask the ABI.1642allocAlign = std::max(allocAlign, cookieAlign);1643}16441645// The allocation alignment may be passed as the second argument.1646if (E->passAlignment()) {1647QualType AlignValT = sizeType;1648if (allocatorType->getNumParams() > 1) {1649AlignValT = allocatorType->getParamType(1);1650assert(getContext().hasSameUnqualifiedType(1651AlignValT->castAs<EnumType>()->getDecl()->getIntegerType(),1652sizeType) &&1653"wrong type for alignment parameter");1654++ParamsToSkip;1655} else {1656// Corner case, passing alignment to 'operator new(size_t, ...)'.1657assert(allocator->isVariadic() && "can't pass alignment to allocator");1658}1659allocatorArgs.add(1660RValue::get(llvm::ConstantInt::get(SizeTy, allocAlign.getQuantity())),1661AlignValT);1662}16631664// FIXME: Why do we not pass a CalleeDecl here?1665EmitCallArgs(allocatorArgs, allocatorType, E->placement_arguments(),1666/*AC*/AbstractCallee(), /*ParamsToSkip*/ParamsToSkip);16671668RValue RV =1669EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);16701671// Set !heapallocsite metadata on the call to operator new.1672if (getDebugInfo())1673if (auto *newCall = dyn_cast<llvm::CallBase>(RV.getScalarVal()))1674getDebugInfo()->addHeapAllocSiteMetadata(newCall, allocType,1675E->getExprLoc());16761677// If this was a call to a global replaceable allocation function that does1678// not take an alignment argument, the allocator is known to produce1679// storage that's suitably aligned for any object that fits, up to a known1680// threshold. Otherwise assume it's suitably aligned for the allocated type.1681CharUnits allocationAlign = allocAlign;1682if (!E->passAlignment() &&1683allocator->isReplaceableGlobalAllocationFunction()) {1684unsigned AllocatorAlign = llvm::bit_floor(std::min<uint64_t>(1685Target.getNewAlign(), getContext().getTypeSize(allocType)));1686allocationAlign = std::max(1687allocationAlign, getContext().toCharUnitsFromBits(AllocatorAlign));1688}16891690allocation = Address(RV.getScalarVal(), Int8Ty, allocationAlign);1691}16921693// Emit a null check on the allocation result if the allocation1694// function is allowed to return null (because it has a non-throwing1695// exception spec or is the reserved placement new) and we have an1696// interesting initializer will be running sanitizers on the initialization.1697bool nullCheck = E->shouldNullCheckAllocation() &&1698(!allocType.isPODType(getContext()) || E->hasInitializer() ||1699sanitizePerformTypeCheck());17001701llvm::BasicBlock *nullCheckBB = nullptr;1702llvm::BasicBlock *contBB = nullptr;17031704// The null-check means that the initializer is conditionally1705// evaluated.1706ConditionalEvaluation conditional(*this);17071708if (nullCheck) {1709conditional.begin(*this);17101711nullCheckBB = Builder.GetInsertBlock();1712llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");1713contBB = createBasicBlock("new.cont");17141715llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");1716Builder.CreateCondBr(isNull, contBB, notNullBB);1717EmitBlock(notNullBB);1718}17191720// If there's an operator delete, enter a cleanup to call it if an1721// exception is thrown.1722EHScopeStack::stable_iterator operatorDeleteCleanup;1723llvm::Instruction *cleanupDominator = nullptr;1724if (E->getOperatorDelete() &&1725!E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {1726EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocAlign,1727allocatorArgs);1728operatorDeleteCleanup = EHStack.stable_begin();1729cleanupDominator = Builder.CreateUnreachable();1730}17311732assert((allocSize == allocSizeWithoutCookie) ==1733CalculateCookiePadding(*this, E).isZero());1734if (allocSize != allocSizeWithoutCookie) {1735assert(E->isArray());1736allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,1737numElements,1738E, allocType);1739}17401741llvm::Type *elementTy = ConvertTypeForMem(allocType);1742Address result = allocation.withElementType(elementTy);17431744// Passing pointer through launder.invariant.group to avoid propagation of1745// vptrs information which may be included in previous type.1746// To not break LTO with different optimizations levels, we do it regardless1747// of optimization level.1748if (CGM.getCodeGenOpts().StrictVTablePointers &&1749allocator->isReservedGlobalPlacementOperator())1750result = Builder.CreateLaunderInvariantGroup(result);17511752// Emit sanitizer checks for pointer value now, so that in the case of an1753// array it was checked only once and not at each constructor call. We may1754// have already checked that the pointer is non-null.1755// FIXME: If we have an array cookie and a potentially-throwing allocator,1756// we'll null check the wrong pointer here.1757SanitizerSet SkippedChecks;1758SkippedChecks.set(SanitizerKind::Null, nullCheck);1759EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall,1760E->getAllocatedTypeSourceInfo()->getTypeLoc().getBeginLoc(),1761result, allocType, result.getAlignment(), SkippedChecks,1762numElements);17631764EmitNewInitializer(*this, E, allocType, elementTy, result, numElements,1765allocSizeWithoutCookie);1766llvm::Value *resultPtr = result.emitRawPointer(*this);1767if (E->isArray()) {1768// NewPtr is a pointer to the base element type. If we're1769// allocating an array of arrays, we'll need to cast back to the1770// array pointer type.1771llvm::Type *resultType = ConvertTypeForMem(E->getType());1772if (resultPtr->getType() != resultType)1773resultPtr = Builder.CreateBitCast(resultPtr, resultType);1774}17751776// Deactivate the 'operator delete' cleanup if we finished1777// initialization.1778if (operatorDeleteCleanup.isValid()) {1779DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);1780cleanupDominator->eraseFromParent();1781}17821783if (nullCheck) {1784conditional.end(*this);17851786llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();1787EmitBlock(contBB);17881789llvm::PHINode *PHI = Builder.CreatePHI(resultPtr->getType(), 2);1790PHI->addIncoming(resultPtr, notNullBB);1791PHI->addIncoming(llvm::Constant::getNullValue(resultPtr->getType()),1792nullCheckBB);17931794resultPtr = PHI;1795}17961797return resultPtr;1798}17991800void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,1801llvm::Value *Ptr, QualType DeleteTy,1802llvm::Value *NumElements,1803CharUnits CookieSize) {1804assert((!NumElements && CookieSize.isZero()) ||1805DeleteFD->getOverloadedOperator() == OO_Array_Delete);18061807const auto *DeleteFTy = DeleteFD->getType()->castAs<FunctionProtoType>();1808CallArgList DeleteArgs;18091810auto Params = getUsualDeleteParams(DeleteFD);1811auto ParamTypeIt = DeleteFTy->param_type_begin();18121813// Pass the pointer itself.1814QualType ArgTy = *ParamTypeIt++;1815llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));1816DeleteArgs.add(RValue::get(DeletePtr), ArgTy);18171818// Pass the std::destroying_delete tag if present.1819llvm::AllocaInst *DestroyingDeleteTag = nullptr;1820if (Params.DestroyingDelete) {1821QualType DDTag = *ParamTypeIt++;1822llvm::Type *Ty = getTypes().ConvertType(DDTag);1823CharUnits Align = CGM.getNaturalTypeAlignment(DDTag);1824DestroyingDeleteTag = CreateTempAlloca(Ty, "destroying.delete.tag");1825DestroyingDeleteTag->setAlignment(Align.getAsAlign());1826DeleteArgs.add(1827RValue::getAggregate(Address(DestroyingDeleteTag, Ty, Align)), DDTag);1828}18291830// Pass the size if the delete function has a size_t parameter.1831if (Params.Size) {1832QualType SizeType = *ParamTypeIt++;1833CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);1834llvm::Value *Size = llvm::ConstantInt::get(ConvertType(SizeType),1835DeleteTypeSize.getQuantity());18361837// For array new, multiply by the number of elements.1838if (NumElements)1839Size = Builder.CreateMul(Size, NumElements);18401841// If there is a cookie, add the cookie size.1842if (!CookieSize.isZero())1843Size = Builder.CreateAdd(1844Size, llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity()));18451846DeleteArgs.add(RValue::get(Size), SizeType);1847}18481849// Pass the alignment if the delete function has an align_val_t parameter.1850if (Params.Alignment) {1851QualType AlignValType = *ParamTypeIt++;1852CharUnits DeleteTypeAlign =1853getContext().toCharUnitsFromBits(getContext().getTypeAlignIfKnown(1854DeleteTy, true /* NeedsPreferredAlignment */));1855llvm::Value *Align = llvm::ConstantInt::get(ConvertType(AlignValType),1856DeleteTypeAlign.getQuantity());1857DeleteArgs.add(RValue::get(Align), AlignValType);1858}18591860assert(ParamTypeIt == DeleteFTy->param_type_end() &&1861"unknown parameter to usual delete function");18621863// Emit the call to delete.1864EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);18651866// If call argument lowering didn't use the destroying_delete_t alloca,1867// remove it again.1868if (DestroyingDeleteTag && DestroyingDeleteTag->use_empty())1869DestroyingDeleteTag->eraseFromParent();1870}18711872namespace {1873/// Calls the given 'operator delete' on a single object.1874struct CallObjectDelete final : EHScopeStack::Cleanup {1875llvm::Value *Ptr;1876const FunctionDecl *OperatorDelete;1877QualType ElementType;18781879CallObjectDelete(llvm::Value *Ptr,1880const FunctionDecl *OperatorDelete,1881QualType ElementType)1882: Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}18831884void Emit(CodeGenFunction &CGF, Flags flags) override {1885CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);1886}1887};1888}18891890void1891CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,1892llvm::Value *CompletePtr,1893QualType ElementType) {1894EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr,1895OperatorDelete, ElementType);1896}18971898/// Emit the code for deleting a single object with a destroying operator1899/// delete. If the element type has a non-virtual destructor, Ptr has already1900/// been converted to the type of the parameter of 'operator delete'. Otherwise1901/// Ptr points to an object of the static type.1902static void EmitDestroyingObjectDelete(CodeGenFunction &CGF,1903const CXXDeleteExpr *DE, Address Ptr,1904QualType ElementType) {1905auto *Dtor = ElementType->getAsCXXRecordDecl()->getDestructor();1906if (Dtor && Dtor->isVirtual())1907CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,1908Dtor);1909else1910CGF.EmitDeleteCall(DE->getOperatorDelete(), Ptr.emitRawPointer(CGF),1911ElementType);1912}19131914/// Emit the code for deleting a single object.1915/// \return \c true if we started emitting UnconditionalDeleteBlock, \c false1916/// if not.1917static bool EmitObjectDelete(CodeGenFunction &CGF,1918const CXXDeleteExpr *DE,1919Address Ptr,1920QualType ElementType,1921llvm::BasicBlock *UnconditionalDeleteBlock) {1922// C++11 [expr.delete]p3:1923// If the static type of the object to be deleted is different from its1924// dynamic type, the static type shall be a base class of the dynamic type1925// of the object to be deleted and the static type shall have a virtual1926// destructor or the behavior is undefined.1927CGF.EmitTypeCheck(CodeGenFunction::TCK_MemberCall, DE->getExprLoc(), Ptr,1928ElementType);19291930const FunctionDecl *OperatorDelete = DE->getOperatorDelete();1931assert(!OperatorDelete->isDestroyingOperatorDelete());19321933// Find the destructor for the type, if applicable. If the1934// destructor is virtual, we'll just emit the vcall and return.1935const CXXDestructorDecl *Dtor = nullptr;1936if (const RecordType *RT = ElementType->getAs<RecordType>()) {1937CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());1938if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {1939Dtor = RD->getDestructor();19401941if (Dtor->isVirtual()) {1942bool UseVirtualCall = true;1943const Expr *Base = DE->getArgument();1944if (auto *DevirtualizedDtor =1945dyn_cast_or_null<const CXXDestructorDecl>(1946Dtor->getDevirtualizedMethod(1947Base, CGF.CGM.getLangOpts().AppleKext))) {1948UseVirtualCall = false;1949const CXXRecordDecl *DevirtualizedClass =1950DevirtualizedDtor->getParent();1951if (declaresSameEntity(getCXXRecord(Base), DevirtualizedClass)) {1952// Devirtualized to the class of the base type (the type of the1953// whole expression).1954Dtor = DevirtualizedDtor;1955} else {1956// Devirtualized to some other type. Would need to cast the this1957// pointer to that type but we don't have support for that yet, so1958// do a virtual call. FIXME: handle the case where it is1959// devirtualized to the derived type (the type of the inner1960// expression) as in EmitCXXMemberOrOperatorMemberCallExpr.1961UseVirtualCall = true;1962}1963}1964if (UseVirtualCall) {1965CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,1966Dtor);1967return false;1968}1969}1970}1971}19721973// Make sure that we call delete even if the dtor throws.1974// This doesn't have to a conditional cleanup because we're going1975// to pop it off in a second.1976CGF.EHStack.pushCleanup<CallObjectDelete>(1977NormalAndEHCleanup, Ptr.emitRawPointer(CGF), OperatorDelete, ElementType);19781979if (Dtor)1980CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,1981/*ForVirtualBase=*/false,1982/*Delegating=*/false,1983Ptr, ElementType);1984else if (auto Lifetime = ElementType.getObjCLifetime()) {1985switch (Lifetime) {1986case Qualifiers::OCL_None:1987case Qualifiers::OCL_ExplicitNone:1988case Qualifiers::OCL_Autoreleasing:1989break;19901991case Qualifiers::OCL_Strong:1992CGF.EmitARCDestroyStrong(Ptr, ARCPreciseLifetime);1993break;19941995case Qualifiers::OCL_Weak:1996CGF.EmitARCDestroyWeak(Ptr);1997break;1998}1999}20002001// When optimizing for size, call 'operator delete' unconditionally.2002if (CGF.CGM.getCodeGenOpts().OptimizeSize > 1) {2003CGF.EmitBlock(UnconditionalDeleteBlock);2004CGF.PopCleanupBlock();2005return true;2006}20072008CGF.PopCleanupBlock();2009return false;2010}20112012namespace {2013/// Calls the given 'operator delete' on an array of objects.2014struct CallArrayDelete final : EHScopeStack::Cleanup {2015llvm::Value *Ptr;2016const FunctionDecl *OperatorDelete;2017llvm::Value *NumElements;2018QualType ElementType;2019CharUnits CookieSize;20202021CallArrayDelete(llvm::Value *Ptr,2022const FunctionDecl *OperatorDelete,2023llvm::Value *NumElements,2024QualType ElementType,2025CharUnits CookieSize)2026: Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),2027ElementType(ElementType), CookieSize(CookieSize) {}20282029void Emit(CodeGenFunction &CGF, Flags flags) override {2030CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType, NumElements,2031CookieSize);2032}2033};2034}20352036/// Emit the code for deleting an array of objects.2037static void EmitArrayDelete(CodeGenFunction &CGF,2038const CXXDeleteExpr *E,2039Address deletedPtr,2040QualType elementType) {2041llvm::Value *numElements = nullptr;2042llvm::Value *allocatedPtr = nullptr;2043CharUnits cookieSize;2044CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,2045numElements, allocatedPtr, cookieSize);20462047assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");20482049// Make sure that we call delete even if one of the dtors throws.2050const FunctionDecl *operatorDelete = E->getOperatorDelete();2051CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,2052allocatedPtr, operatorDelete,2053numElements, elementType,2054cookieSize);20552056// Destroy the elements.2057if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {2058assert(numElements && "no element count for a type with a destructor!");20592060CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);2061CharUnits elementAlign =2062deletedPtr.getAlignment().alignmentOfArrayElement(elementSize);20632064llvm::Value *arrayBegin = deletedPtr.emitRawPointer(CGF);2065llvm::Value *arrayEnd = CGF.Builder.CreateInBoundsGEP(2066deletedPtr.getElementType(), arrayBegin, numElements, "delete.end");20672068// Note that it is legal to allocate a zero-length array, and we2069// can never fold the check away because the length should always2070// come from a cookie.2071CGF.emitArrayDestroy(arrayBegin, arrayEnd, elementType, elementAlign,2072CGF.getDestroyer(dtorKind),2073/*checkZeroLength*/ true,2074CGF.needsEHCleanup(dtorKind));2075}20762077// Pop the cleanup block.2078CGF.PopCleanupBlock();2079}20802081void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {2082const Expr *Arg = E->getArgument();2083Address Ptr = EmitPointerWithAlignment(Arg);20842085// Null check the pointer.2086//2087// We could avoid this null check if we can determine that the object2088// destruction is trivial and doesn't require an array cookie; we can2089// unconditionally perform the operator delete call in that case. For now, we2090// assume that deleted pointers are null rarely enough that it's better to2091// keep the branch. This might be worth revisiting for a -O0 code size win.2092llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");2093llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");20942095llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");20962097Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);2098EmitBlock(DeleteNotNull);2099Ptr.setKnownNonNull();21002101QualType DeleteTy = E->getDestroyedType();21022103// A destroying operator delete overrides the entire operation of the2104// delete expression.2105if (E->getOperatorDelete()->isDestroyingOperatorDelete()) {2106EmitDestroyingObjectDelete(*this, E, Ptr, DeleteTy);2107EmitBlock(DeleteEnd);2108return;2109}21102111// We might be deleting a pointer to array. If so, GEP down to the2112// first non-array element.2113// (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)2114if (DeleteTy->isConstantArrayType()) {2115llvm::Value *Zero = Builder.getInt32(0);2116SmallVector<llvm::Value*,8> GEP;21172118GEP.push_back(Zero); // point at the outermost array21192120// For each layer of array type we're pointing at:2121while (const ConstantArrayType *Arr2122= getContext().getAsConstantArrayType(DeleteTy)) {2123// 1. Unpeel the array type.2124DeleteTy = Arr->getElementType();21252126// 2. GEP to the first element of the array.2127GEP.push_back(Zero);2128}21292130Ptr = Builder.CreateInBoundsGEP(Ptr, GEP, ConvertTypeForMem(DeleteTy),2131Ptr.getAlignment(), "del.first");2132}21332134assert(ConvertTypeForMem(DeleteTy) == Ptr.getElementType());21352136if (E->isArrayForm()) {2137EmitArrayDelete(*this, E, Ptr, DeleteTy);2138EmitBlock(DeleteEnd);2139} else {2140if (!EmitObjectDelete(*this, E, Ptr, DeleteTy, DeleteEnd))2141EmitBlock(DeleteEnd);2142}2143}21442145static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,2146llvm::Type *StdTypeInfoPtrTy,2147bool HasNullCheck) {2148// Get the vtable pointer.2149Address ThisPtr = CGF.EmitLValue(E).getAddress();21502151QualType SrcRecordTy = E->getType();21522153// C++ [class.cdtor]p4:2154// If the operand of typeid refers to the object under construction or2155// destruction and the static type of the operand is neither the constructor2156// or destructor’s class nor one of its bases, the behavior is undefined.2157CGF.EmitTypeCheck(CodeGenFunction::TCK_DynamicOperation, E->getExprLoc(),2158ThisPtr, SrcRecordTy);21592160// Whether we need an explicit null pointer check. For example, with the2161// Microsoft ABI, if this is a call to __RTtypeid, the null pointer check and2162// exception throw is inside the __RTtypeid(nullptr) call2163if (HasNullCheck &&2164CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(SrcRecordTy)) {2165llvm::BasicBlock *BadTypeidBlock =2166CGF.createBasicBlock("typeid.bad_typeid");2167llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");21682169llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);2170CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);21712172CGF.EmitBlock(BadTypeidBlock);2173CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);2174CGF.EmitBlock(EndBlock);2175}21762177return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,2178StdTypeInfoPtrTy);2179}21802181llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {2182// Ideally, we would like to use GlobalsInt8PtrTy here, however, we cannot,2183// primarily because the result of applying typeid is a value of type2184// type_info, which is declared & defined by the standard library2185// implementation and expects to operate on the generic (default) AS.2186// https://reviews.llvm.org/D157452 has more context, and a possible solution.2187llvm::Type *PtrTy = Int8PtrTy;2188LangAS GlobAS = CGM.GetGlobalVarAddressSpace(nullptr);21892190auto MaybeASCast = [=](auto &&TypeInfo) {2191if (GlobAS == LangAS::Default)2192return TypeInfo;2193return getTargetHooks().performAddrSpaceCast(CGM,TypeInfo, GlobAS,2194LangAS::Default, PtrTy);2195};21962197if (E->isTypeOperand()) {2198llvm::Constant *TypeInfo =2199CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));2200return MaybeASCast(TypeInfo);2201}22022203// C++ [expr.typeid]p2:2204// When typeid is applied to a glvalue expression whose type is a2205// polymorphic class type, the result refers to a std::type_info object2206// representing the type of the most derived object (that is, the dynamic2207// type) to which the glvalue refers.2208// If the operand is already most derived object, no need to look up vtable.2209if (E->isPotentiallyEvaluated() && !E->isMostDerived(getContext()))2210return EmitTypeidFromVTable(*this, E->getExprOperand(), PtrTy,2211E->hasNullCheck());22122213QualType OperandTy = E->getExprOperand()->getType();2214return MaybeASCast(CGM.GetAddrOfRTTIDescriptor(OperandTy));2215}22162217static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,2218QualType DestTy) {2219llvm::Type *DestLTy = CGF.ConvertType(DestTy);2220if (DestTy->isPointerType())2221return llvm::Constant::getNullValue(DestLTy);22222223/// C++ [expr.dynamic.cast]p9:2224/// A failed cast to reference type throws std::bad_cast2225if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))2226return nullptr;22272228CGF.Builder.ClearInsertionPoint();2229return llvm::PoisonValue::get(DestLTy);2230}22312232llvm::Value *CodeGenFunction::EmitDynamicCast(Address ThisAddr,2233const CXXDynamicCastExpr *DCE) {2234CGM.EmitExplicitCastExprType(DCE, this);2235QualType DestTy = DCE->getTypeAsWritten();22362237QualType SrcTy = DCE->getSubExpr()->getType();22382239// C++ [expr.dynamic.cast]p7:2240// If T is "pointer to cv void," then the result is a pointer to the most2241// derived object pointed to by v.2242bool IsDynamicCastToVoid = DestTy->isVoidPointerType();2243QualType SrcRecordTy;2244QualType DestRecordTy;2245if (IsDynamicCastToVoid) {2246SrcRecordTy = SrcTy->getPointeeType();2247// No DestRecordTy.2248} else if (const PointerType *DestPTy = DestTy->getAs<PointerType>()) {2249SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();2250DestRecordTy = DestPTy->getPointeeType();2251} else {2252SrcRecordTy = SrcTy;2253DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();2254}22552256// C++ [class.cdtor]p5:2257// If the operand of the dynamic_cast refers to the object under2258// construction or destruction and the static type of the operand is not a2259// pointer to or object of the constructor or destructor’s own class or one2260// of its bases, the dynamic_cast results in undefined behavior.2261EmitTypeCheck(TCK_DynamicOperation, DCE->getExprLoc(), ThisAddr, SrcRecordTy);22622263if (DCE->isAlwaysNull()) {2264if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy)) {2265// Expression emission is expected to retain a valid insertion point.2266if (!Builder.GetInsertBlock())2267EmitBlock(createBasicBlock("dynamic_cast.unreachable"));2268return T;2269}2270}22712272assert(SrcRecordTy->isRecordType() && "source type must be a record type!");22732274// If the destination is effectively final, the cast succeeds if and only2275// if the dynamic type of the pointer is exactly the destination type.2276bool IsExact = !IsDynamicCastToVoid &&2277CGM.getCodeGenOpts().OptimizationLevel > 0 &&2278DestRecordTy->getAsCXXRecordDecl()->isEffectivelyFinal() &&2279CGM.getCXXABI().shouldEmitExactDynamicCast(DestRecordTy);22802281// C++ [expr.dynamic.cast]p4:2282// If the value of v is a null pointer value in the pointer case, the result2283// is the null pointer value of type T.2284bool ShouldNullCheckSrcValue =2285IsExact || CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(2286SrcTy->isPointerType(), SrcRecordTy);22872288llvm::BasicBlock *CastNull = nullptr;2289llvm::BasicBlock *CastNotNull = nullptr;2290llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");22912292if (ShouldNullCheckSrcValue) {2293CastNull = createBasicBlock("dynamic_cast.null");2294CastNotNull = createBasicBlock("dynamic_cast.notnull");22952296llvm::Value *IsNull = Builder.CreateIsNull(ThisAddr);2297Builder.CreateCondBr(IsNull, CastNull, CastNotNull);2298EmitBlock(CastNotNull);2299}23002301llvm::Value *Value;2302if (IsDynamicCastToVoid) {2303Value = CGM.getCXXABI().emitDynamicCastToVoid(*this, ThisAddr, SrcRecordTy);2304} else if (IsExact) {2305// If the destination type is effectively final, this pointer points to the2306// right type if and only if its vptr has the right value.2307Value = CGM.getCXXABI().emitExactDynamicCast(2308*this, ThisAddr, SrcRecordTy, DestTy, DestRecordTy, CastEnd, CastNull);2309} else {2310assert(DestRecordTy->isRecordType() &&2311"destination type must be a record type!");2312Value = CGM.getCXXABI().emitDynamicCastCall(*this, ThisAddr, SrcRecordTy,2313DestTy, DestRecordTy, CastEnd);2314}2315CastNotNull = Builder.GetInsertBlock();23162317llvm::Value *NullValue = nullptr;2318if (ShouldNullCheckSrcValue) {2319EmitBranch(CastEnd);23202321EmitBlock(CastNull);2322NullValue = EmitDynamicCastToNull(*this, DestTy);2323CastNull = Builder.GetInsertBlock();23242325EmitBranch(CastEnd);2326}23272328EmitBlock(CastEnd);23292330if (CastNull) {2331llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);2332PHI->addIncoming(Value, CastNotNull);2333PHI->addIncoming(NullValue, CastNull);23342335Value = PHI;2336}23372338return Value;2339}234023412342