159486a2dSAnders Carlsson //===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
259486a2dSAnders Carlsson //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
659486a2dSAnders Carlsson //
759486a2dSAnders Carlsson //===----------------------------------------------------------------------===//
859486a2dSAnders Carlsson //
959486a2dSAnders Carlsson // This contains code dealing with code generation of C++ expressions
1059486a2dSAnders Carlsson //
1159486a2dSAnders Carlsson //===----------------------------------------------------------------------===//
1259486a2dSAnders Carlsson 
1359486a2dSAnders Carlsson #include "CodeGenFunction.h"
14fe883422SPeter Collingbourne #include "CGCUDARuntime.h"
155d865c32SJohn McCall #include "CGCXXABI.h"
1691bbb554SDevang Patel #include "CGDebugInfo.h"
173a02247dSChandler Carruth #include "CGObjCRuntime.h"
18de0fe07eSJohn McCall #include "ConstantEmitter.h"
196368818fSRichard Trieu #include "clang/Basic/CodeGenOptions.h"
20a8e7df36SMark Lacey #include "clang/CodeGen/CGFunctionInfo.h"
21ffd5551bSChandler Carruth #include "llvm/IR/Intrinsics.h"
22bbe277c4SAnders Carlsson 
2359486a2dSAnders Carlsson using namespace clang;
2459486a2dSAnders Carlsson using namespace CodeGen;
2559486a2dSAnders Carlsson 
26d0a9e807SGeorge Burgess IV namespace {
27d0a9e807SGeorge Burgess IV struct MemberCallInfo {
28d0a9e807SGeorge Burgess IV   RequiredArgs ReqArgs;
29d0a9e807SGeorge Burgess IV   // Number of prefix arguments for the call. Ignores the `this` pointer.
30d0a9e807SGeorge Burgess IV   unsigned PrefixSize;
31d0a9e807SGeorge Burgess IV };
32d0a9e807SGeorge Burgess IV }
33d0a9e807SGeorge Burgess IV 
34d0a9e807SGeorge Burgess IV static MemberCallInfo
35efa956ceSAlexey Samsonov commonEmitCXXMemberOrOperatorCall(CodeGenFunction &CGF, const CXXMethodDecl *MD,
36efa956ceSAlexey Samsonov                                   llvm::Value *This, llvm::Value *ImplicitParam,
37efa956ceSAlexey Samsonov                                   QualType ImplicitParamTy, const CallExpr *CE,
38762672a7SRichard Smith                                   CallArgList &Args, CallArgList *RtlArgs) {
39a5bf76bdSAlexey Samsonov   assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) ||
40a5bf76bdSAlexey Samsonov          isa<CXXOperatorCallExpr>(CE));
4127da15baSAnders Carlsson   assert(MD->isInstance() &&
42a5bf76bdSAlexey Samsonov          "Trying to emit a member or operator call expr on a static method!");
43034e7270SReid Kleckner   ASTContext &C = CGF.getContext();
4427da15baSAnders Carlsson 
4527da15baSAnders Carlsson   // Push the this ptr.
46034e7270SReid Kleckner   const CXXRecordDecl *RD =
47034e7270SReid Kleckner       CGF.CGM.getCXXABI().getThisArgumentTypeForMethod(MD);
48034e7270SReid Kleckner   Args.add(RValue::get(This),
49034e7270SReid Kleckner            RD ? C.getPointerType(C.getTypeDeclType(RD)) : C.VoidPtrTy);
5027da15baSAnders Carlsson 
51ee6bc533STimur Iskhodzhanov   // If there is an implicit parameter (e.g. VTT), emit it.
52ee6bc533STimur Iskhodzhanov   if (ImplicitParam) {
53ee6bc533STimur Iskhodzhanov     Args.add(RValue::get(ImplicitParam), ImplicitParamTy);
54e36a6b3eSAnders Carlsson   }
55e36a6b3eSAnders Carlsson 
56a729c62bSJohn McCall   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
57916db651SJames Y Knight   RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size());
58d0a9e807SGeorge Burgess IV   unsigned PrefixSize = Args.size() - 1;
59a729c62bSJohn McCall 
60a729c62bSJohn McCall   // And the rest of the call args.
61762672a7SRichard Smith   if (RtlArgs) {
62762672a7SRichard Smith     // Special case: if the caller emitted the arguments right-to-left already
63762672a7SRichard Smith     // (prior to emitting the *this argument), we're done. This happens for
64762672a7SRichard Smith     // assignment operators.
65762672a7SRichard Smith     Args.addFrom(*RtlArgs);
66762672a7SRichard Smith   } else if (CE) {
67a5bf76bdSAlexey Samsonov     // Special case: skip first argument of CXXOperatorCall (it is "this").
688e1162c7SAlexey Samsonov     unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0;
69f05779e2SDavid Blaikie     CGF.EmitCallArgs(Args, FPT, drop_begin(CE->arguments(), ArgsToSkip),
708e1162c7SAlexey Samsonov                      CE->getDirectCallee());
71a5bf76bdSAlexey Samsonov   } else {
728e1162c7SAlexey Samsonov     assert(
738e1162c7SAlexey Samsonov         FPT->getNumParams() == 0 &&
748e1162c7SAlexey Samsonov         "No CallExpr specified for function with non-zero number of arguments");
75a5bf76bdSAlexey Samsonov   }
76d0a9e807SGeorge Burgess IV   return {required, PrefixSize};
770c0b6d9aSDavid Majnemer }
7827da15baSAnders Carlsson 
790c0b6d9aSDavid Majnemer RValue CodeGenFunction::EmitCXXMemberOrOperatorCall(
80b92ab1afSJohn McCall     const CXXMethodDecl *MD, const CGCallee &Callee,
81b92ab1afSJohn McCall     ReturnValueSlot ReturnValue,
820c0b6d9aSDavid Majnemer     llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,
83762672a7SRichard Smith     const CallExpr *CE, CallArgList *RtlArgs) {
840c0b6d9aSDavid Majnemer   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
850c0b6d9aSDavid Majnemer   CallArgList Args;
86d0a9e807SGeorge Burgess IV   MemberCallInfo CallInfo = commonEmitCXXMemberOrOperatorCall(
87762672a7SRichard Smith       *this, MD, This, ImplicitParam, ImplicitParamTy, CE, Args, RtlArgs);
88d0a9e807SGeorge Burgess IV   auto &FnInfo = CGM.getTypes().arrangeCXXMethodCall(
89d0a9e807SGeorge Burgess IV       Args, FPT, CallInfo.ReqArgs, CallInfo.PrefixSize);
9009b5bfddSVedant Kumar   return EmitCall(FnInfo, Callee, ReturnValue, Args, nullptr,
9109b5bfddSVedant Kumar                   CE ? CE->getExprLoc() : SourceLocation());
9227da15baSAnders Carlsson }
9327da15baSAnders Carlsson 
94ae81bbb4SAlexey Samsonov RValue CodeGenFunction::EmitCXXDestructorCall(
95b92ab1afSJohn McCall     const CXXDestructorDecl *DD, const CGCallee &Callee, llvm::Value *This,
96ae81bbb4SAlexey Samsonov     llvm::Value *ImplicitParam, QualType ImplicitParamTy, const CallExpr *CE,
97ae81bbb4SAlexey Samsonov     StructorType Type) {
980c0b6d9aSDavid Majnemer   CallArgList Args;
99ae81bbb4SAlexey Samsonov   commonEmitCXXMemberOrOperatorCall(*this, DD, This, ImplicitParam,
100762672a7SRichard Smith                                     ImplicitParamTy, CE, Args, nullptr);
101ae81bbb4SAlexey Samsonov   return EmitCall(CGM.getTypes().arrangeCXXStructorDeclaration(DD, Type),
102b92ab1afSJohn McCall                   Callee, ReturnValueSlot(), Args);
103b92ab1afSJohn McCall }
104b92ab1afSJohn McCall 
105b92ab1afSJohn McCall RValue CodeGenFunction::EmitCXXPseudoDestructorExpr(
106b92ab1afSJohn McCall                                             const CXXPseudoDestructorExpr *E) {
107b92ab1afSJohn McCall   QualType DestroyedType = E->getDestroyedType();
108b92ab1afSJohn McCall   if (DestroyedType.hasStrongOrWeakObjCLifetime()) {
109b92ab1afSJohn McCall     // Automatic Reference Counting:
110b92ab1afSJohn McCall     //   If the pseudo-expression names a retainable object with weak or
111b92ab1afSJohn McCall     //   strong lifetime, the object shall be released.
112b92ab1afSJohn McCall     Expr *BaseExpr = E->getBase();
113b92ab1afSJohn McCall     Address BaseValue = Address::invalid();
114b92ab1afSJohn McCall     Qualifiers BaseQuals;
115b92ab1afSJohn McCall 
116b92ab1afSJohn McCall     // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
117b92ab1afSJohn McCall     if (E->isArrow()) {
118b92ab1afSJohn McCall       BaseValue = EmitPointerWithAlignment(BaseExpr);
119b92ab1afSJohn McCall       const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>();
120b92ab1afSJohn McCall       BaseQuals = PTy->getPointeeType().getQualifiers();
121b92ab1afSJohn McCall     } else {
122b92ab1afSJohn McCall       LValue BaseLV = EmitLValue(BaseExpr);
123b92ab1afSJohn McCall       BaseValue = BaseLV.getAddress();
124b92ab1afSJohn McCall       QualType BaseTy = BaseExpr->getType();
125b92ab1afSJohn McCall       BaseQuals = BaseTy.getQualifiers();
126b92ab1afSJohn McCall     }
127b92ab1afSJohn McCall 
128b92ab1afSJohn McCall     switch (DestroyedType.getObjCLifetime()) {
129b92ab1afSJohn McCall     case Qualifiers::OCL_None:
130b92ab1afSJohn McCall     case Qualifiers::OCL_ExplicitNone:
131b92ab1afSJohn McCall     case Qualifiers::OCL_Autoreleasing:
132b92ab1afSJohn McCall       break;
133b92ab1afSJohn McCall 
134b92ab1afSJohn McCall     case Qualifiers::OCL_Strong:
135b92ab1afSJohn McCall       EmitARCRelease(Builder.CreateLoad(BaseValue,
136b92ab1afSJohn McCall                         DestroyedType.isVolatileQualified()),
137b92ab1afSJohn McCall                      ARCPreciseLifetime);
138b92ab1afSJohn McCall       break;
139b92ab1afSJohn McCall 
140b92ab1afSJohn McCall     case Qualifiers::OCL_Weak:
141b92ab1afSJohn McCall       EmitARCDestroyWeak(BaseValue);
142b92ab1afSJohn McCall       break;
143b92ab1afSJohn McCall     }
144b92ab1afSJohn McCall   } else {
145b92ab1afSJohn McCall     // C++ [expr.pseudo]p1:
146b92ab1afSJohn McCall     //   The result shall only be used as the operand for the function call
147b92ab1afSJohn McCall     //   operator (), and the result of such a call has type void. The only
148b92ab1afSJohn McCall     //   effect is the evaluation of the postfix-expression before the dot or
149b92ab1afSJohn McCall     //   arrow.
150b92ab1afSJohn McCall     EmitIgnoredExpr(E->getBase());
151b92ab1afSJohn McCall   }
152b92ab1afSJohn McCall 
153b92ab1afSJohn McCall   return RValue::get(nullptr);
1540c0b6d9aSDavid Majnemer }
1550c0b6d9aSDavid Majnemer 
1563b33c4ecSRafael Espindola static CXXRecordDecl *getCXXRecord(const Expr *E) {
1573b33c4ecSRafael Espindola   QualType T = E->getType();
1583b33c4ecSRafael Espindola   if (const PointerType *PTy = T->getAs<PointerType>())
1593b33c4ecSRafael Espindola     T = PTy->getPointeeType();
1603b33c4ecSRafael Espindola   const RecordType *Ty = T->castAs<RecordType>();
1613b33c4ecSRafael Espindola   return cast<CXXRecordDecl>(Ty->getDecl());
1623b33c4ecSRafael Espindola }
1633b33c4ecSRafael Espindola 
16464225794SFrancois Pichet // Note: This function also emit constructor calls to support a MSVC
16564225794SFrancois Pichet // extensions allowing explicit constructor function call.
16627da15baSAnders Carlsson RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
16727da15baSAnders Carlsson                                               ReturnValueSlot ReturnValue) {
1682d2e8707SJohn McCall   const Expr *callee = CE->getCallee()->IgnoreParens();
1692d2e8707SJohn McCall 
1702d2e8707SJohn McCall   if (isa<BinaryOperator>(callee))
17127da15baSAnders Carlsson     return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
17227da15baSAnders Carlsson 
1732d2e8707SJohn McCall   const MemberExpr *ME = cast<MemberExpr>(callee);
17427da15baSAnders Carlsson   const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
17527da15baSAnders Carlsson 
17627da15baSAnders Carlsson   if (MD->isStatic()) {
17727da15baSAnders Carlsson     // The method is static, emit it as we would a regular call.
178de6480a3SErich Keane     CGCallee callee =
179de6480a3SErich Keane         CGCallee::forDirect(CGM.GetAddrOfFunction(MD), GlobalDecl(MD));
180b92ab1afSJohn McCall     return EmitCall(getContext().getPointerType(MD->getType()), callee, CE,
18170b9c01bSAlexey Samsonov                     ReturnValue);
18227da15baSAnders Carlsson   }
18327da15baSAnders Carlsson 
184aad4af6dSNico Weber   bool HasQualifier = ME->hasQualifier();
185aad4af6dSNico Weber   NestedNameSpecifier *Qualifier = HasQualifier ? ME->getQualifier() : nullptr;
186aad4af6dSNico Weber   bool IsArrow = ME->isArrow();
187ecbe2e97SRafael Espindola   const Expr *Base = ME->getBase();
188aad4af6dSNico Weber 
189aad4af6dSNico Weber   return EmitCXXMemberOrOperatorMemberCallExpr(
190aad4af6dSNico Weber       CE, MD, ReturnValue, HasQualifier, Qualifier, IsArrow, Base);
191aad4af6dSNico Weber }
192aad4af6dSNico Weber 
193aad4af6dSNico Weber RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr(
194aad4af6dSNico Weber     const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue,
195aad4af6dSNico Weber     bool HasQualifier, NestedNameSpecifier *Qualifier, bool IsArrow,
196aad4af6dSNico Weber     const Expr *Base) {
197aad4af6dSNico Weber   assert(isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE));
198aad4af6dSNico Weber 
199aad4af6dSNico Weber   // Compute the object pointer.
200aad4af6dSNico Weber   bool CanUseVirtualCall = MD->isVirtual() && !HasQualifier;
201ecbe2e97SRafael Espindola 
2028a13c418SCraig Topper   const CXXMethodDecl *DevirtualizedMethod = nullptr;
20322461673SAkira Hatanaka   if (CanUseVirtualCall &&
20422461673SAkira Hatanaka       MD->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) {
2053b33c4ecSRafael Espindola     const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
2063b33c4ecSRafael Espindola     DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
2073b33c4ecSRafael Espindola     assert(DevirtualizedMethod);
2083b33c4ecSRafael Espindola     const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
2093b33c4ecSRafael Espindola     const Expr *Inner = Base->ignoreParenBaseCasts();
2105bd68794SAlexey Bataev     if (DevirtualizedMethod->getReturnType().getCanonicalType() !=
2115bd68794SAlexey Bataev         MD->getReturnType().getCanonicalType())
2125bd68794SAlexey Bataev       // If the return types are not the same, this might be a case where more
2135bd68794SAlexey Bataev       // code needs to run to compensate for it. For example, the derived
2145bd68794SAlexey Bataev       // method might return a type that inherits form from the return
2155bd68794SAlexey Bataev       // type of MD and has a prefix.
2165bd68794SAlexey Bataev       // For now we just avoid devirtualizing these covariant cases.
2175bd68794SAlexey Bataev       DevirtualizedMethod = nullptr;
2185bd68794SAlexey Bataev     else if (getCXXRecord(Inner) == DevirtualizedClass)
2193b33c4ecSRafael Espindola       // If the class of the Inner expression is where the dynamic method
2203b33c4ecSRafael Espindola       // is defined, build the this pointer from it.
2213b33c4ecSRafael Espindola       Base = Inner;
2223b33c4ecSRafael Espindola     else if (getCXXRecord(Base) != DevirtualizedClass) {
2233b33c4ecSRafael Espindola       // If the method is defined in a class that is not the best dynamic
2243b33c4ecSRafael Espindola       // one or the one of the full expression, we would have to build
2253b33c4ecSRafael Espindola       // a derived-to-base cast to compute the correct this pointer, but
2263b33c4ecSRafael Espindola       // we don't have support for that yet, so do a virtual call.
2278a13c418SCraig Topper       DevirtualizedMethod = nullptr;
2283b33c4ecSRafael Espindola     }
2293b33c4ecSRafael Espindola   }
230ecbe2e97SRafael Espindola 
231762672a7SRichard Smith   // C++17 demands that we evaluate the RHS of a (possibly-compound) assignment
232762672a7SRichard Smith   // operator before the LHS.
233762672a7SRichard Smith   CallArgList RtlArgStorage;
234762672a7SRichard Smith   CallArgList *RtlArgs = nullptr;
235762672a7SRichard Smith   if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
236762672a7SRichard Smith     if (OCE->isAssignmentOp()) {
237762672a7SRichard Smith       RtlArgs = &RtlArgStorage;
238762672a7SRichard Smith       EmitCallArgs(*RtlArgs, MD->getType()->castAs<FunctionProtoType>(),
239762672a7SRichard Smith                    drop_begin(CE->arguments(), 1), CE->getDirectCallee(),
240a560ccf2SRichard Smith                    /*ParamsToSkip*/0, EvaluationOrder::ForceRightToLeft);
241762672a7SRichard Smith     }
242762672a7SRichard Smith   }
243762672a7SRichard Smith 
2441860b520SIvan A. Kosarev   LValue This;
2451860b520SIvan A. Kosarev   if (IsArrow) {
2461860b520SIvan A. Kosarev     LValueBaseInfo BaseInfo;
2471860b520SIvan A. Kosarev     TBAAAccessInfo TBAAInfo;
2481860b520SIvan A. Kosarev     Address ThisValue = EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo);
2491860b520SIvan A. Kosarev     This = MakeAddrLValue(ThisValue, Base->getType(), BaseInfo, TBAAInfo);
2501860b520SIvan A. Kosarev   } else {
2511860b520SIvan A. Kosarev     This = EmitLValue(Base);
2521860b520SIvan A. Kosarev   }
253ecbe2e97SRafael Espindola 
25427da15baSAnders Carlsson 
255419bd094SRichard Smith   if (MD->isTrivial() || (MD->isDefaulted() && MD->getParent()->isUnion())) {
2568a13c418SCraig Topper     if (isa<CXXDestructorDecl>(MD)) return RValue::get(nullptr);
25764225794SFrancois Pichet     if (isa<CXXConstructorDecl>(MD) &&
25864225794SFrancois Pichet         cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
2598a13c418SCraig Topper       return RValue::get(nullptr);
2600d635f53SJohn McCall 
261aad4af6dSNico Weber     if (!MD->getParent()->mayInsertExtraPadding()) {
26222653bacSSebastian Redl       if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
26322653bacSSebastian Redl         // We don't like to generate the trivial copy/move assignment operator
26422653bacSSebastian Redl         // when it isn't necessary; just produce the proper effect here.
265762672a7SRichard Smith         LValue RHS = isa<CXXOperatorCallExpr>(CE)
266762672a7SRichard Smith                          ? MakeNaturalAlignAddrLValue(
2675b330e8dSYaxun Liu                                (*RtlArgs)[0].getRValue(*this).getScalarVal(),
268762672a7SRichard Smith                                (*(CE->arg_begin() + 1))->getType())
269762672a7SRichard Smith                          : EmitLValue(*CE->arg_begin());
2701860b520SIvan A. Kosarev         EmitAggregateAssign(This, RHS, CE->getType());
2717f416cc4SJohn McCall         return RValue::get(This.getPointer());
27227da15baSAnders Carlsson       }
27327da15baSAnders Carlsson 
27464225794SFrancois Pichet       if (isa<CXXConstructorDecl>(MD) &&
27522653bacSSebastian Redl           cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
27622653bacSSebastian Redl         // Trivial move and copy ctor are the same.
277525bf650SAlexey Samsonov         assert(CE->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
2781860b520SIvan A. Kosarev         const Expr *Arg = *CE->arg_begin();
2791860b520SIvan A. Kosarev         LValue RHS = EmitLValue(Arg);
2801860b520SIvan A. Kosarev         LValue Dest = MakeAddrLValue(This.getAddress(), Arg->getType());
281e78fac51SRichard Smith         // This is the MSVC p->Ctor::Ctor(...) extension. We assume that's
282e78fac51SRichard Smith         // constructing a new complete object of type Ctor.
283e78fac51SRichard Smith         EmitAggregateCopy(Dest, RHS, Arg->getType(),
284e78fac51SRichard Smith                           AggValueSlot::DoesNotOverlap);
2857f416cc4SJohn McCall         return RValue::get(This.getPointer());
28664225794SFrancois Pichet       }
28764225794SFrancois Pichet       llvm_unreachable("unknown trivial member function");
28864225794SFrancois Pichet     }
289aad4af6dSNico Weber   }
29064225794SFrancois Pichet 
2910d635f53SJohn McCall   // Compute the function type we're calling.
2923abfe958SNico Weber   const CXXMethodDecl *CalleeDecl =
2933abfe958SNico Weber       DevirtualizedMethod ? DevirtualizedMethod : MD;
2948a13c418SCraig Topper   const CGFunctionInfo *FInfo = nullptr;
2953abfe958SNico Weber   if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
2968d2a19b4SRafael Espindola     FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
2978d2a19b4SRafael Espindola         Dtor, StructorType::Complete);
2983abfe958SNico Weber   else if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(CalleeDecl))
2998d2a19b4SRafael Espindola     FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
3008d2a19b4SRafael Espindola         Ctor, StructorType::Complete);
30164225794SFrancois Pichet   else
302ade60977SEli Friedman     FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
3030d635f53SJohn McCall 
304e7de47efSReid Kleckner   llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
3050d635f53SJohn McCall 
306d98f5d78SIvan Krasin   // C++11 [class.mfct.non-static]p2:
307d98f5d78SIvan Krasin   //   If a non-static member function of a class X is called for an object that
308d98f5d78SIvan Krasin   //   is not of type X, or of a type derived from X, the behavior is undefined.
309d98f5d78SIvan Krasin   SourceLocation CallLoc;
310d98f5d78SIvan Krasin   ASTContext &C = getContext();
311d98f5d78SIvan Krasin   if (CE)
312d98f5d78SIvan Krasin     CallLoc = CE->getExprLoc();
313d98f5d78SIvan Krasin 
31434b1fd6aSVedant Kumar   SanitizerSet SkippedChecks;
315ffd7c887SVedant Kumar   if (const auto *CMCE = dyn_cast<CXXMemberCallExpr>(CE)) {
316ffd7c887SVedant Kumar     auto *IOA = CMCE->getImplicitObjectArgument();
317ffd7c887SVedant Kumar     bool IsImplicitObjectCXXThis = IsWrappedCXXThis(IOA);
318ffd7c887SVedant Kumar     if (IsImplicitObjectCXXThis)
319ffd7c887SVedant Kumar       SkippedChecks.set(SanitizerKind::Alignment, true);
320ffd7c887SVedant Kumar     if (IsImplicitObjectCXXThis || isa<DeclRefExpr>(IOA))
32134b1fd6aSVedant Kumar       SkippedChecks.set(SanitizerKind::Null, true);
322ffd7c887SVedant Kumar   }
32334b1fd6aSVedant Kumar   EmitTypeCheck(
32434b1fd6aSVedant Kumar       isa<CXXConstructorDecl>(CalleeDecl) ? CodeGenFunction::TCK_ConstructorCall
325d98f5d78SIvan Krasin                                           : CodeGenFunction::TCK_MemberCall,
32634b1fd6aSVedant Kumar       CallLoc, This.getPointer(), C.getRecordType(CalleeDecl->getParent()),
32734b1fd6aSVedant Kumar       /*Alignment=*/CharUnits::Zero(), SkippedChecks);
328d98f5d78SIvan Krasin 
329018f266bSVedant Kumar   // FIXME: Uses of 'MD' past this point need to be audited. We may need to use
330018f266bSVedant Kumar   // 'CalleeDecl' instead.
331018f266bSVedant Kumar 
33227da15baSAnders Carlsson   // C++ [class.virtual]p12:
33327da15baSAnders Carlsson   //   Explicit qualification with the scope operator (5.1) suppresses the
33427da15baSAnders Carlsson   //   virtual call mechanism.
33527da15baSAnders Carlsson   //
33627da15baSAnders Carlsson   // We also don't emit a virtual call if the base expression has a record type
33727da15baSAnders Carlsson   // because then we know what the type is.
3383b33c4ecSRafael Espindola   bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
3399dc6eef7SStephen Lin 
3400d635f53SJohn McCall   if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
34119cee187SStephen Lin     assert(CE->arg_begin() == CE->arg_end() &&
3429dc6eef7SStephen Lin            "Destructor shouldn't have explicit parameters");
3439dc6eef7SStephen Lin     assert(ReturnValue.isNull() && "Destructor shouldn't have return value");
3449dc6eef7SStephen Lin     if (UseVirtualCall) {
345aad4af6dSNico Weber       CGM.getCXXABI().EmitVirtualDestructorCall(
3461860b520SIvan A. Kosarev           *this, Dtor, Dtor_Complete, This.getAddress(),
3471860b520SIvan A. Kosarev           cast<CXXMemberCallExpr>(CE));
34827da15baSAnders Carlsson     } else {
349b92ab1afSJohn McCall       CGCallee Callee;
350aad4af6dSNico Weber       if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
351aad4af6dSNico Weber         Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
3523b33c4ecSRafael Espindola       else if (!DevirtualizedMethod)
353b92ab1afSJohn McCall         Callee = CGCallee::forDirect(
354b92ab1afSJohn McCall             CGM.getAddrOfCXXStructor(Dtor, StructorType::Complete, FInfo, Ty),
355de6480a3SErich Keane             GlobalDecl(Dtor, Dtor_Complete));
35649e860b2SRafael Espindola       else {
3573b33c4ecSRafael Espindola         const CXXDestructorDecl *DDtor =
3583b33c4ecSRafael Espindola           cast<CXXDestructorDecl>(DevirtualizedMethod);
359b92ab1afSJohn McCall         Callee = CGCallee::forDirect(
360b92ab1afSJohn McCall             CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty),
361de6480a3SErich Keane             GlobalDecl(DDtor, Dtor_Complete));
36249e860b2SRafael Espindola       }
363018f266bSVedant Kumar       EmitCXXMemberOrOperatorCall(
364018f266bSVedant Kumar           CalleeDecl, Callee, ReturnValue, This.getPointer(),
365018f266bSVedant Kumar           /*ImplicitParam=*/nullptr, QualType(), CE, nullptr);
36627da15baSAnders Carlsson     }
3678a13c418SCraig Topper     return RValue::get(nullptr);
3689dc6eef7SStephen Lin   }
3699dc6eef7SStephen Lin 
370b92ab1afSJohn McCall   CGCallee Callee;
3719dc6eef7SStephen Lin   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
372b92ab1afSJohn McCall     Callee = CGCallee::forDirect(
373b92ab1afSJohn McCall         CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty),
374de6480a3SErich Keane         GlobalDecl(Ctor, Ctor_Complete));
3750d635f53SJohn McCall   } else if (UseVirtualCall) {
376ea211002SPeter Collingbourne     Callee = CGCallee::forVirtual(CE, MD, This.getAddress(), Ty);
37727da15baSAnders Carlsson   } else {
3781a7488afSPeter Collingbourne     if (SanOpts.has(SanitizerKind::CFINVCall) &&
3791a7488afSPeter Collingbourne         MD->getParent()->isDynamicClass()) {
3806010880bSPeter Collingbourne       llvm::Value *VTable;
3816010880bSPeter Collingbourne       const CXXRecordDecl *RD;
3826010880bSPeter Collingbourne       std::tie(VTable, RD) =
3831860b520SIvan A. Kosarev           CGM.getCXXABI().LoadVTablePtr(*this, This.getAddress(),
3841860b520SIvan A. Kosarev                                         MD->getParent());
385f2ceec48SStephen Kelly       EmitVTablePtrCheckForCall(RD, VTable, CFITCK_NVCall, CE->getBeginLoc());
3861a7488afSPeter Collingbourne     }
3871a7488afSPeter Collingbourne 
388aad4af6dSNico Weber     if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
389aad4af6dSNico Weber       Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
3903b33c4ecSRafael Espindola     else if (!DevirtualizedMethod)
391de6480a3SErich Keane       Callee =
392de6480a3SErich Keane           CGCallee::forDirect(CGM.GetAddrOfFunction(MD, Ty), GlobalDecl(MD));
39349e860b2SRafael Espindola     else {
394de6480a3SErich Keane       Callee =
395de6480a3SErich Keane           CGCallee::forDirect(CGM.GetAddrOfFunction(DevirtualizedMethod, Ty),
396de6480a3SErich Keane                               GlobalDecl(DevirtualizedMethod));
39749e860b2SRafael Espindola     }
39827da15baSAnders Carlsson   }
39927da15baSAnders Carlsson 
400f1749427STimur Iskhodzhanov   if (MD->isVirtual()) {
4011860b520SIvan A. Kosarev     Address NewThisAddr =
4021860b520SIvan A. Kosarev         CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
4031860b520SIvan A. Kosarev             *this, CalleeDecl, This.getAddress(), UseVirtualCall);
4041860b520SIvan A. Kosarev     This.setAddress(NewThisAddr);
405f1749427STimur Iskhodzhanov   }
40688fd439aSTimur Iskhodzhanov 
407018f266bSVedant Kumar   return EmitCXXMemberOrOperatorCall(
408018f266bSVedant Kumar       CalleeDecl, Callee, ReturnValue, This.getPointer(),
409018f266bSVedant Kumar       /*ImplicitParam=*/nullptr, QualType(), CE, RtlArgs);
41027da15baSAnders Carlsson }
41127da15baSAnders Carlsson 
41227da15baSAnders Carlsson RValue
41327da15baSAnders Carlsson CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
41427da15baSAnders Carlsson                                               ReturnValueSlot ReturnValue) {
41527da15baSAnders Carlsson   const BinaryOperator *BO =
41627da15baSAnders Carlsson       cast<BinaryOperator>(E->getCallee()->IgnoreParens());
41727da15baSAnders Carlsson   const Expr *BaseExpr = BO->getLHS();
41827da15baSAnders Carlsson   const Expr *MemFnExpr = BO->getRHS();
41927da15baSAnders Carlsson 
42027da15baSAnders Carlsson   const MemberPointerType *MPT =
4210009fcc3SJohn McCall     MemFnExpr->getType()->castAs<MemberPointerType>();
422475999dcSJohn McCall 
42327da15baSAnders Carlsson   const FunctionProtoType *FPT =
4240009fcc3SJohn McCall     MPT->getPointeeType()->castAs<FunctionProtoType>();
42527da15baSAnders Carlsson   const CXXRecordDecl *RD =
42627da15baSAnders Carlsson     cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
42727da15baSAnders Carlsson 
42827da15baSAnders Carlsson   // Emit the 'this' pointer.
4297f416cc4SJohn McCall   Address This = Address::invalid();
430e302792bSJohn McCall   if (BO->getOpcode() == BO_PtrMemI)
4317f416cc4SJohn McCall     This = EmitPointerWithAlignment(BaseExpr);
43227da15baSAnders Carlsson   else
43327da15baSAnders Carlsson     This = EmitLValue(BaseExpr).getAddress();
43427da15baSAnders Carlsson 
4357f416cc4SJohn McCall   EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This.getPointer(),
436e30752c9SRichard Smith                 QualType(MPT->getClass(), 0));
43769d0d262SRichard Smith 
438bde62d78SRichard Smith   // Get the member function pointer.
439bde62d78SRichard Smith   llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
440bde62d78SRichard Smith 
441475999dcSJohn McCall   // Ask the ABI to load the callee.  Note that This is modified.
4427f416cc4SJohn McCall   llvm::Value *ThisPtrForCall = nullptr;
443b92ab1afSJohn McCall   CGCallee Callee =
4447f416cc4SJohn McCall     CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This,
4457f416cc4SJohn McCall                                              ThisPtrForCall, MemFnPtr, MPT);
44627da15baSAnders Carlsson 
44727da15baSAnders Carlsson   CallArgList Args;
44827da15baSAnders Carlsson 
44927da15baSAnders Carlsson   QualType ThisType =
45027da15baSAnders Carlsson     getContext().getPointerType(getContext().getTagDeclType(RD));
45127da15baSAnders Carlsson 
45227da15baSAnders Carlsson   // Push the this ptr.
4537f416cc4SJohn McCall   Args.add(RValue::get(ThisPtrForCall), ThisType);
45427da15baSAnders Carlsson 
455916db651SJames Y Knight   RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1);
4568dda7b27SJohn McCall 
45727da15baSAnders Carlsson   // And the rest of the call args
458419996ccSGeorge Burgess IV   EmitCallArgs(Args, FPT, E->arguments());
459d0a9e807SGeorge Burgess IV   return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required,
460d0a9e807SGeorge Burgess IV                                                       /*PrefixSize=*/0),
46109b5bfddSVedant Kumar                   Callee, ReturnValue, Args, nullptr, E->getExprLoc());
46227da15baSAnders Carlsson }
46327da15baSAnders Carlsson 
46427da15baSAnders Carlsson RValue
46527da15baSAnders Carlsson CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
46627da15baSAnders Carlsson                                                const CXXMethodDecl *MD,
46727da15baSAnders Carlsson                                                ReturnValueSlot ReturnValue) {
46827da15baSAnders Carlsson   assert(MD->isInstance() &&
46927da15baSAnders Carlsson          "Trying to emit a member call expr on a static method!");
470aad4af6dSNico Weber   return EmitCXXMemberOrOperatorMemberCallExpr(
471aad4af6dSNico Weber       E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr,
472aad4af6dSNico Weber       /*IsArrow=*/false, E->getArg(0));
47327da15baSAnders Carlsson }
47427da15baSAnders Carlsson 
475fe883422SPeter Collingbourne RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
476fe883422SPeter Collingbourne                                                ReturnValueSlot ReturnValue) {
477fe883422SPeter Collingbourne   return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
478fe883422SPeter Collingbourne }
479fe883422SPeter Collingbourne 
480fde961dbSEli Friedman static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
4817f416cc4SJohn McCall                                             Address DestPtr,
482fde961dbSEli Friedman                                             const CXXRecordDecl *Base) {
483fde961dbSEli Friedman   if (Base->isEmpty())
484fde961dbSEli Friedman     return;
485fde961dbSEli Friedman 
4867f416cc4SJohn McCall   DestPtr = CGF.Builder.CreateElementBitCast(DestPtr, CGF.Int8Ty);
487fde961dbSEli Friedman 
488fde961dbSEli Friedman   const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
4898671c6e0SDavid Majnemer   CharUnits NVSize = Layout.getNonVirtualSize();
4908671c6e0SDavid Majnemer 
4918671c6e0SDavid Majnemer   // We cannot simply zero-initialize the entire base sub-object if vbptrs are
4928671c6e0SDavid Majnemer   // present, they are initialized by the most derived class before calling the
4938671c6e0SDavid Majnemer   // constructor.
4948671c6e0SDavid Majnemer   SmallVector<std::pair<CharUnits, CharUnits>, 1> Stores;
4958671c6e0SDavid Majnemer   Stores.emplace_back(CharUnits::Zero(), NVSize);
4968671c6e0SDavid Majnemer 
4978671c6e0SDavid Majnemer   // Each store is split by the existence of a vbptr.
4988671c6e0SDavid Majnemer   CharUnits VBPtrWidth = CGF.getPointerSize();
4998671c6e0SDavid Majnemer   std::vector<CharUnits> VBPtrOffsets =
5008671c6e0SDavid Majnemer       CGF.CGM.getCXXABI().getVBPtrOffsets(Base);
5018671c6e0SDavid Majnemer   for (CharUnits VBPtrOffset : VBPtrOffsets) {
5027f980d84SDavid Majnemer     // Stop before we hit any virtual base pointers located in virtual bases.
5037f980d84SDavid Majnemer     if (VBPtrOffset >= NVSize)
5047f980d84SDavid Majnemer       break;
5058671c6e0SDavid Majnemer     std::pair<CharUnits, CharUnits> LastStore = Stores.pop_back_val();
5068671c6e0SDavid Majnemer     CharUnits LastStoreOffset = LastStore.first;
5078671c6e0SDavid Majnemer     CharUnits LastStoreSize = LastStore.second;
5088671c6e0SDavid Majnemer 
5098671c6e0SDavid Majnemer     CharUnits SplitBeforeOffset = LastStoreOffset;
5108671c6e0SDavid Majnemer     CharUnits SplitBeforeSize = VBPtrOffset - SplitBeforeOffset;
5118671c6e0SDavid Majnemer     assert(!SplitBeforeSize.isNegative() && "negative store size!");
5128671c6e0SDavid Majnemer     if (!SplitBeforeSize.isZero())
5138671c6e0SDavid Majnemer       Stores.emplace_back(SplitBeforeOffset, SplitBeforeSize);
5148671c6e0SDavid Majnemer 
5158671c6e0SDavid Majnemer     CharUnits SplitAfterOffset = VBPtrOffset + VBPtrWidth;
5168671c6e0SDavid Majnemer     CharUnits SplitAfterSize = LastStoreSize - SplitAfterOffset;
5178671c6e0SDavid Majnemer     assert(!SplitAfterSize.isNegative() && "negative store size!");
5188671c6e0SDavid Majnemer     if (!SplitAfterSize.isZero())
5198671c6e0SDavid Majnemer       Stores.emplace_back(SplitAfterOffset, SplitAfterSize);
5208671c6e0SDavid Majnemer   }
521fde961dbSEli Friedman 
522fde961dbSEli Friedman   // If the type contains a pointer to data member we can't memset it to zero.
523fde961dbSEli Friedman   // Instead, create a null constant and copy it to the destination.
524fde961dbSEli Friedman   // TODO: there are other patterns besides zero that we can usefully memset,
525fde961dbSEli Friedman   // like -1, which happens to be the pattern used by member-pointers.
526fde961dbSEli Friedman   // TODO: isZeroInitializable can be over-conservative in the case where a
527fde961dbSEli Friedman   // virtual base contains a member pointer.
5288671c6e0SDavid Majnemer   llvm::Constant *NullConstantForBase = CGF.CGM.EmitNullConstantForBase(Base);
5298671c6e0SDavid Majnemer   if (!NullConstantForBase->isNullValue()) {
5308671c6e0SDavid Majnemer     llvm::GlobalVariable *NullVariable = new llvm::GlobalVariable(
5318671c6e0SDavid Majnemer         CGF.CGM.getModule(), NullConstantForBase->getType(),
5328671c6e0SDavid Majnemer         /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage,
5338671c6e0SDavid Majnemer         NullConstantForBase, Twine());
5347f416cc4SJohn McCall 
5357f416cc4SJohn McCall     CharUnits Align = std::max(Layout.getNonVirtualAlignment(),
5367f416cc4SJohn McCall                                DestPtr.getAlignment());
537fde961dbSEli Friedman     NullVariable->setAlignment(Align.getQuantity());
5387f416cc4SJohn McCall 
5397f416cc4SJohn McCall     Address SrcPtr = Address(CGF.EmitCastToVoidPtr(NullVariable), Align);
540fde961dbSEli Friedman 
541fde961dbSEli Friedman     // Get and call the appropriate llvm.memcpy overload.
5428671c6e0SDavid Majnemer     for (std::pair<CharUnits, CharUnits> Store : Stores) {
5438671c6e0SDavid Majnemer       CharUnits StoreOffset = Store.first;
5448671c6e0SDavid Majnemer       CharUnits StoreSize = Store.second;
5458671c6e0SDavid Majnemer       llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
5468671c6e0SDavid Majnemer       CGF.Builder.CreateMemCpy(
5478671c6e0SDavid Majnemer           CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
5488671c6e0SDavid Majnemer           CGF.Builder.CreateConstInBoundsByteGEP(SrcPtr, StoreOffset),
5498671c6e0SDavid Majnemer           StoreSizeVal);
550fde961dbSEli Friedman     }
551fde961dbSEli Friedman 
552fde961dbSEli Friedman   // Otherwise, just memset the whole thing to zero.  This is legal
553fde961dbSEli Friedman   // because in LLVM, all default initializers (other than the ones we just
554fde961dbSEli Friedman   // handled above) are guaranteed to have a bit pattern of all zeros.
5558671c6e0SDavid Majnemer   } else {
5568671c6e0SDavid Majnemer     for (std::pair<CharUnits, CharUnits> Store : Stores) {
5578671c6e0SDavid Majnemer       CharUnits StoreOffset = Store.first;
5588671c6e0SDavid Majnemer       CharUnits StoreSize = Store.second;
5598671c6e0SDavid Majnemer       llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
5608671c6e0SDavid Majnemer       CGF.Builder.CreateMemSet(
5618671c6e0SDavid Majnemer           CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
5628671c6e0SDavid Majnemer           CGF.Builder.getInt8(0), StoreSizeVal);
5638671c6e0SDavid Majnemer     }
5648671c6e0SDavid Majnemer   }
565fde961dbSEli Friedman }
566fde961dbSEli Friedman 
56727da15baSAnders Carlsson void
5687a626f63SJohn McCall CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
5697a626f63SJohn McCall                                       AggValueSlot Dest) {
5707a626f63SJohn McCall   assert(!Dest.isIgnored() && "Must have a destination!");
57127da15baSAnders Carlsson   const CXXConstructorDecl *CD = E->getConstructor();
572630c76efSDouglas Gregor 
573630c76efSDouglas Gregor   // If we require zero initialization before (or instead of) calling the
574630c76efSDouglas Gregor   // constructor, as can be the case with a non-user-provided default
57503535265SArgyrios Kyrtzidis   // constructor, emit the zero initialization now, unless destination is
57603535265SArgyrios Kyrtzidis   // already zeroed.
577fde961dbSEli Friedman   if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
578fde961dbSEli Friedman     switch (E->getConstructionKind()) {
579fde961dbSEli Friedman     case CXXConstructExpr::CK_Delegating:
580fde961dbSEli Friedman     case CXXConstructExpr::CK_Complete:
5817f416cc4SJohn McCall       EmitNullInitialization(Dest.getAddress(), E->getType());
582fde961dbSEli Friedman       break;
583fde961dbSEli Friedman     case CXXConstructExpr::CK_VirtualBase:
584fde961dbSEli Friedman     case CXXConstructExpr::CK_NonVirtualBase:
5857f416cc4SJohn McCall       EmitNullBaseClassInitialization(*this, Dest.getAddress(),
5867f416cc4SJohn McCall                                       CD->getParent());
587fde961dbSEli Friedman       break;
588fde961dbSEli Friedman     }
589fde961dbSEli Friedman   }
590630c76efSDouglas Gregor 
591630c76efSDouglas Gregor   // If this is a call to a trivial default constructor, do nothing.
592630c76efSDouglas Gregor   if (CD->isTrivial() && CD->isDefaultConstructor())
59327da15baSAnders Carlsson     return;
594630c76efSDouglas Gregor 
5958ea46b66SJohn McCall   // Elide the constructor if we're constructing from a temporary.
5968ea46b66SJohn McCall   // The temporary check is required because Sema sets this on NRVO
5978ea46b66SJohn McCall   // returns.
5989c6890a7SRichard Smith   if (getLangOpts().ElideConstructors && E->isElidable()) {
5998ea46b66SJohn McCall     assert(getContext().hasSameUnqualifiedType(E->getType(),
6008ea46b66SJohn McCall                                                E->getArg(0)->getType()));
6017a626f63SJohn McCall     if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
6027a626f63SJohn McCall       EmitAggExpr(E->getArg(0), Dest);
60327da15baSAnders Carlsson       return;
60427da15baSAnders Carlsson     }
605222cf0efSDouglas Gregor   }
606630c76efSDouglas Gregor 
607e7545b33SAlexey Bataev   if (const ArrayType *arrayType
608e7545b33SAlexey Bataev         = getContext().getAsArrayType(E->getType())) {
60937605182SSerge Pavlov     EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddress(), E,
61037605182SSerge Pavlov                                Dest.isSanitizerChecked());
611f677a8e9SJohn McCall   } else {
612bceca20aSCameron Esfahani     CXXCtorType Type = Ctor_Complete;
613271c3681SAlexis Hunt     bool ForVirtualBase = false;
61461535005SDouglas Gregor     bool Delegating = false;
615271c3681SAlexis Hunt 
616271c3681SAlexis Hunt     switch (E->getConstructionKind()) {
617271c3681SAlexis Hunt      case CXXConstructExpr::CK_Delegating:
61861bc1737SAlexis Hunt       // We should be emitting a constructor; GlobalDecl will assert this
61961bc1737SAlexis Hunt       Type = CurGD.getCtorType();
62061535005SDouglas Gregor       Delegating = true;
621271c3681SAlexis Hunt       break;
62261bc1737SAlexis Hunt 
623271c3681SAlexis Hunt      case CXXConstructExpr::CK_Complete:
624271c3681SAlexis Hunt       Type = Ctor_Complete;
625271c3681SAlexis Hunt       break;
626271c3681SAlexis Hunt 
627271c3681SAlexis Hunt      case CXXConstructExpr::CK_VirtualBase:
628271c3681SAlexis Hunt       ForVirtualBase = true;
629f3b3ccdaSAdrian Prantl       LLVM_FALLTHROUGH;
630271c3681SAlexis Hunt 
631271c3681SAlexis Hunt      case CXXConstructExpr::CK_NonVirtualBase:
632271c3681SAlexis Hunt       Type = Ctor_Base;
633271c3681SAlexis Hunt     }
634e11f9ce9SAnders Carlsson 
63527da15baSAnders Carlsson     // Call the constructor.
6367f416cc4SJohn McCall     EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating,
63737605182SSerge Pavlov                            Dest.getAddress(), E, Dest.mayOverlap(),
63837605182SSerge Pavlov                            Dest.isSanitizerChecked());
63927da15baSAnders Carlsson   }
640e11f9ce9SAnders Carlsson }
64127da15baSAnders Carlsson 
6427f416cc4SJohn McCall void CodeGenFunction::EmitSynthesizedCXXCopyCtor(Address Dest, Address Src,
64350198098SFariborz Jahanian                                                  const Expr *Exp) {
6445d413781SJohn McCall   if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
645e988bdacSFariborz Jahanian     Exp = E->getSubExpr();
646e988bdacSFariborz Jahanian   assert(isa<CXXConstructExpr>(Exp) &&
647e988bdacSFariborz Jahanian          "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
648e988bdacSFariborz Jahanian   const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
649e988bdacSFariborz Jahanian   const CXXConstructorDecl *CD = E->getConstructor();
650e988bdacSFariborz Jahanian   RunCleanupsScope Scope(*this);
651e988bdacSFariborz Jahanian 
652e988bdacSFariborz Jahanian   // If we require zero initialization before (or instead of) calling the
653e988bdacSFariborz Jahanian   // constructor, as can be the case with a non-user-provided default
654e988bdacSFariborz Jahanian   // constructor, emit the zero initialization now.
655e988bdacSFariborz Jahanian   // FIXME. Do I still need this for a copy ctor synthesis?
656e988bdacSFariborz Jahanian   if (E->requiresZeroInitialization())
657e988bdacSFariborz Jahanian     EmitNullInitialization(Dest, E->getType());
658e988bdacSFariborz Jahanian 
65999da11cfSChandler Carruth   assert(!getContext().getAsConstantArrayType(E->getType())
66099da11cfSChandler Carruth          && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
661525bf650SAlexey Samsonov   EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E);
662e988bdacSFariborz Jahanian }
663e988bdacSFariborz Jahanian 
6648ed55a54SJohn McCall static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
6658ed55a54SJohn McCall                                         const CXXNewExpr *E) {
66621122cf6SAnders Carlsson   if (!E->isArray())
6673eb55cfeSKen Dyck     return CharUnits::Zero();
66821122cf6SAnders Carlsson 
6697ec4b434SJohn McCall   // No cookie is required if the operator new[] being used is the
6707ec4b434SJohn McCall   // reserved placement operator new[].
6717ec4b434SJohn McCall   if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
6723eb55cfeSKen Dyck     return CharUnits::Zero();
673399f499fSAnders Carlsson 
674284c48ffSJohn McCall   return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
67559486a2dSAnders Carlsson }
67659486a2dSAnders Carlsson 
677036f2f6bSJohn McCall static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
678036f2f6bSJohn McCall                                         const CXXNewExpr *e,
679f862eb6aSSebastian Redl                                         unsigned minElements,
680036f2f6bSJohn McCall                                         llvm::Value *&numElements,
681036f2f6bSJohn McCall                                         llvm::Value *&sizeWithoutCookie) {
682036f2f6bSJohn McCall   QualType type = e->getAllocatedType();
68359486a2dSAnders Carlsson 
684036f2f6bSJohn McCall   if (!e->isArray()) {
685036f2f6bSJohn McCall     CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
686036f2f6bSJohn McCall     sizeWithoutCookie
687036f2f6bSJohn McCall       = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
688036f2f6bSJohn McCall     return sizeWithoutCookie;
68905fc5be3SDouglas Gregor   }
69059486a2dSAnders Carlsson 
691036f2f6bSJohn McCall   // The width of size_t.
692036f2f6bSJohn McCall   unsigned sizeWidth = CGF.SizeTy->getBitWidth();
693036f2f6bSJohn McCall 
6948ed55a54SJohn McCall   // Figure out the cookie size.
695036f2f6bSJohn McCall   llvm::APInt cookieSize(sizeWidth,
696036f2f6bSJohn McCall                          CalculateCookiePadding(CGF, e).getQuantity());
6978ed55a54SJohn McCall 
69859486a2dSAnders Carlsson   // Emit the array size expression.
6997648fb46SArgyrios Kyrtzidis   // We multiply the size of all dimensions for NumElements.
7007648fb46SArgyrios Kyrtzidis   // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
701de0fe07eSJohn McCall   numElements =
702de0fe07eSJohn McCall     ConstantEmitter(CGF).tryEmitAbstract(e->getArraySize(), e->getType());
70307527621SNick Lewycky   if (!numElements)
704036f2f6bSJohn McCall     numElements = CGF.EmitScalarExpr(e->getArraySize());
705036f2f6bSJohn McCall   assert(isa<llvm::IntegerType>(numElements->getType()));
7068ed55a54SJohn McCall 
707036f2f6bSJohn McCall   // The number of elements can be have an arbitrary integer type;
708036f2f6bSJohn McCall   // essentially, we need to multiply it by a constant factor, add a
709036f2f6bSJohn McCall   // cookie size, and verify that the result is representable as a
710036f2f6bSJohn McCall   // size_t.  That's just a gloss, though, and it's wrong in one
711036f2f6bSJohn McCall   // important way: if the count is negative, it's an error even if
712036f2f6bSJohn McCall   // the cookie size would bring the total size >= 0.
7136ab2fa8fSDouglas Gregor   bool isSigned
7146ab2fa8fSDouglas Gregor     = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
7152192fe50SChris Lattner   llvm::IntegerType *numElementsType
716036f2f6bSJohn McCall     = cast<llvm::IntegerType>(numElements->getType());
717036f2f6bSJohn McCall   unsigned numElementsWidth = numElementsType->getBitWidth();
718036f2f6bSJohn McCall 
719036f2f6bSJohn McCall   // Compute the constant factor.
720036f2f6bSJohn McCall   llvm::APInt arraySizeMultiplier(sizeWidth, 1);
7217648fb46SArgyrios Kyrtzidis   while (const ConstantArrayType *CAT
722036f2f6bSJohn McCall              = CGF.getContext().getAsConstantArrayType(type)) {
723036f2f6bSJohn McCall     type = CAT->getElementType();
724036f2f6bSJohn McCall     arraySizeMultiplier *= CAT->getSize();
7257648fb46SArgyrios Kyrtzidis   }
72659486a2dSAnders Carlsson 
727036f2f6bSJohn McCall   CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
728036f2f6bSJohn McCall   llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
729036f2f6bSJohn McCall   typeSizeMultiplier *= arraySizeMultiplier;
730036f2f6bSJohn McCall 
731036f2f6bSJohn McCall   // This will be a size_t.
732036f2f6bSJohn McCall   llvm::Value *size;
73332ac583dSChris Lattner 
73432ac583dSChris Lattner   // If someone is doing 'new int[42]' there is no need to do a dynamic check.
73532ac583dSChris Lattner   // Don't bloat the -O0 code.
736036f2f6bSJohn McCall   if (llvm::ConstantInt *numElementsC =
737036f2f6bSJohn McCall         dyn_cast<llvm::ConstantInt>(numElements)) {
738036f2f6bSJohn McCall     const llvm::APInt &count = numElementsC->getValue();
73932ac583dSChris Lattner 
740036f2f6bSJohn McCall     bool hasAnyOverflow = false;
74132ac583dSChris Lattner 
742036f2f6bSJohn McCall     // If 'count' was a negative number, it's an overflow.
743036f2f6bSJohn McCall     if (isSigned && count.isNegative())
744036f2f6bSJohn McCall       hasAnyOverflow = true;
7458ed55a54SJohn McCall 
746036f2f6bSJohn McCall     // We want to do all this arithmetic in size_t.  If numElements is
747036f2f6bSJohn McCall     // wider than that, check whether it's already too big, and if so,
748036f2f6bSJohn McCall     // overflow.
749036f2f6bSJohn McCall     else if (numElementsWidth > sizeWidth &&
750036f2f6bSJohn McCall              numElementsWidth - sizeWidth > count.countLeadingZeros())
751036f2f6bSJohn McCall       hasAnyOverflow = true;
752036f2f6bSJohn McCall 
753036f2f6bSJohn McCall     // Okay, compute a count at the right width.
754036f2f6bSJohn McCall     llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
755036f2f6bSJohn McCall 
756f862eb6aSSebastian Redl     // If there is a brace-initializer, we cannot allocate fewer elements than
757f862eb6aSSebastian Redl     // there are initializers. If we do, that's treated like an overflow.
758f862eb6aSSebastian Redl     if (adjustedCount.ult(minElements))
759f862eb6aSSebastian Redl       hasAnyOverflow = true;
760f862eb6aSSebastian Redl 
761036f2f6bSJohn McCall     // Scale numElements by that.  This might overflow, but we don't
762036f2f6bSJohn McCall     // care because it only overflows if allocationSize does, too, and
763036f2f6bSJohn McCall     // if that overflows then we shouldn't use this.
764036f2f6bSJohn McCall     numElements = llvm::ConstantInt::get(CGF.SizeTy,
765036f2f6bSJohn McCall                                          adjustedCount * arraySizeMultiplier);
766036f2f6bSJohn McCall 
767036f2f6bSJohn McCall     // Compute the size before cookie, and track whether it overflowed.
768036f2f6bSJohn McCall     bool overflow;
769036f2f6bSJohn McCall     llvm::APInt allocationSize
770036f2f6bSJohn McCall       = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
771036f2f6bSJohn McCall     hasAnyOverflow |= overflow;
772036f2f6bSJohn McCall 
773036f2f6bSJohn McCall     // Add in the cookie, and check whether it's overflowed.
774036f2f6bSJohn McCall     if (cookieSize != 0) {
775036f2f6bSJohn McCall       // Save the current size without a cookie.  This shouldn't be
776036f2f6bSJohn McCall       // used if there was overflow.
777036f2f6bSJohn McCall       sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
778036f2f6bSJohn McCall 
779036f2f6bSJohn McCall       allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
780036f2f6bSJohn McCall       hasAnyOverflow |= overflow;
7818ed55a54SJohn McCall     }
7828ed55a54SJohn McCall 
783036f2f6bSJohn McCall     // On overflow, produce a -1 so operator new will fail.
784455f42c9SAaron Ballman     if (hasAnyOverflow) {
785455f42c9SAaron Ballman       size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
786455f42c9SAaron Ballman     } else {
787036f2f6bSJohn McCall       size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
788455f42c9SAaron Ballman     }
78932ac583dSChris Lattner 
790036f2f6bSJohn McCall   // Otherwise, we might need to use the overflow intrinsics.
7918ed55a54SJohn McCall   } else {
792f862eb6aSSebastian Redl     // There are up to five conditions we need to test for:
793036f2f6bSJohn McCall     // 1) if isSigned, we need to check whether numElements is negative;
794036f2f6bSJohn McCall     // 2) if numElementsWidth > sizeWidth, we need to check whether
795036f2f6bSJohn McCall     //   numElements is larger than something representable in size_t;
796f862eb6aSSebastian Redl     // 3) if minElements > 0, we need to check whether numElements is smaller
797f862eb6aSSebastian Redl     //    than that.
798f862eb6aSSebastian Redl     // 4) we need to compute
799036f2f6bSJohn McCall     //      sizeWithoutCookie := numElements * typeSizeMultiplier
800036f2f6bSJohn McCall     //    and check whether it overflows; and
801f862eb6aSSebastian Redl     // 5) if we need a cookie, we need to compute
802036f2f6bSJohn McCall     //      size := sizeWithoutCookie + cookieSize
803036f2f6bSJohn McCall     //    and check whether it overflows.
8048ed55a54SJohn McCall 
8058a13c418SCraig Topper     llvm::Value *hasOverflow = nullptr;
8068ed55a54SJohn McCall 
807036f2f6bSJohn McCall     // If numElementsWidth > sizeWidth, then one way or another, we're
808036f2f6bSJohn McCall     // going to have to do a comparison for (2), and this happens to
809036f2f6bSJohn McCall     // take care of (1), too.
810036f2f6bSJohn McCall     if (numElementsWidth > sizeWidth) {
811036f2f6bSJohn McCall       llvm::APInt threshold(numElementsWidth, 1);
812036f2f6bSJohn McCall       threshold <<= sizeWidth;
8138ed55a54SJohn McCall 
814036f2f6bSJohn McCall       llvm::Value *thresholdV
815036f2f6bSJohn McCall         = llvm::ConstantInt::get(numElementsType, threshold);
816036f2f6bSJohn McCall 
817036f2f6bSJohn McCall       hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
818036f2f6bSJohn McCall       numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
819036f2f6bSJohn McCall 
820036f2f6bSJohn McCall     // Otherwise, if we're signed, we want to sext up to size_t.
821036f2f6bSJohn McCall     } else if (isSigned) {
822036f2f6bSJohn McCall       if (numElementsWidth < sizeWidth)
823036f2f6bSJohn McCall         numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
824036f2f6bSJohn McCall 
825036f2f6bSJohn McCall       // If there's a non-1 type size multiplier, then we can do the
826036f2f6bSJohn McCall       // signedness check at the same time as we do the multiply
827036f2f6bSJohn McCall       // because a negative number times anything will cause an
828f862eb6aSSebastian Redl       // unsigned overflow.  Otherwise, we have to do it here. But at least
829f862eb6aSSebastian Redl       // in this case, we can subsume the >= minElements check.
830036f2f6bSJohn McCall       if (typeSizeMultiplier == 1)
831036f2f6bSJohn McCall         hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
832f862eb6aSSebastian Redl                               llvm::ConstantInt::get(CGF.SizeTy, minElements));
833036f2f6bSJohn McCall 
834036f2f6bSJohn McCall     // Otherwise, zext up to size_t if necessary.
835036f2f6bSJohn McCall     } else if (numElementsWidth < sizeWidth) {
836036f2f6bSJohn McCall       numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
837036f2f6bSJohn McCall     }
838036f2f6bSJohn McCall 
839036f2f6bSJohn McCall     assert(numElements->getType() == CGF.SizeTy);
840036f2f6bSJohn McCall 
841f862eb6aSSebastian Redl     if (minElements) {
842f862eb6aSSebastian Redl       // Don't allow allocation of fewer elements than we have initializers.
843f862eb6aSSebastian Redl       if (!hasOverflow) {
844f862eb6aSSebastian Redl         hasOverflow = CGF.Builder.CreateICmpULT(numElements,
845f862eb6aSSebastian Redl                               llvm::ConstantInt::get(CGF.SizeTy, minElements));
846f862eb6aSSebastian Redl       } else if (numElementsWidth > sizeWidth) {
847f862eb6aSSebastian Redl         // The other existing overflow subsumes this check.
848f862eb6aSSebastian Redl         // We do an unsigned comparison, since any signed value < -1 is
849f862eb6aSSebastian Redl         // taken care of either above or below.
850f862eb6aSSebastian Redl         hasOverflow = CGF.Builder.CreateOr(hasOverflow,
851f862eb6aSSebastian Redl                           CGF.Builder.CreateICmpULT(numElements,
852f862eb6aSSebastian Redl                               llvm::ConstantInt::get(CGF.SizeTy, minElements)));
853f862eb6aSSebastian Redl       }
854f862eb6aSSebastian Redl     }
855f862eb6aSSebastian Redl 
856036f2f6bSJohn McCall     size = numElements;
857036f2f6bSJohn McCall 
858036f2f6bSJohn McCall     // Multiply by the type size if necessary.  This multiplier
859036f2f6bSJohn McCall     // includes all the factors for nested arrays.
8608ed55a54SJohn McCall     //
861036f2f6bSJohn McCall     // This step also causes numElements to be scaled up by the
862036f2f6bSJohn McCall     // nested-array factor if necessary.  Overflow on this computation
863036f2f6bSJohn McCall     // can be ignored because the result shouldn't be used if
864036f2f6bSJohn McCall     // allocation fails.
865036f2f6bSJohn McCall     if (typeSizeMultiplier != 1) {
866*8799caeeSJames Y Knight       llvm::Function *umul_with_overflow
8678d375cefSBenjamin Kramer         = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
8688ed55a54SJohn McCall 
869036f2f6bSJohn McCall       llvm::Value *tsmV =
870036f2f6bSJohn McCall         llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
871036f2f6bSJohn McCall       llvm::Value *result =
87243f9bb73SDavid Blaikie           CGF.Builder.CreateCall(umul_with_overflow, {size, tsmV});
8738ed55a54SJohn McCall 
874036f2f6bSJohn McCall       llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
875036f2f6bSJohn McCall       if (hasOverflow)
876036f2f6bSJohn McCall         hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
8778ed55a54SJohn McCall       else
878036f2f6bSJohn McCall         hasOverflow = overflowed;
87959486a2dSAnders Carlsson 
880036f2f6bSJohn McCall       size = CGF.Builder.CreateExtractValue(result, 0);
881036f2f6bSJohn McCall 
882036f2f6bSJohn McCall       // Also scale up numElements by the array size multiplier.
883036f2f6bSJohn McCall       if (arraySizeMultiplier != 1) {
884036f2f6bSJohn McCall         // If the base element type size is 1, then we can re-use the
885036f2f6bSJohn McCall         // multiply we just did.
886036f2f6bSJohn McCall         if (typeSize.isOne()) {
887036f2f6bSJohn McCall           assert(arraySizeMultiplier == typeSizeMultiplier);
888036f2f6bSJohn McCall           numElements = size;
889036f2f6bSJohn McCall 
890036f2f6bSJohn McCall         // Otherwise we need a separate multiply.
891036f2f6bSJohn McCall         } else {
892036f2f6bSJohn McCall           llvm::Value *asmV =
893036f2f6bSJohn McCall             llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
894036f2f6bSJohn McCall           numElements = CGF.Builder.CreateMul(numElements, asmV);
895036f2f6bSJohn McCall         }
896036f2f6bSJohn McCall       }
897036f2f6bSJohn McCall     } else {
898036f2f6bSJohn McCall       // numElements doesn't need to be scaled.
899036f2f6bSJohn McCall       assert(arraySizeMultiplier == 1);
900036f2f6bSJohn McCall     }
901036f2f6bSJohn McCall 
902036f2f6bSJohn McCall     // Add in the cookie size if necessary.
903036f2f6bSJohn McCall     if (cookieSize != 0) {
904036f2f6bSJohn McCall       sizeWithoutCookie = size;
905036f2f6bSJohn McCall 
906*8799caeeSJames Y Knight       llvm::Function *uadd_with_overflow
9078d375cefSBenjamin Kramer         = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
908036f2f6bSJohn McCall 
909036f2f6bSJohn McCall       llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
910036f2f6bSJohn McCall       llvm::Value *result =
91143f9bb73SDavid Blaikie           CGF.Builder.CreateCall(uadd_with_overflow, {size, cookieSizeV});
912036f2f6bSJohn McCall 
913036f2f6bSJohn McCall       llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
914036f2f6bSJohn McCall       if (hasOverflow)
915036f2f6bSJohn McCall         hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
916036f2f6bSJohn McCall       else
917036f2f6bSJohn McCall         hasOverflow = overflowed;
918036f2f6bSJohn McCall 
919036f2f6bSJohn McCall       size = CGF.Builder.CreateExtractValue(result, 0);
920036f2f6bSJohn McCall     }
921036f2f6bSJohn McCall 
922036f2f6bSJohn McCall     // If we had any possibility of dynamic overflow, make a select to
923036f2f6bSJohn McCall     // overwrite 'size' with an all-ones value, which should cause
924036f2f6bSJohn McCall     // operator new to throw.
925036f2f6bSJohn McCall     if (hasOverflow)
926455f42c9SAaron Ballman       size = CGF.Builder.CreateSelect(hasOverflow,
927455f42c9SAaron Ballman                                  llvm::Constant::getAllOnesValue(CGF.SizeTy),
928036f2f6bSJohn McCall                                       size);
929036f2f6bSJohn McCall   }
930036f2f6bSJohn McCall 
931036f2f6bSJohn McCall   if (cookieSize == 0)
932036f2f6bSJohn McCall     sizeWithoutCookie = size;
933036f2f6bSJohn McCall   else
934036f2f6bSJohn McCall     assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
935036f2f6bSJohn McCall 
936036f2f6bSJohn McCall   return size;
93759486a2dSAnders Carlsson }
93859486a2dSAnders Carlsson 
939f862eb6aSSebastian Redl static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
940e78fac51SRichard Smith                                     QualType AllocType, Address NewPtr,
941e78fac51SRichard Smith                                     AggValueSlot::Overlap_t MayOverlap) {
9421c96bc5dSRichard Smith   // FIXME: Refactor with EmitExprAsInit.
94347fb9508SJohn McCall   switch (CGF.getEvaluationKind(AllocType)) {
94447fb9508SJohn McCall   case TEK_Scalar:
945a2c1124fSDavid Blaikie     CGF.EmitScalarInit(Init, nullptr,
9467f416cc4SJohn McCall                        CGF.MakeAddrLValue(NewPtr, AllocType), false);
94747fb9508SJohn McCall     return;
94847fb9508SJohn McCall   case TEK_Complex:
9497f416cc4SJohn McCall     CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType),
95047fb9508SJohn McCall                                   /*isInit*/ true);
95147fb9508SJohn McCall     return;
95247fb9508SJohn McCall   case TEK_Aggregate: {
9537a626f63SJohn McCall     AggValueSlot Slot
9547f416cc4SJohn McCall       = AggValueSlot::forAddr(NewPtr, AllocType.getQualifiers(),
9558d6fc958SJohn McCall                               AggValueSlot::IsDestructed,
95646759f4fSJohn McCall                               AggValueSlot::DoesNotNeedGCBarriers,
957e78fac51SRichard Smith                               AggValueSlot::IsNotAliased,
95837605182SSerge Pavlov                               MayOverlap, AggValueSlot::IsNotZeroed,
95937605182SSerge Pavlov                               AggValueSlot::IsSanitizerChecked);
9607a626f63SJohn McCall     CGF.EmitAggExpr(Init, Slot);
96147fb9508SJohn McCall     return;
9627a626f63SJohn McCall   }
963d5202e09SFariborz Jahanian   }
96447fb9508SJohn McCall   llvm_unreachable("bad evaluation kind");
96547fb9508SJohn McCall }
966d5202e09SFariborz Jahanian 
967fb901c7aSDavid Blaikie void CodeGenFunction::EmitNewArrayInitializer(
968fb901c7aSDavid Blaikie     const CXXNewExpr *E, QualType ElementType, llvm::Type *ElementTy,
9697f416cc4SJohn McCall     Address BeginPtr, llvm::Value *NumElements,
97006a67e2cSRichard Smith     llvm::Value *AllocSizeWithoutCookie) {
97106a67e2cSRichard Smith   // If we have a type with trivial initialization and no initializer,
97206a67e2cSRichard Smith   // there's nothing to do.
9736047f07eSSebastian Redl   if (!E->hasInitializer())
97406a67e2cSRichard Smith     return;
975b66b08efSFariborz Jahanian 
9767f416cc4SJohn McCall   Address CurPtr = BeginPtr;
977d5202e09SFariborz Jahanian 
97806a67e2cSRichard Smith   unsigned InitListElements = 0;
979f862eb6aSSebastian Redl 
980f862eb6aSSebastian Redl   const Expr *Init = E->getInitializer();
9817f416cc4SJohn McCall   Address EndOfInit = Address::invalid();
98206a67e2cSRichard Smith   QualType::DestructionKind DtorKind = ElementType.isDestructedType();
98306a67e2cSRichard Smith   EHScopeStack::stable_iterator Cleanup;
98406a67e2cSRichard Smith   llvm::Instruction *CleanupDominator = nullptr;
9851c96bc5dSRichard Smith 
9867f416cc4SJohn McCall   CharUnits ElementSize = getContext().getTypeSizeInChars(ElementType);
9877f416cc4SJohn McCall   CharUnits ElementAlign =
9887f416cc4SJohn McCall     BeginPtr.getAlignment().alignmentOfArrayElement(ElementSize);
9897f416cc4SJohn McCall 
9900511d23aSRichard Smith   // Attempt to perform zero-initialization using memset.
9910511d23aSRichard Smith   auto TryMemsetInitialization = [&]() -> bool {
9920511d23aSRichard Smith     // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
9930511d23aSRichard Smith     // we can initialize with a memset to -1.
9940511d23aSRichard Smith     if (!CGM.getTypes().isZeroInitializable(ElementType))
9950511d23aSRichard Smith       return false;
9960511d23aSRichard Smith 
9970511d23aSRichard Smith     // Optimization: since zero initialization will just set the memory
9980511d23aSRichard Smith     // to all zeroes, generate a single memset to do it in one shot.
9990511d23aSRichard Smith 
10000511d23aSRichard Smith     // Subtract out the size of any elements we've already initialized.
10010511d23aSRichard Smith     auto *RemainingSize = AllocSizeWithoutCookie;
10020511d23aSRichard Smith     if (InitListElements) {
10030511d23aSRichard Smith       // We know this can't overflow; we check this when doing the allocation.
10040511d23aSRichard Smith       auto *InitializedSize = llvm::ConstantInt::get(
10050511d23aSRichard Smith           RemainingSize->getType(),
10060511d23aSRichard Smith           getContext().getTypeSizeInChars(ElementType).getQuantity() *
10070511d23aSRichard Smith               InitListElements);
10080511d23aSRichard Smith       RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
10090511d23aSRichard Smith     }
10100511d23aSRichard Smith 
10110511d23aSRichard Smith     // Create the memset.
10120511d23aSRichard Smith     Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize, false);
10130511d23aSRichard Smith     return true;
10140511d23aSRichard Smith   };
10150511d23aSRichard Smith 
1016f862eb6aSSebastian Redl   // If the initializer is an initializer list, first do the explicit elements.
1017f862eb6aSSebastian Redl   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
10180511d23aSRichard Smith     // Initializing from a (braced) string literal is a special case; the init
10190511d23aSRichard Smith     // list element does not initialize a (single) array element.
10200511d23aSRichard Smith     if (ILE->isStringLiteralInit()) {
10210511d23aSRichard Smith       // Initialize the initial portion of length equal to that of the string
10220511d23aSRichard Smith       // literal. The allocation must be for at least this much; we emitted a
10230511d23aSRichard Smith       // check for that earlier.
10240511d23aSRichard Smith       AggValueSlot Slot =
10250511d23aSRichard Smith           AggValueSlot::forAddr(CurPtr, ElementType.getQualifiers(),
10260511d23aSRichard Smith                                 AggValueSlot::IsDestructed,
10270511d23aSRichard Smith                                 AggValueSlot::DoesNotNeedGCBarriers,
1028e78fac51SRichard Smith                                 AggValueSlot::IsNotAliased,
102937605182SSerge Pavlov                                 AggValueSlot::DoesNotOverlap,
103037605182SSerge Pavlov                                 AggValueSlot::IsNotZeroed,
103137605182SSerge Pavlov                                 AggValueSlot::IsSanitizerChecked);
10320511d23aSRichard Smith       EmitAggExpr(ILE->getInit(0), Slot);
10330511d23aSRichard Smith 
10340511d23aSRichard Smith       // Move past these elements.
10350511d23aSRichard Smith       InitListElements =
10360511d23aSRichard Smith           cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe())
10370511d23aSRichard Smith               ->getSize().getZExtValue();
10380511d23aSRichard Smith       CurPtr =
10390511d23aSRichard Smith           Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(),
10400511d23aSRichard Smith                                             Builder.getSize(InitListElements),
10410511d23aSRichard Smith                                             "string.init.end"),
10420511d23aSRichard Smith                   CurPtr.getAlignment().alignmentAtOffset(InitListElements *
10430511d23aSRichard Smith                                                           ElementSize));
10440511d23aSRichard Smith 
10450511d23aSRichard Smith       // Zero out the rest, if any remain.
10460511d23aSRichard Smith       llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
10470511d23aSRichard Smith       if (!ConstNum || !ConstNum->equalsInt(InitListElements)) {
10480511d23aSRichard Smith         bool OK = TryMemsetInitialization();
10490511d23aSRichard Smith         (void)OK;
10500511d23aSRichard Smith         assert(OK && "couldn't memset character type?");
10510511d23aSRichard Smith       }
10520511d23aSRichard Smith       return;
10530511d23aSRichard Smith     }
10540511d23aSRichard Smith 
105506a67e2cSRichard Smith     InitListElements = ILE->getNumInits();
1056f62290a1SChad Rosier 
10571c96bc5dSRichard Smith     // If this is a multi-dimensional array new, we will initialize multiple
10581c96bc5dSRichard Smith     // elements with each init list element.
10591c96bc5dSRichard Smith     QualType AllocType = E->getAllocatedType();
10601c96bc5dSRichard Smith     if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
10611c96bc5dSRichard Smith             AllocType->getAsArrayTypeUnsafe())) {
1062fb901c7aSDavid Blaikie       ElementTy = ConvertTypeForMem(AllocType);
10637f416cc4SJohn McCall       CurPtr = Builder.CreateElementBitCast(CurPtr, ElementTy);
106406a67e2cSRichard Smith       InitListElements *= getContext().getConstantArrayElementCount(CAT);
10651c96bc5dSRichard Smith     }
10661c96bc5dSRichard Smith 
106706a67e2cSRichard Smith     // Enter a partial-destruction Cleanup if necessary.
106806a67e2cSRichard Smith     if (needsEHCleanup(DtorKind)) {
106906a67e2cSRichard Smith       // In principle we could tell the Cleanup where we are more
1070f62290a1SChad Rosier       // directly, but the control flow can get so varied here that it
1071f62290a1SChad Rosier       // would actually be quite complex.  Therefore we go through an
1072f62290a1SChad Rosier       // alloca.
10737f416cc4SJohn McCall       EndOfInit = CreateTempAlloca(BeginPtr.getType(), getPointerAlign(),
10747f416cc4SJohn McCall                                    "array.init.end");
10757f416cc4SJohn McCall       CleanupDominator = Builder.CreateStore(BeginPtr.getPointer(), EndOfInit);
10767f416cc4SJohn McCall       pushIrregularPartialArrayCleanup(BeginPtr.getPointer(), EndOfInit,
10777f416cc4SJohn McCall                                        ElementType, ElementAlign,
107806a67e2cSRichard Smith                                        getDestroyer(DtorKind));
107906a67e2cSRichard Smith       Cleanup = EHStack.stable_begin();
1080f62290a1SChad Rosier     }
1081f62290a1SChad Rosier 
10827f416cc4SJohn McCall     CharUnits StartAlign = CurPtr.getAlignment();
1083f862eb6aSSebastian Redl     for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
1084f62290a1SChad Rosier       // Tell the cleanup that it needs to destroy up to this
1085f62290a1SChad Rosier       // element.  TODO: some of these stores can be trivially
1086f62290a1SChad Rosier       // observed to be unnecessary.
10877f416cc4SJohn McCall       if (EndOfInit.isValid()) {
10887f416cc4SJohn McCall         auto FinishedPtr =
10897f416cc4SJohn McCall           Builder.CreateBitCast(CurPtr.getPointer(), BeginPtr.getType());
10907f416cc4SJohn McCall         Builder.CreateStore(FinishedPtr, EndOfInit);
10917f416cc4SJohn McCall       }
109206a67e2cSRichard Smith       // FIXME: If the last initializer is an incomplete initializer list for
109306a67e2cSRichard Smith       // an array, and we have an array filler, we can fold together the two
109406a67e2cSRichard Smith       // initialization loops.
10951c96bc5dSRichard Smith       StoreAnyExprIntoOneUnit(*this, ILE->getInit(i),
1096e78fac51SRichard Smith                               ILE->getInit(i)->getType(), CurPtr,
1097e78fac51SRichard Smith                               AggValueSlot::DoesNotOverlap);
10987f416cc4SJohn McCall       CurPtr = Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(),
10997f416cc4SJohn McCall                                                  Builder.getSize(1),
11007f416cc4SJohn McCall                                                  "array.exp.next"),
11017f416cc4SJohn McCall                        StartAlign.alignmentAtOffset((i + 1) * ElementSize));
1102f862eb6aSSebastian Redl     }
1103f862eb6aSSebastian Redl 
1104f862eb6aSSebastian Redl     // The remaining elements are filled with the array filler expression.
1105f862eb6aSSebastian Redl     Init = ILE->getArrayFiller();
11061c96bc5dSRichard Smith 
110706a67e2cSRichard Smith     // Extract the initializer for the individual array elements by pulling
110806a67e2cSRichard Smith     // out the array filler from all the nested initializer lists. This avoids
110906a67e2cSRichard Smith     // generating a nested loop for the initialization.
111006a67e2cSRichard Smith     while (Init && Init->getType()->isConstantArrayType()) {
111106a67e2cSRichard Smith       auto *SubILE = dyn_cast<InitListExpr>(Init);
111206a67e2cSRichard Smith       if (!SubILE)
111306a67e2cSRichard Smith         break;
111406a67e2cSRichard Smith       assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
111506a67e2cSRichard Smith       Init = SubILE->getArrayFiller();
1116f862eb6aSSebastian Redl     }
1117f862eb6aSSebastian Redl 
111806a67e2cSRichard Smith     // Switch back to initializing one base element at a time.
11197f416cc4SJohn McCall     CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr.getType());
1120f62290a1SChad Rosier   }
1121e6c980c4SChandler Carruth 
1122454a7cdfSRichard Smith   // If all elements have already been initialized, skip any further
1123454a7cdfSRichard Smith   // initialization.
1124454a7cdfSRichard Smith   llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
1125454a7cdfSRichard Smith   if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
1126454a7cdfSRichard Smith     // If there was a Cleanup, deactivate it.
1127454a7cdfSRichard Smith     if (CleanupDominator)
1128454a7cdfSRichard Smith       DeactivateCleanupBlock(Cleanup, CleanupDominator);
1129454a7cdfSRichard Smith     return;
1130454a7cdfSRichard Smith   }
1131454a7cdfSRichard Smith 
1132454a7cdfSRichard Smith   assert(Init && "have trailing elements to initialize but no initializer");
1133454a7cdfSRichard Smith 
113406a67e2cSRichard Smith   // If this is a constructor call, try to optimize it out, and failing that
113506a67e2cSRichard Smith   // emit a single loop to initialize all remaining elements.
1136454a7cdfSRichard Smith   if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
11376047f07eSSebastian Redl     CXXConstructorDecl *Ctor = CCE->getConstructor();
1138d153103cSDouglas Gregor     if (Ctor->isTrivial()) {
113905fc5be3SDouglas Gregor       // If new expression did not specify value-initialization, then there
114005fc5be3SDouglas Gregor       // is no initialization.
11416047f07eSSebastian Redl       if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
114205fc5be3SDouglas Gregor         return;
114305fc5be3SDouglas Gregor 
114406a67e2cSRichard Smith       if (TryMemsetInitialization())
11453a202f60SAnders Carlsson         return;
11463a202f60SAnders Carlsson     }
114705fc5be3SDouglas Gregor 
114806a67e2cSRichard Smith     // Store the new Cleanup position for irregular Cleanups.
114906a67e2cSRichard Smith     //
115006a67e2cSRichard Smith     // FIXME: Share this cleanup with the constructor call emission rather than
115106a67e2cSRichard Smith     // having it create a cleanup of its own.
11527f416cc4SJohn McCall     if (EndOfInit.isValid())
11537f416cc4SJohn McCall       Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
115406a67e2cSRichard Smith 
115506a67e2cSRichard Smith     // Emit a constructor call loop to initialize the remaining elements.
115606a67e2cSRichard Smith     if (InitListElements)
115706a67e2cSRichard Smith       NumElements = Builder.CreateSub(
115806a67e2cSRichard Smith           NumElements,
115906a67e2cSRichard Smith           llvm::ConstantInt::get(NumElements->getType(), InitListElements));
116070b9c01bSAlexey Samsonov     EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,
116137605182SSerge Pavlov                                /*NewPointerIsChecked*/true,
116248ddcf2cSEli Friedman                                CCE->requiresZeroInitialization());
116305fc5be3SDouglas Gregor     return;
11646047f07eSSebastian Redl   }
116506a67e2cSRichard Smith 
116606a67e2cSRichard Smith   // If this is value-initialization, we can usually use memset.
116706a67e2cSRichard Smith   ImplicitValueInitExpr IVIE(ElementType);
1168454a7cdfSRichard Smith   if (isa<ImplicitValueInitExpr>(Init)) {
116906a67e2cSRichard Smith     if (TryMemsetInitialization())
117006a67e2cSRichard Smith       return;
117106a67e2cSRichard Smith 
117206a67e2cSRichard Smith     // Switch to an ImplicitValueInitExpr for the element type. This handles
117306a67e2cSRichard Smith     // only one case: multidimensional array new of pointers to members. In
117406a67e2cSRichard Smith     // all other cases, we already have an initializer for the array element.
117506a67e2cSRichard Smith     Init = &IVIE;
117606a67e2cSRichard Smith   }
117706a67e2cSRichard Smith 
117806a67e2cSRichard Smith   // At this point we should have found an initializer for the individual
117906a67e2cSRichard Smith   // elements of the array.
118006a67e2cSRichard Smith   assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&
118106a67e2cSRichard Smith          "got wrong type of element to initialize");
118206a67e2cSRichard Smith 
1183454a7cdfSRichard Smith   // If we have an empty initializer list, we can usually use memset.
1184454a7cdfSRichard Smith   if (auto *ILE = dyn_cast<InitListExpr>(Init))
1185454a7cdfSRichard Smith     if (ILE->getNumInits() == 0 && TryMemsetInitialization())
1186d5202e09SFariborz Jahanian       return;
118759486a2dSAnders Carlsson 
1188cb77930dSYunzhong Gao   // If we have a struct whose every field is value-initialized, we can
1189cb77930dSYunzhong Gao   // usually use memset.
1190cb77930dSYunzhong Gao   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
1191cb77930dSYunzhong Gao     if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
1192cb77930dSYunzhong Gao       if (RType->getDecl()->isStruct()) {
1193872307e2SRichard Smith         unsigned NumElements = 0;
1194872307e2SRichard Smith         if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RType->getDecl()))
1195872307e2SRichard Smith           NumElements = CXXRD->getNumBases();
1196cb77930dSYunzhong Gao         for (auto *Field : RType->getDecl()->fields())
1197cb77930dSYunzhong Gao           if (!Field->isUnnamedBitfield())
1198872307e2SRichard Smith             ++NumElements;
1199872307e2SRichard Smith         // FIXME: Recurse into nested InitListExprs.
1200872307e2SRichard Smith         if (ILE->getNumInits() == NumElements)
1201cb77930dSYunzhong Gao           for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
1202cb77930dSYunzhong Gao             if (!isa<ImplicitValueInitExpr>(ILE->getInit(i)))
1203872307e2SRichard Smith               --NumElements;
1204872307e2SRichard Smith         if (ILE->getNumInits() == NumElements && TryMemsetInitialization())
1205cb77930dSYunzhong Gao           return;
1206cb77930dSYunzhong Gao       }
1207cb77930dSYunzhong Gao     }
1208cb77930dSYunzhong Gao   }
1209cb77930dSYunzhong Gao 
121006a67e2cSRichard Smith   // Create the loop blocks.
121106a67e2cSRichard Smith   llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
121206a67e2cSRichard Smith   llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
121306a67e2cSRichard Smith   llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
121459486a2dSAnders Carlsson 
121506a67e2cSRichard Smith   // Find the end of the array, hoisted out of the loop.
121606a67e2cSRichard Smith   llvm::Value *EndPtr =
12177f416cc4SJohn McCall     Builder.CreateInBoundsGEP(BeginPtr.getPointer(), NumElements, "array.end");
121806a67e2cSRichard Smith 
121906a67e2cSRichard Smith   // If the number of elements isn't constant, we have to now check if there is
122006a67e2cSRichard Smith   // anything left to initialize.
122106a67e2cSRichard Smith   if (!ConstNum) {
12227f416cc4SJohn McCall     llvm::Value *IsEmpty =
12237f416cc4SJohn McCall       Builder.CreateICmpEQ(CurPtr.getPointer(), EndPtr, "array.isempty");
122406a67e2cSRichard Smith     Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
122506a67e2cSRichard Smith   }
122606a67e2cSRichard Smith 
122706a67e2cSRichard Smith   // Enter the loop.
122806a67e2cSRichard Smith   EmitBlock(LoopBB);
122906a67e2cSRichard Smith 
123006a67e2cSRichard Smith   // Set up the current-element phi.
123106a67e2cSRichard Smith   llvm::PHINode *CurPtrPhi =
12327f416cc4SJohn McCall     Builder.CreatePHI(CurPtr.getType(), 2, "array.cur");
12337f416cc4SJohn McCall   CurPtrPhi->addIncoming(CurPtr.getPointer(), EntryBB);
12347f416cc4SJohn McCall 
12357f416cc4SJohn McCall   CurPtr = Address(CurPtrPhi, ElementAlign);
123606a67e2cSRichard Smith 
123706a67e2cSRichard Smith   // Store the new Cleanup position for irregular Cleanups.
12387f416cc4SJohn McCall   if (EndOfInit.isValid())
12397f416cc4SJohn McCall     Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
124006a67e2cSRichard Smith 
124106a67e2cSRichard Smith   // Enter a partial-destruction Cleanup if necessary.
124206a67e2cSRichard Smith   if (!CleanupDominator && needsEHCleanup(DtorKind)) {
12437f416cc4SJohn McCall     pushRegularPartialArrayCleanup(BeginPtr.getPointer(), CurPtr.getPointer(),
12447f416cc4SJohn McCall                                    ElementType, ElementAlign,
124506a67e2cSRichard Smith                                    getDestroyer(DtorKind));
124606a67e2cSRichard Smith     Cleanup = EHStack.stable_begin();
124706a67e2cSRichard Smith     CleanupDominator = Builder.CreateUnreachable();
124806a67e2cSRichard Smith   }
124906a67e2cSRichard Smith 
125006a67e2cSRichard Smith   // Emit the initializer into this element.
1251e78fac51SRichard Smith   StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr,
1252e78fac51SRichard Smith                           AggValueSlot::DoesNotOverlap);
125306a67e2cSRichard Smith 
125406a67e2cSRichard Smith   // Leave the Cleanup if we entered one.
125506a67e2cSRichard Smith   if (CleanupDominator) {
125606a67e2cSRichard Smith     DeactivateCleanupBlock(Cleanup, CleanupDominator);
125706a67e2cSRichard Smith     CleanupDominator->eraseFromParent();
125806a67e2cSRichard Smith   }
125906a67e2cSRichard Smith 
126006a67e2cSRichard Smith   // Advance to the next element by adjusting the pointer type as necessary.
126106a67e2cSRichard Smith   llvm::Value *NextPtr =
12627f416cc4SJohn McCall     Builder.CreateConstInBoundsGEP1_32(ElementTy, CurPtr.getPointer(), 1,
12637f416cc4SJohn McCall                                        "array.next");
126406a67e2cSRichard Smith 
126506a67e2cSRichard Smith   // Check whether we've gotten to the end of the array and, if so,
126606a67e2cSRichard Smith   // exit the loop.
126706a67e2cSRichard Smith   llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
126806a67e2cSRichard Smith   Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
126906a67e2cSRichard Smith   CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
127006a67e2cSRichard Smith 
127106a67e2cSRichard Smith   EmitBlock(ContBB);
127206a67e2cSRichard Smith }
127306a67e2cSRichard Smith 
127406a67e2cSRichard Smith static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
1275fb901c7aSDavid Blaikie                                QualType ElementType, llvm::Type *ElementTy,
12767f416cc4SJohn McCall                                Address NewPtr, llvm::Value *NumElements,
127706a67e2cSRichard Smith                                llvm::Value *AllocSizeWithoutCookie) {
12789b479666SDavid Blaikie   ApplyDebugLocation DL(CGF, E);
127906a67e2cSRichard Smith   if (E->isArray())
1280fb901c7aSDavid Blaikie     CGF.EmitNewArrayInitializer(E, ElementType, ElementTy, NewPtr, NumElements,
128106a67e2cSRichard Smith                                 AllocSizeWithoutCookie);
128206a67e2cSRichard Smith   else if (const Expr *Init = E->getInitializer())
1283e78fac51SRichard Smith     StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr,
1284e78fac51SRichard Smith                             AggValueSlot::DoesNotOverlap);
128559486a2dSAnders Carlsson }
128659486a2dSAnders Carlsson 
12878d0dc31dSRichard Smith /// Emit a call to an operator new or operator delete function, as implicitly
12888d0dc31dSRichard Smith /// created by new-expressions and delete-expressions.
12898d0dc31dSRichard Smith static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
1290b92ab1afSJohn McCall                                 const FunctionDecl *CalleeDecl,
12918d0dc31dSRichard Smith                                 const FunctionProtoType *CalleeType,
12928d0dc31dSRichard Smith                                 const CallArgList &Args) {
12933933adddSJames Y Knight   llvm::CallBase *CallOrInvoke;
1294b92ab1afSJohn McCall   llvm::Constant *CalleePtr = CGF.CGM.GetAddrOfFunction(CalleeDecl);
1295de6480a3SErich Keane   CGCallee Callee = CGCallee::forDirect(CalleePtr, GlobalDecl(CalleeDecl));
12968d0dc31dSRichard Smith   RValue RV =
1297f770683fSPeter Collingbourne       CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(
1298f770683fSPeter Collingbourne                        Args, CalleeType, /*chainCall=*/false),
1299b92ab1afSJohn McCall                    Callee, ReturnValueSlot(), Args, &CallOrInvoke);
13008d0dc31dSRichard Smith 
13018d0dc31dSRichard Smith   /// C++1y [expr.new]p10:
13028d0dc31dSRichard Smith   ///   [In a new-expression,] an implementation is allowed to omit a call
13038d0dc31dSRichard Smith   ///   to a replaceable global allocation function.
13048d0dc31dSRichard Smith   ///
13058d0dc31dSRichard Smith   /// We model such elidable calls with the 'builtin' attribute.
1306b92ab1afSJohn McCall   llvm::Function *Fn = dyn_cast<llvm::Function>(CalleePtr);
1307b92ab1afSJohn McCall   if (CalleeDecl->isReplaceableGlobalAllocationFunction() &&
13086956d587SRafael Espindola       Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
13093933adddSJames Y Knight     CallOrInvoke->addAttribute(llvm::AttributeList::FunctionIndex,
13108d0dc31dSRichard Smith                                llvm::Attribute::Builtin);
13118d0dc31dSRichard Smith   }
13128d0dc31dSRichard Smith 
13138d0dc31dSRichard Smith   return RV;
13148d0dc31dSRichard Smith }
13158d0dc31dSRichard Smith 
1316760520bcSRichard Smith RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
1317fa752f23SEric Fiselier                                                  const CallExpr *TheCall,
1318760520bcSRichard Smith                                                  bool IsDelete) {
1319760520bcSRichard Smith   CallArgList Args;
1320fa752f23SEric Fiselier   EmitCallArgs(Args, Type->getParamTypes(), TheCall->arguments());
1321760520bcSRichard Smith   // Find the allocation or deallocation function that we're calling.
1322760520bcSRichard Smith   ASTContext &Ctx = getContext();
1323760520bcSRichard Smith   DeclarationName Name = Ctx.DeclarationNames
1324760520bcSRichard Smith       .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
1325fa752f23SEric Fiselier 
1326760520bcSRichard Smith   for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
1327599bed75SRichard Smith     if (auto *FD = dyn_cast<FunctionDecl>(Decl))
1328599bed75SRichard Smith       if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
1329fa752f23SEric Fiselier         return EmitNewDeleteCall(*this, FD, Type, Args);
1330760520bcSRichard Smith   llvm_unreachable("predeclared global operator new/delete is missing");
1331760520bcSRichard Smith }
1332760520bcSRichard Smith 
13335b34958bSRichard Smith namespace {
13345b34958bSRichard Smith /// The parameters to pass to a usual operator delete.
13355b34958bSRichard Smith struct UsualDeleteParams {
13365b34958bSRichard Smith   bool DestroyingDelete = false;
13375b34958bSRichard Smith   bool Size = false;
13385b34958bSRichard Smith   bool Alignment = false;
13395b34958bSRichard Smith };
13405b34958bSRichard Smith }
13415b34958bSRichard Smith 
13425b34958bSRichard Smith static UsualDeleteParams getUsualDeleteParams(const FunctionDecl *FD) {
13435b34958bSRichard Smith   UsualDeleteParams Params;
13445b34958bSRichard Smith 
13455b34958bSRichard Smith   const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
1346b2f0f057SRichard Smith   auto AI = FPT->param_type_begin(), AE = FPT->param_type_end();
1347e9abe648SDaniel Jasper 
1348b2f0f057SRichard Smith   // The first argument is always a void*.
1349b2f0f057SRichard Smith   ++AI;
1350b2f0f057SRichard Smith 
13515b34958bSRichard Smith   // The next parameter may be a std::destroying_delete_t.
13525b34958bSRichard Smith   if (FD->isDestroyingOperatorDelete()) {
13535b34958bSRichard Smith     Params.DestroyingDelete = true;
13545b34958bSRichard Smith     assert(AI != AE);
13555b34958bSRichard Smith     ++AI;
13565b34958bSRichard Smith   }
1357b2f0f057SRichard Smith 
13585b34958bSRichard Smith   // Figure out what other parameters we should be implicitly passing.
1359b2f0f057SRichard Smith   if (AI != AE && (*AI)->isIntegerType()) {
13605b34958bSRichard Smith     Params.Size = true;
1361b2f0f057SRichard Smith     ++AI;
1362b2f0f057SRichard Smith   }
1363b2f0f057SRichard Smith 
1364b2f0f057SRichard Smith   if (AI != AE && (*AI)->isAlignValT()) {
13655b34958bSRichard Smith     Params.Alignment = true;
1366b2f0f057SRichard Smith     ++AI;
1367b2f0f057SRichard Smith   }
1368b2f0f057SRichard Smith 
1369b2f0f057SRichard Smith   assert(AI == AE && "unexpected usual deallocation function parameter");
13705b34958bSRichard Smith   return Params;
1371b2f0f057SRichard Smith }
1372b2f0f057SRichard Smith 
1373b2f0f057SRichard Smith namespace {
1374b2f0f057SRichard Smith   /// A cleanup to call the given 'operator delete' function upon abnormal
1375b2f0f057SRichard Smith   /// exit from a new expression. Templated on a traits type that deals with
1376b2f0f057SRichard Smith   /// ensuring that the arguments dominate the cleanup if necessary.
1377b2f0f057SRichard Smith   template<typename Traits>
1378b2f0f057SRichard Smith   class CallDeleteDuringNew final : public EHScopeStack::Cleanup {
1379b2f0f057SRichard Smith     /// Type used to hold llvm::Value*s.
1380b2f0f057SRichard Smith     typedef typename Traits::ValueTy ValueTy;
1381b2f0f057SRichard Smith     /// Type used to hold RValues.
1382b2f0f057SRichard Smith     typedef typename Traits::RValueTy RValueTy;
1383b2f0f057SRichard Smith     struct PlacementArg {
1384b2f0f057SRichard Smith       RValueTy ArgValue;
1385b2f0f057SRichard Smith       QualType ArgType;
1386b2f0f057SRichard Smith     };
1387b2f0f057SRichard Smith 
1388b2f0f057SRichard Smith     unsigned NumPlacementArgs : 31;
1389b2f0f057SRichard Smith     unsigned PassAlignmentToPlacementDelete : 1;
1390b2f0f057SRichard Smith     const FunctionDecl *OperatorDelete;
1391b2f0f057SRichard Smith     ValueTy Ptr;
1392b2f0f057SRichard Smith     ValueTy AllocSize;
1393b2f0f057SRichard Smith     CharUnits AllocAlign;
1394b2f0f057SRichard Smith 
1395b2f0f057SRichard Smith     PlacementArg *getPlacementArgs() {
1396b2f0f057SRichard Smith       return reinterpret_cast<PlacementArg *>(this + 1);
1397b2f0f057SRichard Smith     }
1398e9abe648SDaniel Jasper 
1399e9abe648SDaniel Jasper   public:
1400e9abe648SDaniel Jasper     static size_t getExtraSize(size_t NumPlacementArgs) {
1401b2f0f057SRichard Smith       return NumPlacementArgs * sizeof(PlacementArg);
1402e9abe648SDaniel Jasper     }
1403e9abe648SDaniel Jasper 
1404e9abe648SDaniel Jasper     CallDeleteDuringNew(size_t NumPlacementArgs,
1405b2f0f057SRichard Smith                         const FunctionDecl *OperatorDelete, ValueTy Ptr,
1406b2f0f057SRichard Smith                         ValueTy AllocSize, bool PassAlignmentToPlacementDelete,
1407b2f0f057SRichard Smith                         CharUnits AllocAlign)
1408b2f0f057SRichard Smith       : NumPlacementArgs(NumPlacementArgs),
1409b2f0f057SRichard Smith         PassAlignmentToPlacementDelete(PassAlignmentToPlacementDelete),
1410b2f0f057SRichard Smith         OperatorDelete(OperatorDelete), Ptr(Ptr), AllocSize(AllocSize),
1411b2f0f057SRichard Smith         AllocAlign(AllocAlign) {}
1412e9abe648SDaniel Jasper 
1413b2f0f057SRichard Smith     void setPlacementArg(unsigned I, RValueTy Arg, QualType Type) {
1414e9abe648SDaniel Jasper       assert(I < NumPlacementArgs && "index out of range");
1415b2f0f057SRichard Smith       getPlacementArgs()[I] = {Arg, Type};
1416e9abe648SDaniel Jasper     }
1417e9abe648SDaniel Jasper 
1418e9abe648SDaniel Jasper     void Emit(CodeGenFunction &CGF, Flags flags) override {
1419b2f0f057SRichard Smith       const FunctionProtoType *FPT =
1420b2f0f057SRichard Smith           OperatorDelete->getType()->getAs<FunctionProtoType>();
1421e9abe648SDaniel Jasper       CallArgList DeleteArgs;
1422824c2f53SJohn McCall 
14235b34958bSRichard Smith       // The first argument is always a void* (or C* for a destroying operator
14245b34958bSRichard Smith       // delete for class type C).
1425b2f0f057SRichard Smith       DeleteArgs.add(Traits::get(CGF, Ptr), FPT->getParamType(0));
1426189e52fcSRichard Smith 
1427b2f0f057SRichard Smith       // Figure out what other parameters we should be implicitly passing.
14285b34958bSRichard Smith       UsualDeleteParams Params;
1429b2f0f057SRichard Smith       if (NumPlacementArgs) {
1430b2f0f057SRichard Smith         // A placement deallocation function is implicitly passed an alignment
1431b2f0f057SRichard Smith         // if the placement allocation function was, but is never passed a size.
14325b34958bSRichard Smith         Params.Alignment = PassAlignmentToPlacementDelete;
1433b2f0f057SRichard Smith       } else {
1434b2f0f057SRichard Smith         // For a non-placement new-expression, 'operator delete' can take a
1435b2f0f057SRichard Smith         // size and/or an alignment if it has the right parameters.
14365b34958bSRichard Smith         Params = getUsualDeleteParams(OperatorDelete);
1437189e52fcSRichard Smith       }
1438824c2f53SJohn McCall 
14395b34958bSRichard Smith       assert(!Params.DestroyingDelete &&
14405b34958bSRichard Smith              "should not call destroying delete in a new-expression");
14415b34958bSRichard Smith 
1442b2f0f057SRichard Smith       // The second argument can be a std::size_t (for non-placement delete).
14435b34958bSRichard Smith       if (Params.Size)
1444b2f0f057SRichard Smith         DeleteArgs.add(Traits::get(CGF, AllocSize),
1445b2f0f057SRichard Smith                        CGF.getContext().getSizeType());
1446824c2f53SJohn McCall 
1447b2f0f057SRichard Smith       // The next (second or third) argument can be a std::align_val_t, which
1448b2f0f057SRichard Smith       // is an enum whose underlying type is std::size_t.
1449b2f0f057SRichard Smith       // FIXME: Use the right type as the parameter type. Note that in a call
1450b2f0f057SRichard Smith       // to operator delete(size_t, ...), we may not have it available.
14515b34958bSRichard Smith       if (Params.Alignment)
1452b2f0f057SRichard Smith         DeleteArgs.add(RValue::get(llvm::ConstantInt::get(
1453b2f0f057SRichard Smith                            CGF.SizeTy, AllocAlign.getQuantity())),
1454b2f0f057SRichard Smith                        CGF.getContext().getSizeType());
14557f9c92a9SJohn McCall 
14567f9c92a9SJohn McCall       // Pass the rest of the arguments, which must match exactly.
14577f9c92a9SJohn McCall       for (unsigned I = 0; I != NumPlacementArgs; ++I) {
1458b2f0f057SRichard Smith         auto Arg = getPlacementArgs()[I];
1459b2f0f057SRichard Smith         DeleteArgs.add(Traits::get(CGF, Arg.ArgValue), Arg.ArgType);
14607f9c92a9SJohn McCall       }
14617f9c92a9SJohn McCall 
14627f9c92a9SJohn McCall       // Call 'operator delete'.
14638d0dc31dSRichard Smith       EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
14647f9c92a9SJohn McCall     }
14657f9c92a9SJohn McCall   };
1466ab9db510SAlexander Kornienko }
14677f9c92a9SJohn McCall 
14687f9c92a9SJohn McCall /// Enter a cleanup to call 'operator delete' if the initializer in a
14697f9c92a9SJohn McCall /// new-expression throws.
14707f9c92a9SJohn McCall static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
14717f9c92a9SJohn McCall                                   const CXXNewExpr *E,
14727f416cc4SJohn McCall                                   Address NewPtr,
14737f9c92a9SJohn McCall                                   llvm::Value *AllocSize,
1474b2f0f057SRichard Smith                                   CharUnits AllocAlign,
14757f9c92a9SJohn McCall                                   const CallArgList &NewArgs) {
1476b2f0f057SRichard Smith   unsigned NumNonPlacementArgs = E->passAlignment() ? 2 : 1;
1477b2f0f057SRichard Smith 
14787f9c92a9SJohn McCall   // If we're not inside a conditional branch, then the cleanup will
14797f9c92a9SJohn McCall   // dominate and we can do the easier (and more efficient) thing.
14807f9c92a9SJohn McCall   if (!CGF.isInConditionalBranch()) {
1481b2f0f057SRichard Smith     struct DirectCleanupTraits {
1482b2f0f057SRichard Smith       typedef llvm::Value *ValueTy;
1483b2f0f057SRichard Smith       typedef RValue RValueTy;
1484b2f0f057SRichard Smith       static RValue get(CodeGenFunction &, ValueTy V) { return RValue::get(V); }
1485b2f0f057SRichard Smith       static RValue get(CodeGenFunction &, RValueTy V) { return V; }
1486b2f0f057SRichard Smith     };
1487b2f0f057SRichard Smith 
1488b2f0f057SRichard Smith     typedef CallDeleteDuringNew<DirectCleanupTraits> DirectCleanup;
1489b2f0f057SRichard Smith 
1490b2f0f057SRichard Smith     DirectCleanup *Cleanup = CGF.EHStack
1491b2f0f057SRichard Smith       .pushCleanupWithExtra<DirectCleanup>(EHCleanup,
14927f9c92a9SJohn McCall                                            E->getNumPlacementArgs(),
14937f9c92a9SJohn McCall                                            E->getOperatorDelete(),
14947f416cc4SJohn McCall                                            NewPtr.getPointer(),
1495b2f0f057SRichard Smith                                            AllocSize,
1496b2f0f057SRichard Smith                                            E->passAlignment(),
1497b2f0f057SRichard Smith                                            AllocAlign);
1498b2f0f057SRichard Smith     for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
1499b2f0f057SRichard Smith       auto &Arg = NewArgs[I + NumNonPlacementArgs];
15005b330e8dSYaxun Liu       Cleanup->setPlacementArg(I, Arg.getRValue(CGF), Arg.Ty);
1501b2f0f057SRichard Smith     }
15027f9c92a9SJohn McCall 
15037f9c92a9SJohn McCall     return;
15047f9c92a9SJohn McCall   }
15057f9c92a9SJohn McCall 
15067f9c92a9SJohn McCall   // Otherwise, we need to save all this stuff.
1507cb5f77f0SJohn McCall   DominatingValue<RValue>::saved_type SavedNewPtr =
15087f416cc4SJohn McCall     DominatingValue<RValue>::save(CGF, RValue::get(NewPtr.getPointer()));
1509cb5f77f0SJohn McCall   DominatingValue<RValue>::saved_type SavedAllocSize =
1510cb5f77f0SJohn McCall     DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
15117f9c92a9SJohn McCall 
1512b2f0f057SRichard Smith   struct ConditionalCleanupTraits {
1513b2f0f057SRichard Smith     typedef DominatingValue<RValue>::saved_type ValueTy;
1514b2f0f057SRichard Smith     typedef DominatingValue<RValue>::saved_type RValueTy;
1515b2f0f057SRichard Smith     static RValue get(CodeGenFunction &CGF, ValueTy V) {
1516b2f0f057SRichard Smith       return V.restore(CGF);
1517b2f0f057SRichard Smith     }
1518b2f0f057SRichard Smith   };
1519b2f0f057SRichard Smith   typedef CallDeleteDuringNew<ConditionalCleanupTraits> ConditionalCleanup;
1520b2f0f057SRichard Smith 
1521b2f0f057SRichard Smith   ConditionalCleanup *Cleanup = CGF.EHStack
1522b2f0f057SRichard Smith     .pushCleanupWithExtra<ConditionalCleanup>(EHCleanup,
15237f9c92a9SJohn McCall                                               E->getNumPlacementArgs(),
15247f9c92a9SJohn McCall                                               E->getOperatorDelete(),
15257f9c92a9SJohn McCall                                               SavedNewPtr,
1526b2f0f057SRichard Smith                                               SavedAllocSize,
1527b2f0f057SRichard Smith                                               E->passAlignment(),
1528b2f0f057SRichard Smith                                               AllocAlign);
1529b2f0f057SRichard Smith   for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
1530b2f0f057SRichard Smith     auto &Arg = NewArgs[I + NumNonPlacementArgs];
15315b330e8dSYaxun Liu     Cleanup->setPlacementArg(
15325b330e8dSYaxun Liu         I, DominatingValue<RValue>::save(CGF, Arg.getRValue(CGF)), Arg.Ty);
1533b2f0f057SRichard Smith   }
15347f9c92a9SJohn McCall 
1535f4beacd0SJohn McCall   CGF.initFullExprCleanup();
1536824c2f53SJohn McCall }
1537824c2f53SJohn McCall 
153859486a2dSAnders Carlsson llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
153975f9498aSJohn McCall   // The element type being allocated.
154075f9498aSJohn McCall   QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
15418ed55a54SJohn McCall 
154275f9498aSJohn McCall   // 1. Build a call to the allocation function.
154375f9498aSJohn McCall   FunctionDecl *allocator = E->getOperatorNew();
154459486a2dSAnders Carlsson 
1545f862eb6aSSebastian Redl   // If there is a brace-initializer, cannot allocate fewer elements than inits.
1546f862eb6aSSebastian Redl   unsigned minElements = 0;
1547f862eb6aSSebastian Redl   if (E->isArray() && E->hasInitializer()) {
15480511d23aSRichard Smith     const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer());
15490511d23aSRichard Smith     if (ILE && ILE->isStringLiteralInit())
15500511d23aSRichard Smith       minElements =
15510511d23aSRichard Smith           cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe())
15520511d23aSRichard Smith               ->getSize().getZExtValue();
15530511d23aSRichard Smith     else if (ILE)
1554f862eb6aSSebastian Redl       minElements = ILE->getNumInits();
1555f862eb6aSSebastian Redl   }
1556f862eb6aSSebastian Redl 
15578a13c418SCraig Topper   llvm::Value *numElements = nullptr;
15588a13c418SCraig Topper   llvm::Value *allocSizeWithoutCookie = nullptr;
155975f9498aSJohn McCall   llvm::Value *allocSize =
1560f862eb6aSSebastian Redl     EmitCXXNewAllocSize(*this, E, minElements, numElements,
1561f862eb6aSSebastian Redl                         allocSizeWithoutCookie);
1562b2f0f057SRichard Smith   CharUnits allocAlign = getContext().getTypeAlignInChars(allocType);
156359486a2dSAnders Carlsson 
15647f416cc4SJohn McCall   // Emit the allocation call.  If the allocator is a global placement
15657f416cc4SJohn McCall   // operator, just "inline" it directly.
15667f416cc4SJohn McCall   Address allocation = Address::invalid();
15677f416cc4SJohn McCall   CallArgList allocatorArgs;
15687f416cc4SJohn McCall   if (allocator->isReservedGlobalPlacementOperator()) {
156953dcf94dSJohn McCall     assert(E->getNumPlacementArgs() == 1);
157053dcf94dSJohn McCall     const Expr *arg = *E->placement_arguments().begin();
157153dcf94dSJohn McCall 
15728f248234SKrzysztof Parzyszek     LValueBaseInfo BaseInfo;
15738f248234SKrzysztof Parzyszek     allocation = EmitPointerWithAlignment(arg, &BaseInfo);
15747f416cc4SJohn McCall 
15757f416cc4SJohn McCall     // The pointer expression will, in many cases, be an opaque void*.
15767f416cc4SJohn McCall     // In these cases, discard the computed alignment and use the
15777f416cc4SJohn McCall     // formal alignment of the allocated type.
15788f248234SKrzysztof Parzyszek     if (BaseInfo.getAlignmentSource() != AlignmentSource::Decl)
1579b2f0f057SRichard Smith       allocation = Address(allocation.getPointer(), allocAlign);
15807f416cc4SJohn McCall 
158153dcf94dSJohn McCall     // Set up allocatorArgs for the call to operator delete if it's not
158253dcf94dSJohn McCall     // the reserved global operator.
158353dcf94dSJohn McCall     if (E->getOperatorDelete() &&
158453dcf94dSJohn McCall         !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
158553dcf94dSJohn McCall       allocatorArgs.add(RValue::get(allocSize), getContext().getSizeType());
158653dcf94dSJohn McCall       allocatorArgs.add(RValue::get(allocation.getPointer()), arg->getType());
158753dcf94dSJohn McCall     }
158853dcf94dSJohn McCall 
15897f416cc4SJohn McCall   } else {
15907f416cc4SJohn McCall     const FunctionProtoType *allocatorType =
15917f416cc4SJohn McCall       allocator->getType()->castAs<FunctionProtoType>();
1592b2f0f057SRichard Smith     unsigned ParamsToSkip = 0;
15937f416cc4SJohn McCall 
15947f416cc4SJohn McCall     // The allocation size is the first argument.
15957f416cc4SJohn McCall     QualType sizeType = getContext().getSizeType();
159643dca6a8SEli Friedman     allocatorArgs.add(RValue::get(allocSize), sizeType);
1597b2f0f057SRichard Smith     ++ParamsToSkip;
159859486a2dSAnders Carlsson 
1599b2f0f057SRichard Smith     if (allocSize != allocSizeWithoutCookie) {
1600b2f0f057SRichard Smith       CharUnits cookieAlign = getSizeAlign(); // FIXME: Ask the ABI.
1601b2f0f057SRichard Smith       allocAlign = std::max(allocAlign, cookieAlign);
1602b2f0f057SRichard Smith     }
1603b2f0f057SRichard Smith 
1604b2f0f057SRichard Smith     // The allocation alignment may be passed as the second argument.
1605b2f0f057SRichard Smith     if (E->passAlignment()) {
1606b2f0f057SRichard Smith       QualType AlignValT = sizeType;
1607b2f0f057SRichard Smith       if (allocatorType->getNumParams() > 1) {
1608b2f0f057SRichard Smith         AlignValT = allocatorType->getParamType(1);
1609b2f0f057SRichard Smith         assert(getContext().hasSameUnqualifiedType(
1610b2f0f057SRichard Smith                    AlignValT->castAs<EnumType>()->getDecl()->getIntegerType(),
1611b2f0f057SRichard Smith                    sizeType) &&
1612b2f0f057SRichard Smith                "wrong type for alignment parameter");
1613b2f0f057SRichard Smith         ++ParamsToSkip;
1614b2f0f057SRichard Smith       } else {
1615b2f0f057SRichard Smith         // Corner case, passing alignment to 'operator new(size_t, ...)'.
1616b2f0f057SRichard Smith         assert(allocator->isVariadic() && "can't pass alignment to allocator");
1617b2f0f057SRichard Smith       }
1618b2f0f057SRichard Smith       allocatorArgs.add(
1619b2f0f057SRichard Smith           RValue::get(llvm::ConstantInt::get(SizeTy, allocAlign.getQuantity())),
1620b2f0f057SRichard Smith           AlignValT);
1621b2f0f057SRichard Smith     }
1622b2f0f057SRichard Smith 
1623b2f0f057SRichard Smith     // FIXME: Why do we not pass a CalleeDecl here?
1624f05779e2SDavid Blaikie     EmitCallArgs(allocatorArgs, allocatorType, E->placement_arguments(),
1625ed00ea08SVedant Kumar                  /*AC*/AbstractCallee(), /*ParamsToSkip*/ParamsToSkip);
162659486a2dSAnders Carlsson 
16277f416cc4SJohn McCall     RValue RV =
16287f416cc4SJohn McCall       EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
16297f416cc4SJohn McCall 
1630b2f0f057SRichard Smith     // If this was a call to a global replaceable allocation function that does
1631b2f0f057SRichard Smith     // not take an alignment argument, the allocator is known to produce
1632b2f0f057SRichard Smith     // storage that's suitably aligned for any object that fits, up to a known
1633b2f0f057SRichard Smith     // threshold. Otherwise assume it's suitably aligned for the allocated type.
1634b2f0f057SRichard Smith     CharUnits allocationAlign = allocAlign;
1635b2f0f057SRichard Smith     if (!E->passAlignment() &&
1636b2f0f057SRichard Smith         allocator->isReplaceableGlobalAllocationFunction()) {
1637b2f0f057SRichard Smith       unsigned AllocatorAlign = llvm::PowerOf2Floor(std::min<uint64_t>(
1638b2f0f057SRichard Smith           Target.getNewAlign(), getContext().getTypeSize(allocType)));
1639b2f0f057SRichard Smith       allocationAlign = std::max(
1640b2f0f057SRichard Smith           allocationAlign, getContext().toCharUnitsFromBits(AllocatorAlign));
16417f416cc4SJohn McCall     }
16427f416cc4SJohn McCall 
16437f416cc4SJohn McCall     allocation = Address(RV.getScalarVal(), allocationAlign);
16447ec4b434SJohn McCall   }
164559486a2dSAnders Carlsson 
164675f9498aSJohn McCall   // Emit a null check on the allocation result if the allocation
164775f9498aSJohn McCall   // function is allowed to return null (because it has a non-throwing
1648902a0238SRichard Smith   // exception spec or is the reserved placement new) and we have an
16492f72a752SRichard Smith   // interesting initializer will be running sanitizers on the initialization.
16509b6dfac5SBruno Ricci   bool nullCheck = E->shouldNullCheckAllocation() &&
16512f72a752SRichard Smith                    (!allocType.isPODType(getContext()) || E->hasInitializer() ||
16522f72a752SRichard Smith                     sanitizePerformTypeCheck());
165359486a2dSAnders Carlsson 
16548a13c418SCraig Topper   llvm::BasicBlock *nullCheckBB = nullptr;
16558a13c418SCraig Topper   llvm::BasicBlock *contBB = nullptr;
165659486a2dSAnders Carlsson 
1657f7dcf320SJohn McCall   // The null-check means that the initializer is conditionally
1658f7dcf320SJohn McCall   // evaluated.
1659f7dcf320SJohn McCall   ConditionalEvaluation conditional(*this);
1660f7dcf320SJohn McCall 
166175f9498aSJohn McCall   if (nullCheck) {
1662f7dcf320SJohn McCall     conditional.begin(*this);
166375f9498aSJohn McCall 
166475f9498aSJohn McCall     nullCheckBB = Builder.GetInsertBlock();
166575f9498aSJohn McCall     llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
166675f9498aSJohn McCall     contBB = createBasicBlock("new.cont");
166775f9498aSJohn McCall 
16687f416cc4SJohn McCall     llvm::Value *isNull =
16697f416cc4SJohn McCall       Builder.CreateIsNull(allocation.getPointer(), "new.isnull");
167075f9498aSJohn McCall     Builder.CreateCondBr(isNull, contBB, notNullBB);
167175f9498aSJohn McCall     EmitBlock(notNullBB);
167259486a2dSAnders Carlsson   }
167359486a2dSAnders Carlsson 
1674824c2f53SJohn McCall   // If there's an operator delete, enter a cleanup to call it if an
1675824c2f53SJohn McCall   // exception is thrown.
167675f9498aSJohn McCall   EHScopeStack::stable_iterator operatorDeleteCleanup;
16778a13c418SCraig Topper   llvm::Instruction *cleanupDominator = nullptr;
16787ec4b434SJohn McCall   if (E->getOperatorDelete() &&
16797ec4b434SJohn McCall       !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
1680b2f0f057SRichard Smith     EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocAlign,
1681b2f0f057SRichard Smith                           allocatorArgs);
168275f9498aSJohn McCall     operatorDeleteCleanup = EHStack.stable_begin();
1683f4beacd0SJohn McCall     cleanupDominator = Builder.CreateUnreachable();
1684824c2f53SJohn McCall   }
1685824c2f53SJohn McCall 
1686cf9b1f65SEli Friedman   assert((allocSize == allocSizeWithoutCookie) ==
1687cf9b1f65SEli Friedman          CalculateCookiePadding(*this, E).isZero());
1688cf9b1f65SEli Friedman   if (allocSize != allocSizeWithoutCookie) {
1689cf9b1f65SEli Friedman     assert(E->isArray());
1690cf9b1f65SEli Friedman     allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1691cf9b1f65SEli Friedman                                                        numElements,
1692cf9b1f65SEli Friedman                                                        E, allocType);
1693cf9b1f65SEli Friedman   }
1694cf9b1f65SEli Friedman 
1695fb901c7aSDavid Blaikie   llvm::Type *elementTy = ConvertTypeForMem(allocType);
16967f416cc4SJohn McCall   Address result = Builder.CreateElementBitCast(allocation, elementTy);
1697824c2f53SJohn McCall 
16985dde8094SPiotr Padlewski   // Passing pointer through launder.invariant.group to avoid propagation of
1699338c9d0aSPiotr Padlewski   // vptrs information which may be included in previous type.
170031fd99cfSPiotr Padlewski   // To not break LTO with different optimizations levels, we do it regardless
170131fd99cfSPiotr Padlewski   // of optimization level.
1702338c9d0aSPiotr Padlewski   if (CGM.getCodeGenOpts().StrictVTablePointers &&
1703338c9d0aSPiotr Padlewski       allocator->isReservedGlobalPlacementOperator())
17045dde8094SPiotr Padlewski     result = Address(Builder.CreateLaunderInvariantGroup(result.getPointer()),
1705338c9d0aSPiotr Padlewski                      result.getAlignment());
1706338c9d0aSPiotr Padlewski 
170737605182SSerge Pavlov   // Emit sanitizer checks for pointer value now, so that in the case of an
1708cfa79b27SRichard Smith   // array it was checked only once and not at each constructor call. We may
1709cfa79b27SRichard Smith   // have already checked that the pointer is non-null.
1710cfa79b27SRichard Smith   // FIXME: If we have an array cookie and a potentially-throwing allocator,
1711cfa79b27SRichard Smith   // we'll null check the wrong pointer here.
1712cfa79b27SRichard Smith   SanitizerSet SkippedChecks;
1713cfa79b27SRichard Smith   SkippedChecks.set(SanitizerKind::Null, nullCheck);
171437605182SSerge Pavlov   EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall,
171537605182SSerge Pavlov                 E->getAllocatedTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1716cfa79b27SRichard Smith                 result.getPointer(), allocType, result.getAlignment(),
1717cfa79b27SRichard Smith                 SkippedChecks, numElements);
171837605182SSerge Pavlov 
1719fb901c7aSDavid Blaikie   EmitNewInitializer(*this, E, allocType, elementTy, result, numElements,
172099210dc9SJohn McCall                      allocSizeWithoutCookie);
17218ed55a54SJohn McCall   if (E->isArray()) {
17228ed55a54SJohn McCall     // NewPtr is a pointer to the base element type.  If we're
17238ed55a54SJohn McCall     // allocating an array of arrays, we'll need to cast back to the
17248ed55a54SJohn McCall     // array pointer type.
17252192fe50SChris Lattner     llvm::Type *resultType = ConvertTypeForMem(E->getType());
17267f416cc4SJohn McCall     if (result.getType() != resultType)
172775f9498aSJohn McCall       result = Builder.CreateBitCast(result, resultType);
172847b4629bSFariborz Jahanian   }
172959486a2dSAnders Carlsson 
1730824c2f53SJohn McCall   // Deactivate the 'operator delete' cleanup if we finished
1731824c2f53SJohn McCall   // initialization.
1732f4beacd0SJohn McCall   if (operatorDeleteCleanup.isValid()) {
1733f4beacd0SJohn McCall     DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1734f4beacd0SJohn McCall     cleanupDominator->eraseFromParent();
1735f4beacd0SJohn McCall   }
1736824c2f53SJohn McCall 
17377f416cc4SJohn McCall   llvm::Value *resultPtr = result.getPointer();
173875f9498aSJohn McCall   if (nullCheck) {
1739f7dcf320SJohn McCall     conditional.end(*this);
1740f7dcf320SJohn McCall 
174175f9498aSJohn McCall     llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
174275f9498aSJohn McCall     EmitBlock(contBB);
174359486a2dSAnders Carlsson 
17447f416cc4SJohn McCall     llvm::PHINode *PHI = Builder.CreatePHI(resultPtr->getType(), 2);
17457f416cc4SJohn McCall     PHI->addIncoming(resultPtr, notNullBB);
17467f416cc4SJohn McCall     PHI->addIncoming(llvm::Constant::getNullValue(resultPtr->getType()),
174775f9498aSJohn McCall                      nullCheckBB);
174859486a2dSAnders Carlsson 
17497f416cc4SJohn McCall     resultPtr = PHI;
175059486a2dSAnders Carlsson   }
175159486a2dSAnders Carlsson 
17527f416cc4SJohn McCall   return resultPtr;
175359486a2dSAnders Carlsson }
175459486a2dSAnders Carlsson 
175559486a2dSAnders Carlsson void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1756b2f0f057SRichard Smith                                      llvm::Value *Ptr, QualType DeleteTy,
1757b2f0f057SRichard Smith                                      llvm::Value *NumElements,
1758b2f0f057SRichard Smith                                      CharUnits CookieSize) {
1759b2f0f057SRichard Smith   assert((!NumElements && CookieSize.isZero()) ||
1760b2f0f057SRichard Smith          DeleteFD->getOverloadedOperator() == OO_Array_Delete);
17618ed55a54SJohn McCall 
176259486a2dSAnders Carlsson   const FunctionProtoType *DeleteFTy =
176359486a2dSAnders Carlsson     DeleteFD->getType()->getAs<FunctionProtoType>();
176459486a2dSAnders Carlsson 
176559486a2dSAnders Carlsson   CallArgList DeleteArgs;
176659486a2dSAnders Carlsson 
17675b34958bSRichard Smith   auto Params = getUsualDeleteParams(DeleteFD);
1768b2f0f057SRichard Smith   auto ParamTypeIt = DeleteFTy->param_type_begin();
1769b2f0f057SRichard Smith 
1770b2f0f057SRichard Smith   // Pass the pointer itself.
1771b2f0f057SRichard Smith   QualType ArgTy = *ParamTypeIt++;
177259486a2dSAnders Carlsson   llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
177343dca6a8SEli Friedman   DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
177459486a2dSAnders Carlsson 
17755b34958bSRichard Smith   // Pass the std::destroying_delete tag if present.
17765b34958bSRichard Smith   if (Params.DestroyingDelete) {
17775b34958bSRichard Smith     QualType DDTag = *ParamTypeIt++;
17785b34958bSRichard Smith     // Just pass an 'undef'. We expect the tag type to be an empty struct.
17795b34958bSRichard Smith     auto *V = llvm::UndefValue::get(getTypes().ConvertType(DDTag));
17805b34958bSRichard Smith     DeleteArgs.add(RValue::get(V), DDTag);
17815b34958bSRichard Smith   }
17825b34958bSRichard Smith 
1783b2f0f057SRichard Smith   // Pass the size if the delete function has a size_t parameter.
17845b34958bSRichard Smith   if (Params.Size) {
1785b2f0f057SRichard Smith     QualType SizeType = *ParamTypeIt++;
1786b2f0f057SRichard Smith     CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1787b2f0f057SRichard Smith     llvm::Value *Size = llvm::ConstantInt::get(ConvertType(SizeType),
1788b2f0f057SRichard Smith                                                DeleteTypeSize.getQuantity());
1789b2f0f057SRichard Smith 
1790b2f0f057SRichard Smith     // For array new, multiply by the number of elements.
1791b2f0f057SRichard Smith     if (NumElements)
1792b2f0f057SRichard Smith       Size = Builder.CreateMul(Size, NumElements);
1793b2f0f057SRichard Smith 
1794b2f0f057SRichard Smith     // If there is a cookie, add the cookie size.
1795b2f0f057SRichard Smith     if (!CookieSize.isZero())
1796b2f0f057SRichard Smith       Size = Builder.CreateAdd(
1797b2f0f057SRichard Smith           Size, llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity()));
1798b2f0f057SRichard Smith 
1799b2f0f057SRichard Smith     DeleteArgs.add(RValue::get(Size), SizeType);
1800b2f0f057SRichard Smith   }
1801b2f0f057SRichard Smith 
1802b2f0f057SRichard Smith   // Pass the alignment if the delete function has an align_val_t parameter.
18035b34958bSRichard Smith   if (Params.Alignment) {
1804b2f0f057SRichard Smith     QualType AlignValType = *ParamTypeIt++;
1805b2f0f057SRichard Smith     CharUnits DeleteTypeAlign = getContext().toCharUnitsFromBits(
1806b2f0f057SRichard Smith         getContext().getTypeAlignIfKnown(DeleteTy));
1807b2f0f057SRichard Smith     llvm::Value *Align = llvm::ConstantInt::get(ConvertType(AlignValType),
1808b2f0f057SRichard Smith                                                 DeleteTypeAlign.getQuantity());
1809b2f0f057SRichard Smith     DeleteArgs.add(RValue::get(Align), AlignValType);
1810b2f0f057SRichard Smith   }
1811b2f0f057SRichard Smith 
1812b2f0f057SRichard Smith   assert(ParamTypeIt == DeleteFTy->param_type_end() &&
1813b2f0f057SRichard Smith          "unknown parameter to usual delete function");
181459486a2dSAnders Carlsson 
181559486a2dSAnders Carlsson   // Emit the call to delete.
18168d0dc31dSRichard Smith   EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
181759486a2dSAnders Carlsson }
181859486a2dSAnders Carlsson 
18198ed55a54SJohn McCall namespace {
18208ed55a54SJohn McCall   /// Calls the given 'operator delete' on a single object.
18217e70d680SDavid Blaikie   struct CallObjectDelete final : EHScopeStack::Cleanup {
18228ed55a54SJohn McCall     llvm::Value *Ptr;
18238ed55a54SJohn McCall     const FunctionDecl *OperatorDelete;
18248ed55a54SJohn McCall     QualType ElementType;
18258ed55a54SJohn McCall 
18268ed55a54SJohn McCall     CallObjectDelete(llvm::Value *Ptr,
18278ed55a54SJohn McCall                      const FunctionDecl *OperatorDelete,
18288ed55a54SJohn McCall                      QualType ElementType)
18298ed55a54SJohn McCall       : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
18308ed55a54SJohn McCall 
18314f12f10dSCraig Topper     void Emit(CodeGenFunction &CGF, Flags flags) override {
18328ed55a54SJohn McCall       CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
18338ed55a54SJohn McCall     }
18348ed55a54SJohn McCall   };
1835ab9db510SAlexander Kornienko }
18368ed55a54SJohn McCall 
18370c0b6d9aSDavid Majnemer void
18380c0b6d9aSDavid Majnemer CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
18390c0b6d9aSDavid Majnemer                                              llvm::Value *CompletePtr,
18400c0b6d9aSDavid Majnemer                                              QualType ElementType) {
18410c0b6d9aSDavid Majnemer   EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr,
18420c0b6d9aSDavid Majnemer                                         OperatorDelete, ElementType);
18430c0b6d9aSDavid Majnemer }
18440c0b6d9aSDavid Majnemer 
18455b34958bSRichard Smith /// Emit the code for deleting a single object with a destroying operator
18465b34958bSRichard Smith /// delete. If the element type has a non-virtual destructor, Ptr has already
18475b34958bSRichard Smith /// been converted to the type of the parameter of 'operator delete'. Otherwise
18485b34958bSRichard Smith /// Ptr points to an object of the static type.
18495b34958bSRichard Smith static void EmitDestroyingObjectDelete(CodeGenFunction &CGF,
18505b34958bSRichard Smith                                        const CXXDeleteExpr *DE, Address Ptr,
18515b34958bSRichard Smith                                        QualType ElementType) {
18525b34958bSRichard Smith   auto *Dtor = ElementType->getAsCXXRecordDecl()->getDestructor();
18535b34958bSRichard Smith   if (Dtor && Dtor->isVirtual())
18545b34958bSRichard Smith     CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
18555b34958bSRichard Smith                                                 Dtor);
18565b34958bSRichard Smith   else
18575b34958bSRichard Smith     CGF.EmitDeleteCall(DE->getOperatorDelete(), Ptr.getPointer(), ElementType);
18585b34958bSRichard Smith }
18595b34958bSRichard Smith 
18608ed55a54SJohn McCall /// Emit the code for deleting a single object.
18618ed55a54SJohn McCall static void EmitObjectDelete(CodeGenFunction &CGF,
18620868137aSDavid Majnemer                              const CXXDeleteExpr *DE,
18637f416cc4SJohn McCall                              Address Ptr,
18640868137aSDavid Majnemer                              QualType ElementType) {
1865d98f5d78SIvan Krasin   // C++11 [expr.delete]p3:
1866d98f5d78SIvan Krasin   //   If the static type of the object to be deleted is different from its
1867d98f5d78SIvan Krasin   //   dynamic type, the static type shall be a base class of the dynamic type
1868d98f5d78SIvan Krasin   //   of the object to be deleted and the static type shall have a virtual
1869d98f5d78SIvan Krasin   //   destructor or the behavior is undefined.
1870d98f5d78SIvan Krasin   CGF.EmitTypeCheck(CodeGenFunction::TCK_MemberCall,
1871d98f5d78SIvan Krasin                     DE->getExprLoc(), Ptr.getPointer(),
1872d98f5d78SIvan Krasin                     ElementType);
1873d98f5d78SIvan Krasin 
18745b34958bSRichard Smith   const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
18755b34958bSRichard Smith   assert(!OperatorDelete->isDestroyingOperatorDelete());
18765b34958bSRichard Smith 
18778ed55a54SJohn McCall   // Find the destructor for the type, if applicable.  If the
18788ed55a54SJohn McCall   // destructor is virtual, we'll just emit the vcall and return.
18798a13c418SCraig Topper   const CXXDestructorDecl *Dtor = nullptr;
18808ed55a54SJohn McCall   if (const RecordType *RT = ElementType->getAs<RecordType>()) {
18818ed55a54SJohn McCall     CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1882b23533dbSEli Friedman     if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
18838ed55a54SJohn McCall       Dtor = RD->getDestructor();
18848ed55a54SJohn McCall 
18858ed55a54SJohn McCall       if (Dtor->isVirtual()) {
18860868137aSDavid Majnemer         CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
18870868137aSDavid Majnemer                                                     Dtor);
18888ed55a54SJohn McCall         return;
18898ed55a54SJohn McCall       }
18908ed55a54SJohn McCall     }
18918ed55a54SJohn McCall   }
18928ed55a54SJohn McCall 
18938ed55a54SJohn McCall   // Make sure that we call delete even if the dtor throws.
1894e4df6c8dSJohn McCall   // This doesn't have to a conditional cleanup because we're going
1895e4df6c8dSJohn McCall   // to pop it off in a second.
18968ed55a54SJohn McCall   CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
18977f416cc4SJohn McCall                                             Ptr.getPointer(),
18987f416cc4SJohn McCall                                             OperatorDelete, ElementType);
18998ed55a54SJohn McCall 
19008ed55a54SJohn McCall   if (Dtor)
19018ed55a54SJohn McCall     CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
190261535005SDouglas Gregor                               /*ForVirtualBase=*/false,
190361535005SDouglas Gregor                               /*Delegating=*/false,
190461535005SDouglas Gregor                               Ptr);
1905460ce58fSJohn McCall   else if (auto Lifetime = ElementType.getObjCLifetime()) {
1906460ce58fSJohn McCall     switch (Lifetime) {
190731168b07SJohn McCall     case Qualifiers::OCL_None:
190831168b07SJohn McCall     case Qualifiers::OCL_ExplicitNone:
190931168b07SJohn McCall     case Qualifiers::OCL_Autoreleasing:
191031168b07SJohn McCall       break;
191131168b07SJohn McCall 
19127f416cc4SJohn McCall     case Qualifiers::OCL_Strong:
19137f416cc4SJohn McCall       CGF.EmitARCDestroyStrong(Ptr, ARCPreciseLifetime);
191431168b07SJohn McCall       break;
191531168b07SJohn McCall 
191631168b07SJohn McCall     case Qualifiers::OCL_Weak:
191731168b07SJohn McCall       CGF.EmitARCDestroyWeak(Ptr);
191831168b07SJohn McCall       break;
191931168b07SJohn McCall     }
192031168b07SJohn McCall   }
19218ed55a54SJohn McCall 
19228ed55a54SJohn McCall   CGF.PopCleanupBlock();
19238ed55a54SJohn McCall }
19248ed55a54SJohn McCall 
19258ed55a54SJohn McCall namespace {
19268ed55a54SJohn McCall   /// Calls the given 'operator delete' on an array of objects.
19277e70d680SDavid Blaikie   struct CallArrayDelete final : EHScopeStack::Cleanup {
19288ed55a54SJohn McCall     llvm::Value *Ptr;
19298ed55a54SJohn McCall     const FunctionDecl *OperatorDelete;
19308ed55a54SJohn McCall     llvm::Value *NumElements;
19318ed55a54SJohn McCall     QualType ElementType;
19328ed55a54SJohn McCall     CharUnits CookieSize;
19338ed55a54SJohn McCall 
19348ed55a54SJohn McCall     CallArrayDelete(llvm::Value *Ptr,
19358ed55a54SJohn McCall                     const FunctionDecl *OperatorDelete,
19368ed55a54SJohn McCall                     llvm::Value *NumElements,
19378ed55a54SJohn McCall                     QualType ElementType,
19388ed55a54SJohn McCall                     CharUnits CookieSize)
19398ed55a54SJohn McCall       : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
19408ed55a54SJohn McCall         ElementType(ElementType), CookieSize(CookieSize) {}
19418ed55a54SJohn McCall 
19424f12f10dSCraig Topper     void Emit(CodeGenFunction &CGF, Flags flags) override {
1943b2f0f057SRichard Smith       CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType, NumElements,
1944b2f0f057SRichard Smith                          CookieSize);
19458ed55a54SJohn McCall     }
19468ed55a54SJohn McCall   };
1947ab9db510SAlexander Kornienko }
19488ed55a54SJohn McCall 
19498ed55a54SJohn McCall /// Emit the code for deleting an array of objects.
19508ed55a54SJohn McCall static void EmitArrayDelete(CodeGenFunction &CGF,
1951284c48ffSJohn McCall                             const CXXDeleteExpr *E,
19527f416cc4SJohn McCall                             Address deletedPtr,
1953ca2c56f2SJohn McCall                             QualType elementType) {
19548a13c418SCraig Topper   llvm::Value *numElements = nullptr;
19558a13c418SCraig Topper   llvm::Value *allocatedPtr = nullptr;
1956ca2c56f2SJohn McCall   CharUnits cookieSize;
1957ca2c56f2SJohn McCall   CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1958ca2c56f2SJohn McCall                                       numElements, allocatedPtr, cookieSize);
19598ed55a54SJohn McCall 
1960ca2c56f2SJohn McCall   assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
19618ed55a54SJohn McCall 
19628ed55a54SJohn McCall   // Make sure that we call delete even if one of the dtors throws.
1963ca2c56f2SJohn McCall   const FunctionDecl *operatorDelete = E->getOperatorDelete();
19648ed55a54SJohn McCall   CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
1965ca2c56f2SJohn McCall                                            allocatedPtr, operatorDelete,
1966ca2c56f2SJohn McCall                                            numElements, elementType,
1967ca2c56f2SJohn McCall                                            cookieSize);
19688ed55a54SJohn McCall 
1969ca2c56f2SJohn McCall   // Destroy the elements.
1970ca2c56f2SJohn McCall   if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1971ca2c56f2SJohn McCall     assert(numElements && "no element count for a type with a destructor!");
197231168b07SJohn McCall 
19737f416cc4SJohn McCall     CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
19747f416cc4SJohn McCall     CharUnits elementAlign =
19757f416cc4SJohn McCall       deletedPtr.getAlignment().alignmentOfArrayElement(elementSize);
19767f416cc4SJohn McCall 
19777f416cc4SJohn McCall     llvm::Value *arrayBegin = deletedPtr.getPointer();
1978ca2c56f2SJohn McCall     llvm::Value *arrayEnd =
19797f416cc4SJohn McCall       CGF.Builder.CreateInBoundsGEP(arrayBegin, numElements, "delete.end");
198097eab0a2SJohn McCall 
198197eab0a2SJohn McCall     // Note that it is legal to allocate a zero-length array, and we
198297eab0a2SJohn McCall     // can never fold the check away because the length should always
198397eab0a2SJohn McCall     // come from a cookie.
19847f416cc4SJohn McCall     CGF.emitArrayDestroy(arrayBegin, arrayEnd, elementType, elementAlign,
1985ca2c56f2SJohn McCall                          CGF.getDestroyer(dtorKind),
198697eab0a2SJohn McCall                          /*checkZeroLength*/ true,
1987ca2c56f2SJohn McCall                          CGF.needsEHCleanup(dtorKind));
19888ed55a54SJohn McCall   }
19898ed55a54SJohn McCall 
1990ca2c56f2SJohn McCall   // Pop the cleanup block.
19918ed55a54SJohn McCall   CGF.PopCleanupBlock();
19928ed55a54SJohn McCall }
19938ed55a54SJohn McCall 
199459486a2dSAnders Carlsson void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
199559486a2dSAnders Carlsson   const Expr *Arg = E->getArgument();
19967f416cc4SJohn McCall   Address Ptr = EmitPointerWithAlignment(Arg);
199759486a2dSAnders Carlsson 
199859486a2dSAnders Carlsson   // Null check the pointer.
199959486a2dSAnders Carlsson   llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
200059486a2dSAnders Carlsson   llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
200159486a2dSAnders Carlsson 
20027f416cc4SJohn McCall   llvm::Value *IsNull = Builder.CreateIsNull(Ptr.getPointer(), "isnull");
200359486a2dSAnders Carlsson 
200459486a2dSAnders Carlsson   Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
200559486a2dSAnders Carlsson   EmitBlock(DeleteNotNull);
200659486a2dSAnders Carlsson 
20075b34958bSRichard Smith   QualType DeleteTy = E->getDestroyedType();
20085b34958bSRichard Smith 
20095b34958bSRichard Smith   // A destroying operator delete overrides the entire operation of the
20105b34958bSRichard Smith   // delete expression.
20115b34958bSRichard Smith   if (E->getOperatorDelete()->isDestroyingOperatorDelete()) {
20125b34958bSRichard Smith     EmitDestroyingObjectDelete(*this, E, Ptr, DeleteTy);
20135b34958bSRichard Smith     EmitBlock(DeleteEnd);
20145b34958bSRichard Smith     return;
20155b34958bSRichard Smith   }
20165b34958bSRichard Smith 
20178ed55a54SJohn McCall   // We might be deleting a pointer to array.  If so, GEP down to the
20188ed55a54SJohn McCall   // first non-array element.
20198ed55a54SJohn McCall   // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
20208ed55a54SJohn McCall   if (DeleteTy->isConstantArrayType()) {
20218ed55a54SJohn McCall     llvm::Value *Zero = Builder.getInt32(0);
20220e62c1ccSChris Lattner     SmallVector<llvm::Value*,8> GEP;
202359486a2dSAnders Carlsson 
20248ed55a54SJohn McCall     GEP.push_back(Zero); // point at the outermost array
20258ed55a54SJohn McCall 
20268ed55a54SJohn McCall     // For each layer of array type we're pointing at:
20278ed55a54SJohn McCall     while (const ConstantArrayType *Arr
20288ed55a54SJohn McCall              = getContext().getAsConstantArrayType(DeleteTy)) {
20298ed55a54SJohn McCall       // 1. Unpeel the array type.
20308ed55a54SJohn McCall       DeleteTy = Arr->getElementType();
20318ed55a54SJohn McCall 
20328ed55a54SJohn McCall       // 2. GEP to the first element of the array.
20338ed55a54SJohn McCall       GEP.push_back(Zero);
20348ed55a54SJohn McCall     }
20358ed55a54SJohn McCall 
20367f416cc4SJohn McCall     Ptr = Address(Builder.CreateInBoundsGEP(Ptr.getPointer(), GEP, "del.first"),
20377f416cc4SJohn McCall                   Ptr.getAlignment());
20388ed55a54SJohn McCall   }
20398ed55a54SJohn McCall 
20407f416cc4SJohn McCall   assert(ConvertTypeForMem(DeleteTy) == Ptr.getElementType());
20418ed55a54SJohn McCall 
20427270ef57SReid Kleckner   if (E->isArrayForm()) {
20437270ef57SReid Kleckner     EmitArrayDelete(*this, E, Ptr, DeleteTy);
20447270ef57SReid Kleckner   } else {
20457270ef57SReid Kleckner     EmitObjectDelete(*this, E, Ptr, DeleteTy);
20467270ef57SReid Kleckner   }
204759486a2dSAnders Carlsson 
204859486a2dSAnders Carlsson   EmitBlock(DeleteEnd);
204959486a2dSAnders Carlsson }
205059486a2dSAnders Carlsson 
20511c3d95ebSDavid Majnemer static bool isGLValueFromPointerDeref(const Expr *E) {
20521c3d95ebSDavid Majnemer   E = E->IgnoreParens();
20531c3d95ebSDavid Majnemer 
20541c3d95ebSDavid Majnemer   if (const auto *CE = dyn_cast<CastExpr>(E)) {
20551c3d95ebSDavid Majnemer     if (!CE->getSubExpr()->isGLValue())
20561c3d95ebSDavid Majnemer       return false;
20571c3d95ebSDavid Majnemer     return isGLValueFromPointerDeref(CE->getSubExpr());
20581c3d95ebSDavid Majnemer   }
20591c3d95ebSDavid Majnemer 
20601c3d95ebSDavid Majnemer   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
20611c3d95ebSDavid Majnemer     return isGLValueFromPointerDeref(OVE->getSourceExpr());
20621c3d95ebSDavid Majnemer 
20631c3d95ebSDavid Majnemer   if (const auto *BO = dyn_cast<BinaryOperator>(E))
20641c3d95ebSDavid Majnemer     if (BO->getOpcode() == BO_Comma)
20651c3d95ebSDavid Majnemer       return isGLValueFromPointerDeref(BO->getRHS());
20661c3d95ebSDavid Majnemer 
20671c3d95ebSDavid Majnemer   if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E))
20681c3d95ebSDavid Majnemer     return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
20691c3d95ebSDavid Majnemer            isGLValueFromPointerDeref(ACO->getFalseExpr());
20701c3d95ebSDavid Majnemer 
20711c3d95ebSDavid Majnemer   // C++11 [expr.sub]p1:
20721c3d95ebSDavid Majnemer   //   The expression E1[E2] is identical (by definition) to *((E1)+(E2))
20731c3d95ebSDavid Majnemer   if (isa<ArraySubscriptExpr>(E))
20741c3d95ebSDavid Majnemer     return true;
20751c3d95ebSDavid Majnemer 
20761c3d95ebSDavid Majnemer   if (const auto *UO = dyn_cast<UnaryOperator>(E))
20771c3d95ebSDavid Majnemer     if (UO->getOpcode() == UO_Deref)
20781c3d95ebSDavid Majnemer       return true;
20791c3d95ebSDavid Majnemer 
20801c3d95ebSDavid Majnemer   return false;
20811c3d95ebSDavid Majnemer }
20821c3d95ebSDavid Majnemer 
2083747e301eSWarren Hunt static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
20842192fe50SChris Lattner                                          llvm::Type *StdTypeInfoPtrTy) {
2085940f02d2SAnders Carlsson   // Get the vtable pointer.
20867f416cc4SJohn McCall   Address ThisPtr = CGF.EmitLValue(E).getAddress();
2087940f02d2SAnders Carlsson 
2088d71ad177SStephan Bergmann   QualType SrcRecordTy = E->getType();
2089d71ad177SStephan Bergmann 
2090d71ad177SStephan Bergmann   // C++ [class.cdtor]p4:
2091d71ad177SStephan Bergmann   //   If the operand of typeid refers to the object under construction or
2092d71ad177SStephan Bergmann   //   destruction and the static type of the operand is neither the constructor
2093d71ad177SStephan Bergmann   //   or destructor’s class nor one of its bases, the behavior is undefined.
2094d71ad177SStephan Bergmann   CGF.EmitTypeCheck(CodeGenFunction::TCK_DynamicOperation, E->getExprLoc(),
2095d71ad177SStephan Bergmann                     ThisPtr.getPointer(), SrcRecordTy);
2096d71ad177SStephan Bergmann 
2097940f02d2SAnders Carlsson   // C++ [expr.typeid]p2:
2098940f02d2SAnders Carlsson   //   If the glvalue expression is obtained by applying the unary * operator to
2099940f02d2SAnders Carlsson   //   a pointer and the pointer is a null pointer value, the typeid expression
2100940f02d2SAnders Carlsson   //   throws the std::bad_typeid exception.
21011c3d95ebSDavid Majnemer   //
21021c3d95ebSDavid Majnemer   // However, this paragraph's intent is not clear.  We choose a very generous
21031c3d95ebSDavid Majnemer   // interpretation which implores us to consider comma operators, conditional
21041c3d95ebSDavid Majnemer   // operators, parentheses and other such constructs.
21051c3d95ebSDavid Majnemer   if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(
21061c3d95ebSDavid Majnemer           isGLValueFromPointerDeref(E), SrcRecordTy)) {
2107940f02d2SAnders Carlsson     llvm::BasicBlock *BadTypeidBlock =
2108940f02d2SAnders Carlsson         CGF.createBasicBlock("typeid.bad_typeid");
21091162d25cSDavid Majnemer     llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
2110940f02d2SAnders Carlsson 
21117f416cc4SJohn McCall     llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr.getPointer());
2112940f02d2SAnders Carlsson     CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
2113940f02d2SAnders Carlsson 
2114940f02d2SAnders Carlsson     CGF.EmitBlock(BadTypeidBlock);
21151162d25cSDavid Majnemer     CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
2116940f02d2SAnders Carlsson     CGF.EmitBlock(EndBlock);
2117940f02d2SAnders Carlsson   }
2118940f02d2SAnders Carlsson 
21191162d25cSDavid Majnemer   return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
21201162d25cSDavid Majnemer                                         StdTypeInfoPtrTy);
2121940f02d2SAnders Carlsson }
2122940f02d2SAnders Carlsson 
212359486a2dSAnders Carlsson llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
21242192fe50SChris Lattner   llvm::Type *StdTypeInfoPtrTy =
2125940f02d2SAnders Carlsson     ConvertType(E->getType())->getPointerTo();
2126fd7dfeb7SAnders Carlsson 
21273f4336cbSAnders Carlsson   if (E->isTypeOperand()) {
21283f4336cbSAnders Carlsson     llvm::Constant *TypeInfo =
2129143c55eaSDavid Majnemer         CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
2130940f02d2SAnders Carlsson     return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
21313f4336cbSAnders Carlsson   }
2132fd7dfeb7SAnders Carlsson 
2133940f02d2SAnders Carlsson   // C++ [expr.typeid]p2:
2134940f02d2SAnders Carlsson   //   When typeid is applied to a glvalue expression whose type is a
2135940f02d2SAnders Carlsson   //   polymorphic class type, the result refers to a std::type_info object
2136940f02d2SAnders Carlsson   //   representing the type of the most derived object (that is, the dynamic
2137940f02d2SAnders Carlsson   //   type) to which the glvalue refers.
2138ef8bf436SRichard Smith   if (E->isPotentiallyEvaluated())
2139940f02d2SAnders Carlsson     return EmitTypeidFromVTable(*this, E->getExprOperand(),
2140940f02d2SAnders Carlsson                                 StdTypeInfoPtrTy);
2141940f02d2SAnders Carlsson 
2142940f02d2SAnders Carlsson   QualType OperandTy = E->getExprOperand()->getType();
2143940f02d2SAnders Carlsson   return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
2144940f02d2SAnders Carlsson                                StdTypeInfoPtrTy);
214559486a2dSAnders Carlsson }
214659486a2dSAnders Carlsson 
2147c1c9971cSAnders Carlsson static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
2148c1c9971cSAnders Carlsson                                           QualType DestTy) {
21492192fe50SChris Lattner   llvm::Type *DestLTy = CGF.ConvertType(DestTy);
2150c1c9971cSAnders Carlsson   if (DestTy->isPointerType())
2151c1c9971cSAnders Carlsson     return llvm::Constant::getNullValue(DestLTy);
2152c1c9971cSAnders Carlsson 
2153c1c9971cSAnders Carlsson   /// C++ [expr.dynamic.cast]p9:
2154c1c9971cSAnders Carlsson   ///   A failed cast to reference type throws std::bad_cast
21551162d25cSDavid Majnemer   if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
21561162d25cSDavid Majnemer     return nullptr;
2157c1c9971cSAnders Carlsson 
2158c1c9971cSAnders Carlsson   CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
2159c1c9971cSAnders Carlsson   return llvm::UndefValue::get(DestLTy);
2160c1c9971cSAnders Carlsson }
2161c1c9971cSAnders Carlsson 
21627f416cc4SJohn McCall llvm::Value *CodeGenFunction::EmitDynamicCast(Address ThisAddr,
216359486a2dSAnders Carlsson                                               const CXXDynamicCastExpr *DCE) {
21642bf9b4c0SAlexey Bataev   CGM.EmitExplicitCastExprType(DCE, this);
21653f4336cbSAnders Carlsson   QualType DestTy = DCE->getTypeAsWritten();
21663f4336cbSAnders Carlsson 
2167c1c9971cSAnders Carlsson   QualType SrcTy = DCE->getSubExpr()->getType();
2168c1c9971cSAnders Carlsson 
21691162d25cSDavid Majnemer   // C++ [expr.dynamic.cast]p7:
21701162d25cSDavid Majnemer   //   If T is "pointer to cv void," then the result is a pointer to the most
21711162d25cSDavid Majnemer   //   derived object pointed to by v.
21721162d25cSDavid Majnemer   const PointerType *DestPTy = DestTy->getAs<PointerType>();
21731162d25cSDavid Majnemer 
21741162d25cSDavid Majnemer   bool isDynamicCastToVoid;
21751162d25cSDavid Majnemer   QualType SrcRecordTy;
21761162d25cSDavid Majnemer   QualType DestRecordTy;
21771162d25cSDavid Majnemer   if (DestPTy) {
21781162d25cSDavid Majnemer     isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType();
21791162d25cSDavid Majnemer     SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
21801162d25cSDavid Majnemer     DestRecordTy = DestPTy->getPointeeType();
21811162d25cSDavid Majnemer   } else {
21821162d25cSDavid Majnemer     isDynamicCastToVoid = false;
21831162d25cSDavid Majnemer     SrcRecordTy = SrcTy;
21841162d25cSDavid Majnemer     DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
21851162d25cSDavid Majnemer   }
21861162d25cSDavid Majnemer 
2187d71ad177SStephan Bergmann   // C++ [class.cdtor]p5:
2188d71ad177SStephan Bergmann   //   If the operand of the dynamic_cast refers to the object under
2189d71ad177SStephan Bergmann   //   construction or destruction and the static type of the operand is not a
2190d71ad177SStephan Bergmann   //   pointer to or object of the constructor or destructor’s own class or one
2191d71ad177SStephan Bergmann   //   of its bases, the dynamic_cast results in undefined behavior.
2192d71ad177SStephan Bergmann   EmitTypeCheck(TCK_DynamicOperation, DCE->getExprLoc(), ThisAddr.getPointer(),
2193d71ad177SStephan Bergmann                 SrcRecordTy);
2194d71ad177SStephan Bergmann 
2195d71ad177SStephan Bergmann   if (DCE->isAlwaysNull())
2196d71ad177SStephan Bergmann     if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy))
2197d71ad177SStephan Bergmann       return T;
2198d71ad177SStephan Bergmann 
21991162d25cSDavid Majnemer   assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
22001162d25cSDavid Majnemer 
2201882d790fSAnders Carlsson   // C++ [expr.dynamic.cast]p4:
2202882d790fSAnders Carlsson   //   If the value of v is a null pointer value in the pointer case, the result
2203882d790fSAnders Carlsson   //   is the null pointer value of type T.
22041162d25cSDavid Majnemer   bool ShouldNullCheckSrcValue =
22051162d25cSDavid Majnemer       CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(),
22061162d25cSDavid Majnemer                                                          SrcRecordTy);
220759486a2dSAnders Carlsson 
22088a13c418SCraig Topper   llvm::BasicBlock *CastNull = nullptr;
22098a13c418SCraig Topper   llvm::BasicBlock *CastNotNull = nullptr;
2210882d790fSAnders Carlsson   llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
2211fa8b4955SDouglas Gregor 
2212882d790fSAnders Carlsson   if (ShouldNullCheckSrcValue) {
2213882d790fSAnders Carlsson     CastNull = createBasicBlock("dynamic_cast.null");
2214882d790fSAnders Carlsson     CastNotNull = createBasicBlock("dynamic_cast.notnull");
2215882d790fSAnders Carlsson 
22167f416cc4SJohn McCall     llvm::Value *IsNull = Builder.CreateIsNull(ThisAddr.getPointer());
2217882d790fSAnders Carlsson     Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
2218882d790fSAnders Carlsson     EmitBlock(CastNotNull);
221959486a2dSAnders Carlsson   }
222059486a2dSAnders Carlsson 
22217f416cc4SJohn McCall   llvm::Value *Value;
22221162d25cSDavid Majnemer   if (isDynamicCastToVoid) {
22237f416cc4SJohn McCall     Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, ThisAddr, SrcRecordTy,
22241162d25cSDavid Majnemer                                                   DestTy);
22251162d25cSDavid Majnemer   } else {
22261162d25cSDavid Majnemer     assert(DestRecordTy->isRecordType() &&
22271162d25cSDavid Majnemer            "destination type must be a record type!");
22287f416cc4SJohn McCall     Value = CGM.getCXXABI().EmitDynamicCastCall(*this, ThisAddr, SrcRecordTy,
22291162d25cSDavid Majnemer                                                 DestTy, DestRecordTy, CastEnd);
223067528eaaSDavid Majnemer     CastNotNull = Builder.GetInsertBlock();
22311162d25cSDavid Majnemer   }
22323f4336cbSAnders Carlsson 
2233882d790fSAnders Carlsson   if (ShouldNullCheckSrcValue) {
2234882d790fSAnders Carlsson     EmitBranch(CastEnd);
223559486a2dSAnders Carlsson 
2236882d790fSAnders Carlsson     EmitBlock(CastNull);
2237882d790fSAnders Carlsson     EmitBranch(CastEnd);
223859486a2dSAnders Carlsson   }
223959486a2dSAnders Carlsson 
2240882d790fSAnders Carlsson   EmitBlock(CastEnd);
224159486a2dSAnders Carlsson 
2242882d790fSAnders Carlsson   if (ShouldNullCheckSrcValue) {
2243882d790fSAnders Carlsson     llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
2244882d790fSAnders Carlsson     PHI->addIncoming(Value, CastNotNull);
2245882d790fSAnders Carlsson     PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
224659486a2dSAnders Carlsson 
2247882d790fSAnders Carlsson     Value = PHI;
224859486a2dSAnders Carlsson   }
224959486a2dSAnders Carlsson 
2250882d790fSAnders Carlsson   return Value;
225159486a2dSAnders Carlsson }
2252