10b57cec5SDimitry Andric //===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This contains code dealing with code generation of C++ expressions
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "CGCUDARuntime.h"
140b57cec5SDimitry Andric #include "CGCXXABI.h"
150b57cec5SDimitry Andric #include "CGDebugInfo.h"
160b57cec5SDimitry Andric #include "CGObjCRuntime.h"
170b57cec5SDimitry Andric #include "CodeGenFunction.h"
180b57cec5SDimitry Andric #include "ConstantEmitter.h"
190b57cec5SDimitry Andric #include "TargetInfo.h"
200b57cec5SDimitry Andric #include "clang/Basic/CodeGenOptions.h"
210b57cec5SDimitry Andric #include "clang/CodeGen/CGFunctionInfo.h"
220b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
230b57cec5SDimitry Andric 
240b57cec5SDimitry Andric using namespace clang;
250b57cec5SDimitry Andric using namespace CodeGen;
260b57cec5SDimitry Andric 
270b57cec5SDimitry Andric namespace {
280b57cec5SDimitry Andric struct MemberCallInfo {
290b57cec5SDimitry Andric   RequiredArgs ReqArgs;
300b57cec5SDimitry Andric   // Number of prefix arguments for the call. Ignores the `this` pointer.
310b57cec5SDimitry Andric   unsigned PrefixSize;
320b57cec5SDimitry Andric };
330b57cec5SDimitry Andric }
340b57cec5SDimitry Andric 
350b57cec5SDimitry Andric static MemberCallInfo
commonEmitCXXMemberOrOperatorCall(CodeGenFunction & CGF,const CXXMethodDecl * MD,llvm::Value * This,llvm::Value * ImplicitParam,QualType ImplicitParamTy,const CallExpr * CE,CallArgList & Args,CallArgList * RtlArgs)360b57cec5SDimitry Andric commonEmitCXXMemberOrOperatorCall(CodeGenFunction &CGF, const CXXMethodDecl *MD,
370b57cec5SDimitry Andric                                   llvm::Value *This, llvm::Value *ImplicitParam,
380b57cec5SDimitry Andric                                   QualType ImplicitParamTy, const CallExpr *CE,
390b57cec5SDimitry Andric                                   CallArgList &Args, CallArgList *RtlArgs) {
400b57cec5SDimitry Andric   assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) ||
410b57cec5SDimitry Andric          isa<CXXOperatorCallExpr>(CE));
420b57cec5SDimitry Andric   assert(MD->isInstance() &&
430b57cec5SDimitry Andric          "Trying to emit a member or operator call expr on a static method!");
440b57cec5SDimitry Andric 
450b57cec5SDimitry Andric   // Push the this ptr.
460b57cec5SDimitry Andric   const CXXRecordDecl *RD =
470b57cec5SDimitry Andric       CGF.CGM.getCXXABI().getThisArgumentTypeForMethod(MD);
480b57cec5SDimitry Andric   Args.add(RValue::get(This), CGF.getTypes().DeriveThisType(RD, MD));
490b57cec5SDimitry Andric 
500b57cec5SDimitry Andric   // If there is an implicit parameter (e.g. VTT), emit it.
510b57cec5SDimitry Andric   if (ImplicitParam) {
520b57cec5SDimitry Andric     Args.add(RValue::get(ImplicitParam), ImplicitParamTy);
530b57cec5SDimitry Andric   }
540b57cec5SDimitry Andric 
550b57cec5SDimitry Andric   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
560b57cec5SDimitry Andric   RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size());
570b57cec5SDimitry Andric   unsigned PrefixSize = Args.size() - 1;
580b57cec5SDimitry Andric 
590b57cec5SDimitry Andric   // And the rest of the call args.
600b57cec5SDimitry Andric   if (RtlArgs) {
610b57cec5SDimitry Andric     // Special case: if the caller emitted the arguments right-to-left already
620b57cec5SDimitry Andric     // (prior to emitting the *this argument), we're done. This happens for
630b57cec5SDimitry Andric     // assignment operators.
640b57cec5SDimitry Andric     Args.addFrom(*RtlArgs);
650b57cec5SDimitry Andric   } else if (CE) {
660b57cec5SDimitry Andric     // Special case: skip first argument of CXXOperatorCall (it is "this").
670b57cec5SDimitry Andric     unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0;
680b57cec5SDimitry Andric     CGF.EmitCallArgs(Args, FPT, drop_begin(CE->arguments(), ArgsToSkip),
690b57cec5SDimitry Andric                      CE->getDirectCallee());
700b57cec5SDimitry Andric   } else {
710b57cec5SDimitry Andric     assert(
720b57cec5SDimitry Andric         FPT->getNumParams() == 0 &&
730b57cec5SDimitry Andric         "No CallExpr specified for function with non-zero number of arguments");
740b57cec5SDimitry Andric   }
750b57cec5SDimitry Andric   return {required, PrefixSize};
760b57cec5SDimitry Andric }
770b57cec5SDimitry Andric 
EmitCXXMemberOrOperatorCall(const CXXMethodDecl * MD,const CGCallee & Callee,ReturnValueSlot ReturnValue,llvm::Value * This,llvm::Value * ImplicitParam,QualType ImplicitParamTy,const CallExpr * CE,CallArgList * RtlArgs)780b57cec5SDimitry Andric RValue CodeGenFunction::EmitCXXMemberOrOperatorCall(
790b57cec5SDimitry Andric     const CXXMethodDecl *MD, const CGCallee &Callee,
800b57cec5SDimitry Andric     ReturnValueSlot ReturnValue,
810b57cec5SDimitry Andric     llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,
820b57cec5SDimitry Andric     const CallExpr *CE, CallArgList *RtlArgs) {
830b57cec5SDimitry Andric   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
840b57cec5SDimitry Andric   CallArgList Args;
850b57cec5SDimitry Andric   MemberCallInfo CallInfo = commonEmitCXXMemberOrOperatorCall(
860b57cec5SDimitry Andric       *this, MD, This, ImplicitParam, ImplicitParamTy, CE, Args, RtlArgs);
870b57cec5SDimitry Andric   auto &FnInfo = CGM.getTypes().arrangeCXXMethodCall(
880b57cec5SDimitry Andric       Args, FPT, CallInfo.ReqArgs, CallInfo.PrefixSize);
890b57cec5SDimitry Andric   return EmitCall(FnInfo, Callee, ReturnValue, Args, nullptr,
905f7ddb14SDimitry Andric                   CE && CE == MustTailCall,
910b57cec5SDimitry Andric                   CE ? CE->getExprLoc() : SourceLocation());
920b57cec5SDimitry Andric }
930b57cec5SDimitry Andric 
EmitCXXDestructorCall(GlobalDecl Dtor,const CGCallee & Callee,llvm::Value * This,QualType ThisTy,llvm::Value * ImplicitParam,QualType ImplicitParamTy,const CallExpr * CE)940b57cec5SDimitry Andric RValue CodeGenFunction::EmitCXXDestructorCall(
950b57cec5SDimitry Andric     GlobalDecl Dtor, const CGCallee &Callee, llvm::Value *This, QualType ThisTy,
960b57cec5SDimitry Andric     llvm::Value *ImplicitParam, QualType ImplicitParamTy, const CallExpr *CE) {
970b57cec5SDimitry Andric   const CXXMethodDecl *DtorDecl = cast<CXXMethodDecl>(Dtor.getDecl());
980b57cec5SDimitry Andric 
990b57cec5SDimitry Andric   assert(!ThisTy.isNull());
1000b57cec5SDimitry Andric   assert(ThisTy->getAsCXXRecordDecl() == DtorDecl->getParent() &&
1010b57cec5SDimitry Andric          "Pointer/Object mixup");
1020b57cec5SDimitry Andric 
1030b57cec5SDimitry Andric   LangAS SrcAS = ThisTy.getAddressSpace();
1040b57cec5SDimitry Andric   LangAS DstAS = DtorDecl->getMethodQualifiers().getAddressSpace();
1050b57cec5SDimitry Andric   if (SrcAS != DstAS) {
1060b57cec5SDimitry Andric     QualType DstTy = DtorDecl->getThisType();
1070b57cec5SDimitry Andric     llvm::Type *NewType = CGM.getTypes().ConvertType(DstTy);
1080b57cec5SDimitry Andric     This = getTargetHooks().performAddrSpaceCast(*this, This, SrcAS, DstAS,
1090b57cec5SDimitry Andric                                                  NewType);
1100b57cec5SDimitry Andric   }
1110b57cec5SDimitry Andric 
1120b57cec5SDimitry Andric   CallArgList Args;
1130b57cec5SDimitry Andric   commonEmitCXXMemberOrOperatorCall(*this, DtorDecl, This, ImplicitParam,
1140b57cec5SDimitry Andric                                     ImplicitParamTy, CE, Args, nullptr);
1150b57cec5SDimitry Andric   return EmitCall(CGM.getTypes().arrangeCXXStructorDeclaration(Dtor), Callee,
1165f7ddb14SDimitry Andric                   ReturnValueSlot(), Args, nullptr, CE && CE == MustTailCall,
117c3ca3130SDimitry Andric                   CE ? CE->getExprLoc() : SourceLocation{});
1180b57cec5SDimitry Andric }
1190b57cec5SDimitry Andric 
EmitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr * E)1200b57cec5SDimitry Andric RValue CodeGenFunction::EmitCXXPseudoDestructorExpr(
1210b57cec5SDimitry Andric                                             const CXXPseudoDestructorExpr *E) {
1220b57cec5SDimitry Andric   QualType DestroyedType = E->getDestroyedType();
1230b57cec5SDimitry Andric   if (DestroyedType.hasStrongOrWeakObjCLifetime()) {
1240b57cec5SDimitry Andric     // Automatic Reference Counting:
1250b57cec5SDimitry Andric     //   If the pseudo-expression names a retainable object with weak or
1260b57cec5SDimitry Andric     //   strong lifetime, the object shall be released.
1270b57cec5SDimitry Andric     Expr *BaseExpr = E->getBase();
1280b57cec5SDimitry Andric     Address BaseValue = Address::invalid();
1290b57cec5SDimitry Andric     Qualifiers BaseQuals;
1300b57cec5SDimitry Andric 
1310b57cec5SDimitry Andric     // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
1320b57cec5SDimitry Andric     if (E->isArrow()) {
1330b57cec5SDimitry Andric       BaseValue = EmitPointerWithAlignment(BaseExpr);
134480093f4SDimitry Andric       const auto *PTy = BaseExpr->getType()->castAs<PointerType>();
1350b57cec5SDimitry Andric       BaseQuals = PTy->getPointeeType().getQualifiers();
1360b57cec5SDimitry Andric     } else {
1370b57cec5SDimitry Andric       LValue BaseLV = EmitLValue(BaseExpr);
138480093f4SDimitry Andric       BaseValue = BaseLV.getAddress(*this);
1390b57cec5SDimitry Andric       QualType BaseTy = BaseExpr->getType();
1400b57cec5SDimitry Andric       BaseQuals = BaseTy.getQualifiers();
1410b57cec5SDimitry Andric     }
1420b57cec5SDimitry Andric 
1430b57cec5SDimitry Andric     switch (DestroyedType.getObjCLifetime()) {
1440b57cec5SDimitry Andric     case Qualifiers::OCL_None:
1450b57cec5SDimitry Andric     case Qualifiers::OCL_ExplicitNone:
1460b57cec5SDimitry Andric     case Qualifiers::OCL_Autoreleasing:
1470b57cec5SDimitry Andric       break;
1480b57cec5SDimitry Andric 
1490b57cec5SDimitry Andric     case Qualifiers::OCL_Strong:
1500b57cec5SDimitry Andric       EmitARCRelease(Builder.CreateLoad(BaseValue,
1510b57cec5SDimitry Andric                         DestroyedType.isVolatileQualified()),
1520b57cec5SDimitry Andric                      ARCPreciseLifetime);
1530b57cec5SDimitry Andric       break;
1540b57cec5SDimitry Andric 
1550b57cec5SDimitry Andric     case Qualifiers::OCL_Weak:
1560b57cec5SDimitry Andric       EmitARCDestroyWeak(BaseValue);
1570b57cec5SDimitry Andric       break;
1580b57cec5SDimitry Andric     }
1590b57cec5SDimitry Andric   } else {
1600b57cec5SDimitry Andric     // C++ [expr.pseudo]p1:
1610b57cec5SDimitry Andric     //   The result shall only be used as the operand for the function call
1620b57cec5SDimitry Andric     //   operator (), and the result of such a call has type void. The only
1630b57cec5SDimitry Andric     //   effect is the evaluation of the postfix-expression before the dot or
1640b57cec5SDimitry Andric     //   arrow.
1650b57cec5SDimitry Andric     EmitIgnoredExpr(E->getBase());
1660b57cec5SDimitry Andric   }
1670b57cec5SDimitry Andric 
1680b57cec5SDimitry Andric   return RValue::get(nullptr);
1690b57cec5SDimitry Andric }
1700b57cec5SDimitry Andric 
getCXXRecord(const Expr * E)1710b57cec5SDimitry Andric static CXXRecordDecl *getCXXRecord(const Expr *E) {
1720b57cec5SDimitry Andric   QualType T = E->getType();
1730b57cec5SDimitry Andric   if (const PointerType *PTy = T->getAs<PointerType>())
1740b57cec5SDimitry Andric     T = PTy->getPointeeType();
1750b57cec5SDimitry Andric   const RecordType *Ty = T->castAs<RecordType>();
1760b57cec5SDimitry Andric   return cast<CXXRecordDecl>(Ty->getDecl());
1770b57cec5SDimitry Andric }
1780b57cec5SDimitry Andric 
1790b57cec5SDimitry Andric // Note: This function also emit constructor calls to support a MSVC
1800b57cec5SDimitry Andric // extensions allowing explicit constructor function call.
EmitCXXMemberCallExpr(const CXXMemberCallExpr * CE,ReturnValueSlot ReturnValue)1810b57cec5SDimitry Andric RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
1820b57cec5SDimitry Andric                                               ReturnValueSlot ReturnValue) {
1830b57cec5SDimitry Andric   const Expr *callee = CE->getCallee()->IgnoreParens();
1840b57cec5SDimitry Andric 
1850b57cec5SDimitry Andric   if (isa<BinaryOperator>(callee))
1860b57cec5SDimitry Andric     return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
1870b57cec5SDimitry Andric 
1880b57cec5SDimitry Andric   const MemberExpr *ME = cast<MemberExpr>(callee);
1890b57cec5SDimitry Andric   const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
1900b57cec5SDimitry Andric 
1910b57cec5SDimitry Andric   if (MD->isStatic()) {
1920b57cec5SDimitry Andric     // The method is static, emit it as we would a regular call.
1930b57cec5SDimitry Andric     CGCallee callee =
1940b57cec5SDimitry Andric         CGCallee::forDirect(CGM.GetAddrOfFunction(MD), GlobalDecl(MD));
1950b57cec5SDimitry Andric     return EmitCall(getContext().getPointerType(MD->getType()), callee, CE,
1960b57cec5SDimitry Andric                     ReturnValue);
1970b57cec5SDimitry Andric   }
1980b57cec5SDimitry Andric 
1990b57cec5SDimitry Andric   bool HasQualifier = ME->hasQualifier();
2000b57cec5SDimitry Andric   NestedNameSpecifier *Qualifier = HasQualifier ? ME->getQualifier() : nullptr;
2010b57cec5SDimitry Andric   bool IsArrow = ME->isArrow();
2020b57cec5SDimitry Andric   const Expr *Base = ME->getBase();
2030b57cec5SDimitry Andric 
2040b57cec5SDimitry Andric   return EmitCXXMemberOrOperatorMemberCallExpr(
2050b57cec5SDimitry Andric       CE, MD, ReturnValue, HasQualifier, Qualifier, IsArrow, Base);
2060b57cec5SDimitry Andric }
2070b57cec5SDimitry Andric 
EmitCXXMemberOrOperatorMemberCallExpr(const CallExpr * CE,const CXXMethodDecl * MD,ReturnValueSlot ReturnValue,bool HasQualifier,NestedNameSpecifier * Qualifier,bool IsArrow,const Expr * Base)2080b57cec5SDimitry Andric RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr(
2090b57cec5SDimitry Andric     const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue,
2100b57cec5SDimitry Andric     bool HasQualifier, NestedNameSpecifier *Qualifier, bool IsArrow,
2110b57cec5SDimitry Andric     const Expr *Base) {
2120b57cec5SDimitry Andric   assert(isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE));
2130b57cec5SDimitry Andric 
2140b57cec5SDimitry Andric   // Compute the object pointer.
2150b57cec5SDimitry Andric   bool CanUseVirtualCall = MD->isVirtual() && !HasQualifier;
2160b57cec5SDimitry Andric 
2170b57cec5SDimitry Andric   const CXXMethodDecl *DevirtualizedMethod = nullptr;
2180b57cec5SDimitry Andric   if (CanUseVirtualCall &&
2190b57cec5SDimitry Andric       MD->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) {
2200b57cec5SDimitry Andric     const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
2210b57cec5SDimitry Andric     DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
2220b57cec5SDimitry Andric     assert(DevirtualizedMethod);
2230b57cec5SDimitry Andric     const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
224af732203SDimitry Andric     const Expr *Inner = Base->IgnoreParenBaseCasts();
2250b57cec5SDimitry Andric     if (DevirtualizedMethod->getReturnType().getCanonicalType() !=
2260b57cec5SDimitry Andric         MD->getReturnType().getCanonicalType())
2270b57cec5SDimitry Andric       // If the return types are not the same, this might be a case where more
2280b57cec5SDimitry Andric       // code needs to run to compensate for it. For example, the derived
2290b57cec5SDimitry Andric       // method might return a type that inherits form from the return
2300b57cec5SDimitry Andric       // type of MD and has a prefix.
2310b57cec5SDimitry Andric       // For now we just avoid devirtualizing these covariant cases.
2320b57cec5SDimitry Andric       DevirtualizedMethod = nullptr;
2330b57cec5SDimitry Andric     else if (getCXXRecord(Inner) == DevirtualizedClass)
2340b57cec5SDimitry Andric       // If the class of the Inner expression is where the dynamic method
2350b57cec5SDimitry Andric       // is defined, build the this pointer from it.
2360b57cec5SDimitry Andric       Base = Inner;
2370b57cec5SDimitry Andric     else if (getCXXRecord(Base) != DevirtualizedClass) {
2380b57cec5SDimitry Andric       // If the method is defined in a class that is not the best dynamic
2390b57cec5SDimitry Andric       // one or the one of the full expression, we would have to build
2400b57cec5SDimitry Andric       // a derived-to-base cast to compute the correct this pointer, but
2410b57cec5SDimitry Andric       // we don't have support for that yet, so do a virtual call.
2420b57cec5SDimitry Andric       DevirtualizedMethod = nullptr;
2430b57cec5SDimitry Andric     }
2440b57cec5SDimitry Andric   }
2450b57cec5SDimitry Andric 
246480093f4SDimitry Andric   bool TrivialForCodegen =
247480093f4SDimitry Andric       MD->isTrivial() || (MD->isDefaulted() && MD->getParent()->isUnion());
248480093f4SDimitry Andric   bool TrivialAssignment =
249480093f4SDimitry Andric       TrivialForCodegen &&
250480093f4SDimitry Andric       (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
251480093f4SDimitry Andric       !MD->getParent()->mayInsertExtraPadding();
252480093f4SDimitry Andric 
2530b57cec5SDimitry Andric   // C++17 demands that we evaluate the RHS of a (possibly-compound) assignment
2540b57cec5SDimitry Andric   // operator before the LHS.
2550b57cec5SDimitry Andric   CallArgList RtlArgStorage;
2560b57cec5SDimitry Andric   CallArgList *RtlArgs = nullptr;
257480093f4SDimitry Andric   LValue TrivialAssignmentRHS;
2580b57cec5SDimitry Andric   if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
2590b57cec5SDimitry Andric     if (OCE->isAssignmentOp()) {
260480093f4SDimitry Andric       if (TrivialAssignment) {
261480093f4SDimitry Andric         TrivialAssignmentRHS = EmitLValue(CE->getArg(1));
262480093f4SDimitry Andric       } else {
2630b57cec5SDimitry Andric         RtlArgs = &RtlArgStorage;
2640b57cec5SDimitry Andric         EmitCallArgs(*RtlArgs, MD->getType()->castAs<FunctionProtoType>(),
2650b57cec5SDimitry Andric                      drop_begin(CE->arguments(), 1), CE->getDirectCallee(),
2660b57cec5SDimitry Andric                      /*ParamsToSkip*/0, EvaluationOrder::ForceRightToLeft);
2670b57cec5SDimitry Andric       }
2680b57cec5SDimitry Andric     }
269480093f4SDimitry Andric   }
2700b57cec5SDimitry Andric 
2710b57cec5SDimitry Andric   LValue This;
2720b57cec5SDimitry Andric   if (IsArrow) {
2730b57cec5SDimitry Andric     LValueBaseInfo BaseInfo;
2740b57cec5SDimitry Andric     TBAAAccessInfo TBAAInfo;
2750b57cec5SDimitry Andric     Address ThisValue = EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo);
2760b57cec5SDimitry Andric     This = MakeAddrLValue(ThisValue, Base->getType(), BaseInfo, TBAAInfo);
2770b57cec5SDimitry Andric   } else {
2780b57cec5SDimitry Andric     This = EmitLValue(Base);
2790b57cec5SDimitry Andric   }
2800b57cec5SDimitry Andric 
2810b57cec5SDimitry Andric   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2820b57cec5SDimitry Andric     // This is the MSVC p->Ctor::Ctor(...) extension. We assume that's
2830b57cec5SDimitry Andric     // constructing a new complete object of type Ctor.
2840b57cec5SDimitry Andric     assert(!RtlArgs);
2850b57cec5SDimitry Andric     assert(ReturnValue.isNull() && "Constructor shouldn't have return value");
2860b57cec5SDimitry Andric     CallArgList Args;
2870b57cec5SDimitry Andric     commonEmitCXXMemberOrOperatorCall(
288480093f4SDimitry Andric         *this, Ctor, This.getPointer(*this), /*ImplicitParam=*/nullptr,
2890b57cec5SDimitry Andric         /*ImplicitParamTy=*/QualType(), CE, Args, nullptr);
2900b57cec5SDimitry Andric 
2910b57cec5SDimitry Andric     EmitCXXConstructorCall(Ctor, Ctor_Complete, /*ForVirtualBase=*/false,
292480093f4SDimitry Andric                            /*Delegating=*/false, This.getAddress(*this), Args,
2930b57cec5SDimitry Andric                            AggValueSlot::DoesNotOverlap, CE->getExprLoc(),
2940b57cec5SDimitry Andric                            /*NewPointerIsChecked=*/false);
2950b57cec5SDimitry Andric     return RValue::get(nullptr);
2960b57cec5SDimitry Andric   }
2970b57cec5SDimitry Andric 
298480093f4SDimitry Andric   if (TrivialForCodegen) {
299480093f4SDimitry Andric     if (isa<CXXDestructorDecl>(MD))
300480093f4SDimitry Andric       return RValue::get(nullptr);
301480093f4SDimitry Andric 
302480093f4SDimitry Andric     if (TrivialAssignment) {
3030b57cec5SDimitry Andric       // We don't like to generate the trivial copy/move assignment operator
3040b57cec5SDimitry Andric       // when it isn't necessary; just produce the proper effect here.
305480093f4SDimitry Andric       // It's important that we use the result of EmitLValue here rather than
306480093f4SDimitry Andric       // emitting call arguments, in order to preserve TBAA information from
307480093f4SDimitry Andric       // the RHS.
3080b57cec5SDimitry Andric       LValue RHS = isa<CXXOperatorCallExpr>(CE)
309480093f4SDimitry Andric                        ? TrivialAssignmentRHS
3100b57cec5SDimitry Andric                        : EmitLValue(*CE->arg_begin());
3110b57cec5SDimitry Andric       EmitAggregateAssign(This, RHS, CE->getType());
312480093f4SDimitry Andric       return RValue::get(This.getPointer(*this));
3130b57cec5SDimitry Andric     }
314480093f4SDimitry Andric 
315480093f4SDimitry Andric     assert(MD->getParent()->mayInsertExtraPadding() &&
316480093f4SDimitry Andric            "unknown trivial member function");
3170b57cec5SDimitry Andric   }
3180b57cec5SDimitry Andric 
3190b57cec5SDimitry Andric   // Compute the function type we're calling.
3200b57cec5SDimitry Andric   const CXXMethodDecl *CalleeDecl =
3210b57cec5SDimitry Andric       DevirtualizedMethod ? DevirtualizedMethod : MD;
3220b57cec5SDimitry Andric   const CGFunctionInfo *FInfo = nullptr;
3230b57cec5SDimitry Andric   if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
3240b57cec5SDimitry Andric     FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
3250b57cec5SDimitry Andric         GlobalDecl(Dtor, Dtor_Complete));
3260b57cec5SDimitry Andric   else
3270b57cec5SDimitry Andric     FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
3280b57cec5SDimitry Andric 
3290b57cec5SDimitry Andric   llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
3300b57cec5SDimitry Andric 
3310b57cec5SDimitry Andric   // C++11 [class.mfct.non-static]p2:
3320b57cec5SDimitry Andric   //   If a non-static member function of a class X is called for an object that
3330b57cec5SDimitry Andric   //   is not of type X, or of a type derived from X, the behavior is undefined.
3340b57cec5SDimitry Andric   SourceLocation CallLoc;
3350b57cec5SDimitry Andric   ASTContext &C = getContext();
3360b57cec5SDimitry Andric   if (CE)
3370b57cec5SDimitry Andric     CallLoc = CE->getExprLoc();
3380b57cec5SDimitry Andric 
3390b57cec5SDimitry Andric   SanitizerSet SkippedChecks;
3400b57cec5SDimitry Andric   if (const auto *CMCE = dyn_cast<CXXMemberCallExpr>(CE)) {
3410b57cec5SDimitry Andric     auto *IOA = CMCE->getImplicitObjectArgument();
3420b57cec5SDimitry Andric     bool IsImplicitObjectCXXThis = IsWrappedCXXThis(IOA);
3430b57cec5SDimitry Andric     if (IsImplicitObjectCXXThis)
3440b57cec5SDimitry Andric       SkippedChecks.set(SanitizerKind::Alignment, true);
3450b57cec5SDimitry Andric     if (IsImplicitObjectCXXThis || isa<DeclRefExpr>(IOA))
3460b57cec5SDimitry Andric       SkippedChecks.set(SanitizerKind::Null, true);
3470b57cec5SDimitry Andric   }
348480093f4SDimitry Andric   EmitTypeCheck(CodeGenFunction::TCK_MemberCall, CallLoc,
349480093f4SDimitry Andric                 This.getPointer(*this),
3500b57cec5SDimitry Andric                 C.getRecordType(CalleeDecl->getParent()),
3510b57cec5SDimitry Andric                 /*Alignment=*/CharUnits::Zero(), SkippedChecks);
3520b57cec5SDimitry Andric 
3530b57cec5SDimitry Andric   // C++ [class.virtual]p12:
3540b57cec5SDimitry Andric   //   Explicit qualification with the scope operator (5.1) suppresses the
3550b57cec5SDimitry Andric   //   virtual call mechanism.
3560b57cec5SDimitry Andric   //
3570b57cec5SDimitry Andric   // We also don't emit a virtual call if the base expression has a record type
3580b57cec5SDimitry Andric   // because then we know what the type is.
3590b57cec5SDimitry Andric   bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
3600b57cec5SDimitry Andric 
3610b57cec5SDimitry Andric   if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl)) {
3620b57cec5SDimitry Andric     assert(CE->arg_begin() == CE->arg_end() &&
3630b57cec5SDimitry Andric            "Destructor shouldn't have explicit parameters");
3640b57cec5SDimitry Andric     assert(ReturnValue.isNull() && "Destructor shouldn't have return value");
3650b57cec5SDimitry Andric     if (UseVirtualCall) {
366480093f4SDimitry Andric       CGM.getCXXABI().EmitVirtualDestructorCall(*this, Dtor, Dtor_Complete,
367480093f4SDimitry Andric                                                 This.getAddress(*this),
3680b57cec5SDimitry Andric                                                 cast<CXXMemberCallExpr>(CE));
3690b57cec5SDimitry Andric     } else {
3700b57cec5SDimitry Andric       GlobalDecl GD(Dtor, Dtor_Complete);
3710b57cec5SDimitry Andric       CGCallee Callee;
3720b57cec5SDimitry Andric       if (getLangOpts().AppleKext && Dtor->isVirtual() && HasQualifier)
3730b57cec5SDimitry Andric         Callee = BuildAppleKextVirtualCall(Dtor, Qualifier, Ty);
3740b57cec5SDimitry Andric       else if (!DevirtualizedMethod)
3750b57cec5SDimitry Andric         Callee =
3760b57cec5SDimitry Andric             CGCallee::forDirect(CGM.getAddrOfCXXStructor(GD, FInfo, Ty), GD);
3770b57cec5SDimitry Andric       else {
3780b57cec5SDimitry Andric         Callee = CGCallee::forDirect(CGM.GetAddrOfFunction(GD, Ty), GD);
3790b57cec5SDimitry Andric       }
3800b57cec5SDimitry Andric 
3810b57cec5SDimitry Andric       QualType ThisTy =
3820b57cec5SDimitry Andric           IsArrow ? Base->getType()->getPointeeType() : Base->getType();
383480093f4SDimitry Andric       EmitCXXDestructorCall(GD, Callee, This.getPointer(*this), ThisTy,
3840b57cec5SDimitry Andric                             /*ImplicitParam=*/nullptr,
385c3ca3130SDimitry Andric                             /*ImplicitParamTy=*/QualType(), CE);
3860b57cec5SDimitry Andric     }
3870b57cec5SDimitry Andric     return RValue::get(nullptr);
3880b57cec5SDimitry Andric   }
3890b57cec5SDimitry Andric 
3900b57cec5SDimitry Andric   // FIXME: Uses of 'MD' past this point need to be audited. We may need to use
3910b57cec5SDimitry Andric   // 'CalleeDecl' instead.
3920b57cec5SDimitry Andric 
3930b57cec5SDimitry Andric   CGCallee Callee;
3940b57cec5SDimitry Andric   if (UseVirtualCall) {
395480093f4SDimitry Andric     Callee = CGCallee::forVirtual(CE, MD, This.getAddress(*this), Ty);
3960b57cec5SDimitry Andric   } else {
3970b57cec5SDimitry Andric     if (SanOpts.has(SanitizerKind::CFINVCall) &&
3980b57cec5SDimitry Andric         MD->getParent()->isDynamicClass()) {
3990b57cec5SDimitry Andric       llvm::Value *VTable;
4000b57cec5SDimitry Andric       const CXXRecordDecl *RD;
401480093f4SDimitry Andric       std::tie(VTable, RD) = CGM.getCXXABI().LoadVTablePtr(
402480093f4SDimitry Andric           *this, This.getAddress(*this), CalleeDecl->getParent());
4030b57cec5SDimitry Andric       EmitVTablePtrCheckForCall(RD, VTable, CFITCK_NVCall, CE->getBeginLoc());
4040b57cec5SDimitry Andric     }
4050b57cec5SDimitry Andric 
4060b57cec5SDimitry Andric     if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
4070b57cec5SDimitry Andric       Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
4080b57cec5SDimitry Andric     else if (!DevirtualizedMethod)
4090b57cec5SDimitry Andric       Callee =
4100b57cec5SDimitry Andric           CGCallee::forDirect(CGM.GetAddrOfFunction(MD, Ty), GlobalDecl(MD));
4110b57cec5SDimitry Andric     else {
4120b57cec5SDimitry Andric       Callee =
4130b57cec5SDimitry Andric           CGCallee::forDirect(CGM.GetAddrOfFunction(DevirtualizedMethod, Ty),
4140b57cec5SDimitry Andric                               GlobalDecl(DevirtualizedMethod));
4150b57cec5SDimitry Andric     }
4160b57cec5SDimitry Andric   }
4170b57cec5SDimitry Andric 
4180b57cec5SDimitry Andric   if (MD->isVirtual()) {
4190b57cec5SDimitry Andric     Address NewThisAddr =
4200b57cec5SDimitry Andric         CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
421480093f4SDimitry Andric             *this, CalleeDecl, This.getAddress(*this), UseVirtualCall);
4220b57cec5SDimitry Andric     This.setAddress(NewThisAddr);
4230b57cec5SDimitry Andric   }
4240b57cec5SDimitry Andric 
4250b57cec5SDimitry Andric   return EmitCXXMemberOrOperatorCall(
426480093f4SDimitry Andric       CalleeDecl, Callee, ReturnValue, This.getPointer(*this),
4270b57cec5SDimitry Andric       /*ImplicitParam=*/nullptr, QualType(), CE, RtlArgs);
4280b57cec5SDimitry Andric }
4290b57cec5SDimitry Andric 
4300b57cec5SDimitry Andric RValue
EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr * E,ReturnValueSlot ReturnValue)4310b57cec5SDimitry Andric CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
4320b57cec5SDimitry Andric                                               ReturnValueSlot ReturnValue) {
4330b57cec5SDimitry Andric   const BinaryOperator *BO =
4340b57cec5SDimitry Andric       cast<BinaryOperator>(E->getCallee()->IgnoreParens());
4350b57cec5SDimitry Andric   const Expr *BaseExpr = BO->getLHS();
4360b57cec5SDimitry Andric   const Expr *MemFnExpr = BO->getRHS();
4370b57cec5SDimitry Andric 
438a7dea167SDimitry Andric   const auto *MPT = MemFnExpr->getType()->castAs<MemberPointerType>();
439a7dea167SDimitry Andric   const auto *FPT = MPT->getPointeeType()->castAs<FunctionProtoType>();
440a7dea167SDimitry Andric   const auto *RD =
441a7dea167SDimitry Andric       cast<CXXRecordDecl>(MPT->getClass()->castAs<RecordType>()->getDecl());
4420b57cec5SDimitry Andric 
4430b57cec5SDimitry Andric   // Emit the 'this' pointer.
4440b57cec5SDimitry Andric   Address This = Address::invalid();
4450b57cec5SDimitry Andric   if (BO->getOpcode() == BO_PtrMemI)
4460b57cec5SDimitry Andric     This = EmitPointerWithAlignment(BaseExpr);
4470b57cec5SDimitry Andric   else
448480093f4SDimitry Andric     This = EmitLValue(BaseExpr).getAddress(*this);
4490b57cec5SDimitry Andric 
4500b57cec5SDimitry Andric   EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This.getPointer(),
4510b57cec5SDimitry Andric                 QualType(MPT->getClass(), 0));
4520b57cec5SDimitry Andric 
4530b57cec5SDimitry Andric   // Get the member function pointer.
4540b57cec5SDimitry Andric   llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
4550b57cec5SDimitry Andric 
4560b57cec5SDimitry Andric   // Ask the ABI to load the callee.  Note that This is modified.
4570b57cec5SDimitry Andric   llvm::Value *ThisPtrForCall = nullptr;
4580b57cec5SDimitry Andric   CGCallee Callee =
4590b57cec5SDimitry Andric     CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This,
4600b57cec5SDimitry Andric                                              ThisPtrForCall, MemFnPtr, MPT);
4610b57cec5SDimitry Andric 
4620b57cec5SDimitry Andric   CallArgList Args;
4630b57cec5SDimitry Andric 
4640b57cec5SDimitry Andric   QualType ThisType =
4650b57cec5SDimitry Andric     getContext().getPointerType(getContext().getTagDeclType(RD));
4660b57cec5SDimitry Andric 
4670b57cec5SDimitry Andric   // Push the this ptr.
4680b57cec5SDimitry Andric   Args.add(RValue::get(ThisPtrForCall), ThisType);
4690b57cec5SDimitry Andric 
4700b57cec5SDimitry Andric   RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1);
4710b57cec5SDimitry Andric 
4720b57cec5SDimitry Andric   // And the rest of the call args
4730b57cec5SDimitry Andric   EmitCallArgs(Args, FPT, E->arguments());
4740b57cec5SDimitry Andric   return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required,
4750b57cec5SDimitry Andric                                                       /*PrefixSize=*/0),
4765f7ddb14SDimitry Andric                   Callee, ReturnValue, Args, nullptr, E == MustTailCall,
4775f7ddb14SDimitry Andric                   E->getExprLoc());
4780b57cec5SDimitry Andric }
4790b57cec5SDimitry Andric 
4800b57cec5SDimitry Andric RValue
EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr * E,const CXXMethodDecl * MD,ReturnValueSlot ReturnValue)4810b57cec5SDimitry Andric CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
4820b57cec5SDimitry Andric                                                const CXXMethodDecl *MD,
4830b57cec5SDimitry Andric                                                ReturnValueSlot ReturnValue) {
4840b57cec5SDimitry Andric   assert(MD->isInstance() &&
4850b57cec5SDimitry Andric          "Trying to emit a member call expr on a static method!");
4860b57cec5SDimitry Andric   return EmitCXXMemberOrOperatorMemberCallExpr(
4870b57cec5SDimitry Andric       E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr,
4880b57cec5SDimitry Andric       /*IsArrow=*/false, E->getArg(0));
4890b57cec5SDimitry Andric }
4900b57cec5SDimitry Andric 
EmitCUDAKernelCallExpr(const CUDAKernelCallExpr * E,ReturnValueSlot ReturnValue)4910b57cec5SDimitry Andric RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
4920b57cec5SDimitry Andric                                                ReturnValueSlot ReturnValue) {
4930b57cec5SDimitry Andric   return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
4940b57cec5SDimitry Andric }
4950b57cec5SDimitry Andric 
EmitNullBaseClassInitialization(CodeGenFunction & CGF,Address DestPtr,const CXXRecordDecl * Base)4960b57cec5SDimitry Andric static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
4970b57cec5SDimitry Andric                                             Address DestPtr,
4980b57cec5SDimitry Andric                                             const CXXRecordDecl *Base) {
4990b57cec5SDimitry Andric   if (Base->isEmpty())
5000b57cec5SDimitry Andric     return;
5010b57cec5SDimitry Andric 
5020b57cec5SDimitry Andric   DestPtr = CGF.Builder.CreateElementBitCast(DestPtr, CGF.Int8Ty);
5030b57cec5SDimitry Andric 
5040b57cec5SDimitry Andric   const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
5050b57cec5SDimitry Andric   CharUnits NVSize = Layout.getNonVirtualSize();
5060b57cec5SDimitry Andric 
5070b57cec5SDimitry Andric   // We cannot simply zero-initialize the entire base sub-object if vbptrs are
5080b57cec5SDimitry Andric   // present, they are initialized by the most derived class before calling the
5090b57cec5SDimitry Andric   // constructor.
5100b57cec5SDimitry Andric   SmallVector<std::pair<CharUnits, CharUnits>, 1> Stores;
5110b57cec5SDimitry Andric   Stores.emplace_back(CharUnits::Zero(), NVSize);
5120b57cec5SDimitry Andric 
5130b57cec5SDimitry Andric   // Each store is split by the existence of a vbptr.
5140b57cec5SDimitry Andric   CharUnits VBPtrWidth = CGF.getPointerSize();
5150b57cec5SDimitry Andric   std::vector<CharUnits> VBPtrOffsets =
5160b57cec5SDimitry Andric       CGF.CGM.getCXXABI().getVBPtrOffsets(Base);
5170b57cec5SDimitry Andric   for (CharUnits VBPtrOffset : VBPtrOffsets) {
5180b57cec5SDimitry Andric     // Stop before we hit any virtual base pointers located in virtual bases.
5190b57cec5SDimitry Andric     if (VBPtrOffset >= NVSize)
5200b57cec5SDimitry Andric       break;
5210b57cec5SDimitry Andric     std::pair<CharUnits, CharUnits> LastStore = Stores.pop_back_val();
5220b57cec5SDimitry Andric     CharUnits LastStoreOffset = LastStore.first;
5230b57cec5SDimitry Andric     CharUnits LastStoreSize = LastStore.second;
5240b57cec5SDimitry Andric 
5250b57cec5SDimitry Andric     CharUnits SplitBeforeOffset = LastStoreOffset;
5260b57cec5SDimitry Andric     CharUnits SplitBeforeSize = VBPtrOffset - SplitBeforeOffset;
5270b57cec5SDimitry Andric     assert(!SplitBeforeSize.isNegative() && "negative store size!");
5280b57cec5SDimitry Andric     if (!SplitBeforeSize.isZero())
5290b57cec5SDimitry Andric       Stores.emplace_back(SplitBeforeOffset, SplitBeforeSize);
5300b57cec5SDimitry Andric 
5310b57cec5SDimitry Andric     CharUnits SplitAfterOffset = VBPtrOffset + VBPtrWidth;
5320b57cec5SDimitry Andric     CharUnits SplitAfterSize = LastStoreSize - SplitAfterOffset;
5330b57cec5SDimitry Andric     assert(!SplitAfterSize.isNegative() && "negative store size!");
5340b57cec5SDimitry Andric     if (!SplitAfterSize.isZero())
5350b57cec5SDimitry Andric       Stores.emplace_back(SplitAfterOffset, SplitAfterSize);
5360b57cec5SDimitry Andric   }
5370b57cec5SDimitry Andric 
5380b57cec5SDimitry Andric   // If the type contains a pointer to data member we can't memset it to zero.
5390b57cec5SDimitry Andric   // Instead, create a null constant and copy it to the destination.
5400b57cec5SDimitry Andric   // TODO: there are other patterns besides zero that we can usefully memset,
5410b57cec5SDimitry Andric   // like -1, which happens to be the pattern used by member-pointers.
5420b57cec5SDimitry Andric   // TODO: isZeroInitializable can be over-conservative in the case where a
5430b57cec5SDimitry Andric   // virtual base contains a member pointer.
5440b57cec5SDimitry Andric   llvm::Constant *NullConstantForBase = CGF.CGM.EmitNullConstantForBase(Base);
5450b57cec5SDimitry Andric   if (!NullConstantForBase->isNullValue()) {
5460b57cec5SDimitry Andric     llvm::GlobalVariable *NullVariable = new llvm::GlobalVariable(
5470b57cec5SDimitry Andric         CGF.CGM.getModule(), NullConstantForBase->getType(),
5480b57cec5SDimitry Andric         /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage,
5490b57cec5SDimitry Andric         NullConstantForBase, Twine());
5500b57cec5SDimitry Andric 
5510b57cec5SDimitry Andric     CharUnits Align = std::max(Layout.getNonVirtualAlignment(),
5520b57cec5SDimitry Andric                                DestPtr.getAlignment());
553a7dea167SDimitry Andric     NullVariable->setAlignment(Align.getAsAlign());
5540b57cec5SDimitry Andric 
5550b57cec5SDimitry Andric     Address SrcPtr = Address(CGF.EmitCastToVoidPtr(NullVariable), Align);
5560b57cec5SDimitry Andric 
5570b57cec5SDimitry Andric     // Get and call the appropriate llvm.memcpy overload.
5580b57cec5SDimitry Andric     for (std::pair<CharUnits, CharUnits> Store : Stores) {
5590b57cec5SDimitry Andric       CharUnits StoreOffset = Store.first;
5600b57cec5SDimitry Andric       CharUnits StoreSize = Store.second;
5610b57cec5SDimitry Andric       llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
5620b57cec5SDimitry Andric       CGF.Builder.CreateMemCpy(
5630b57cec5SDimitry Andric           CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
5640b57cec5SDimitry Andric           CGF.Builder.CreateConstInBoundsByteGEP(SrcPtr, StoreOffset),
5650b57cec5SDimitry Andric           StoreSizeVal);
5660b57cec5SDimitry Andric     }
5670b57cec5SDimitry Andric 
5680b57cec5SDimitry Andric   // Otherwise, just memset the whole thing to zero.  This is legal
5690b57cec5SDimitry Andric   // because in LLVM, all default initializers (other than the ones we just
5700b57cec5SDimitry Andric   // handled above) are guaranteed to have a bit pattern of all zeros.
5710b57cec5SDimitry Andric   } else {
5720b57cec5SDimitry Andric     for (std::pair<CharUnits, CharUnits> Store : Stores) {
5730b57cec5SDimitry Andric       CharUnits StoreOffset = Store.first;
5740b57cec5SDimitry Andric       CharUnits StoreSize = Store.second;
5750b57cec5SDimitry Andric       llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
5760b57cec5SDimitry Andric       CGF.Builder.CreateMemSet(
5770b57cec5SDimitry Andric           CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
5780b57cec5SDimitry Andric           CGF.Builder.getInt8(0), StoreSizeVal);
5790b57cec5SDimitry Andric     }
5800b57cec5SDimitry Andric   }
5810b57cec5SDimitry Andric }
5820b57cec5SDimitry Andric 
5830b57cec5SDimitry Andric void
EmitCXXConstructExpr(const CXXConstructExpr * E,AggValueSlot Dest)5840b57cec5SDimitry Andric CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
5850b57cec5SDimitry Andric                                       AggValueSlot Dest) {
5860b57cec5SDimitry Andric   assert(!Dest.isIgnored() && "Must have a destination!");
5870b57cec5SDimitry Andric   const CXXConstructorDecl *CD = E->getConstructor();
5880b57cec5SDimitry Andric 
5890b57cec5SDimitry Andric   // If we require zero initialization before (or instead of) calling the
5900b57cec5SDimitry Andric   // constructor, as can be the case with a non-user-provided default
5910b57cec5SDimitry Andric   // constructor, emit the zero initialization now, unless destination is
5920b57cec5SDimitry Andric   // already zeroed.
5930b57cec5SDimitry Andric   if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
5940b57cec5SDimitry Andric     switch (E->getConstructionKind()) {
5950b57cec5SDimitry Andric     case CXXConstructExpr::CK_Delegating:
5960b57cec5SDimitry Andric     case CXXConstructExpr::CK_Complete:
5970b57cec5SDimitry Andric       EmitNullInitialization(Dest.getAddress(), E->getType());
5980b57cec5SDimitry Andric       break;
5990b57cec5SDimitry Andric     case CXXConstructExpr::CK_VirtualBase:
6000b57cec5SDimitry Andric     case CXXConstructExpr::CK_NonVirtualBase:
6010b57cec5SDimitry Andric       EmitNullBaseClassInitialization(*this, Dest.getAddress(),
6020b57cec5SDimitry Andric                                       CD->getParent());
6030b57cec5SDimitry Andric       break;
6040b57cec5SDimitry Andric     }
6050b57cec5SDimitry Andric   }
6060b57cec5SDimitry Andric 
6070b57cec5SDimitry Andric   // If this is a call to a trivial default constructor, do nothing.
6080b57cec5SDimitry Andric   if (CD->isTrivial() && CD->isDefaultConstructor())
6090b57cec5SDimitry Andric     return;
6100b57cec5SDimitry Andric 
6110b57cec5SDimitry Andric   // Elide the constructor if we're constructing from a temporary.
6120b57cec5SDimitry Andric   if (getLangOpts().ElideConstructors && E->isElidable()) {
613*7224d412SDimitry Andric     // FIXME: This only handles the simplest case, where the source object
614*7224d412SDimitry Andric     //        is passed directly as the first argument to the constructor.
615*7224d412SDimitry Andric     //        This should also handle stepping though implicit casts and
616*7224d412SDimitry Andric     //        conversion sequences which involve two steps, with a
617*7224d412SDimitry Andric     //        conversion operator followed by a converting constructor.
618*7224d412SDimitry Andric     const Expr *SrcObj = E->getArg(0);
619*7224d412SDimitry Andric     assert(SrcObj->isTemporaryObject(getContext(), CD->getParent()));
620*7224d412SDimitry Andric     assert(
621*7224d412SDimitry Andric         getContext().hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
622*7224d412SDimitry Andric     EmitAggExpr(SrcObj, Dest);
6230b57cec5SDimitry Andric     return;
6240b57cec5SDimitry Andric   }
6250b57cec5SDimitry Andric 
6260b57cec5SDimitry Andric   if (const ArrayType *arrayType
6270b57cec5SDimitry Andric         = getContext().getAsArrayType(E->getType())) {
6280b57cec5SDimitry Andric     EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddress(), E,
6290b57cec5SDimitry Andric                                Dest.isSanitizerChecked());
6300b57cec5SDimitry Andric   } else {
6310b57cec5SDimitry Andric     CXXCtorType Type = Ctor_Complete;
6320b57cec5SDimitry Andric     bool ForVirtualBase = false;
6330b57cec5SDimitry Andric     bool Delegating = false;
6340b57cec5SDimitry Andric 
6350b57cec5SDimitry Andric     switch (E->getConstructionKind()) {
6360b57cec5SDimitry Andric      case CXXConstructExpr::CK_Delegating:
6370b57cec5SDimitry Andric       // We should be emitting a constructor; GlobalDecl will assert this
6380b57cec5SDimitry Andric       Type = CurGD.getCtorType();
6390b57cec5SDimitry Andric       Delegating = true;
6400b57cec5SDimitry Andric       break;
6410b57cec5SDimitry Andric 
6420b57cec5SDimitry Andric      case CXXConstructExpr::CK_Complete:
6430b57cec5SDimitry Andric       Type = Ctor_Complete;
6440b57cec5SDimitry Andric       break;
6450b57cec5SDimitry Andric 
6460b57cec5SDimitry Andric      case CXXConstructExpr::CK_VirtualBase:
6470b57cec5SDimitry Andric       ForVirtualBase = true;
6480b57cec5SDimitry Andric       LLVM_FALLTHROUGH;
6490b57cec5SDimitry Andric 
6500b57cec5SDimitry Andric      case CXXConstructExpr::CK_NonVirtualBase:
6510b57cec5SDimitry Andric       Type = Ctor_Base;
6520b57cec5SDimitry Andric      }
6530b57cec5SDimitry Andric 
6540b57cec5SDimitry Andric      // Call the constructor.
6550b57cec5SDimitry Andric      EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating, Dest, E);
6560b57cec5SDimitry Andric   }
6570b57cec5SDimitry Andric }
6580b57cec5SDimitry Andric 
EmitSynthesizedCXXCopyCtor(Address Dest,Address Src,const Expr * Exp)6590b57cec5SDimitry Andric void CodeGenFunction::EmitSynthesizedCXXCopyCtor(Address Dest, Address Src,
6600b57cec5SDimitry Andric                                                  const Expr *Exp) {
6610b57cec5SDimitry Andric   if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
6620b57cec5SDimitry Andric     Exp = E->getSubExpr();
6630b57cec5SDimitry Andric   assert(isa<CXXConstructExpr>(Exp) &&
6640b57cec5SDimitry Andric          "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
6650b57cec5SDimitry Andric   const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
6660b57cec5SDimitry Andric   const CXXConstructorDecl *CD = E->getConstructor();
6670b57cec5SDimitry Andric   RunCleanupsScope Scope(*this);
6680b57cec5SDimitry Andric 
6690b57cec5SDimitry Andric   // If we require zero initialization before (or instead of) calling the
6700b57cec5SDimitry Andric   // constructor, as can be the case with a non-user-provided default
6710b57cec5SDimitry Andric   // constructor, emit the zero initialization now.
6720b57cec5SDimitry Andric   // FIXME. Do I still need this for a copy ctor synthesis?
6730b57cec5SDimitry Andric   if (E->requiresZeroInitialization())
6740b57cec5SDimitry Andric     EmitNullInitialization(Dest, E->getType());
6750b57cec5SDimitry Andric 
6760b57cec5SDimitry Andric   assert(!getContext().getAsConstantArrayType(E->getType())
6770b57cec5SDimitry Andric          && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
6780b57cec5SDimitry Andric   EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E);
6790b57cec5SDimitry Andric }
6800b57cec5SDimitry Andric 
CalculateCookiePadding(CodeGenFunction & CGF,const CXXNewExpr * E)6810b57cec5SDimitry Andric static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
6820b57cec5SDimitry Andric                                         const CXXNewExpr *E) {
6830b57cec5SDimitry Andric   if (!E->isArray())
6840b57cec5SDimitry Andric     return CharUnits::Zero();
6850b57cec5SDimitry Andric 
6860b57cec5SDimitry Andric   // No cookie is required if the operator new[] being used is the
6870b57cec5SDimitry Andric   // reserved placement operator new[].
6880b57cec5SDimitry Andric   if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
6890b57cec5SDimitry Andric     return CharUnits::Zero();
6900b57cec5SDimitry Andric 
6910b57cec5SDimitry Andric   return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
6920b57cec5SDimitry Andric }
6930b57cec5SDimitry Andric 
EmitCXXNewAllocSize(CodeGenFunction & CGF,const CXXNewExpr * e,unsigned minElements,llvm::Value * & numElements,llvm::Value * & sizeWithoutCookie)6940b57cec5SDimitry Andric static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
6950b57cec5SDimitry Andric                                         const CXXNewExpr *e,
6960b57cec5SDimitry Andric                                         unsigned minElements,
6970b57cec5SDimitry Andric                                         llvm::Value *&numElements,
6980b57cec5SDimitry Andric                                         llvm::Value *&sizeWithoutCookie) {
6990b57cec5SDimitry Andric   QualType type = e->getAllocatedType();
7000b57cec5SDimitry Andric 
7010b57cec5SDimitry Andric   if (!e->isArray()) {
7020b57cec5SDimitry Andric     CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
7030b57cec5SDimitry Andric     sizeWithoutCookie
7040b57cec5SDimitry Andric       = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
7050b57cec5SDimitry Andric     return sizeWithoutCookie;
7060b57cec5SDimitry Andric   }
7070b57cec5SDimitry Andric 
7080b57cec5SDimitry Andric   // The width of size_t.
7090b57cec5SDimitry Andric   unsigned sizeWidth = CGF.SizeTy->getBitWidth();
7100b57cec5SDimitry Andric 
7110b57cec5SDimitry Andric   // Figure out the cookie size.
7120b57cec5SDimitry Andric   llvm::APInt cookieSize(sizeWidth,
7130b57cec5SDimitry Andric                          CalculateCookiePadding(CGF, e).getQuantity());
7140b57cec5SDimitry Andric 
7150b57cec5SDimitry Andric   // Emit the array size expression.
7160b57cec5SDimitry Andric   // We multiply the size of all dimensions for NumElements.
7170b57cec5SDimitry Andric   // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
7180b57cec5SDimitry Andric   numElements =
7190b57cec5SDimitry Andric     ConstantEmitter(CGF).tryEmitAbstract(*e->getArraySize(), e->getType());
7200b57cec5SDimitry Andric   if (!numElements)
7210b57cec5SDimitry Andric     numElements = CGF.EmitScalarExpr(*e->getArraySize());
7220b57cec5SDimitry Andric   assert(isa<llvm::IntegerType>(numElements->getType()));
7230b57cec5SDimitry Andric 
7240b57cec5SDimitry Andric   // The number of elements can be have an arbitrary integer type;
7250b57cec5SDimitry Andric   // essentially, we need to multiply it by a constant factor, add a
7260b57cec5SDimitry Andric   // cookie size, and verify that the result is representable as a
7270b57cec5SDimitry Andric   // size_t.  That's just a gloss, though, and it's wrong in one
7280b57cec5SDimitry Andric   // important way: if the count is negative, it's an error even if
7290b57cec5SDimitry Andric   // the cookie size would bring the total size >= 0.
7300b57cec5SDimitry Andric   bool isSigned
7310b57cec5SDimitry Andric     = (*e->getArraySize())->getType()->isSignedIntegerOrEnumerationType();
7320b57cec5SDimitry Andric   llvm::IntegerType *numElementsType
7330b57cec5SDimitry Andric     = cast<llvm::IntegerType>(numElements->getType());
7340b57cec5SDimitry Andric   unsigned numElementsWidth = numElementsType->getBitWidth();
7350b57cec5SDimitry Andric 
7360b57cec5SDimitry Andric   // Compute the constant factor.
7370b57cec5SDimitry Andric   llvm::APInt arraySizeMultiplier(sizeWidth, 1);
7380b57cec5SDimitry Andric   while (const ConstantArrayType *CAT
7390b57cec5SDimitry Andric              = CGF.getContext().getAsConstantArrayType(type)) {
7400b57cec5SDimitry Andric     type = CAT->getElementType();
7410b57cec5SDimitry Andric     arraySizeMultiplier *= CAT->getSize();
7420b57cec5SDimitry Andric   }
7430b57cec5SDimitry Andric 
7440b57cec5SDimitry Andric   CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
7450b57cec5SDimitry Andric   llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
7460b57cec5SDimitry Andric   typeSizeMultiplier *= arraySizeMultiplier;
7470b57cec5SDimitry Andric 
7480b57cec5SDimitry Andric   // This will be a size_t.
7490b57cec5SDimitry Andric   llvm::Value *size;
7500b57cec5SDimitry Andric 
7510b57cec5SDimitry Andric   // If someone is doing 'new int[42]' there is no need to do a dynamic check.
7520b57cec5SDimitry Andric   // Don't bloat the -O0 code.
7530b57cec5SDimitry Andric   if (llvm::ConstantInt *numElementsC =
7540b57cec5SDimitry Andric         dyn_cast<llvm::ConstantInt>(numElements)) {
7550b57cec5SDimitry Andric     const llvm::APInt &count = numElementsC->getValue();
7560b57cec5SDimitry Andric 
7570b57cec5SDimitry Andric     bool hasAnyOverflow = false;
7580b57cec5SDimitry Andric 
7590b57cec5SDimitry Andric     // If 'count' was a negative number, it's an overflow.
7600b57cec5SDimitry Andric     if (isSigned && count.isNegative())
7610b57cec5SDimitry Andric       hasAnyOverflow = true;
7620b57cec5SDimitry Andric 
7630b57cec5SDimitry Andric     // We want to do all this arithmetic in size_t.  If numElements is
7640b57cec5SDimitry Andric     // wider than that, check whether it's already too big, and if so,
7650b57cec5SDimitry Andric     // overflow.
7660b57cec5SDimitry Andric     else if (numElementsWidth > sizeWidth &&
7670b57cec5SDimitry Andric              numElementsWidth - sizeWidth > count.countLeadingZeros())
7680b57cec5SDimitry Andric       hasAnyOverflow = true;
7690b57cec5SDimitry Andric 
7700b57cec5SDimitry Andric     // Okay, compute a count at the right width.
7710b57cec5SDimitry Andric     llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
7720b57cec5SDimitry Andric 
7730b57cec5SDimitry Andric     // If there is a brace-initializer, we cannot allocate fewer elements than
7740b57cec5SDimitry Andric     // there are initializers. If we do, that's treated like an overflow.
7750b57cec5SDimitry Andric     if (adjustedCount.ult(minElements))
7760b57cec5SDimitry Andric       hasAnyOverflow = true;
7770b57cec5SDimitry Andric 
7780b57cec5SDimitry Andric     // Scale numElements by that.  This might overflow, but we don't
7790b57cec5SDimitry Andric     // care because it only overflows if allocationSize does, too, and
7800b57cec5SDimitry Andric     // if that overflows then we shouldn't use this.
7810b57cec5SDimitry Andric     numElements = llvm::ConstantInt::get(CGF.SizeTy,
7820b57cec5SDimitry Andric                                          adjustedCount * arraySizeMultiplier);
7830b57cec5SDimitry Andric 
7840b57cec5SDimitry Andric     // Compute the size before cookie, and track whether it overflowed.
7850b57cec5SDimitry Andric     bool overflow;
7860b57cec5SDimitry Andric     llvm::APInt allocationSize
7870b57cec5SDimitry Andric       = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
7880b57cec5SDimitry Andric     hasAnyOverflow |= overflow;
7890b57cec5SDimitry Andric 
7900b57cec5SDimitry Andric     // Add in the cookie, and check whether it's overflowed.
7910b57cec5SDimitry Andric     if (cookieSize != 0) {
7920b57cec5SDimitry Andric       // Save the current size without a cookie.  This shouldn't be
7930b57cec5SDimitry Andric       // used if there was overflow.
7940b57cec5SDimitry Andric       sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
7950b57cec5SDimitry Andric 
7960b57cec5SDimitry Andric       allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
7970b57cec5SDimitry Andric       hasAnyOverflow |= overflow;
7980b57cec5SDimitry Andric     }
7990b57cec5SDimitry Andric 
8000b57cec5SDimitry Andric     // On overflow, produce a -1 so operator new will fail.
8010b57cec5SDimitry Andric     if (hasAnyOverflow) {
8020b57cec5SDimitry Andric       size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
8030b57cec5SDimitry Andric     } else {
8040b57cec5SDimitry Andric       size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
8050b57cec5SDimitry Andric     }
8060b57cec5SDimitry Andric 
8070b57cec5SDimitry Andric   // Otherwise, we might need to use the overflow intrinsics.
8080b57cec5SDimitry Andric   } else {
8090b57cec5SDimitry Andric     // There are up to five conditions we need to test for:
8100b57cec5SDimitry Andric     // 1) if isSigned, we need to check whether numElements is negative;
8110b57cec5SDimitry Andric     // 2) if numElementsWidth > sizeWidth, we need to check whether
8120b57cec5SDimitry Andric     //   numElements is larger than something representable in size_t;
8130b57cec5SDimitry Andric     // 3) if minElements > 0, we need to check whether numElements is smaller
8140b57cec5SDimitry Andric     //    than that.
8150b57cec5SDimitry Andric     // 4) we need to compute
8160b57cec5SDimitry Andric     //      sizeWithoutCookie := numElements * typeSizeMultiplier
8170b57cec5SDimitry Andric     //    and check whether it overflows; and
8180b57cec5SDimitry Andric     // 5) if we need a cookie, we need to compute
8190b57cec5SDimitry Andric     //      size := sizeWithoutCookie + cookieSize
8200b57cec5SDimitry Andric     //    and check whether it overflows.
8210b57cec5SDimitry Andric 
8220b57cec5SDimitry Andric     llvm::Value *hasOverflow = nullptr;
8230b57cec5SDimitry Andric 
8240b57cec5SDimitry Andric     // If numElementsWidth > sizeWidth, then one way or another, we're
8250b57cec5SDimitry Andric     // going to have to do a comparison for (2), and this happens to
8260b57cec5SDimitry Andric     // take care of (1), too.
8270b57cec5SDimitry Andric     if (numElementsWidth > sizeWidth) {
8280b57cec5SDimitry Andric       llvm::APInt threshold(numElementsWidth, 1);
8290b57cec5SDimitry Andric       threshold <<= sizeWidth;
8300b57cec5SDimitry Andric 
8310b57cec5SDimitry Andric       llvm::Value *thresholdV
8320b57cec5SDimitry Andric         = llvm::ConstantInt::get(numElementsType, threshold);
8330b57cec5SDimitry Andric 
8340b57cec5SDimitry Andric       hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
8350b57cec5SDimitry Andric       numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
8360b57cec5SDimitry Andric 
8370b57cec5SDimitry Andric     // Otherwise, if we're signed, we want to sext up to size_t.
8380b57cec5SDimitry Andric     } else if (isSigned) {
8390b57cec5SDimitry Andric       if (numElementsWidth < sizeWidth)
8400b57cec5SDimitry Andric         numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
8410b57cec5SDimitry Andric 
8420b57cec5SDimitry Andric       // If there's a non-1 type size multiplier, then we can do the
8430b57cec5SDimitry Andric       // signedness check at the same time as we do the multiply
8440b57cec5SDimitry Andric       // because a negative number times anything will cause an
8450b57cec5SDimitry Andric       // unsigned overflow.  Otherwise, we have to do it here. But at least
8460b57cec5SDimitry Andric       // in this case, we can subsume the >= minElements check.
8470b57cec5SDimitry Andric       if (typeSizeMultiplier == 1)
8480b57cec5SDimitry Andric         hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
8490b57cec5SDimitry Andric                               llvm::ConstantInt::get(CGF.SizeTy, minElements));
8500b57cec5SDimitry Andric 
8510b57cec5SDimitry Andric     // Otherwise, zext up to size_t if necessary.
8520b57cec5SDimitry Andric     } else if (numElementsWidth < sizeWidth) {
8530b57cec5SDimitry Andric       numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
8540b57cec5SDimitry Andric     }
8550b57cec5SDimitry Andric 
8560b57cec5SDimitry Andric     assert(numElements->getType() == CGF.SizeTy);
8570b57cec5SDimitry Andric 
8580b57cec5SDimitry Andric     if (minElements) {
8590b57cec5SDimitry Andric       // Don't allow allocation of fewer elements than we have initializers.
8600b57cec5SDimitry Andric       if (!hasOverflow) {
8610b57cec5SDimitry Andric         hasOverflow = CGF.Builder.CreateICmpULT(numElements,
8620b57cec5SDimitry Andric                               llvm::ConstantInt::get(CGF.SizeTy, minElements));
8630b57cec5SDimitry Andric       } else if (numElementsWidth > sizeWidth) {
8640b57cec5SDimitry Andric         // The other existing overflow subsumes this check.
8650b57cec5SDimitry Andric         // We do an unsigned comparison, since any signed value < -1 is
8660b57cec5SDimitry Andric         // taken care of either above or below.
8670b57cec5SDimitry Andric         hasOverflow = CGF.Builder.CreateOr(hasOverflow,
8680b57cec5SDimitry Andric                           CGF.Builder.CreateICmpULT(numElements,
8690b57cec5SDimitry Andric                               llvm::ConstantInt::get(CGF.SizeTy, minElements)));
8700b57cec5SDimitry Andric       }
8710b57cec5SDimitry Andric     }
8720b57cec5SDimitry Andric 
8730b57cec5SDimitry Andric     size = numElements;
8740b57cec5SDimitry Andric 
8750b57cec5SDimitry Andric     // Multiply by the type size if necessary.  This multiplier
8760b57cec5SDimitry Andric     // includes all the factors for nested arrays.
8770b57cec5SDimitry Andric     //
8780b57cec5SDimitry Andric     // This step also causes numElements to be scaled up by the
8790b57cec5SDimitry Andric     // nested-array factor if necessary.  Overflow on this computation
8800b57cec5SDimitry Andric     // can be ignored because the result shouldn't be used if
8810b57cec5SDimitry Andric     // allocation fails.
8820b57cec5SDimitry Andric     if (typeSizeMultiplier != 1) {
8830b57cec5SDimitry Andric       llvm::Function *umul_with_overflow
8840b57cec5SDimitry Andric         = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
8850b57cec5SDimitry Andric 
8860b57cec5SDimitry Andric       llvm::Value *tsmV =
8870b57cec5SDimitry Andric         llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
8880b57cec5SDimitry Andric       llvm::Value *result =
8890b57cec5SDimitry Andric           CGF.Builder.CreateCall(umul_with_overflow, {size, tsmV});
8900b57cec5SDimitry Andric 
8910b57cec5SDimitry Andric       llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
8920b57cec5SDimitry Andric       if (hasOverflow)
8930b57cec5SDimitry Andric         hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
8940b57cec5SDimitry Andric       else
8950b57cec5SDimitry Andric         hasOverflow = overflowed;
8960b57cec5SDimitry Andric 
8970b57cec5SDimitry Andric       size = CGF.Builder.CreateExtractValue(result, 0);
8980b57cec5SDimitry Andric 
8990b57cec5SDimitry Andric       // Also scale up numElements by the array size multiplier.
9000b57cec5SDimitry Andric       if (arraySizeMultiplier != 1) {
9010b57cec5SDimitry Andric         // If the base element type size is 1, then we can re-use the
9020b57cec5SDimitry Andric         // multiply we just did.
9030b57cec5SDimitry Andric         if (typeSize.isOne()) {
9040b57cec5SDimitry Andric           assert(arraySizeMultiplier == typeSizeMultiplier);
9050b57cec5SDimitry Andric           numElements = size;
9060b57cec5SDimitry Andric 
9070b57cec5SDimitry Andric         // Otherwise we need a separate multiply.
9080b57cec5SDimitry Andric         } else {
9090b57cec5SDimitry Andric           llvm::Value *asmV =
9100b57cec5SDimitry Andric             llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
9110b57cec5SDimitry Andric           numElements = CGF.Builder.CreateMul(numElements, asmV);
9120b57cec5SDimitry Andric         }
9130b57cec5SDimitry Andric       }
9140b57cec5SDimitry Andric     } else {
9150b57cec5SDimitry Andric       // numElements doesn't need to be scaled.
9160b57cec5SDimitry Andric       assert(arraySizeMultiplier == 1);
9170b57cec5SDimitry Andric     }
9180b57cec5SDimitry Andric 
9190b57cec5SDimitry Andric     // Add in the cookie size if necessary.
9200b57cec5SDimitry Andric     if (cookieSize != 0) {
9210b57cec5SDimitry Andric       sizeWithoutCookie = size;
9220b57cec5SDimitry Andric 
9230b57cec5SDimitry Andric       llvm::Function *uadd_with_overflow
9240b57cec5SDimitry Andric         = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
9250b57cec5SDimitry Andric 
9260b57cec5SDimitry Andric       llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
9270b57cec5SDimitry Andric       llvm::Value *result =
9280b57cec5SDimitry Andric           CGF.Builder.CreateCall(uadd_with_overflow, {size, cookieSizeV});
9290b57cec5SDimitry Andric 
9300b57cec5SDimitry Andric       llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
9310b57cec5SDimitry Andric       if (hasOverflow)
9320b57cec5SDimitry Andric         hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
9330b57cec5SDimitry Andric       else
9340b57cec5SDimitry Andric         hasOverflow = overflowed;
9350b57cec5SDimitry Andric 
9360b57cec5SDimitry Andric       size = CGF.Builder.CreateExtractValue(result, 0);
9370b57cec5SDimitry Andric     }
9380b57cec5SDimitry Andric 
9390b57cec5SDimitry Andric     // If we had any possibility of dynamic overflow, make a select to
9400b57cec5SDimitry Andric     // overwrite 'size' with an all-ones value, which should cause
9410b57cec5SDimitry Andric     // operator new to throw.
9420b57cec5SDimitry Andric     if (hasOverflow)
9430b57cec5SDimitry Andric       size = CGF.Builder.CreateSelect(hasOverflow,
9440b57cec5SDimitry Andric                                  llvm::Constant::getAllOnesValue(CGF.SizeTy),
9450b57cec5SDimitry Andric                                       size);
9460b57cec5SDimitry Andric   }
9470b57cec5SDimitry Andric 
9480b57cec5SDimitry Andric   if (cookieSize == 0)
9490b57cec5SDimitry Andric     sizeWithoutCookie = size;
9500b57cec5SDimitry Andric   else
9510b57cec5SDimitry Andric     assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
9520b57cec5SDimitry Andric 
9530b57cec5SDimitry Andric   return size;
9540b57cec5SDimitry Andric }
9550b57cec5SDimitry Andric 
StoreAnyExprIntoOneUnit(CodeGenFunction & CGF,const Expr * Init,QualType AllocType,Address NewPtr,AggValueSlot::Overlap_t MayOverlap)9560b57cec5SDimitry Andric static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
9570b57cec5SDimitry Andric                                     QualType AllocType, Address NewPtr,
9580b57cec5SDimitry Andric                                     AggValueSlot::Overlap_t MayOverlap) {
9590b57cec5SDimitry Andric   // FIXME: Refactor with EmitExprAsInit.
9600b57cec5SDimitry Andric   switch (CGF.getEvaluationKind(AllocType)) {
9610b57cec5SDimitry Andric   case TEK_Scalar:
9620b57cec5SDimitry Andric     CGF.EmitScalarInit(Init, nullptr,
9630b57cec5SDimitry Andric                        CGF.MakeAddrLValue(NewPtr, AllocType), false);
9640b57cec5SDimitry Andric     return;
9650b57cec5SDimitry Andric   case TEK_Complex:
9660b57cec5SDimitry Andric     CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType),
9670b57cec5SDimitry Andric                                   /*isInit*/ true);
9680b57cec5SDimitry Andric     return;
9690b57cec5SDimitry Andric   case TEK_Aggregate: {
9700b57cec5SDimitry Andric     AggValueSlot Slot
9710b57cec5SDimitry Andric       = AggValueSlot::forAddr(NewPtr, AllocType.getQualifiers(),
9720b57cec5SDimitry Andric                               AggValueSlot::IsDestructed,
9730b57cec5SDimitry Andric                               AggValueSlot::DoesNotNeedGCBarriers,
9740b57cec5SDimitry Andric                               AggValueSlot::IsNotAliased,
9750b57cec5SDimitry Andric                               MayOverlap, AggValueSlot::IsNotZeroed,
9760b57cec5SDimitry Andric                               AggValueSlot::IsSanitizerChecked);
9770b57cec5SDimitry Andric     CGF.EmitAggExpr(Init, Slot);
9780b57cec5SDimitry Andric     return;
9790b57cec5SDimitry Andric   }
9800b57cec5SDimitry Andric   }
9810b57cec5SDimitry Andric   llvm_unreachable("bad evaluation kind");
9820b57cec5SDimitry Andric }
9830b57cec5SDimitry Andric 
EmitNewArrayInitializer(const CXXNewExpr * E,QualType ElementType,llvm::Type * ElementTy,Address BeginPtr,llvm::Value * NumElements,llvm::Value * AllocSizeWithoutCookie)9840b57cec5SDimitry Andric void CodeGenFunction::EmitNewArrayInitializer(
9850b57cec5SDimitry Andric     const CXXNewExpr *E, QualType ElementType, llvm::Type *ElementTy,
9860b57cec5SDimitry Andric     Address BeginPtr, llvm::Value *NumElements,
9870b57cec5SDimitry Andric     llvm::Value *AllocSizeWithoutCookie) {
9880b57cec5SDimitry Andric   // If we have a type with trivial initialization and no initializer,
9890b57cec5SDimitry Andric   // there's nothing to do.
9900b57cec5SDimitry Andric   if (!E->hasInitializer())
9910b57cec5SDimitry Andric     return;
9920b57cec5SDimitry Andric 
9930b57cec5SDimitry Andric   Address CurPtr = BeginPtr;
9940b57cec5SDimitry Andric 
9950b57cec5SDimitry Andric   unsigned InitListElements = 0;
9960b57cec5SDimitry Andric 
9970b57cec5SDimitry Andric   const Expr *Init = E->getInitializer();
9980b57cec5SDimitry Andric   Address EndOfInit = Address::invalid();
9990b57cec5SDimitry Andric   QualType::DestructionKind DtorKind = ElementType.isDestructedType();
10000b57cec5SDimitry Andric   EHScopeStack::stable_iterator Cleanup;
10010b57cec5SDimitry Andric   llvm::Instruction *CleanupDominator = nullptr;
10020b57cec5SDimitry Andric 
10030b57cec5SDimitry Andric   CharUnits ElementSize = getContext().getTypeSizeInChars(ElementType);
10040b57cec5SDimitry Andric   CharUnits ElementAlign =
10050b57cec5SDimitry Andric     BeginPtr.getAlignment().alignmentOfArrayElement(ElementSize);
10060b57cec5SDimitry Andric 
10070b57cec5SDimitry Andric   // Attempt to perform zero-initialization using memset.
10080b57cec5SDimitry Andric   auto TryMemsetInitialization = [&]() -> bool {
10090b57cec5SDimitry Andric     // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
10100b57cec5SDimitry Andric     // we can initialize with a memset to -1.
10110b57cec5SDimitry Andric     if (!CGM.getTypes().isZeroInitializable(ElementType))
10120b57cec5SDimitry Andric       return false;
10130b57cec5SDimitry Andric 
10140b57cec5SDimitry Andric     // Optimization: since zero initialization will just set the memory
10150b57cec5SDimitry Andric     // to all zeroes, generate a single memset to do it in one shot.
10160b57cec5SDimitry Andric 
10170b57cec5SDimitry Andric     // Subtract out the size of any elements we've already initialized.
10180b57cec5SDimitry Andric     auto *RemainingSize = AllocSizeWithoutCookie;
10190b57cec5SDimitry Andric     if (InitListElements) {
10200b57cec5SDimitry Andric       // We know this can't overflow; we check this when doing the allocation.
10210b57cec5SDimitry Andric       auto *InitializedSize = llvm::ConstantInt::get(
10220b57cec5SDimitry Andric           RemainingSize->getType(),
10230b57cec5SDimitry Andric           getContext().getTypeSizeInChars(ElementType).getQuantity() *
10240b57cec5SDimitry Andric               InitListElements);
10250b57cec5SDimitry Andric       RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
10260b57cec5SDimitry Andric     }
10270b57cec5SDimitry Andric 
10280b57cec5SDimitry Andric     // Create the memset.
10290b57cec5SDimitry Andric     Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize, false);
10300b57cec5SDimitry Andric     return true;
10310b57cec5SDimitry Andric   };
10320b57cec5SDimitry Andric 
10330b57cec5SDimitry Andric   // If the initializer is an initializer list, first do the explicit elements.
10340b57cec5SDimitry Andric   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
10350b57cec5SDimitry Andric     // Initializing from a (braced) string literal is a special case; the init
10360b57cec5SDimitry Andric     // list element does not initialize a (single) array element.
10370b57cec5SDimitry Andric     if (ILE->isStringLiteralInit()) {
10380b57cec5SDimitry Andric       // Initialize the initial portion of length equal to that of the string
10390b57cec5SDimitry Andric       // literal. The allocation must be for at least this much; we emitted a
10400b57cec5SDimitry Andric       // check for that earlier.
10410b57cec5SDimitry Andric       AggValueSlot Slot =
10420b57cec5SDimitry Andric           AggValueSlot::forAddr(CurPtr, ElementType.getQualifiers(),
10430b57cec5SDimitry Andric                                 AggValueSlot::IsDestructed,
10440b57cec5SDimitry Andric                                 AggValueSlot::DoesNotNeedGCBarriers,
10450b57cec5SDimitry Andric                                 AggValueSlot::IsNotAliased,
10460b57cec5SDimitry Andric                                 AggValueSlot::DoesNotOverlap,
10470b57cec5SDimitry Andric                                 AggValueSlot::IsNotZeroed,
10480b57cec5SDimitry Andric                                 AggValueSlot::IsSanitizerChecked);
10490b57cec5SDimitry Andric       EmitAggExpr(ILE->getInit(0), Slot);
10500b57cec5SDimitry Andric 
10510b57cec5SDimitry Andric       // Move past these elements.
10520b57cec5SDimitry Andric       InitListElements =
10530b57cec5SDimitry Andric           cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe())
10540b57cec5SDimitry Andric               ->getSize().getZExtValue();
10550b57cec5SDimitry Andric       CurPtr =
10565f7ddb14SDimitry Andric           Address(Builder.CreateInBoundsGEP(CurPtr.getElementType(),
10575f7ddb14SDimitry Andric                                             CurPtr.getPointer(),
10580b57cec5SDimitry Andric                                             Builder.getSize(InitListElements),
10590b57cec5SDimitry Andric                                             "string.init.end"),
10600b57cec5SDimitry Andric                   CurPtr.getAlignment().alignmentAtOffset(InitListElements *
10610b57cec5SDimitry Andric                                                           ElementSize));
10620b57cec5SDimitry Andric 
10630b57cec5SDimitry Andric       // Zero out the rest, if any remain.
10640b57cec5SDimitry Andric       llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
10650b57cec5SDimitry Andric       if (!ConstNum || !ConstNum->equalsInt(InitListElements)) {
10660b57cec5SDimitry Andric         bool OK = TryMemsetInitialization();
10670b57cec5SDimitry Andric         (void)OK;
10680b57cec5SDimitry Andric         assert(OK && "couldn't memset character type?");
10690b57cec5SDimitry Andric       }
10700b57cec5SDimitry Andric       return;
10710b57cec5SDimitry Andric     }
10720b57cec5SDimitry Andric 
10730b57cec5SDimitry Andric     InitListElements = ILE->getNumInits();
10740b57cec5SDimitry Andric 
10750b57cec5SDimitry Andric     // If this is a multi-dimensional array new, we will initialize multiple
10760b57cec5SDimitry Andric     // elements with each init list element.
10770b57cec5SDimitry Andric     QualType AllocType = E->getAllocatedType();
10780b57cec5SDimitry Andric     if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
10790b57cec5SDimitry Andric             AllocType->getAsArrayTypeUnsafe())) {
10800b57cec5SDimitry Andric       ElementTy = ConvertTypeForMem(AllocType);
10810b57cec5SDimitry Andric       CurPtr = Builder.CreateElementBitCast(CurPtr, ElementTy);
10820b57cec5SDimitry Andric       InitListElements *= getContext().getConstantArrayElementCount(CAT);
10830b57cec5SDimitry Andric     }
10840b57cec5SDimitry Andric 
10850b57cec5SDimitry Andric     // Enter a partial-destruction Cleanup if necessary.
10860b57cec5SDimitry Andric     if (needsEHCleanup(DtorKind)) {
10870b57cec5SDimitry Andric       // In principle we could tell the Cleanup where we are more
10880b57cec5SDimitry Andric       // directly, but the control flow can get so varied here that it
10890b57cec5SDimitry Andric       // would actually be quite complex.  Therefore we go through an
10900b57cec5SDimitry Andric       // alloca.
10910b57cec5SDimitry Andric       EndOfInit = CreateTempAlloca(BeginPtr.getType(), getPointerAlign(),
10920b57cec5SDimitry Andric                                    "array.init.end");
10930b57cec5SDimitry Andric       CleanupDominator = Builder.CreateStore(BeginPtr.getPointer(), EndOfInit);
10940b57cec5SDimitry Andric       pushIrregularPartialArrayCleanup(BeginPtr.getPointer(), EndOfInit,
10950b57cec5SDimitry Andric                                        ElementType, ElementAlign,
10960b57cec5SDimitry Andric                                        getDestroyer(DtorKind));
10970b57cec5SDimitry Andric       Cleanup = EHStack.stable_begin();
10980b57cec5SDimitry Andric     }
10990b57cec5SDimitry Andric 
11000b57cec5SDimitry Andric     CharUnits StartAlign = CurPtr.getAlignment();
11010b57cec5SDimitry Andric     for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
11020b57cec5SDimitry Andric       // Tell the cleanup that it needs to destroy up to this
11030b57cec5SDimitry Andric       // element.  TODO: some of these stores can be trivially
11040b57cec5SDimitry Andric       // observed to be unnecessary.
11050b57cec5SDimitry Andric       if (EndOfInit.isValid()) {
11060b57cec5SDimitry Andric         auto FinishedPtr =
11070b57cec5SDimitry Andric           Builder.CreateBitCast(CurPtr.getPointer(), BeginPtr.getType());
11080b57cec5SDimitry Andric         Builder.CreateStore(FinishedPtr, EndOfInit);
11090b57cec5SDimitry Andric       }
11100b57cec5SDimitry Andric       // FIXME: If the last initializer is an incomplete initializer list for
11110b57cec5SDimitry Andric       // an array, and we have an array filler, we can fold together the two
11120b57cec5SDimitry Andric       // initialization loops.
11130b57cec5SDimitry Andric       StoreAnyExprIntoOneUnit(*this, ILE->getInit(i),
11140b57cec5SDimitry Andric                               ILE->getInit(i)->getType(), CurPtr,
11150b57cec5SDimitry Andric                               AggValueSlot::DoesNotOverlap);
11165f7ddb14SDimitry Andric       CurPtr = Address(Builder.CreateInBoundsGEP(CurPtr.getElementType(),
11175f7ddb14SDimitry Andric                                                  CurPtr.getPointer(),
11180b57cec5SDimitry Andric                                                  Builder.getSize(1),
11190b57cec5SDimitry Andric                                                  "array.exp.next"),
11200b57cec5SDimitry Andric                        StartAlign.alignmentAtOffset((i + 1) * ElementSize));
11210b57cec5SDimitry Andric     }
11220b57cec5SDimitry Andric 
11230b57cec5SDimitry Andric     // The remaining elements are filled with the array filler expression.
11240b57cec5SDimitry Andric     Init = ILE->getArrayFiller();
11250b57cec5SDimitry Andric 
11260b57cec5SDimitry Andric     // Extract the initializer for the individual array elements by pulling
11270b57cec5SDimitry Andric     // out the array filler from all the nested initializer lists. This avoids
11280b57cec5SDimitry Andric     // generating a nested loop for the initialization.
11290b57cec5SDimitry Andric     while (Init && Init->getType()->isConstantArrayType()) {
11300b57cec5SDimitry Andric       auto *SubILE = dyn_cast<InitListExpr>(Init);
11310b57cec5SDimitry Andric       if (!SubILE)
11320b57cec5SDimitry Andric         break;
11330b57cec5SDimitry Andric       assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
11340b57cec5SDimitry Andric       Init = SubILE->getArrayFiller();
11350b57cec5SDimitry Andric     }
11360b57cec5SDimitry Andric 
11370b57cec5SDimitry Andric     // Switch back to initializing one base element at a time.
11380b57cec5SDimitry Andric     CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr.getType());
11390b57cec5SDimitry Andric   }
11400b57cec5SDimitry Andric 
11410b57cec5SDimitry Andric   // If all elements have already been initialized, skip any further
11420b57cec5SDimitry Andric   // initialization.
11430b57cec5SDimitry Andric   llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
11440b57cec5SDimitry Andric   if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
11450b57cec5SDimitry Andric     // If there was a Cleanup, deactivate it.
11460b57cec5SDimitry Andric     if (CleanupDominator)
11470b57cec5SDimitry Andric       DeactivateCleanupBlock(Cleanup, CleanupDominator);
11480b57cec5SDimitry Andric     return;
11490b57cec5SDimitry Andric   }
11500b57cec5SDimitry Andric 
11510b57cec5SDimitry Andric   assert(Init && "have trailing elements to initialize but no initializer");
11520b57cec5SDimitry Andric 
11530b57cec5SDimitry Andric   // If this is a constructor call, try to optimize it out, and failing that
11540b57cec5SDimitry Andric   // emit a single loop to initialize all remaining elements.
11550b57cec5SDimitry Andric   if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
11560b57cec5SDimitry Andric     CXXConstructorDecl *Ctor = CCE->getConstructor();
11570b57cec5SDimitry Andric     if (Ctor->isTrivial()) {
11580b57cec5SDimitry Andric       // If new expression did not specify value-initialization, then there
11590b57cec5SDimitry Andric       // is no initialization.
11600b57cec5SDimitry Andric       if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
11610b57cec5SDimitry Andric         return;
11620b57cec5SDimitry Andric 
11630b57cec5SDimitry Andric       if (TryMemsetInitialization())
11640b57cec5SDimitry Andric         return;
11650b57cec5SDimitry Andric     }
11660b57cec5SDimitry Andric 
11670b57cec5SDimitry Andric     // Store the new Cleanup position for irregular Cleanups.
11680b57cec5SDimitry Andric     //
11690b57cec5SDimitry Andric     // FIXME: Share this cleanup with the constructor call emission rather than
11700b57cec5SDimitry Andric     // having it create a cleanup of its own.
11710b57cec5SDimitry Andric     if (EndOfInit.isValid())
11720b57cec5SDimitry Andric       Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
11730b57cec5SDimitry Andric 
11740b57cec5SDimitry Andric     // Emit a constructor call loop to initialize the remaining elements.
11750b57cec5SDimitry Andric     if (InitListElements)
11760b57cec5SDimitry Andric       NumElements = Builder.CreateSub(
11770b57cec5SDimitry Andric           NumElements,
11780b57cec5SDimitry Andric           llvm::ConstantInt::get(NumElements->getType(), InitListElements));
11790b57cec5SDimitry Andric     EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,
11800b57cec5SDimitry Andric                                /*NewPointerIsChecked*/true,
11810b57cec5SDimitry Andric                                CCE->requiresZeroInitialization());
11820b57cec5SDimitry Andric     return;
11830b57cec5SDimitry Andric   }
11840b57cec5SDimitry Andric 
11850b57cec5SDimitry Andric   // If this is value-initialization, we can usually use memset.
11860b57cec5SDimitry Andric   ImplicitValueInitExpr IVIE(ElementType);
11870b57cec5SDimitry Andric   if (isa<ImplicitValueInitExpr>(Init)) {
11880b57cec5SDimitry Andric     if (TryMemsetInitialization())
11890b57cec5SDimitry Andric       return;
11900b57cec5SDimitry Andric 
11910b57cec5SDimitry Andric     // Switch to an ImplicitValueInitExpr for the element type. This handles
11920b57cec5SDimitry Andric     // only one case: multidimensional array new of pointers to members. In
11930b57cec5SDimitry Andric     // all other cases, we already have an initializer for the array element.
11940b57cec5SDimitry Andric     Init = &IVIE;
11950b57cec5SDimitry Andric   }
11960b57cec5SDimitry Andric 
11970b57cec5SDimitry Andric   // At this point we should have found an initializer for the individual
11980b57cec5SDimitry Andric   // elements of the array.
11990b57cec5SDimitry Andric   assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&
12000b57cec5SDimitry Andric          "got wrong type of element to initialize");
12010b57cec5SDimitry Andric 
12020b57cec5SDimitry Andric   // If we have an empty initializer list, we can usually use memset.
12030b57cec5SDimitry Andric   if (auto *ILE = dyn_cast<InitListExpr>(Init))
12040b57cec5SDimitry Andric     if (ILE->getNumInits() == 0 && TryMemsetInitialization())
12050b57cec5SDimitry Andric       return;
12060b57cec5SDimitry Andric 
12070b57cec5SDimitry Andric   // If we have a struct whose every field is value-initialized, we can
12080b57cec5SDimitry Andric   // usually use memset.
12090b57cec5SDimitry Andric   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
12100b57cec5SDimitry Andric     if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
12110b57cec5SDimitry Andric       if (RType->getDecl()->isStruct()) {
12120b57cec5SDimitry Andric         unsigned NumElements = 0;
12130b57cec5SDimitry Andric         if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RType->getDecl()))
12140b57cec5SDimitry Andric           NumElements = CXXRD->getNumBases();
12150b57cec5SDimitry Andric         for (auto *Field : RType->getDecl()->fields())
12160b57cec5SDimitry Andric           if (!Field->isUnnamedBitfield())
12170b57cec5SDimitry Andric             ++NumElements;
12180b57cec5SDimitry Andric         // FIXME: Recurse into nested InitListExprs.
12190b57cec5SDimitry Andric         if (ILE->getNumInits() == NumElements)
12200b57cec5SDimitry Andric           for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
12210b57cec5SDimitry Andric             if (!isa<ImplicitValueInitExpr>(ILE->getInit(i)))
12220b57cec5SDimitry Andric               --NumElements;
12230b57cec5SDimitry Andric         if (ILE->getNumInits() == NumElements && TryMemsetInitialization())
12240b57cec5SDimitry Andric           return;
12250b57cec5SDimitry Andric       }
12260b57cec5SDimitry Andric     }
12270b57cec5SDimitry Andric   }
12280b57cec5SDimitry Andric 
12290b57cec5SDimitry Andric   // Create the loop blocks.
12300b57cec5SDimitry Andric   llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
12310b57cec5SDimitry Andric   llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
12320b57cec5SDimitry Andric   llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
12330b57cec5SDimitry Andric 
12340b57cec5SDimitry Andric   // Find the end of the array, hoisted out of the loop.
12350b57cec5SDimitry Andric   llvm::Value *EndPtr =
12365f7ddb14SDimitry Andric     Builder.CreateInBoundsGEP(BeginPtr.getElementType(), BeginPtr.getPointer(),
12375f7ddb14SDimitry Andric                               NumElements, "array.end");
12380b57cec5SDimitry Andric 
12390b57cec5SDimitry Andric   // If the number of elements isn't constant, we have to now check if there is
12400b57cec5SDimitry Andric   // anything left to initialize.
12410b57cec5SDimitry Andric   if (!ConstNum) {
12420b57cec5SDimitry Andric     llvm::Value *IsEmpty =
12430b57cec5SDimitry Andric       Builder.CreateICmpEQ(CurPtr.getPointer(), EndPtr, "array.isempty");
12440b57cec5SDimitry Andric     Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
12450b57cec5SDimitry Andric   }
12460b57cec5SDimitry Andric 
12470b57cec5SDimitry Andric   // Enter the loop.
12480b57cec5SDimitry Andric   EmitBlock(LoopBB);
12490b57cec5SDimitry Andric 
12500b57cec5SDimitry Andric   // Set up the current-element phi.
12510b57cec5SDimitry Andric   llvm::PHINode *CurPtrPhi =
12520b57cec5SDimitry Andric     Builder.CreatePHI(CurPtr.getType(), 2, "array.cur");
12530b57cec5SDimitry Andric   CurPtrPhi->addIncoming(CurPtr.getPointer(), EntryBB);
12540b57cec5SDimitry Andric 
12550b57cec5SDimitry Andric   CurPtr = Address(CurPtrPhi, ElementAlign);
12560b57cec5SDimitry Andric 
12570b57cec5SDimitry Andric   // Store the new Cleanup position for irregular Cleanups.
12580b57cec5SDimitry Andric   if (EndOfInit.isValid())
12590b57cec5SDimitry Andric     Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
12600b57cec5SDimitry Andric 
12610b57cec5SDimitry Andric   // Enter a partial-destruction Cleanup if necessary.
12620b57cec5SDimitry Andric   if (!CleanupDominator && needsEHCleanup(DtorKind)) {
12630b57cec5SDimitry Andric     pushRegularPartialArrayCleanup(BeginPtr.getPointer(), CurPtr.getPointer(),
12640b57cec5SDimitry Andric                                    ElementType, ElementAlign,
12650b57cec5SDimitry Andric                                    getDestroyer(DtorKind));
12660b57cec5SDimitry Andric     Cleanup = EHStack.stable_begin();
12670b57cec5SDimitry Andric     CleanupDominator = Builder.CreateUnreachable();
12680b57cec5SDimitry Andric   }
12690b57cec5SDimitry Andric 
12700b57cec5SDimitry Andric   // Emit the initializer into this element.
12710b57cec5SDimitry Andric   StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr,
12720b57cec5SDimitry Andric                           AggValueSlot::DoesNotOverlap);
12730b57cec5SDimitry Andric 
12740b57cec5SDimitry Andric   // Leave the Cleanup if we entered one.
12750b57cec5SDimitry Andric   if (CleanupDominator) {
12760b57cec5SDimitry Andric     DeactivateCleanupBlock(Cleanup, CleanupDominator);
12770b57cec5SDimitry Andric     CleanupDominator->eraseFromParent();
12780b57cec5SDimitry Andric   }
12790b57cec5SDimitry Andric 
12800b57cec5SDimitry Andric   // Advance to the next element by adjusting the pointer type as necessary.
12810b57cec5SDimitry Andric   llvm::Value *NextPtr =
12820b57cec5SDimitry Andric     Builder.CreateConstInBoundsGEP1_32(ElementTy, CurPtr.getPointer(), 1,
12830b57cec5SDimitry Andric                                        "array.next");
12840b57cec5SDimitry Andric 
12850b57cec5SDimitry Andric   // Check whether we've gotten to the end of the array and, if so,
12860b57cec5SDimitry Andric   // exit the loop.
12870b57cec5SDimitry Andric   llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
12880b57cec5SDimitry Andric   Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
12890b57cec5SDimitry Andric   CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
12900b57cec5SDimitry Andric 
12910b57cec5SDimitry Andric   EmitBlock(ContBB);
12920b57cec5SDimitry Andric }
12930b57cec5SDimitry Andric 
EmitNewInitializer(CodeGenFunction & CGF,const CXXNewExpr * E,QualType ElementType,llvm::Type * ElementTy,Address NewPtr,llvm::Value * NumElements,llvm::Value * AllocSizeWithoutCookie)12940b57cec5SDimitry Andric static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
12950b57cec5SDimitry Andric                                QualType ElementType, llvm::Type *ElementTy,
12960b57cec5SDimitry Andric                                Address NewPtr, llvm::Value *NumElements,
12970b57cec5SDimitry Andric                                llvm::Value *AllocSizeWithoutCookie) {
12980b57cec5SDimitry Andric   ApplyDebugLocation DL(CGF, E);
12990b57cec5SDimitry Andric   if (E->isArray())
13000b57cec5SDimitry Andric     CGF.EmitNewArrayInitializer(E, ElementType, ElementTy, NewPtr, NumElements,
13010b57cec5SDimitry Andric                                 AllocSizeWithoutCookie);
13020b57cec5SDimitry Andric   else if (const Expr *Init = E->getInitializer())
13030b57cec5SDimitry Andric     StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr,
13040b57cec5SDimitry Andric                             AggValueSlot::DoesNotOverlap);
13050b57cec5SDimitry Andric }
13060b57cec5SDimitry Andric 
13070b57cec5SDimitry Andric /// Emit a call to an operator new or operator delete function, as implicitly
13080b57cec5SDimitry Andric /// created by new-expressions and delete-expressions.
EmitNewDeleteCall(CodeGenFunction & CGF,const FunctionDecl * CalleeDecl,const FunctionProtoType * CalleeType,const CallArgList & Args)13090b57cec5SDimitry Andric static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
13100b57cec5SDimitry Andric                                 const FunctionDecl *CalleeDecl,
13110b57cec5SDimitry Andric                                 const FunctionProtoType *CalleeType,
13120b57cec5SDimitry Andric                                 const CallArgList &Args) {
13130b57cec5SDimitry Andric   llvm::CallBase *CallOrInvoke;
13140b57cec5SDimitry Andric   llvm::Constant *CalleePtr = CGF.CGM.GetAddrOfFunction(CalleeDecl);
13150b57cec5SDimitry Andric   CGCallee Callee = CGCallee::forDirect(CalleePtr, GlobalDecl(CalleeDecl));
13160b57cec5SDimitry Andric   RValue RV =
13170b57cec5SDimitry Andric       CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(
13180b57cec5SDimitry Andric                        Args, CalleeType, /*ChainCall=*/false),
13190b57cec5SDimitry Andric                    Callee, ReturnValueSlot(), Args, &CallOrInvoke);
13200b57cec5SDimitry Andric 
13210b57cec5SDimitry Andric   /// C++1y [expr.new]p10:
13220b57cec5SDimitry Andric   ///   [In a new-expression,] an implementation is allowed to omit a call
13230b57cec5SDimitry Andric   ///   to a replaceable global allocation function.
13240b57cec5SDimitry Andric   ///
13250b57cec5SDimitry Andric   /// We model such elidable calls with the 'builtin' attribute.
13260b57cec5SDimitry Andric   llvm::Function *Fn = dyn_cast<llvm::Function>(CalleePtr);
13270b57cec5SDimitry Andric   if (CalleeDecl->isReplaceableGlobalAllocationFunction() &&
13280b57cec5SDimitry Andric       Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
13290b57cec5SDimitry Andric     CallOrInvoke->addAttribute(llvm::AttributeList::FunctionIndex,
13300b57cec5SDimitry Andric                                llvm::Attribute::Builtin);
13310b57cec5SDimitry Andric   }
13320b57cec5SDimitry Andric 
13330b57cec5SDimitry Andric   return RV;
13340b57cec5SDimitry Andric }
13350b57cec5SDimitry Andric 
EmitBuiltinNewDeleteCall(const FunctionProtoType * Type,const CallExpr * TheCall,bool IsDelete)13360b57cec5SDimitry Andric RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
13370b57cec5SDimitry Andric                                                  const CallExpr *TheCall,
13380b57cec5SDimitry Andric                                                  bool IsDelete) {
13390b57cec5SDimitry Andric   CallArgList Args;
1340af732203SDimitry Andric   EmitCallArgs(Args, Type, TheCall->arguments());
13410b57cec5SDimitry Andric   // Find the allocation or deallocation function that we're calling.
13420b57cec5SDimitry Andric   ASTContext &Ctx = getContext();
13430b57cec5SDimitry Andric   DeclarationName Name = Ctx.DeclarationNames
13440b57cec5SDimitry Andric       .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
13450b57cec5SDimitry Andric 
13460b57cec5SDimitry Andric   for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
13470b57cec5SDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(Decl))
13480b57cec5SDimitry Andric       if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
13490b57cec5SDimitry Andric         return EmitNewDeleteCall(*this, FD, Type, Args);
13500b57cec5SDimitry Andric   llvm_unreachable("predeclared global operator new/delete is missing");
13510b57cec5SDimitry Andric }
13520b57cec5SDimitry Andric 
13530b57cec5SDimitry Andric namespace {
13540b57cec5SDimitry Andric /// The parameters to pass to a usual operator delete.
13550b57cec5SDimitry Andric struct UsualDeleteParams {
13560b57cec5SDimitry Andric   bool DestroyingDelete = false;
13570b57cec5SDimitry Andric   bool Size = false;
13580b57cec5SDimitry Andric   bool Alignment = false;
13590b57cec5SDimitry Andric };
13600b57cec5SDimitry Andric }
13610b57cec5SDimitry Andric 
getUsualDeleteParams(const FunctionDecl * FD)13620b57cec5SDimitry Andric static UsualDeleteParams getUsualDeleteParams(const FunctionDecl *FD) {
13630b57cec5SDimitry Andric   UsualDeleteParams Params;
13640b57cec5SDimitry Andric 
13650b57cec5SDimitry Andric   const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
13660b57cec5SDimitry Andric   auto AI = FPT->param_type_begin(), AE = FPT->param_type_end();
13670b57cec5SDimitry Andric 
13680b57cec5SDimitry Andric   // The first argument is always a void*.
13690b57cec5SDimitry Andric   ++AI;
13700b57cec5SDimitry Andric 
13710b57cec5SDimitry Andric   // The next parameter may be a std::destroying_delete_t.
13720b57cec5SDimitry Andric   if (FD->isDestroyingOperatorDelete()) {
13730b57cec5SDimitry Andric     Params.DestroyingDelete = true;
13740b57cec5SDimitry Andric     assert(AI != AE);
13750b57cec5SDimitry Andric     ++AI;
13760b57cec5SDimitry Andric   }
13770b57cec5SDimitry Andric 
13780b57cec5SDimitry Andric   // Figure out what other parameters we should be implicitly passing.
13790b57cec5SDimitry Andric   if (AI != AE && (*AI)->isIntegerType()) {
13800b57cec5SDimitry Andric     Params.Size = true;
13810b57cec5SDimitry Andric     ++AI;
13820b57cec5SDimitry Andric   }
13830b57cec5SDimitry Andric 
13840b57cec5SDimitry Andric   if (AI != AE && (*AI)->isAlignValT()) {
13850b57cec5SDimitry Andric     Params.Alignment = true;
13860b57cec5SDimitry Andric     ++AI;
13870b57cec5SDimitry Andric   }
13880b57cec5SDimitry Andric 
13890b57cec5SDimitry Andric   assert(AI == AE && "unexpected usual deallocation function parameter");
13900b57cec5SDimitry Andric   return Params;
13910b57cec5SDimitry Andric }
13920b57cec5SDimitry Andric 
13930b57cec5SDimitry Andric namespace {
13940b57cec5SDimitry Andric   /// A cleanup to call the given 'operator delete' function upon abnormal
13950b57cec5SDimitry Andric   /// exit from a new expression. Templated on a traits type that deals with
13960b57cec5SDimitry Andric   /// ensuring that the arguments dominate the cleanup if necessary.
13970b57cec5SDimitry Andric   template<typename Traits>
13980b57cec5SDimitry Andric   class CallDeleteDuringNew final : public EHScopeStack::Cleanup {
13990b57cec5SDimitry Andric     /// Type used to hold llvm::Value*s.
14000b57cec5SDimitry Andric     typedef typename Traits::ValueTy ValueTy;
14010b57cec5SDimitry Andric     /// Type used to hold RValues.
14020b57cec5SDimitry Andric     typedef typename Traits::RValueTy RValueTy;
14030b57cec5SDimitry Andric     struct PlacementArg {
14040b57cec5SDimitry Andric       RValueTy ArgValue;
14050b57cec5SDimitry Andric       QualType ArgType;
14060b57cec5SDimitry Andric     };
14070b57cec5SDimitry Andric 
14080b57cec5SDimitry Andric     unsigned NumPlacementArgs : 31;
14090b57cec5SDimitry Andric     unsigned PassAlignmentToPlacementDelete : 1;
14100b57cec5SDimitry Andric     const FunctionDecl *OperatorDelete;
14110b57cec5SDimitry Andric     ValueTy Ptr;
14120b57cec5SDimitry Andric     ValueTy AllocSize;
14130b57cec5SDimitry Andric     CharUnits AllocAlign;
14140b57cec5SDimitry Andric 
getPlacementArgs()14150b57cec5SDimitry Andric     PlacementArg *getPlacementArgs() {
14160b57cec5SDimitry Andric       return reinterpret_cast<PlacementArg *>(this + 1);
14170b57cec5SDimitry Andric     }
14180b57cec5SDimitry Andric 
14190b57cec5SDimitry Andric   public:
getExtraSize(size_t NumPlacementArgs)14200b57cec5SDimitry Andric     static size_t getExtraSize(size_t NumPlacementArgs) {
14210b57cec5SDimitry Andric       return NumPlacementArgs * sizeof(PlacementArg);
14220b57cec5SDimitry Andric     }
14230b57cec5SDimitry Andric 
CallDeleteDuringNew(size_t NumPlacementArgs,const FunctionDecl * OperatorDelete,ValueTy Ptr,ValueTy AllocSize,bool PassAlignmentToPlacementDelete,CharUnits AllocAlign)14240b57cec5SDimitry Andric     CallDeleteDuringNew(size_t NumPlacementArgs,
14250b57cec5SDimitry Andric                         const FunctionDecl *OperatorDelete, ValueTy Ptr,
14260b57cec5SDimitry Andric                         ValueTy AllocSize, bool PassAlignmentToPlacementDelete,
14270b57cec5SDimitry Andric                         CharUnits AllocAlign)
14280b57cec5SDimitry Andric       : NumPlacementArgs(NumPlacementArgs),
14290b57cec5SDimitry Andric         PassAlignmentToPlacementDelete(PassAlignmentToPlacementDelete),
14300b57cec5SDimitry Andric         OperatorDelete(OperatorDelete), Ptr(Ptr), AllocSize(AllocSize),
14310b57cec5SDimitry Andric         AllocAlign(AllocAlign) {}
14320b57cec5SDimitry Andric 
setPlacementArg(unsigned I,RValueTy Arg,QualType Type)14330b57cec5SDimitry Andric     void setPlacementArg(unsigned I, RValueTy Arg, QualType Type) {
14340b57cec5SDimitry Andric       assert(I < NumPlacementArgs && "index out of range");
14350b57cec5SDimitry Andric       getPlacementArgs()[I] = {Arg, Type};
14360b57cec5SDimitry Andric     }
14370b57cec5SDimitry Andric 
Emit(CodeGenFunction & CGF,Flags flags)14380b57cec5SDimitry Andric     void Emit(CodeGenFunction &CGF, Flags flags) override {
1439480093f4SDimitry Andric       const auto *FPT = OperatorDelete->getType()->castAs<FunctionProtoType>();
14400b57cec5SDimitry Andric       CallArgList DeleteArgs;
14410b57cec5SDimitry Andric 
14420b57cec5SDimitry Andric       // The first argument is always a void* (or C* for a destroying operator
14430b57cec5SDimitry Andric       // delete for class type C).
14440b57cec5SDimitry Andric       DeleteArgs.add(Traits::get(CGF, Ptr), FPT->getParamType(0));
14450b57cec5SDimitry Andric 
14460b57cec5SDimitry Andric       // Figure out what other parameters we should be implicitly passing.
14470b57cec5SDimitry Andric       UsualDeleteParams Params;
14480b57cec5SDimitry Andric       if (NumPlacementArgs) {
14490b57cec5SDimitry Andric         // A placement deallocation function is implicitly passed an alignment
14500b57cec5SDimitry Andric         // if the placement allocation function was, but is never passed a size.
14510b57cec5SDimitry Andric         Params.Alignment = PassAlignmentToPlacementDelete;
14520b57cec5SDimitry Andric       } else {
14530b57cec5SDimitry Andric         // For a non-placement new-expression, 'operator delete' can take a
14540b57cec5SDimitry Andric         // size and/or an alignment if it has the right parameters.
14550b57cec5SDimitry Andric         Params = getUsualDeleteParams(OperatorDelete);
14560b57cec5SDimitry Andric       }
14570b57cec5SDimitry Andric 
14580b57cec5SDimitry Andric       assert(!Params.DestroyingDelete &&
14590b57cec5SDimitry Andric              "should not call destroying delete in a new-expression");
14600b57cec5SDimitry Andric 
14610b57cec5SDimitry Andric       // The second argument can be a std::size_t (for non-placement delete).
14620b57cec5SDimitry Andric       if (Params.Size)
14630b57cec5SDimitry Andric         DeleteArgs.add(Traits::get(CGF, AllocSize),
14640b57cec5SDimitry Andric                        CGF.getContext().getSizeType());
14650b57cec5SDimitry Andric 
14660b57cec5SDimitry Andric       // The next (second or third) argument can be a std::align_val_t, which
14670b57cec5SDimitry Andric       // is an enum whose underlying type is std::size_t.
14680b57cec5SDimitry Andric       // FIXME: Use the right type as the parameter type. Note that in a call
14690b57cec5SDimitry Andric       // to operator delete(size_t, ...), we may not have it available.
14700b57cec5SDimitry Andric       if (Params.Alignment)
14710b57cec5SDimitry Andric         DeleteArgs.add(RValue::get(llvm::ConstantInt::get(
14720b57cec5SDimitry Andric                            CGF.SizeTy, AllocAlign.getQuantity())),
14730b57cec5SDimitry Andric                        CGF.getContext().getSizeType());
14740b57cec5SDimitry Andric 
14750b57cec5SDimitry Andric       // Pass the rest of the arguments, which must match exactly.
14760b57cec5SDimitry Andric       for (unsigned I = 0; I != NumPlacementArgs; ++I) {
14770b57cec5SDimitry Andric         auto Arg = getPlacementArgs()[I];
14780b57cec5SDimitry Andric         DeleteArgs.add(Traits::get(CGF, Arg.ArgValue), Arg.ArgType);
14790b57cec5SDimitry Andric       }
14800b57cec5SDimitry Andric 
14810b57cec5SDimitry Andric       // Call 'operator delete'.
14820b57cec5SDimitry Andric       EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
14830b57cec5SDimitry Andric     }
14840b57cec5SDimitry Andric   };
14850b57cec5SDimitry Andric }
14860b57cec5SDimitry Andric 
14870b57cec5SDimitry Andric /// Enter a cleanup to call 'operator delete' if the initializer in a
14880b57cec5SDimitry Andric /// new-expression throws.
EnterNewDeleteCleanup(CodeGenFunction & CGF,const CXXNewExpr * E,Address NewPtr,llvm::Value * AllocSize,CharUnits AllocAlign,const CallArgList & NewArgs)14890b57cec5SDimitry Andric static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
14900b57cec5SDimitry Andric                                   const CXXNewExpr *E,
14910b57cec5SDimitry Andric                                   Address NewPtr,
14920b57cec5SDimitry Andric                                   llvm::Value *AllocSize,
14930b57cec5SDimitry Andric                                   CharUnits AllocAlign,
14940b57cec5SDimitry Andric                                   const CallArgList &NewArgs) {
14950b57cec5SDimitry Andric   unsigned NumNonPlacementArgs = E->passAlignment() ? 2 : 1;
14960b57cec5SDimitry Andric 
14970b57cec5SDimitry Andric   // If we're not inside a conditional branch, then the cleanup will
14980b57cec5SDimitry Andric   // dominate and we can do the easier (and more efficient) thing.
14990b57cec5SDimitry Andric   if (!CGF.isInConditionalBranch()) {
15000b57cec5SDimitry Andric     struct DirectCleanupTraits {
15010b57cec5SDimitry Andric       typedef llvm::Value *ValueTy;
15020b57cec5SDimitry Andric       typedef RValue RValueTy;
15030b57cec5SDimitry Andric       static RValue get(CodeGenFunction &, ValueTy V) { return RValue::get(V); }
15040b57cec5SDimitry Andric       static RValue get(CodeGenFunction &, RValueTy V) { return V; }
15050b57cec5SDimitry Andric     };
15060b57cec5SDimitry Andric 
15070b57cec5SDimitry Andric     typedef CallDeleteDuringNew<DirectCleanupTraits> DirectCleanup;
15080b57cec5SDimitry Andric 
15090b57cec5SDimitry Andric     DirectCleanup *Cleanup = CGF.EHStack
15100b57cec5SDimitry Andric       .pushCleanupWithExtra<DirectCleanup>(EHCleanup,
15110b57cec5SDimitry Andric                                            E->getNumPlacementArgs(),
15120b57cec5SDimitry Andric                                            E->getOperatorDelete(),
15130b57cec5SDimitry Andric                                            NewPtr.getPointer(),
15140b57cec5SDimitry Andric                                            AllocSize,
15150b57cec5SDimitry Andric                                            E->passAlignment(),
15160b57cec5SDimitry Andric                                            AllocAlign);
15170b57cec5SDimitry Andric     for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
15180b57cec5SDimitry Andric       auto &Arg = NewArgs[I + NumNonPlacementArgs];
15190b57cec5SDimitry Andric       Cleanup->setPlacementArg(I, Arg.getRValue(CGF), Arg.Ty);
15200b57cec5SDimitry Andric     }
15210b57cec5SDimitry Andric 
15220b57cec5SDimitry Andric     return;
15230b57cec5SDimitry Andric   }
15240b57cec5SDimitry Andric 
15250b57cec5SDimitry Andric   // Otherwise, we need to save all this stuff.
15260b57cec5SDimitry Andric   DominatingValue<RValue>::saved_type SavedNewPtr =
15270b57cec5SDimitry Andric     DominatingValue<RValue>::save(CGF, RValue::get(NewPtr.getPointer()));
15280b57cec5SDimitry Andric   DominatingValue<RValue>::saved_type SavedAllocSize =
15290b57cec5SDimitry Andric     DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
15300b57cec5SDimitry Andric 
15310b57cec5SDimitry Andric   struct ConditionalCleanupTraits {
15320b57cec5SDimitry Andric     typedef DominatingValue<RValue>::saved_type ValueTy;
15330b57cec5SDimitry Andric     typedef DominatingValue<RValue>::saved_type RValueTy;
15340b57cec5SDimitry Andric     static RValue get(CodeGenFunction &CGF, ValueTy V) {
15350b57cec5SDimitry Andric       return V.restore(CGF);
15360b57cec5SDimitry Andric     }
15370b57cec5SDimitry Andric   };
15380b57cec5SDimitry Andric   typedef CallDeleteDuringNew<ConditionalCleanupTraits> ConditionalCleanup;
15390b57cec5SDimitry Andric 
15400b57cec5SDimitry Andric   ConditionalCleanup *Cleanup = CGF.EHStack
15410b57cec5SDimitry Andric     .pushCleanupWithExtra<ConditionalCleanup>(EHCleanup,
15420b57cec5SDimitry Andric                                               E->getNumPlacementArgs(),
15430b57cec5SDimitry Andric                                               E->getOperatorDelete(),
15440b57cec5SDimitry Andric                                               SavedNewPtr,
15450b57cec5SDimitry Andric                                               SavedAllocSize,
15460b57cec5SDimitry Andric                                               E->passAlignment(),
15470b57cec5SDimitry Andric                                               AllocAlign);
15480b57cec5SDimitry Andric   for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
15490b57cec5SDimitry Andric     auto &Arg = NewArgs[I + NumNonPlacementArgs];
15500b57cec5SDimitry Andric     Cleanup->setPlacementArg(
15510b57cec5SDimitry Andric         I, DominatingValue<RValue>::save(CGF, Arg.getRValue(CGF)), Arg.Ty);
15520b57cec5SDimitry Andric   }
15530b57cec5SDimitry Andric 
15540b57cec5SDimitry Andric   CGF.initFullExprCleanup();
15550b57cec5SDimitry Andric }
15560b57cec5SDimitry Andric 
EmitCXXNewExpr(const CXXNewExpr * E)15570b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
15580b57cec5SDimitry Andric   // The element type being allocated.
15590b57cec5SDimitry Andric   QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
15600b57cec5SDimitry Andric 
15610b57cec5SDimitry Andric   // 1. Build a call to the allocation function.
15620b57cec5SDimitry Andric   FunctionDecl *allocator = E->getOperatorNew();
15630b57cec5SDimitry Andric 
15640b57cec5SDimitry Andric   // If there is a brace-initializer, cannot allocate fewer elements than inits.
15650b57cec5SDimitry Andric   unsigned minElements = 0;
15660b57cec5SDimitry Andric   if (E->isArray() && E->hasInitializer()) {
15670b57cec5SDimitry Andric     const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer());
15680b57cec5SDimitry Andric     if (ILE && ILE->isStringLiteralInit())
15690b57cec5SDimitry Andric       minElements =
15700b57cec5SDimitry Andric           cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe())
15710b57cec5SDimitry Andric               ->getSize().getZExtValue();
15720b57cec5SDimitry Andric     else if (ILE)
15730b57cec5SDimitry Andric       minElements = ILE->getNumInits();
15740b57cec5SDimitry Andric   }
15750b57cec5SDimitry Andric 
15760b57cec5SDimitry Andric   llvm::Value *numElements = nullptr;
15770b57cec5SDimitry Andric   llvm::Value *allocSizeWithoutCookie = nullptr;
15780b57cec5SDimitry Andric   llvm::Value *allocSize =
15790b57cec5SDimitry Andric     EmitCXXNewAllocSize(*this, E, minElements, numElements,
15800b57cec5SDimitry Andric                         allocSizeWithoutCookie);
1581af732203SDimitry Andric   CharUnits allocAlign = getContext().getPreferredTypeAlignInChars(allocType);
15820b57cec5SDimitry Andric 
15830b57cec5SDimitry Andric   // Emit the allocation call.  If the allocator is a global placement
15840b57cec5SDimitry Andric   // operator, just "inline" it directly.
15850b57cec5SDimitry Andric   Address allocation = Address::invalid();
15860b57cec5SDimitry Andric   CallArgList allocatorArgs;
15870b57cec5SDimitry Andric   if (allocator->isReservedGlobalPlacementOperator()) {
15880b57cec5SDimitry Andric     assert(E->getNumPlacementArgs() == 1);
15890b57cec5SDimitry Andric     const Expr *arg = *E->placement_arguments().begin();
15900b57cec5SDimitry Andric 
15910b57cec5SDimitry Andric     LValueBaseInfo BaseInfo;
15920b57cec5SDimitry Andric     allocation = EmitPointerWithAlignment(arg, &BaseInfo);
15930b57cec5SDimitry Andric 
15940b57cec5SDimitry Andric     // The pointer expression will, in many cases, be an opaque void*.
15950b57cec5SDimitry Andric     // In these cases, discard the computed alignment and use the
15960b57cec5SDimitry Andric     // formal alignment of the allocated type.
15970b57cec5SDimitry Andric     if (BaseInfo.getAlignmentSource() != AlignmentSource::Decl)
15980b57cec5SDimitry Andric       allocation = Address(allocation.getPointer(), allocAlign);
15990b57cec5SDimitry Andric 
16000b57cec5SDimitry Andric     // Set up allocatorArgs for the call to operator delete if it's not
16010b57cec5SDimitry Andric     // the reserved global operator.
16020b57cec5SDimitry Andric     if (E->getOperatorDelete() &&
16030b57cec5SDimitry Andric         !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
16040b57cec5SDimitry Andric       allocatorArgs.add(RValue::get(allocSize), getContext().getSizeType());
16050b57cec5SDimitry Andric       allocatorArgs.add(RValue::get(allocation.getPointer()), arg->getType());
16060b57cec5SDimitry Andric     }
16070b57cec5SDimitry Andric 
16080b57cec5SDimitry Andric   } else {
16090b57cec5SDimitry Andric     const FunctionProtoType *allocatorType =
16100b57cec5SDimitry Andric       allocator->getType()->castAs<FunctionProtoType>();
16110b57cec5SDimitry Andric     unsigned ParamsToSkip = 0;
16120b57cec5SDimitry Andric 
16130b57cec5SDimitry Andric     // The allocation size is the first argument.
16140b57cec5SDimitry Andric     QualType sizeType = getContext().getSizeType();
16150b57cec5SDimitry Andric     allocatorArgs.add(RValue::get(allocSize), sizeType);
16160b57cec5SDimitry Andric     ++ParamsToSkip;
16170b57cec5SDimitry Andric 
16180b57cec5SDimitry Andric     if (allocSize != allocSizeWithoutCookie) {
16190b57cec5SDimitry Andric       CharUnits cookieAlign = getSizeAlign(); // FIXME: Ask the ABI.
16200b57cec5SDimitry Andric       allocAlign = std::max(allocAlign, cookieAlign);
16210b57cec5SDimitry Andric     }
16220b57cec5SDimitry Andric 
16230b57cec5SDimitry Andric     // The allocation alignment may be passed as the second argument.
16240b57cec5SDimitry Andric     if (E->passAlignment()) {
16250b57cec5SDimitry Andric       QualType AlignValT = sizeType;
16260b57cec5SDimitry Andric       if (allocatorType->getNumParams() > 1) {
16270b57cec5SDimitry Andric         AlignValT = allocatorType->getParamType(1);
16280b57cec5SDimitry Andric         assert(getContext().hasSameUnqualifiedType(
16290b57cec5SDimitry Andric                    AlignValT->castAs<EnumType>()->getDecl()->getIntegerType(),
16300b57cec5SDimitry Andric                    sizeType) &&
16310b57cec5SDimitry Andric                "wrong type for alignment parameter");
16320b57cec5SDimitry Andric         ++ParamsToSkip;
16330b57cec5SDimitry Andric       } else {
16340b57cec5SDimitry Andric         // Corner case, passing alignment to 'operator new(size_t, ...)'.
16350b57cec5SDimitry Andric         assert(allocator->isVariadic() && "can't pass alignment to allocator");
16360b57cec5SDimitry Andric       }
16370b57cec5SDimitry Andric       allocatorArgs.add(
16380b57cec5SDimitry Andric           RValue::get(llvm::ConstantInt::get(SizeTy, allocAlign.getQuantity())),
16390b57cec5SDimitry Andric           AlignValT);
16400b57cec5SDimitry Andric     }
16410b57cec5SDimitry Andric 
16420b57cec5SDimitry Andric     // FIXME: Why do we not pass a CalleeDecl here?
16430b57cec5SDimitry Andric     EmitCallArgs(allocatorArgs, allocatorType, E->placement_arguments(),
16440b57cec5SDimitry Andric                  /*AC*/AbstractCallee(), /*ParamsToSkip*/ParamsToSkip);
16450b57cec5SDimitry Andric 
16460b57cec5SDimitry Andric     RValue RV =
16470b57cec5SDimitry Andric       EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
16480b57cec5SDimitry Andric 
16495ffd83dbSDimitry Andric     // Set !heapallocsite metadata on the call to operator new.
16505ffd83dbSDimitry Andric     if (getDebugInfo())
16515ffd83dbSDimitry Andric       if (auto *newCall = dyn_cast<llvm::CallBase>(RV.getScalarVal()))
16525ffd83dbSDimitry Andric         getDebugInfo()->addHeapAllocSiteMetadata(newCall, allocType,
16535ffd83dbSDimitry Andric                                                  E->getExprLoc());
16545ffd83dbSDimitry Andric 
16550b57cec5SDimitry Andric     // If this was a call to a global replaceable allocation function that does
16560b57cec5SDimitry Andric     // not take an alignment argument, the allocator is known to produce
16570b57cec5SDimitry Andric     // storage that's suitably aligned for any object that fits, up to a known
16580b57cec5SDimitry Andric     // threshold. Otherwise assume it's suitably aligned for the allocated type.
16590b57cec5SDimitry Andric     CharUnits allocationAlign = allocAlign;
16600b57cec5SDimitry Andric     if (!E->passAlignment() &&
16610b57cec5SDimitry Andric         allocator->isReplaceableGlobalAllocationFunction()) {
16620b57cec5SDimitry Andric       unsigned AllocatorAlign = llvm::PowerOf2Floor(std::min<uint64_t>(
16630b57cec5SDimitry Andric           Target.getNewAlign(), getContext().getTypeSize(allocType)));
16640b57cec5SDimitry Andric       allocationAlign = std::max(
16650b57cec5SDimitry Andric           allocationAlign, getContext().toCharUnitsFromBits(AllocatorAlign));
16660b57cec5SDimitry Andric     }
16670b57cec5SDimitry Andric 
16680b57cec5SDimitry Andric     allocation = Address(RV.getScalarVal(), allocationAlign);
16690b57cec5SDimitry Andric   }
16700b57cec5SDimitry Andric 
16710b57cec5SDimitry Andric   // Emit a null check on the allocation result if the allocation
16720b57cec5SDimitry Andric   // function is allowed to return null (because it has a non-throwing
16730b57cec5SDimitry Andric   // exception spec or is the reserved placement new) and we have an
16740b57cec5SDimitry Andric   // interesting initializer will be running sanitizers on the initialization.
16750b57cec5SDimitry Andric   bool nullCheck = E->shouldNullCheckAllocation() &&
16760b57cec5SDimitry Andric                    (!allocType.isPODType(getContext()) || E->hasInitializer() ||
16770b57cec5SDimitry Andric                     sanitizePerformTypeCheck());
16780b57cec5SDimitry Andric 
16790b57cec5SDimitry Andric   llvm::BasicBlock *nullCheckBB = nullptr;
16800b57cec5SDimitry Andric   llvm::BasicBlock *contBB = nullptr;
16810b57cec5SDimitry Andric 
16820b57cec5SDimitry Andric   // The null-check means that the initializer is conditionally
16830b57cec5SDimitry Andric   // evaluated.
16840b57cec5SDimitry Andric   ConditionalEvaluation conditional(*this);
16850b57cec5SDimitry Andric 
16860b57cec5SDimitry Andric   if (nullCheck) {
16870b57cec5SDimitry Andric     conditional.begin(*this);
16880b57cec5SDimitry Andric 
16890b57cec5SDimitry Andric     nullCheckBB = Builder.GetInsertBlock();
16900b57cec5SDimitry Andric     llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
16910b57cec5SDimitry Andric     contBB = createBasicBlock("new.cont");
16920b57cec5SDimitry Andric 
16930b57cec5SDimitry Andric     llvm::Value *isNull =
16940b57cec5SDimitry Andric       Builder.CreateIsNull(allocation.getPointer(), "new.isnull");
16950b57cec5SDimitry Andric     Builder.CreateCondBr(isNull, contBB, notNullBB);
16960b57cec5SDimitry Andric     EmitBlock(notNullBB);
16970b57cec5SDimitry Andric   }
16980b57cec5SDimitry Andric 
16990b57cec5SDimitry Andric   // If there's an operator delete, enter a cleanup to call it if an
17000b57cec5SDimitry Andric   // exception is thrown.
17010b57cec5SDimitry Andric   EHScopeStack::stable_iterator operatorDeleteCleanup;
17020b57cec5SDimitry Andric   llvm::Instruction *cleanupDominator = nullptr;
17030b57cec5SDimitry Andric   if (E->getOperatorDelete() &&
17040b57cec5SDimitry Andric       !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
17050b57cec5SDimitry Andric     EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocAlign,
17060b57cec5SDimitry Andric                           allocatorArgs);
17070b57cec5SDimitry Andric     operatorDeleteCleanup = EHStack.stable_begin();
17080b57cec5SDimitry Andric     cleanupDominator = Builder.CreateUnreachable();
17090b57cec5SDimitry Andric   }
17100b57cec5SDimitry Andric 
17110b57cec5SDimitry Andric   assert((allocSize == allocSizeWithoutCookie) ==
17120b57cec5SDimitry Andric          CalculateCookiePadding(*this, E).isZero());
17130b57cec5SDimitry Andric   if (allocSize != allocSizeWithoutCookie) {
17140b57cec5SDimitry Andric     assert(E->isArray());
17150b57cec5SDimitry Andric     allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
17160b57cec5SDimitry Andric                                                        numElements,
17170b57cec5SDimitry Andric                                                        E, allocType);
17180b57cec5SDimitry Andric   }
17190b57cec5SDimitry Andric 
17200b57cec5SDimitry Andric   llvm::Type *elementTy = ConvertTypeForMem(allocType);
17210b57cec5SDimitry Andric   Address result = Builder.CreateElementBitCast(allocation, elementTy);
17220b57cec5SDimitry Andric 
17230b57cec5SDimitry Andric   // Passing pointer through launder.invariant.group to avoid propagation of
17240b57cec5SDimitry Andric   // vptrs information which may be included in previous type.
17250b57cec5SDimitry Andric   // To not break LTO with different optimizations levels, we do it regardless
17260b57cec5SDimitry Andric   // of optimization level.
17270b57cec5SDimitry Andric   if (CGM.getCodeGenOpts().StrictVTablePointers &&
17280b57cec5SDimitry Andric       allocator->isReservedGlobalPlacementOperator())
17290b57cec5SDimitry Andric     result = Address(Builder.CreateLaunderInvariantGroup(result.getPointer()),
17300b57cec5SDimitry Andric                      result.getAlignment());
17310b57cec5SDimitry Andric 
17320b57cec5SDimitry Andric   // Emit sanitizer checks for pointer value now, so that in the case of an
17330b57cec5SDimitry Andric   // array it was checked only once and not at each constructor call. We may
17340b57cec5SDimitry Andric   // have already checked that the pointer is non-null.
17350b57cec5SDimitry Andric   // FIXME: If we have an array cookie and a potentially-throwing allocator,
17360b57cec5SDimitry Andric   // we'll null check the wrong pointer here.
17370b57cec5SDimitry Andric   SanitizerSet SkippedChecks;
17380b57cec5SDimitry Andric   SkippedChecks.set(SanitizerKind::Null, nullCheck);
17390b57cec5SDimitry Andric   EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall,
17400b57cec5SDimitry Andric                 E->getAllocatedTypeSourceInfo()->getTypeLoc().getBeginLoc(),
17410b57cec5SDimitry Andric                 result.getPointer(), allocType, result.getAlignment(),
17420b57cec5SDimitry Andric                 SkippedChecks, numElements);
17430b57cec5SDimitry Andric 
17440b57cec5SDimitry Andric   EmitNewInitializer(*this, E, allocType, elementTy, result, numElements,
17450b57cec5SDimitry Andric                      allocSizeWithoutCookie);
17460b57cec5SDimitry Andric   if (E->isArray()) {
17470b57cec5SDimitry Andric     // NewPtr is a pointer to the base element type.  If we're
17480b57cec5SDimitry Andric     // allocating an array of arrays, we'll need to cast back to the
17490b57cec5SDimitry Andric     // array pointer type.
17500b57cec5SDimitry Andric     llvm::Type *resultType = ConvertTypeForMem(E->getType());
17510b57cec5SDimitry Andric     if (result.getType() != resultType)
17520b57cec5SDimitry Andric       result = Builder.CreateBitCast(result, resultType);
17530b57cec5SDimitry Andric   }
17540b57cec5SDimitry Andric 
17550b57cec5SDimitry Andric   // Deactivate the 'operator delete' cleanup if we finished
17560b57cec5SDimitry Andric   // initialization.
17570b57cec5SDimitry Andric   if (operatorDeleteCleanup.isValid()) {
17580b57cec5SDimitry Andric     DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
17590b57cec5SDimitry Andric     cleanupDominator->eraseFromParent();
17600b57cec5SDimitry Andric   }
17610b57cec5SDimitry Andric 
17620b57cec5SDimitry Andric   llvm::Value *resultPtr = result.getPointer();
17630b57cec5SDimitry Andric   if (nullCheck) {
17640b57cec5SDimitry Andric     conditional.end(*this);
17650b57cec5SDimitry Andric 
17660b57cec5SDimitry Andric     llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
17670b57cec5SDimitry Andric     EmitBlock(contBB);
17680b57cec5SDimitry Andric 
17690b57cec5SDimitry Andric     llvm::PHINode *PHI = Builder.CreatePHI(resultPtr->getType(), 2);
17700b57cec5SDimitry Andric     PHI->addIncoming(resultPtr, notNullBB);
17710b57cec5SDimitry Andric     PHI->addIncoming(llvm::Constant::getNullValue(resultPtr->getType()),
17720b57cec5SDimitry Andric                      nullCheckBB);
17730b57cec5SDimitry Andric 
17740b57cec5SDimitry Andric     resultPtr = PHI;
17750b57cec5SDimitry Andric   }
17760b57cec5SDimitry Andric 
17770b57cec5SDimitry Andric   return resultPtr;
17780b57cec5SDimitry Andric }
17790b57cec5SDimitry Andric 
EmitDeleteCall(const FunctionDecl * DeleteFD,llvm::Value * Ptr,QualType DeleteTy,llvm::Value * NumElements,CharUnits CookieSize)17800b57cec5SDimitry Andric void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
17810b57cec5SDimitry Andric                                      llvm::Value *Ptr, QualType DeleteTy,
17820b57cec5SDimitry Andric                                      llvm::Value *NumElements,
17830b57cec5SDimitry Andric                                      CharUnits CookieSize) {
17840b57cec5SDimitry Andric   assert((!NumElements && CookieSize.isZero()) ||
17850b57cec5SDimitry Andric          DeleteFD->getOverloadedOperator() == OO_Array_Delete);
17860b57cec5SDimitry Andric 
1787480093f4SDimitry Andric   const auto *DeleteFTy = DeleteFD->getType()->castAs<FunctionProtoType>();
17880b57cec5SDimitry Andric   CallArgList DeleteArgs;
17890b57cec5SDimitry Andric 
17900b57cec5SDimitry Andric   auto Params = getUsualDeleteParams(DeleteFD);
17910b57cec5SDimitry Andric   auto ParamTypeIt = DeleteFTy->param_type_begin();
17920b57cec5SDimitry Andric 
17930b57cec5SDimitry Andric   // Pass the pointer itself.
17940b57cec5SDimitry Andric   QualType ArgTy = *ParamTypeIt++;
17950b57cec5SDimitry Andric   llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
17960b57cec5SDimitry Andric   DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
17970b57cec5SDimitry Andric 
17980b57cec5SDimitry Andric   // Pass the std::destroying_delete tag if present.
1799af732203SDimitry Andric   llvm::AllocaInst *DestroyingDeleteTag = nullptr;
18000b57cec5SDimitry Andric   if (Params.DestroyingDelete) {
18010b57cec5SDimitry Andric     QualType DDTag = *ParamTypeIt++;
1802af732203SDimitry Andric     llvm::Type *Ty = getTypes().ConvertType(DDTag);
1803af732203SDimitry Andric     CharUnits Align = CGM.getNaturalTypeAlignment(DDTag);
1804af732203SDimitry Andric     DestroyingDeleteTag = CreateTempAlloca(Ty, "destroying.delete.tag");
1805af732203SDimitry Andric     DestroyingDeleteTag->setAlignment(Align.getAsAlign());
1806af732203SDimitry Andric     DeleteArgs.add(RValue::getAggregate(Address(DestroyingDeleteTag, Align)), DDTag);
18070b57cec5SDimitry Andric   }
18080b57cec5SDimitry Andric 
18090b57cec5SDimitry Andric   // Pass the size if the delete function has a size_t parameter.
18100b57cec5SDimitry Andric   if (Params.Size) {
18110b57cec5SDimitry Andric     QualType SizeType = *ParamTypeIt++;
18120b57cec5SDimitry Andric     CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
18130b57cec5SDimitry Andric     llvm::Value *Size = llvm::ConstantInt::get(ConvertType(SizeType),
18140b57cec5SDimitry Andric                                                DeleteTypeSize.getQuantity());
18150b57cec5SDimitry Andric 
18160b57cec5SDimitry Andric     // For array new, multiply by the number of elements.
18170b57cec5SDimitry Andric     if (NumElements)
18180b57cec5SDimitry Andric       Size = Builder.CreateMul(Size, NumElements);
18190b57cec5SDimitry Andric 
18200b57cec5SDimitry Andric     // If there is a cookie, add the cookie size.
18210b57cec5SDimitry Andric     if (!CookieSize.isZero())
18220b57cec5SDimitry Andric       Size = Builder.CreateAdd(
18230b57cec5SDimitry Andric           Size, llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity()));
18240b57cec5SDimitry Andric 
18250b57cec5SDimitry Andric     DeleteArgs.add(RValue::get(Size), SizeType);
18260b57cec5SDimitry Andric   }
18270b57cec5SDimitry Andric 
18280b57cec5SDimitry Andric   // Pass the alignment if the delete function has an align_val_t parameter.
18290b57cec5SDimitry Andric   if (Params.Alignment) {
18300b57cec5SDimitry Andric     QualType AlignValType = *ParamTypeIt++;
1831af732203SDimitry Andric     CharUnits DeleteTypeAlign =
1832af732203SDimitry Andric         getContext().toCharUnitsFromBits(getContext().getTypeAlignIfKnown(
1833af732203SDimitry Andric             DeleteTy, true /* NeedsPreferredAlignment */));
18340b57cec5SDimitry Andric     llvm::Value *Align = llvm::ConstantInt::get(ConvertType(AlignValType),
18350b57cec5SDimitry Andric                                                 DeleteTypeAlign.getQuantity());
18360b57cec5SDimitry Andric     DeleteArgs.add(RValue::get(Align), AlignValType);
18370b57cec5SDimitry Andric   }
18380b57cec5SDimitry Andric 
18390b57cec5SDimitry Andric   assert(ParamTypeIt == DeleteFTy->param_type_end() &&
18400b57cec5SDimitry Andric          "unknown parameter to usual delete function");
18410b57cec5SDimitry Andric 
18420b57cec5SDimitry Andric   // Emit the call to delete.
18430b57cec5SDimitry Andric   EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
1844af732203SDimitry Andric 
1845af732203SDimitry Andric   // If call argument lowering didn't use the destroying_delete_t alloca,
1846af732203SDimitry Andric   // remove it again.
1847af732203SDimitry Andric   if (DestroyingDeleteTag && DestroyingDeleteTag->use_empty())
1848af732203SDimitry Andric     DestroyingDeleteTag->eraseFromParent();
18490b57cec5SDimitry Andric }
18500b57cec5SDimitry Andric 
18510b57cec5SDimitry Andric namespace {
18520b57cec5SDimitry Andric   /// Calls the given 'operator delete' on a single object.
18530b57cec5SDimitry Andric   struct CallObjectDelete final : EHScopeStack::Cleanup {
18540b57cec5SDimitry Andric     llvm::Value *Ptr;
18550b57cec5SDimitry Andric     const FunctionDecl *OperatorDelete;
18560b57cec5SDimitry Andric     QualType ElementType;
18570b57cec5SDimitry Andric 
CallObjectDelete__anonb29e8e2e0511::CallObjectDelete18580b57cec5SDimitry Andric     CallObjectDelete(llvm::Value *Ptr,
18590b57cec5SDimitry Andric                      const FunctionDecl *OperatorDelete,
18600b57cec5SDimitry Andric                      QualType ElementType)
18610b57cec5SDimitry Andric       : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
18620b57cec5SDimitry Andric 
Emit__anonb29e8e2e0511::CallObjectDelete18630b57cec5SDimitry Andric     void Emit(CodeGenFunction &CGF, Flags flags) override {
18640b57cec5SDimitry Andric       CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
18650b57cec5SDimitry Andric     }
18660b57cec5SDimitry Andric   };
18670b57cec5SDimitry Andric }
18680b57cec5SDimitry Andric 
18690b57cec5SDimitry Andric void
pushCallObjectDeleteCleanup(const FunctionDecl * OperatorDelete,llvm::Value * CompletePtr,QualType ElementType)18700b57cec5SDimitry Andric CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
18710b57cec5SDimitry Andric                                              llvm::Value *CompletePtr,
18720b57cec5SDimitry Andric                                              QualType ElementType) {
18730b57cec5SDimitry Andric   EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr,
18740b57cec5SDimitry Andric                                         OperatorDelete, ElementType);
18750b57cec5SDimitry Andric }
18760b57cec5SDimitry Andric 
18770b57cec5SDimitry Andric /// Emit the code for deleting a single object with a destroying operator
18780b57cec5SDimitry Andric /// delete. If the element type has a non-virtual destructor, Ptr has already
18790b57cec5SDimitry Andric /// been converted to the type of the parameter of 'operator delete'. Otherwise
18800b57cec5SDimitry Andric /// Ptr points to an object of the static type.
EmitDestroyingObjectDelete(CodeGenFunction & CGF,const CXXDeleteExpr * DE,Address Ptr,QualType ElementType)18810b57cec5SDimitry Andric static void EmitDestroyingObjectDelete(CodeGenFunction &CGF,
18820b57cec5SDimitry Andric                                        const CXXDeleteExpr *DE, Address Ptr,
18830b57cec5SDimitry Andric                                        QualType ElementType) {
18840b57cec5SDimitry Andric   auto *Dtor = ElementType->getAsCXXRecordDecl()->getDestructor();
18850b57cec5SDimitry Andric   if (Dtor && Dtor->isVirtual())
18860b57cec5SDimitry Andric     CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
18870b57cec5SDimitry Andric                                                 Dtor);
18880b57cec5SDimitry Andric   else
18890b57cec5SDimitry Andric     CGF.EmitDeleteCall(DE->getOperatorDelete(), Ptr.getPointer(), ElementType);
18900b57cec5SDimitry Andric }
18910b57cec5SDimitry Andric 
18920b57cec5SDimitry Andric /// Emit the code for deleting a single object.
18935ffd83dbSDimitry Andric /// \return \c true if we started emitting UnconditionalDeleteBlock, \c false
18945ffd83dbSDimitry Andric /// if not.
EmitObjectDelete(CodeGenFunction & CGF,const CXXDeleteExpr * DE,Address Ptr,QualType ElementType,llvm::BasicBlock * UnconditionalDeleteBlock)18955ffd83dbSDimitry Andric static bool EmitObjectDelete(CodeGenFunction &CGF,
18960b57cec5SDimitry Andric                              const CXXDeleteExpr *DE,
18970b57cec5SDimitry Andric                              Address Ptr,
18985ffd83dbSDimitry Andric                              QualType ElementType,
18995ffd83dbSDimitry Andric                              llvm::BasicBlock *UnconditionalDeleteBlock) {
19000b57cec5SDimitry Andric   // C++11 [expr.delete]p3:
19010b57cec5SDimitry Andric   //   If the static type of the object to be deleted is different from its
19020b57cec5SDimitry Andric   //   dynamic type, the static type shall be a base class of the dynamic type
19030b57cec5SDimitry Andric   //   of the object to be deleted and the static type shall have a virtual
19040b57cec5SDimitry Andric   //   destructor or the behavior is undefined.
19050b57cec5SDimitry Andric   CGF.EmitTypeCheck(CodeGenFunction::TCK_MemberCall,
19060b57cec5SDimitry Andric                     DE->getExprLoc(), Ptr.getPointer(),
19070b57cec5SDimitry Andric                     ElementType);
19080b57cec5SDimitry Andric 
19090b57cec5SDimitry Andric   const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
19100b57cec5SDimitry Andric   assert(!OperatorDelete->isDestroyingOperatorDelete());
19110b57cec5SDimitry Andric 
19120b57cec5SDimitry Andric   // Find the destructor for the type, if applicable.  If the
19130b57cec5SDimitry Andric   // destructor is virtual, we'll just emit the vcall and return.
19140b57cec5SDimitry Andric   const CXXDestructorDecl *Dtor = nullptr;
19150b57cec5SDimitry Andric   if (const RecordType *RT = ElementType->getAs<RecordType>()) {
19160b57cec5SDimitry Andric     CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
19170b57cec5SDimitry Andric     if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
19180b57cec5SDimitry Andric       Dtor = RD->getDestructor();
19190b57cec5SDimitry Andric 
19200b57cec5SDimitry Andric       if (Dtor->isVirtual()) {
1921a7dea167SDimitry Andric         bool UseVirtualCall = true;
1922a7dea167SDimitry Andric         const Expr *Base = DE->getArgument();
1923a7dea167SDimitry Andric         if (auto *DevirtualizedDtor =
1924a7dea167SDimitry Andric                 dyn_cast_or_null<const CXXDestructorDecl>(
1925a7dea167SDimitry Andric                     Dtor->getDevirtualizedMethod(
1926a7dea167SDimitry Andric                         Base, CGF.CGM.getLangOpts().AppleKext))) {
1927a7dea167SDimitry Andric           UseVirtualCall = false;
1928a7dea167SDimitry Andric           const CXXRecordDecl *DevirtualizedClass =
1929a7dea167SDimitry Andric               DevirtualizedDtor->getParent();
1930a7dea167SDimitry Andric           if (declaresSameEntity(getCXXRecord(Base), DevirtualizedClass)) {
1931a7dea167SDimitry Andric             // Devirtualized to the class of the base type (the type of the
1932a7dea167SDimitry Andric             // whole expression).
1933a7dea167SDimitry Andric             Dtor = DevirtualizedDtor;
1934a7dea167SDimitry Andric           } else {
1935a7dea167SDimitry Andric             // Devirtualized to some other type. Would need to cast the this
1936a7dea167SDimitry Andric             // pointer to that type but we don't have support for that yet, so
1937a7dea167SDimitry Andric             // do a virtual call. FIXME: handle the case where it is
1938a7dea167SDimitry Andric             // devirtualized to the derived type (the type of the inner
1939a7dea167SDimitry Andric             // expression) as in EmitCXXMemberOrOperatorMemberCallExpr.
1940a7dea167SDimitry Andric             UseVirtualCall = true;
1941a7dea167SDimitry Andric           }
1942a7dea167SDimitry Andric         }
1943a7dea167SDimitry Andric         if (UseVirtualCall) {
19440b57cec5SDimitry Andric           CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
19450b57cec5SDimitry Andric                                                       Dtor);
19465ffd83dbSDimitry Andric           return false;
19470b57cec5SDimitry Andric         }
19480b57cec5SDimitry Andric       }
19490b57cec5SDimitry Andric     }
1950a7dea167SDimitry Andric   }
19510b57cec5SDimitry Andric 
19520b57cec5SDimitry Andric   // Make sure that we call delete even if the dtor throws.
19530b57cec5SDimitry Andric   // This doesn't have to a conditional cleanup because we're going
19540b57cec5SDimitry Andric   // to pop it off in a second.
19550b57cec5SDimitry Andric   CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
19560b57cec5SDimitry Andric                                             Ptr.getPointer(),
19570b57cec5SDimitry Andric                                             OperatorDelete, ElementType);
19580b57cec5SDimitry Andric 
19590b57cec5SDimitry Andric   if (Dtor)
19600b57cec5SDimitry Andric     CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
19610b57cec5SDimitry Andric                               /*ForVirtualBase=*/false,
19620b57cec5SDimitry Andric                               /*Delegating=*/false,
19630b57cec5SDimitry Andric                               Ptr, ElementType);
19640b57cec5SDimitry Andric   else if (auto Lifetime = ElementType.getObjCLifetime()) {
19650b57cec5SDimitry Andric     switch (Lifetime) {
19660b57cec5SDimitry Andric     case Qualifiers::OCL_None:
19670b57cec5SDimitry Andric     case Qualifiers::OCL_ExplicitNone:
19680b57cec5SDimitry Andric     case Qualifiers::OCL_Autoreleasing:
19690b57cec5SDimitry Andric       break;
19700b57cec5SDimitry Andric 
19710b57cec5SDimitry Andric     case Qualifiers::OCL_Strong:
19720b57cec5SDimitry Andric       CGF.EmitARCDestroyStrong(Ptr, ARCPreciseLifetime);
19730b57cec5SDimitry Andric       break;
19740b57cec5SDimitry Andric 
19750b57cec5SDimitry Andric     case Qualifiers::OCL_Weak:
19760b57cec5SDimitry Andric       CGF.EmitARCDestroyWeak(Ptr);
19770b57cec5SDimitry Andric       break;
19780b57cec5SDimitry Andric     }
19790b57cec5SDimitry Andric   }
19800b57cec5SDimitry Andric 
19815ffd83dbSDimitry Andric   // When optimizing for size, call 'operator delete' unconditionally.
19825ffd83dbSDimitry Andric   if (CGF.CGM.getCodeGenOpts().OptimizeSize > 1) {
19835ffd83dbSDimitry Andric     CGF.EmitBlock(UnconditionalDeleteBlock);
19840b57cec5SDimitry Andric     CGF.PopCleanupBlock();
19855ffd83dbSDimitry Andric     return true;
19865ffd83dbSDimitry Andric   }
19875ffd83dbSDimitry Andric 
19885ffd83dbSDimitry Andric   CGF.PopCleanupBlock();
19895ffd83dbSDimitry Andric   return false;
19900b57cec5SDimitry Andric }
19910b57cec5SDimitry Andric 
19920b57cec5SDimitry Andric namespace {
19930b57cec5SDimitry Andric   /// Calls the given 'operator delete' on an array of objects.
19940b57cec5SDimitry Andric   struct CallArrayDelete final : EHScopeStack::Cleanup {
19950b57cec5SDimitry Andric     llvm::Value *Ptr;
19960b57cec5SDimitry Andric     const FunctionDecl *OperatorDelete;
19970b57cec5SDimitry Andric     llvm::Value *NumElements;
19980b57cec5SDimitry Andric     QualType ElementType;
19990b57cec5SDimitry Andric     CharUnits CookieSize;
20000b57cec5SDimitry Andric 
CallArrayDelete__anonb29e8e2e0611::CallArrayDelete20010b57cec5SDimitry Andric     CallArrayDelete(llvm::Value *Ptr,
20020b57cec5SDimitry Andric                     const FunctionDecl *OperatorDelete,
20030b57cec5SDimitry Andric                     llvm::Value *NumElements,
20040b57cec5SDimitry Andric                     QualType ElementType,
20050b57cec5SDimitry Andric                     CharUnits CookieSize)
20060b57cec5SDimitry Andric       : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
20070b57cec5SDimitry Andric         ElementType(ElementType), CookieSize(CookieSize) {}
20080b57cec5SDimitry Andric 
Emit__anonb29e8e2e0611::CallArrayDelete20090b57cec5SDimitry Andric     void Emit(CodeGenFunction &CGF, Flags flags) override {
20100b57cec5SDimitry Andric       CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType, NumElements,
20110b57cec5SDimitry Andric                          CookieSize);
20120b57cec5SDimitry Andric     }
20130b57cec5SDimitry Andric   };
20140b57cec5SDimitry Andric }
20150b57cec5SDimitry Andric 
20160b57cec5SDimitry Andric /// Emit the code for deleting an array of objects.
EmitArrayDelete(CodeGenFunction & CGF,const CXXDeleteExpr * E,Address deletedPtr,QualType elementType)20170b57cec5SDimitry Andric static void EmitArrayDelete(CodeGenFunction &CGF,
20180b57cec5SDimitry Andric                             const CXXDeleteExpr *E,
20190b57cec5SDimitry Andric                             Address deletedPtr,
20200b57cec5SDimitry Andric                             QualType elementType) {
20210b57cec5SDimitry Andric   llvm::Value *numElements = nullptr;
20220b57cec5SDimitry Andric   llvm::Value *allocatedPtr = nullptr;
20230b57cec5SDimitry Andric   CharUnits cookieSize;
20240b57cec5SDimitry Andric   CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
20250b57cec5SDimitry Andric                                       numElements, allocatedPtr, cookieSize);
20260b57cec5SDimitry Andric 
20270b57cec5SDimitry Andric   assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
20280b57cec5SDimitry Andric 
20290b57cec5SDimitry Andric   // Make sure that we call delete even if one of the dtors throws.
20300b57cec5SDimitry Andric   const FunctionDecl *operatorDelete = E->getOperatorDelete();
20310b57cec5SDimitry Andric   CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
20320b57cec5SDimitry Andric                                            allocatedPtr, operatorDelete,
20330b57cec5SDimitry Andric                                            numElements, elementType,
20340b57cec5SDimitry Andric                                            cookieSize);
20350b57cec5SDimitry Andric 
20360b57cec5SDimitry Andric   // Destroy the elements.
20370b57cec5SDimitry Andric   if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
20380b57cec5SDimitry Andric     assert(numElements && "no element count for a type with a destructor!");
20390b57cec5SDimitry Andric 
20400b57cec5SDimitry Andric     CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
20410b57cec5SDimitry Andric     CharUnits elementAlign =
20420b57cec5SDimitry Andric       deletedPtr.getAlignment().alignmentOfArrayElement(elementSize);
20430b57cec5SDimitry Andric 
20440b57cec5SDimitry Andric     llvm::Value *arrayBegin = deletedPtr.getPointer();
20455f7ddb14SDimitry Andric     llvm::Value *arrayEnd = CGF.Builder.CreateInBoundsGEP(
20465f7ddb14SDimitry Andric       deletedPtr.getElementType(), arrayBegin, numElements, "delete.end");
20470b57cec5SDimitry Andric 
20480b57cec5SDimitry Andric     // Note that it is legal to allocate a zero-length array, and we
20490b57cec5SDimitry Andric     // can never fold the check away because the length should always
20500b57cec5SDimitry Andric     // come from a cookie.
20510b57cec5SDimitry Andric     CGF.emitArrayDestroy(arrayBegin, arrayEnd, elementType, elementAlign,
20520b57cec5SDimitry Andric                          CGF.getDestroyer(dtorKind),
20530b57cec5SDimitry Andric                          /*checkZeroLength*/ true,
20540b57cec5SDimitry Andric                          CGF.needsEHCleanup(dtorKind));
20550b57cec5SDimitry Andric   }
20560b57cec5SDimitry Andric 
20570b57cec5SDimitry Andric   // Pop the cleanup block.
20580b57cec5SDimitry Andric   CGF.PopCleanupBlock();
20590b57cec5SDimitry Andric }
20600b57cec5SDimitry Andric 
EmitCXXDeleteExpr(const CXXDeleteExpr * E)20610b57cec5SDimitry Andric void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
20620b57cec5SDimitry Andric   const Expr *Arg = E->getArgument();
20630b57cec5SDimitry Andric   Address Ptr = EmitPointerWithAlignment(Arg);
20640b57cec5SDimitry Andric 
20650b57cec5SDimitry Andric   // Null check the pointer.
20665ffd83dbSDimitry Andric   //
20675ffd83dbSDimitry Andric   // We could avoid this null check if we can determine that the object
20685ffd83dbSDimitry Andric   // destruction is trivial and doesn't require an array cookie; we can
20695ffd83dbSDimitry Andric   // unconditionally perform the operator delete call in that case. For now, we
20705ffd83dbSDimitry Andric   // assume that deleted pointers are null rarely enough that it's better to
20715ffd83dbSDimitry Andric   // keep the branch. This might be worth revisiting for a -O0 code size win.
20720b57cec5SDimitry Andric   llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
20730b57cec5SDimitry Andric   llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
20740b57cec5SDimitry Andric 
20750b57cec5SDimitry Andric   llvm::Value *IsNull = Builder.CreateIsNull(Ptr.getPointer(), "isnull");
20760b57cec5SDimitry Andric 
20770b57cec5SDimitry Andric   Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
20780b57cec5SDimitry Andric   EmitBlock(DeleteNotNull);
20790b57cec5SDimitry Andric 
20800b57cec5SDimitry Andric   QualType DeleteTy = E->getDestroyedType();
20810b57cec5SDimitry Andric 
20820b57cec5SDimitry Andric   // A destroying operator delete overrides the entire operation of the
20830b57cec5SDimitry Andric   // delete expression.
20840b57cec5SDimitry Andric   if (E->getOperatorDelete()->isDestroyingOperatorDelete()) {
20850b57cec5SDimitry Andric     EmitDestroyingObjectDelete(*this, E, Ptr, DeleteTy);
20860b57cec5SDimitry Andric     EmitBlock(DeleteEnd);
20870b57cec5SDimitry Andric     return;
20880b57cec5SDimitry Andric   }
20890b57cec5SDimitry Andric 
20900b57cec5SDimitry Andric   // We might be deleting a pointer to array.  If so, GEP down to the
20910b57cec5SDimitry Andric   // first non-array element.
20920b57cec5SDimitry Andric   // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
20930b57cec5SDimitry Andric   if (DeleteTy->isConstantArrayType()) {
20940b57cec5SDimitry Andric     llvm::Value *Zero = Builder.getInt32(0);
20950b57cec5SDimitry Andric     SmallVector<llvm::Value*,8> GEP;
20960b57cec5SDimitry Andric 
20970b57cec5SDimitry Andric     GEP.push_back(Zero); // point at the outermost array
20980b57cec5SDimitry Andric 
20990b57cec5SDimitry Andric     // For each layer of array type we're pointing at:
21000b57cec5SDimitry Andric     while (const ConstantArrayType *Arr
21010b57cec5SDimitry Andric              = getContext().getAsConstantArrayType(DeleteTy)) {
21020b57cec5SDimitry Andric       // 1. Unpeel the array type.
21030b57cec5SDimitry Andric       DeleteTy = Arr->getElementType();
21040b57cec5SDimitry Andric 
21050b57cec5SDimitry Andric       // 2. GEP to the first element of the array.
21060b57cec5SDimitry Andric       GEP.push_back(Zero);
21070b57cec5SDimitry Andric     }
21080b57cec5SDimitry Andric 
21095f7ddb14SDimitry Andric     Ptr = Address(Builder.CreateInBoundsGEP(Ptr.getElementType(),
21105f7ddb14SDimitry Andric                                             Ptr.getPointer(), GEP, "del.first"),
21110b57cec5SDimitry Andric                   Ptr.getAlignment());
21120b57cec5SDimitry Andric   }
21130b57cec5SDimitry Andric 
21140b57cec5SDimitry Andric   assert(ConvertTypeForMem(DeleteTy) == Ptr.getElementType());
21150b57cec5SDimitry Andric 
21160b57cec5SDimitry Andric   if (E->isArrayForm()) {
21170b57cec5SDimitry Andric     EmitArrayDelete(*this, E, Ptr, DeleteTy);
21180b57cec5SDimitry Andric     EmitBlock(DeleteEnd);
21195ffd83dbSDimitry Andric   } else {
21205ffd83dbSDimitry Andric     if (!EmitObjectDelete(*this, E, Ptr, DeleteTy, DeleteEnd))
21215ffd83dbSDimitry Andric       EmitBlock(DeleteEnd);
21225ffd83dbSDimitry Andric   }
21230b57cec5SDimitry Andric }
21240b57cec5SDimitry Andric 
isGLValueFromPointerDeref(const Expr * E)21250b57cec5SDimitry Andric static bool isGLValueFromPointerDeref(const Expr *E) {
21260b57cec5SDimitry Andric   E = E->IgnoreParens();
21270b57cec5SDimitry Andric 
21280b57cec5SDimitry Andric   if (const auto *CE = dyn_cast<CastExpr>(E)) {
21290b57cec5SDimitry Andric     if (!CE->getSubExpr()->isGLValue())
21300b57cec5SDimitry Andric       return false;
21310b57cec5SDimitry Andric     return isGLValueFromPointerDeref(CE->getSubExpr());
21320b57cec5SDimitry Andric   }
21330b57cec5SDimitry Andric 
21340b57cec5SDimitry Andric   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
21350b57cec5SDimitry Andric     return isGLValueFromPointerDeref(OVE->getSourceExpr());
21360b57cec5SDimitry Andric 
21370b57cec5SDimitry Andric   if (const auto *BO = dyn_cast<BinaryOperator>(E))
21380b57cec5SDimitry Andric     if (BO->getOpcode() == BO_Comma)
21390b57cec5SDimitry Andric       return isGLValueFromPointerDeref(BO->getRHS());
21400b57cec5SDimitry Andric 
21410b57cec5SDimitry Andric   if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E))
21420b57cec5SDimitry Andric     return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
21430b57cec5SDimitry Andric            isGLValueFromPointerDeref(ACO->getFalseExpr());
21440b57cec5SDimitry Andric 
21450b57cec5SDimitry Andric   // C++11 [expr.sub]p1:
21460b57cec5SDimitry Andric   //   The expression E1[E2] is identical (by definition) to *((E1)+(E2))
21470b57cec5SDimitry Andric   if (isa<ArraySubscriptExpr>(E))
21480b57cec5SDimitry Andric     return true;
21490b57cec5SDimitry Andric 
21500b57cec5SDimitry Andric   if (const auto *UO = dyn_cast<UnaryOperator>(E))
21510b57cec5SDimitry Andric     if (UO->getOpcode() == UO_Deref)
21520b57cec5SDimitry Andric       return true;
21530b57cec5SDimitry Andric 
21540b57cec5SDimitry Andric   return false;
21550b57cec5SDimitry Andric }
21560b57cec5SDimitry Andric 
EmitTypeidFromVTable(CodeGenFunction & CGF,const Expr * E,llvm::Type * StdTypeInfoPtrTy)21570b57cec5SDimitry Andric static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
21580b57cec5SDimitry Andric                                          llvm::Type *StdTypeInfoPtrTy) {
21590b57cec5SDimitry Andric   // Get the vtable pointer.
2160480093f4SDimitry Andric   Address ThisPtr = CGF.EmitLValue(E).getAddress(CGF);
21610b57cec5SDimitry Andric 
21620b57cec5SDimitry Andric   QualType SrcRecordTy = E->getType();
21630b57cec5SDimitry Andric 
21640b57cec5SDimitry Andric   // C++ [class.cdtor]p4:
21650b57cec5SDimitry Andric   //   If the operand of typeid refers to the object under construction or
21660b57cec5SDimitry Andric   //   destruction and the static type of the operand is neither the constructor
21670b57cec5SDimitry Andric   //   or destructor’s class nor one of its bases, the behavior is undefined.
21680b57cec5SDimitry Andric   CGF.EmitTypeCheck(CodeGenFunction::TCK_DynamicOperation, E->getExprLoc(),
21690b57cec5SDimitry Andric                     ThisPtr.getPointer(), SrcRecordTy);
21700b57cec5SDimitry Andric 
21710b57cec5SDimitry Andric   // C++ [expr.typeid]p2:
21720b57cec5SDimitry Andric   //   If the glvalue expression is obtained by applying the unary * operator to
21730b57cec5SDimitry Andric   //   a pointer and the pointer is a null pointer value, the typeid expression
21740b57cec5SDimitry Andric   //   throws the std::bad_typeid exception.
21750b57cec5SDimitry Andric   //
21760b57cec5SDimitry Andric   // However, this paragraph's intent is not clear.  We choose a very generous
21770b57cec5SDimitry Andric   // interpretation which implores us to consider comma operators, conditional
21780b57cec5SDimitry Andric   // operators, parentheses and other such constructs.
21790b57cec5SDimitry Andric   if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(
21800b57cec5SDimitry Andric           isGLValueFromPointerDeref(E), SrcRecordTy)) {
21810b57cec5SDimitry Andric     llvm::BasicBlock *BadTypeidBlock =
21820b57cec5SDimitry Andric         CGF.createBasicBlock("typeid.bad_typeid");
21830b57cec5SDimitry Andric     llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
21840b57cec5SDimitry Andric 
21850b57cec5SDimitry Andric     llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr.getPointer());
21860b57cec5SDimitry Andric     CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
21870b57cec5SDimitry Andric 
21880b57cec5SDimitry Andric     CGF.EmitBlock(BadTypeidBlock);
21890b57cec5SDimitry Andric     CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
21900b57cec5SDimitry Andric     CGF.EmitBlock(EndBlock);
21910b57cec5SDimitry Andric   }
21920b57cec5SDimitry Andric 
21930b57cec5SDimitry Andric   return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
21940b57cec5SDimitry Andric                                         StdTypeInfoPtrTy);
21950b57cec5SDimitry Andric }
21960b57cec5SDimitry Andric 
EmitCXXTypeidExpr(const CXXTypeidExpr * E)21970b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
21980b57cec5SDimitry Andric   llvm::Type *StdTypeInfoPtrTy =
21990b57cec5SDimitry Andric     ConvertType(E->getType())->getPointerTo();
22000b57cec5SDimitry Andric 
22010b57cec5SDimitry Andric   if (E->isTypeOperand()) {
22020b57cec5SDimitry Andric     llvm::Constant *TypeInfo =
22030b57cec5SDimitry Andric         CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
22040b57cec5SDimitry Andric     return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
22050b57cec5SDimitry Andric   }
22060b57cec5SDimitry Andric 
22070b57cec5SDimitry Andric   // C++ [expr.typeid]p2:
22080b57cec5SDimitry Andric   //   When typeid is applied to a glvalue expression whose type is a
22090b57cec5SDimitry Andric   //   polymorphic class type, the result refers to a std::type_info object
22100b57cec5SDimitry Andric   //   representing the type of the most derived object (that is, the dynamic
22110b57cec5SDimitry Andric   //   type) to which the glvalue refers.
2212af732203SDimitry Andric   // If the operand is already most derived object, no need to look up vtable.
2213af732203SDimitry Andric   if (E->isPotentiallyEvaluated() && !E->isMostDerived(getContext()))
22140b57cec5SDimitry Andric     return EmitTypeidFromVTable(*this, E->getExprOperand(),
22150b57cec5SDimitry Andric                                 StdTypeInfoPtrTy);
22160b57cec5SDimitry Andric 
22170b57cec5SDimitry Andric   QualType OperandTy = E->getExprOperand()->getType();
22180b57cec5SDimitry Andric   return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
22190b57cec5SDimitry Andric                                StdTypeInfoPtrTy);
22200b57cec5SDimitry Andric }
22210b57cec5SDimitry Andric 
EmitDynamicCastToNull(CodeGenFunction & CGF,QualType DestTy)22220b57cec5SDimitry Andric static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
22230b57cec5SDimitry Andric                                           QualType DestTy) {
22240b57cec5SDimitry Andric   llvm::Type *DestLTy = CGF.ConvertType(DestTy);
22250b57cec5SDimitry Andric   if (DestTy->isPointerType())
22260b57cec5SDimitry Andric     return llvm::Constant::getNullValue(DestLTy);
22270b57cec5SDimitry Andric 
22280b57cec5SDimitry Andric   /// C++ [expr.dynamic.cast]p9:
22290b57cec5SDimitry Andric   ///   A failed cast to reference type throws std::bad_cast
22300b57cec5SDimitry Andric   if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
22310b57cec5SDimitry Andric     return nullptr;
22320b57cec5SDimitry Andric 
22330b57cec5SDimitry Andric   CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
22340b57cec5SDimitry Andric   return llvm::UndefValue::get(DestLTy);
22350b57cec5SDimitry Andric }
22360b57cec5SDimitry Andric 
EmitDynamicCast(Address ThisAddr,const CXXDynamicCastExpr * DCE)22370b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitDynamicCast(Address ThisAddr,
22380b57cec5SDimitry Andric                                               const CXXDynamicCastExpr *DCE) {
22390b57cec5SDimitry Andric   CGM.EmitExplicitCastExprType(DCE, this);
22400b57cec5SDimitry Andric   QualType DestTy = DCE->getTypeAsWritten();
22410b57cec5SDimitry Andric 
22420b57cec5SDimitry Andric   QualType SrcTy = DCE->getSubExpr()->getType();
22430b57cec5SDimitry Andric 
22440b57cec5SDimitry Andric   // C++ [expr.dynamic.cast]p7:
22450b57cec5SDimitry Andric   //   If T is "pointer to cv void," then the result is a pointer to the most
22460b57cec5SDimitry Andric   //   derived object pointed to by v.
22470b57cec5SDimitry Andric   const PointerType *DestPTy = DestTy->getAs<PointerType>();
22480b57cec5SDimitry Andric 
22490b57cec5SDimitry Andric   bool isDynamicCastToVoid;
22500b57cec5SDimitry Andric   QualType SrcRecordTy;
22510b57cec5SDimitry Andric   QualType DestRecordTy;
22520b57cec5SDimitry Andric   if (DestPTy) {
22530b57cec5SDimitry Andric     isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType();
22540b57cec5SDimitry Andric     SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
22550b57cec5SDimitry Andric     DestRecordTy = DestPTy->getPointeeType();
22560b57cec5SDimitry Andric   } else {
22570b57cec5SDimitry Andric     isDynamicCastToVoid = false;
22580b57cec5SDimitry Andric     SrcRecordTy = SrcTy;
22590b57cec5SDimitry Andric     DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
22600b57cec5SDimitry Andric   }
22610b57cec5SDimitry Andric 
22620b57cec5SDimitry Andric   // C++ [class.cdtor]p5:
22630b57cec5SDimitry Andric   //   If the operand of the dynamic_cast refers to the object under
22640b57cec5SDimitry Andric   //   construction or destruction and the static type of the operand is not a
22650b57cec5SDimitry Andric   //   pointer to or object of the constructor or destructor’s own class or one
22660b57cec5SDimitry Andric   //   of its bases, the dynamic_cast results in undefined behavior.
22670b57cec5SDimitry Andric   EmitTypeCheck(TCK_DynamicOperation, DCE->getExprLoc(), ThisAddr.getPointer(),
22680b57cec5SDimitry Andric                 SrcRecordTy);
22690b57cec5SDimitry Andric 
22700b57cec5SDimitry Andric   if (DCE->isAlwaysNull())
22710b57cec5SDimitry Andric     if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy))
22720b57cec5SDimitry Andric       return T;
22730b57cec5SDimitry Andric 
22740b57cec5SDimitry Andric   assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
22750b57cec5SDimitry Andric 
22760b57cec5SDimitry Andric   // C++ [expr.dynamic.cast]p4:
22770b57cec5SDimitry Andric   //   If the value of v is a null pointer value in the pointer case, the result
22780b57cec5SDimitry Andric   //   is the null pointer value of type T.
22790b57cec5SDimitry Andric   bool ShouldNullCheckSrcValue =
22800b57cec5SDimitry Andric       CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(),
22810b57cec5SDimitry Andric                                                          SrcRecordTy);
22820b57cec5SDimitry Andric 
22830b57cec5SDimitry Andric   llvm::BasicBlock *CastNull = nullptr;
22840b57cec5SDimitry Andric   llvm::BasicBlock *CastNotNull = nullptr;
22850b57cec5SDimitry Andric   llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
22860b57cec5SDimitry Andric 
22870b57cec5SDimitry Andric   if (ShouldNullCheckSrcValue) {
22880b57cec5SDimitry Andric     CastNull = createBasicBlock("dynamic_cast.null");
22890b57cec5SDimitry Andric     CastNotNull = createBasicBlock("dynamic_cast.notnull");
22900b57cec5SDimitry Andric 
22910b57cec5SDimitry Andric     llvm::Value *IsNull = Builder.CreateIsNull(ThisAddr.getPointer());
22920b57cec5SDimitry Andric     Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
22930b57cec5SDimitry Andric     EmitBlock(CastNotNull);
22940b57cec5SDimitry Andric   }
22950b57cec5SDimitry Andric 
22960b57cec5SDimitry Andric   llvm::Value *Value;
22970b57cec5SDimitry Andric   if (isDynamicCastToVoid) {
22980b57cec5SDimitry Andric     Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, ThisAddr, SrcRecordTy,
22990b57cec5SDimitry Andric                                                   DestTy);
23000b57cec5SDimitry Andric   } else {
23010b57cec5SDimitry Andric     assert(DestRecordTy->isRecordType() &&
23020b57cec5SDimitry Andric            "destination type must be a record type!");
23030b57cec5SDimitry Andric     Value = CGM.getCXXABI().EmitDynamicCastCall(*this, ThisAddr, SrcRecordTy,
23040b57cec5SDimitry Andric                                                 DestTy, DestRecordTy, CastEnd);
23050b57cec5SDimitry Andric     CastNotNull = Builder.GetInsertBlock();
23060b57cec5SDimitry Andric   }
23070b57cec5SDimitry Andric 
23080b57cec5SDimitry Andric   if (ShouldNullCheckSrcValue) {
23090b57cec5SDimitry Andric     EmitBranch(CastEnd);
23100b57cec5SDimitry Andric 
23110b57cec5SDimitry Andric     EmitBlock(CastNull);
23120b57cec5SDimitry Andric     EmitBranch(CastEnd);
23130b57cec5SDimitry Andric   }
23140b57cec5SDimitry Andric 
23150b57cec5SDimitry Andric   EmitBlock(CastEnd);
23160b57cec5SDimitry Andric 
23170b57cec5SDimitry Andric   if (ShouldNullCheckSrcValue) {
23180b57cec5SDimitry Andric     llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
23190b57cec5SDimitry Andric     PHI->addIncoming(Value, CastNotNull);
23200b57cec5SDimitry Andric     PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
23210b57cec5SDimitry Andric 
23220b57cec5SDimitry Andric     Value = PHI;
23230b57cec5SDimitry Andric   }
23240b57cec5SDimitry Andric 
23250b57cec5SDimitry Andric   return Value;
23260b57cec5SDimitry Andric }
2327