159486a2dSAnders Carlsson //===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
259486a2dSAnders Carlsson //
359486a2dSAnders Carlsson //                     The LLVM Compiler Infrastructure
459486a2dSAnders Carlsson //
559486a2dSAnders Carlsson // This file is distributed under the University of Illinois Open Source
659486a2dSAnders Carlsson // License. See LICENSE.TXT for details.
759486a2dSAnders Carlsson //
859486a2dSAnders Carlsson //===----------------------------------------------------------------------===//
959486a2dSAnders Carlsson //
1059486a2dSAnders Carlsson // This contains code dealing with code generation of C++ expressions
1159486a2dSAnders Carlsson //
1259486a2dSAnders Carlsson //===----------------------------------------------------------------------===//
1359486a2dSAnders Carlsson 
1459486a2dSAnders Carlsson #include "CodeGenFunction.h"
15fe883422SPeter Collingbourne #include "CGCUDARuntime.h"
165d865c32SJohn McCall #include "CGCXXABI.h"
1791bbb554SDevang Patel #include "CGDebugInfo.h"
183a02247dSChandler Carruth #include "CGObjCRuntime.h"
19a8e7df36SMark Lacey #include "clang/CodeGen/CGFunctionInfo.h"
2010a4972aSSaleem Abdulrasool #include "clang/Frontend/CodeGenOptions.h"
21c80ceea9SChandler Carruth #include "llvm/IR/CallSite.h"
22ffd5551bSChandler Carruth #include "llvm/IR/Intrinsics.h"
23bbe277c4SAnders Carlsson 
2459486a2dSAnders Carlsson using namespace clang;
2559486a2dSAnders Carlsson using namespace CodeGen;
2659486a2dSAnders Carlsson 
27d0a9e807SGeorge Burgess IV namespace {
28d0a9e807SGeorge Burgess IV struct MemberCallInfo {
29d0a9e807SGeorge Burgess IV   RequiredArgs ReqArgs;
30d0a9e807SGeorge Burgess IV   // Number of prefix arguments for the call. Ignores the `this` pointer.
31d0a9e807SGeorge Burgess IV   unsigned PrefixSize;
32d0a9e807SGeorge Burgess IV };
33d0a9e807SGeorge Burgess IV }
34d0a9e807SGeorge Burgess IV 
35d0a9e807SGeorge Burgess IV static MemberCallInfo
36efa956ceSAlexey Samsonov commonEmitCXXMemberOrOperatorCall(CodeGenFunction &CGF, const CXXMethodDecl *MD,
37efa956ceSAlexey Samsonov                                   llvm::Value *This, llvm::Value *ImplicitParam,
38efa956ceSAlexey Samsonov                                   QualType ImplicitParamTy, const CallExpr *CE,
39762672a7SRichard Smith                                   CallArgList &Args, CallArgList *RtlArgs) {
40a5bf76bdSAlexey Samsonov   assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) ||
41a5bf76bdSAlexey Samsonov          isa<CXXOperatorCallExpr>(CE));
4227da15baSAnders Carlsson   assert(MD->isInstance() &&
43a5bf76bdSAlexey Samsonov          "Trying to emit a member or operator call expr on a static method!");
44034e7270SReid Kleckner   ASTContext &C = CGF.getContext();
4527da15baSAnders Carlsson 
4627da15baSAnders Carlsson   // Push the this ptr.
47034e7270SReid Kleckner   const CXXRecordDecl *RD =
48034e7270SReid Kleckner       CGF.CGM.getCXXABI().getThisArgumentTypeForMethod(MD);
49034e7270SReid Kleckner   Args.add(RValue::get(This),
50034e7270SReid Kleckner            RD ? C.getPointerType(C.getTypeDeclType(RD)) : C.VoidPtrTy);
5127da15baSAnders Carlsson 
52ee6bc533STimur Iskhodzhanov   // If there is an implicit parameter (e.g. VTT), emit it.
53ee6bc533STimur Iskhodzhanov   if (ImplicitParam) {
54ee6bc533STimur Iskhodzhanov     Args.add(RValue::get(ImplicitParam), ImplicitParamTy);
55e36a6b3eSAnders Carlsson   }
56e36a6b3eSAnders Carlsson 
57a729c62bSJohn McCall   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
58419996ccSGeorge Burgess IV   RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size(), MD);
59d0a9e807SGeorge Burgess IV   unsigned PrefixSize = Args.size() - 1;
60a729c62bSJohn McCall 
61a729c62bSJohn McCall   // And the rest of the call args.
62762672a7SRichard Smith   if (RtlArgs) {
63762672a7SRichard Smith     // Special case: if the caller emitted the arguments right-to-left already
64762672a7SRichard Smith     // (prior to emitting the *this argument), we're done. This happens for
65762672a7SRichard Smith     // assignment operators.
66762672a7SRichard Smith     Args.addFrom(*RtlArgs);
67762672a7SRichard Smith   } else if (CE) {
68a5bf76bdSAlexey Samsonov     // Special case: skip first argument of CXXOperatorCall (it is "this").
698e1162c7SAlexey Samsonov     unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0;
70f05779e2SDavid Blaikie     CGF.EmitCallArgs(Args, FPT, drop_begin(CE->arguments(), ArgsToSkip),
718e1162c7SAlexey Samsonov                      CE->getDirectCallee());
72a5bf76bdSAlexey Samsonov   } else {
738e1162c7SAlexey Samsonov     assert(
748e1162c7SAlexey Samsonov         FPT->getNumParams() == 0 &&
758e1162c7SAlexey Samsonov         "No CallExpr specified for function with non-zero number of arguments");
76a5bf76bdSAlexey Samsonov   }
77d0a9e807SGeorge Burgess IV   return {required, PrefixSize};
780c0b6d9aSDavid Majnemer }
7927da15baSAnders Carlsson 
800c0b6d9aSDavid Majnemer RValue CodeGenFunction::EmitCXXMemberOrOperatorCall(
81b92ab1afSJohn McCall     const CXXMethodDecl *MD, const CGCallee &Callee,
82b92ab1afSJohn McCall     ReturnValueSlot ReturnValue,
830c0b6d9aSDavid Majnemer     llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,
84762672a7SRichard Smith     const CallExpr *CE, CallArgList *RtlArgs) {
850c0b6d9aSDavid Majnemer   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
860c0b6d9aSDavid Majnemer   CallArgList Args;
87d0a9e807SGeorge Burgess IV   MemberCallInfo CallInfo = commonEmitCXXMemberOrOperatorCall(
88762672a7SRichard Smith       *this, MD, This, ImplicitParam, ImplicitParamTy, CE, Args, RtlArgs);
89d0a9e807SGeorge Burgess IV   auto &FnInfo = CGM.getTypes().arrangeCXXMethodCall(
90d0a9e807SGeorge Burgess IV       Args, FPT, CallInfo.ReqArgs, CallInfo.PrefixSize);
91b92ab1afSJohn McCall   return EmitCall(FnInfo, Callee, ReturnValue, Args);
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.
178b92ab1afSJohn McCall     CGCallee callee = CGCallee::forDirect(CGM.GetAddrOfFunction(MD), MD);
179b92ab1afSJohn McCall     return EmitCall(getContext().getPointerType(MD->getType()), callee, CE,
18070b9c01bSAlexey Samsonov                     ReturnValue);
18127da15baSAnders Carlsson   }
18227da15baSAnders Carlsson 
183aad4af6dSNico Weber   bool HasQualifier = ME->hasQualifier();
184aad4af6dSNico Weber   NestedNameSpecifier *Qualifier = HasQualifier ? ME->getQualifier() : nullptr;
185aad4af6dSNico Weber   bool IsArrow = ME->isArrow();
186ecbe2e97SRafael Espindola   const Expr *Base = ME->getBase();
187aad4af6dSNico Weber 
188aad4af6dSNico Weber   return EmitCXXMemberOrOperatorMemberCallExpr(
189aad4af6dSNico Weber       CE, MD, ReturnValue, HasQualifier, Qualifier, IsArrow, Base);
190aad4af6dSNico Weber }
191aad4af6dSNico Weber 
192aad4af6dSNico Weber RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr(
193aad4af6dSNico Weber     const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue,
194aad4af6dSNico Weber     bool HasQualifier, NestedNameSpecifier *Qualifier, bool IsArrow,
195aad4af6dSNico Weber     const Expr *Base) {
196aad4af6dSNico Weber   assert(isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE));
197aad4af6dSNico Weber 
198aad4af6dSNico Weber   // Compute the object pointer.
199aad4af6dSNico Weber   bool CanUseVirtualCall = MD->isVirtual() && !HasQualifier;
200ecbe2e97SRafael Espindola 
2018a13c418SCraig Topper   const CXXMethodDecl *DevirtualizedMethod = nullptr;
2027463ed7cSBenjamin Kramer   if (CanUseVirtualCall && CanDevirtualizeMemberFunctionCall(Base, MD)) {
2033b33c4ecSRafael Espindola     const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
2043b33c4ecSRafael Espindola     DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
2053b33c4ecSRafael Espindola     assert(DevirtualizedMethod);
2063b33c4ecSRafael Espindola     const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
2073b33c4ecSRafael Espindola     const Expr *Inner = Base->ignoreParenBaseCasts();
2085bd68794SAlexey Bataev     if (DevirtualizedMethod->getReturnType().getCanonicalType() !=
2095bd68794SAlexey Bataev         MD->getReturnType().getCanonicalType())
2105bd68794SAlexey Bataev       // If the return types are not the same, this might be a case where more
2115bd68794SAlexey Bataev       // code needs to run to compensate for it. For example, the derived
2125bd68794SAlexey Bataev       // method might return a type that inherits form from the return
2135bd68794SAlexey Bataev       // type of MD and has a prefix.
2145bd68794SAlexey Bataev       // For now we just avoid devirtualizing these covariant cases.
2155bd68794SAlexey Bataev       DevirtualizedMethod = nullptr;
2165bd68794SAlexey Bataev     else if (getCXXRecord(Inner) == DevirtualizedClass)
2173b33c4ecSRafael Espindola       // If the class of the Inner expression is where the dynamic method
2183b33c4ecSRafael Espindola       // is defined, build the this pointer from it.
2193b33c4ecSRafael Espindola       Base = Inner;
2203b33c4ecSRafael Espindola     else if (getCXXRecord(Base) != DevirtualizedClass) {
2213b33c4ecSRafael Espindola       // If the method is defined in a class that is not the best dynamic
2223b33c4ecSRafael Espindola       // one or the one of the full expression, we would have to build
2233b33c4ecSRafael Espindola       // a derived-to-base cast to compute the correct this pointer, but
2243b33c4ecSRafael Espindola       // we don't have support for that yet, so do a virtual call.
2258a13c418SCraig Topper       DevirtualizedMethod = nullptr;
2263b33c4ecSRafael Espindola     }
2273b33c4ecSRafael Espindola   }
228ecbe2e97SRafael Espindola 
229762672a7SRichard Smith   // C++17 demands that we evaluate the RHS of a (possibly-compound) assignment
230762672a7SRichard Smith   // operator before the LHS.
231762672a7SRichard Smith   CallArgList RtlArgStorage;
232762672a7SRichard Smith   CallArgList *RtlArgs = nullptr;
233762672a7SRichard Smith   if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
234762672a7SRichard Smith     if (OCE->isAssignmentOp()) {
235762672a7SRichard Smith       RtlArgs = &RtlArgStorage;
236762672a7SRichard Smith       EmitCallArgs(*RtlArgs, MD->getType()->castAs<FunctionProtoType>(),
237762672a7SRichard Smith                    drop_begin(CE->arguments(), 1), CE->getDirectCallee(),
238a560ccf2SRichard Smith                    /*ParamsToSkip*/0, EvaluationOrder::ForceRightToLeft);
239762672a7SRichard Smith     }
240762672a7SRichard Smith   }
241762672a7SRichard Smith 
2427f416cc4SJohn McCall   Address This = Address::invalid();
243aad4af6dSNico Weber   if (IsArrow)
2447f416cc4SJohn McCall     This = EmitPointerWithAlignment(Base);
245f93ac894SFariborz Jahanian   else
2463b33c4ecSRafael Espindola     This = EmitLValue(Base).getAddress();
247ecbe2e97SRafael Espindola 
24827da15baSAnders Carlsson 
249419bd094SRichard Smith   if (MD->isTrivial() || (MD->isDefaulted() && MD->getParent()->isUnion())) {
2508a13c418SCraig Topper     if (isa<CXXDestructorDecl>(MD)) return RValue::get(nullptr);
25164225794SFrancois Pichet     if (isa<CXXConstructorDecl>(MD) &&
25264225794SFrancois Pichet         cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
2538a13c418SCraig Topper       return RValue::get(nullptr);
2540d635f53SJohn McCall 
255aad4af6dSNico Weber     if (!MD->getParent()->mayInsertExtraPadding()) {
25622653bacSSebastian Redl       if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
25722653bacSSebastian Redl         // We don't like to generate the trivial copy/move assignment operator
25822653bacSSebastian Redl         // when it isn't necessary; just produce the proper effect here.
259762672a7SRichard Smith         LValue RHS = isa<CXXOperatorCallExpr>(CE)
260762672a7SRichard Smith                          ? MakeNaturalAlignAddrLValue(
261762672a7SRichard Smith                                (*RtlArgs)[0].RV.getScalarVal(),
262762672a7SRichard Smith                                (*(CE->arg_begin() + 1))->getType())
263762672a7SRichard Smith                          : EmitLValue(*CE->arg_begin());
264762672a7SRichard Smith         EmitAggregateAssign(This, RHS.getAddress(), CE->getType());
2657f416cc4SJohn McCall         return RValue::get(This.getPointer());
26627da15baSAnders Carlsson       }
26727da15baSAnders Carlsson 
26864225794SFrancois Pichet       if (isa<CXXConstructorDecl>(MD) &&
26922653bacSSebastian Redl           cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
27022653bacSSebastian Redl         // Trivial move and copy ctor are the same.
271525bf650SAlexey Samsonov         assert(CE->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
2727f416cc4SJohn McCall         Address RHS = EmitLValue(*CE->arg_begin()).getAddress();
273f48ee448SBenjamin Kramer         EmitAggregateCopy(This, RHS, (*CE->arg_begin())->getType());
2747f416cc4SJohn McCall         return RValue::get(This.getPointer());
27564225794SFrancois Pichet       }
27664225794SFrancois Pichet       llvm_unreachable("unknown trivial member function");
27764225794SFrancois Pichet     }
278aad4af6dSNico Weber   }
27964225794SFrancois Pichet 
2800d635f53SJohn McCall   // Compute the function type we're calling.
2813abfe958SNico Weber   const CXXMethodDecl *CalleeDecl =
2823abfe958SNico Weber       DevirtualizedMethod ? DevirtualizedMethod : MD;
2838a13c418SCraig Topper   const CGFunctionInfo *FInfo = nullptr;
2843abfe958SNico Weber   if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
2858d2a19b4SRafael Espindola     FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
2868d2a19b4SRafael Espindola         Dtor, StructorType::Complete);
2873abfe958SNico Weber   else if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(CalleeDecl))
2888d2a19b4SRafael Espindola     FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
2898d2a19b4SRafael Espindola         Ctor, StructorType::Complete);
29064225794SFrancois Pichet   else
291ade60977SEli Friedman     FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
2920d635f53SJohn McCall 
293e7de47efSReid Kleckner   llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
2940d635f53SJohn McCall 
295d98f5d78SIvan Krasin   // C++11 [class.mfct.non-static]p2:
296d98f5d78SIvan Krasin   //   If a non-static member function of a class X is called for an object that
297d98f5d78SIvan Krasin   //   is not of type X, or of a type derived from X, the behavior is undefined.
298d98f5d78SIvan Krasin   SourceLocation CallLoc;
299d98f5d78SIvan Krasin   ASTContext &C = getContext();
300d98f5d78SIvan Krasin   if (CE)
301d98f5d78SIvan Krasin     CallLoc = CE->getExprLoc();
302d98f5d78SIvan Krasin 
30334b1fd6aSVedant Kumar   SanitizerSet SkippedChecks;
30434b1fd6aSVedant Kumar   if (const auto *CMCE = dyn_cast<CXXMemberCallExpr>(CE))
305e550d11dSVedant Kumar     if (IsDeclRefOrWrappedCXXThis(CMCE->getImplicitObjectArgument()))
30634b1fd6aSVedant Kumar       SkippedChecks.set(SanitizerKind::Null, true);
30734b1fd6aSVedant Kumar   EmitTypeCheck(
30834b1fd6aSVedant Kumar       isa<CXXConstructorDecl>(CalleeDecl) ? CodeGenFunction::TCK_ConstructorCall
309d98f5d78SIvan Krasin                                           : CodeGenFunction::TCK_MemberCall,
31034b1fd6aSVedant Kumar       CallLoc, This.getPointer(), C.getRecordType(CalleeDecl->getParent()),
31134b1fd6aSVedant Kumar       /*Alignment=*/CharUnits::Zero(), SkippedChecks);
312d98f5d78SIvan Krasin 
313018f266bSVedant Kumar   // FIXME: Uses of 'MD' past this point need to be audited. We may need to use
314018f266bSVedant Kumar   // 'CalleeDecl' instead.
315018f266bSVedant Kumar 
31627da15baSAnders Carlsson   // C++ [class.virtual]p12:
31727da15baSAnders Carlsson   //   Explicit qualification with the scope operator (5.1) suppresses the
31827da15baSAnders Carlsson   //   virtual call mechanism.
31927da15baSAnders Carlsson   //
32027da15baSAnders Carlsson   // We also don't emit a virtual call if the base expression has a record type
32127da15baSAnders Carlsson   // because then we know what the type is.
3223b33c4ecSRafael Espindola   bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
3239dc6eef7SStephen Lin 
3240d635f53SJohn McCall   if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
32519cee187SStephen Lin     assert(CE->arg_begin() == CE->arg_end() &&
3269dc6eef7SStephen Lin            "Destructor shouldn't have explicit parameters");
3279dc6eef7SStephen Lin     assert(ReturnValue.isNull() && "Destructor shouldn't have return value");
3289dc6eef7SStephen Lin     if (UseVirtualCall) {
329aad4af6dSNico Weber       CGM.getCXXABI().EmitVirtualDestructorCall(
330aad4af6dSNico Weber           *this, Dtor, Dtor_Complete, This, cast<CXXMemberCallExpr>(CE));
33127da15baSAnders Carlsson     } else {
332b92ab1afSJohn McCall       CGCallee Callee;
333aad4af6dSNico Weber       if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
334aad4af6dSNico Weber         Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
3353b33c4ecSRafael Espindola       else if (!DevirtualizedMethod)
336b92ab1afSJohn McCall         Callee = CGCallee::forDirect(
337b92ab1afSJohn McCall             CGM.getAddrOfCXXStructor(Dtor, StructorType::Complete, FInfo, Ty),
338b92ab1afSJohn McCall                                      Dtor);
33949e860b2SRafael Espindola       else {
3403b33c4ecSRafael Espindola         const CXXDestructorDecl *DDtor =
3413b33c4ecSRafael Espindola           cast<CXXDestructorDecl>(DevirtualizedMethod);
342b92ab1afSJohn McCall         Callee = CGCallee::forDirect(
343b92ab1afSJohn McCall                   CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty),
344b92ab1afSJohn McCall                                      DDtor);
34549e860b2SRafael Espindola       }
346018f266bSVedant Kumar       EmitCXXMemberOrOperatorCall(
347018f266bSVedant Kumar           CalleeDecl, Callee, ReturnValue, This.getPointer(),
348018f266bSVedant Kumar           /*ImplicitParam=*/nullptr, QualType(), CE, nullptr);
34927da15baSAnders Carlsson     }
3508a13c418SCraig Topper     return RValue::get(nullptr);
3519dc6eef7SStephen Lin   }
3529dc6eef7SStephen Lin 
353b92ab1afSJohn McCall   CGCallee Callee;
3549dc6eef7SStephen Lin   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
355b92ab1afSJohn McCall     Callee = CGCallee::forDirect(
356b92ab1afSJohn McCall                   CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty),
357b92ab1afSJohn McCall                                  Ctor);
3580d635f53SJohn McCall   } else if (UseVirtualCall) {
3596708c4a1SPeter Collingbourne     Callee = CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, Ty,
3606708c4a1SPeter Collingbourne                                                        CE->getLocStart());
36127da15baSAnders Carlsson   } else {
3621a7488afSPeter Collingbourne     if (SanOpts.has(SanitizerKind::CFINVCall) &&
3631a7488afSPeter Collingbourne         MD->getParent()->isDynamicClass()) {
3644b1ac72cSPiotr Padlewski       llvm::Value *VTable = GetVTablePtr(This, Int8PtrTy, MD->getParent());
365fb532b9aSPeter Collingbourne       EmitVTablePtrCheckForCall(MD->getParent(), VTable, CFITCK_NVCall,
366fb532b9aSPeter Collingbourne                                 CE->getLocStart());
3671a7488afSPeter Collingbourne     }
3681a7488afSPeter Collingbourne 
369aad4af6dSNico Weber     if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
370aad4af6dSNico Weber       Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
3713b33c4ecSRafael Espindola     else if (!DevirtualizedMethod)
372b92ab1afSJohn McCall       Callee = CGCallee::forDirect(CGM.GetAddrOfFunction(MD, Ty), MD);
37349e860b2SRafael Espindola     else {
374b92ab1afSJohn McCall       Callee = CGCallee::forDirect(
375b92ab1afSJohn McCall                                 CGM.GetAddrOfFunction(DevirtualizedMethod, Ty),
376b92ab1afSJohn McCall                                    DevirtualizedMethod);
37749e860b2SRafael Espindola     }
37827da15baSAnders Carlsson   }
37927da15baSAnders Carlsson 
380f1749427STimur Iskhodzhanov   if (MD->isVirtual()) {
381f1749427STimur Iskhodzhanov     This = CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
3824b60f30aSReid Kleckner         *this, CalleeDecl, This, UseVirtualCall);
383f1749427STimur Iskhodzhanov   }
38488fd439aSTimur Iskhodzhanov 
385018f266bSVedant Kumar   return EmitCXXMemberOrOperatorCall(
386018f266bSVedant Kumar       CalleeDecl, Callee, ReturnValue, This.getPointer(),
387018f266bSVedant Kumar       /*ImplicitParam=*/nullptr, QualType(), CE, RtlArgs);
38827da15baSAnders Carlsson }
38927da15baSAnders Carlsson 
39027da15baSAnders Carlsson RValue
39127da15baSAnders Carlsson CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
39227da15baSAnders Carlsson                                               ReturnValueSlot ReturnValue) {
39327da15baSAnders Carlsson   const BinaryOperator *BO =
39427da15baSAnders Carlsson       cast<BinaryOperator>(E->getCallee()->IgnoreParens());
39527da15baSAnders Carlsson   const Expr *BaseExpr = BO->getLHS();
39627da15baSAnders Carlsson   const Expr *MemFnExpr = BO->getRHS();
39727da15baSAnders Carlsson 
39827da15baSAnders Carlsson   const MemberPointerType *MPT =
3990009fcc3SJohn McCall     MemFnExpr->getType()->castAs<MemberPointerType>();
400475999dcSJohn McCall 
40127da15baSAnders Carlsson   const FunctionProtoType *FPT =
4020009fcc3SJohn McCall     MPT->getPointeeType()->castAs<FunctionProtoType>();
40327da15baSAnders Carlsson   const CXXRecordDecl *RD =
40427da15baSAnders Carlsson     cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
40527da15baSAnders Carlsson 
40627da15baSAnders Carlsson   // Emit the 'this' pointer.
4077f416cc4SJohn McCall   Address This = Address::invalid();
408e302792bSJohn McCall   if (BO->getOpcode() == BO_PtrMemI)
4097f416cc4SJohn McCall     This = EmitPointerWithAlignment(BaseExpr);
41027da15baSAnders Carlsson   else
41127da15baSAnders Carlsson     This = EmitLValue(BaseExpr).getAddress();
41227da15baSAnders Carlsson 
4137f416cc4SJohn McCall   EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This.getPointer(),
414e30752c9SRichard Smith                 QualType(MPT->getClass(), 0));
41569d0d262SRichard Smith 
416bde62d78SRichard Smith   // Get the member function pointer.
417bde62d78SRichard Smith   llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
418bde62d78SRichard Smith 
419475999dcSJohn McCall   // Ask the ABI to load the callee.  Note that This is modified.
4207f416cc4SJohn McCall   llvm::Value *ThisPtrForCall = nullptr;
421b92ab1afSJohn McCall   CGCallee Callee =
4227f416cc4SJohn McCall     CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This,
4237f416cc4SJohn McCall                                              ThisPtrForCall, MemFnPtr, MPT);
42427da15baSAnders Carlsson 
42527da15baSAnders Carlsson   CallArgList Args;
42627da15baSAnders Carlsson 
42727da15baSAnders Carlsson   QualType ThisType =
42827da15baSAnders Carlsson     getContext().getPointerType(getContext().getTagDeclType(RD));
42927da15baSAnders Carlsson 
43027da15baSAnders Carlsson   // Push the this ptr.
4317f416cc4SJohn McCall   Args.add(RValue::get(ThisPtrForCall), ThisType);
43227da15baSAnders Carlsson 
433419996ccSGeorge Burgess IV   RequiredArgs required =
434419996ccSGeorge Burgess IV       RequiredArgs::forPrototypePlus(FPT, 1, /*FD=*/nullptr);
4358dda7b27SJohn McCall 
43627da15baSAnders Carlsson   // And the rest of the call args
437419996ccSGeorge Burgess IV   EmitCallArgs(Args, FPT, E->arguments());
438d0a9e807SGeorge Burgess IV   return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required,
439d0a9e807SGeorge Burgess IV                                                       /*PrefixSize=*/0),
4405fa40c3bSNick Lewycky                   Callee, ReturnValue, Args);
44127da15baSAnders Carlsson }
44227da15baSAnders Carlsson 
44327da15baSAnders Carlsson RValue
44427da15baSAnders Carlsson CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
44527da15baSAnders Carlsson                                                const CXXMethodDecl *MD,
44627da15baSAnders Carlsson                                                ReturnValueSlot ReturnValue) {
44727da15baSAnders Carlsson   assert(MD->isInstance() &&
44827da15baSAnders Carlsson          "Trying to emit a member call expr on a static method!");
449aad4af6dSNico Weber   return EmitCXXMemberOrOperatorMemberCallExpr(
450aad4af6dSNico Weber       E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr,
451aad4af6dSNico Weber       /*IsArrow=*/false, E->getArg(0));
45227da15baSAnders Carlsson }
45327da15baSAnders Carlsson 
454fe883422SPeter Collingbourne RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
455fe883422SPeter Collingbourne                                                ReturnValueSlot ReturnValue) {
456fe883422SPeter Collingbourne   return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
457fe883422SPeter Collingbourne }
458fe883422SPeter Collingbourne 
459fde961dbSEli Friedman static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
4607f416cc4SJohn McCall                                             Address DestPtr,
461fde961dbSEli Friedman                                             const CXXRecordDecl *Base) {
462fde961dbSEli Friedman   if (Base->isEmpty())
463fde961dbSEli Friedman     return;
464fde961dbSEli Friedman 
4657f416cc4SJohn McCall   DestPtr = CGF.Builder.CreateElementBitCast(DestPtr, CGF.Int8Ty);
466fde961dbSEli Friedman 
467fde961dbSEli Friedman   const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
4688671c6e0SDavid Majnemer   CharUnits NVSize = Layout.getNonVirtualSize();
4698671c6e0SDavid Majnemer 
4708671c6e0SDavid Majnemer   // We cannot simply zero-initialize the entire base sub-object if vbptrs are
4718671c6e0SDavid Majnemer   // present, they are initialized by the most derived class before calling the
4728671c6e0SDavid Majnemer   // constructor.
4738671c6e0SDavid Majnemer   SmallVector<std::pair<CharUnits, CharUnits>, 1> Stores;
4748671c6e0SDavid Majnemer   Stores.emplace_back(CharUnits::Zero(), NVSize);
4758671c6e0SDavid Majnemer 
4768671c6e0SDavid Majnemer   // Each store is split by the existence of a vbptr.
4778671c6e0SDavid Majnemer   CharUnits VBPtrWidth = CGF.getPointerSize();
4788671c6e0SDavid Majnemer   std::vector<CharUnits> VBPtrOffsets =
4798671c6e0SDavid Majnemer       CGF.CGM.getCXXABI().getVBPtrOffsets(Base);
4808671c6e0SDavid Majnemer   for (CharUnits VBPtrOffset : VBPtrOffsets) {
4817f980d84SDavid Majnemer     // Stop before we hit any virtual base pointers located in virtual bases.
4827f980d84SDavid Majnemer     if (VBPtrOffset >= NVSize)
4837f980d84SDavid Majnemer       break;
4848671c6e0SDavid Majnemer     std::pair<CharUnits, CharUnits> LastStore = Stores.pop_back_val();
4858671c6e0SDavid Majnemer     CharUnits LastStoreOffset = LastStore.first;
4868671c6e0SDavid Majnemer     CharUnits LastStoreSize = LastStore.second;
4878671c6e0SDavid Majnemer 
4888671c6e0SDavid Majnemer     CharUnits SplitBeforeOffset = LastStoreOffset;
4898671c6e0SDavid Majnemer     CharUnits SplitBeforeSize = VBPtrOffset - SplitBeforeOffset;
4908671c6e0SDavid Majnemer     assert(!SplitBeforeSize.isNegative() && "negative store size!");
4918671c6e0SDavid Majnemer     if (!SplitBeforeSize.isZero())
4928671c6e0SDavid Majnemer       Stores.emplace_back(SplitBeforeOffset, SplitBeforeSize);
4938671c6e0SDavid Majnemer 
4948671c6e0SDavid Majnemer     CharUnits SplitAfterOffset = VBPtrOffset + VBPtrWidth;
4958671c6e0SDavid Majnemer     CharUnits SplitAfterSize = LastStoreSize - SplitAfterOffset;
4968671c6e0SDavid Majnemer     assert(!SplitAfterSize.isNegative() && "negative store size!");
4978671c6e0SDavid Majnemer     if (!SplitAfterSize.isZero())
4988671c6e0SDavid Majnemer       Stores.emplace_back(SplitAfterOffset, SplitAfterSize);
4998671c6e0SDavid Majnemer   }
500fde961dbSEli Friedman 
501fde961dbSEli Friedman   // If the type contains a pointer to data member we can't memset it to zero.
502fde961dbSEli Friedman   // Instead, create a null constant and copy it to the destination.
503fde961dbSEli Friedman   // TODO: there are other patterns besides zero that we can usefully memset,
504fde961dbSEli Friedman   // like -1, which happens to be the pattern used by member-pointers.
505fde961dbSEli Friedman   // TODO: isZeroInitializable can be over-conservative in the case where a
506fde961dbSEli Friedman   // virtual base contains a member pointer.
5078671c6e0SDavid Majnemer   llvm::Constant *NullConstantForBase = CGF.CGM.EmitNullConstantForBase(Base);
5088671c6e0SDavid Majnemer   if (!NullConstantForBase->isNullValue()) {
5098671c6e0SDavid Majnemer     llvm::GlobalVariable *NullVariable = new llvm::GlobalVariable(
5108671c6e0SDavid Majnemer         CGF.CGM.getModule(), NullConstantForBase->getType(),
5118671c6e0SDavid Majnemer         /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage,
5128671c6e0SDavid Majnemer         NullConstantForBase, Twine());
5137f416cc4SJohn McCall 
5147f416cc4SJohn McCall     CharUnits Align = std::max(Layout.getNonVirtualAlignment(),
5157f416cc4SJohn McCall                                DestPtr.getAlignment());
516fde961dbSEli Friedman     NullVariable->setAlignment(Align.getQuantity());
5177f416cc4SJohn McCall 
5187f416cc4SJohn McCall     Address SrcPtr = Address(CGF.EmitCastToVoidPtr(NullVariable), Align);
519fde961dbSEli Friedman 
520fde961dbSEli Friedman     // Get and call the appropriate llvm.memcpy overload.
5218671c6e0SDavid Majnemer     for (std::pair<CharUnits, CharUnits> Store : Stores) {
5228671c6e0SDavid Majnemer       CharUnits StoreOffset = Store.first;
5238671c6e0SDavid Majnemer       CharUnits StoreSize = Store.second;
5248671c6e0SDavid Majnemer       llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
5258671c6e0SDavid Majnemer       CGF.Builder.CreateMemCpy(
5268671c6e0SDavid Majnemer           CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
5278671c6e0SDavid Majnemer           CGF.Builder.CreateConstInBoundsByteGEP(SrcPtr, StoreOffset),
5288671c6e0SDavid Majnemer           StoreSizeVal);
529fde961dbSEli Friedman     }
530fde961dbSEli Friedman 
531fde961dbSEli Friedman   // Otherwise, just memset the whole thing to zero.  This is legal
532fde961dbSEli Friedman   // because in LLVM, all default initializers (other than the ones we just
533fde961dbSEli Friedman   // handled above) are guaranteed to have a bit pattern of all zeros.
5348671c6e0SDavid Majnemer   } else {
5358671c6e0SDavid Majnemer     for (std::pair<CharUnits, CharUnits> Store : Stores) {
5368671c6e0SDavid Majnemer       CharUnits StoreOffset = Store.first;
5378671c6e0SDavid Majnemer       CharUnits StoreSize = Store.second;
5388671c6e0SDavid Majnemer       llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
5398671c6e0SDavid Majnemer       CGF.Builder.CreateMemSet(
5408671c6e0SDavid Majnemer           CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
5418671c6e0SDavid Majnemer           CGF.Builder.getInt8(0), StoreSizeVal);
5428671c6e0SDavid Majnemer     }
5438671c6e0SDavid Majnemer   }
544fde961dbSEli Friedman }
545fde961dbSEli Friedman 
54627da15baSAnders Carlsson void
5477a626f63SJohn McCall CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
5487a626f63SJohn McCall                                       AggValueSlot Dest) {
5497a626f63SJohn McCall   assert(!Dest.isIgnored() && "Must have a destination!");
55027da15baSAnders Carlsson   const CXXConstructorDecl *CD = E->getConstructor();
551630c76efSDouglas Gregor 
552630c76efSDouglas Gregor   // If we require zero initialization before (or instead of) calling the
553630c76efSDouglas Gregor   // constructor, as can be the case with a non-user-provided default
55403535265SArgyrios Kyrtzidis   // constructor, emit the zero initialization now, unless destination is
55503535265SArgyrios Kyrtzidis   // already zeroed.
556fde961dbSEli Friedman   if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
557fde961dbSEli Friedman     switch (E->getConstructionKind()) {
558fde961dbSEli Friedman     case CXXConstructExpr::CK_Delegating:
559fde961dbSEli Friedman     case CXXConstructExpr::CK_Complete:
5607f416cc4SJohn McCall       EmitNullInitialization(Dest.getAddress(), E->getType());
561fde961dbSEli Friedman       break;
562fde961dbSEli Friedman     case CXXConstructExpr::CK_VirtualBase:
563fde961dbSEli Friedman     case CXXConstructExpr::CK_NonVirtualBase:
5647f416cc4SJohn McCall       EmitNullBaseClassInitialization(*this, Dest.getAddress(),
5657f416cc4SJohn McCall                                       CD->getParent());
566fde961dbSEli Friedman       break;
567fde961dbSEli Friedman     }
568fde961dbSEli Friedman   }
569630c76efSDouglas Gregor 
570630c76efSDouglas Gregor   // If this is a call to a trivial default constructor, do nothing.
571630c76efSDouglas Gregor   if (CD->isTrivial() && CD->isDefaultConstructor())
57227da15baSAnders Carlsson     return;
573630c76efSDouglas Gregor 
5748ea46b66SJohn McCall   // Elide the constructor if we're constructing from a temporary.
5758ea46b66SJohn McCall   // The temporary check is required because Sema sets this on NRVO
5768ea46b66SJohn McCall   // returns.
5779c6890a7SRichard Smith   if (getLangOpts().ElideConstructors && E->isElidable()) {
5788ea46b66SJohn McCall     assert(getContext().hasSameUnqualifiedType(E->getType(),
5798ea46b66SJohn McCall                                                E->getArg(0)->getType()));
5807a626f63SJohn McCall     if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
5817a626f63SJohn McCall       EmitAggExpr(E->getArg(0), Dest);
58227da15baSAnders Carlsson       return;
58327da15baSAnders Carlsson     }
584222cf0efSDouglas Gregor   }
585630c76efSDouglas Gregor 
586e7545b33SAlexey Bataev   if (const ArrayType *arrayType
587e7545b33SAlexey Bataev         = getContext().getAsArrayType(E->getType())) {
5887f416cc4SJohn McCall     EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddress(), E);
589f677a8e9SJohn McCall   } else {
590bceca20aSCameron Esfahani     CXXCtorType Type = Ctor_Complete;
591271c3681SAlexis Hunt     bool ForVirtualBase = false;
59261535005SDouglas Gregor     bool Delegating = false;
593271c3681SAlexis Hunt 
594271c3681SAlexis Hunt     switch (E->getConstructionKind()) {
595271c3681SAlexis Hunt      case CXXConstructExpr::CK_Delegating:
59661bc1737SAlexis Hunt       // We should be emitting a constructor; GlobalDecl will assert this
59761bc1737SAlexis Hunt       Type = CurGD.getCtorType();
59861535005SDouglas Gregor       Delegating = true;
599271c3681SAlexis Hunt       break;
60061bc1737SAlexis Hunt 
601271c3681SAlexis Hunt      case CXXConstructExpr::CK_Complete:
602271c3681SAlexis Hunt       Type = Ctor_Complete;
603271c3681SAlexis Hunt       break;
604271c3681SAlexis Hunt 
605271c3681SAlexis Hunt      case CXXConstructExpr::CK_VirtualBase:
606271c3681SAlexis Hunt       ForVirtualBase = true;
607271c3681SAlexis Hunt       // fall-through
608271c3681SAlexis Hunt 
609271c3681SAlexis Hunt      case CXXConstructExpr::CK_NonVirtualBase:
610271c3681SAlexis Hunt       Type = Ctor_Base;
611271c3681SAlexis Hunt     }
612e11f9ce9SAnders Carlsson 
61327da15baSAnders Carlsson     // Call the constructor.
6147f416cc4SJohn McCall     EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating,
6157f416cc4SJohn McCall                            Dest.getAddress(), E);
61627da15baSAnders Carlsson   }
617e11f9ce9SAnders Carlsson }
61827da15baSAnders Carlsson 
6197f416cc4SJohn McCall void CodeGenFunction::EmitSynthesizedCXXCopyCtor(Address Dest, Address Src,
62050198098SFariborz Jahanian                                                  const Expr *Exp) {
6215d413781SJohn McCall   if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
622e988bdacSFariborz Jahanian     Exp = E->getSubExpr();
623e988bdacSFariborz Jahanian   assert(isa<CXXConstructExpr>(Exp) &&
624e988bdacSFariborz Jahanian          "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
625e988bdacSFariborz Jahanian   const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
626e988bdacSFariborz Jahanian   const CXXConstructorDecl *CD = E->getConstructor();
627e988bdacSFariborz Jahanian   RunCleanupsScope Scope(*this);
628e988bdacSFariborz Jahanian 
629e988bdacSFariborz Jahanian   // If we require zero initialization before (or instead of) calling the
630e988bdacSFariborz Jahanian   // constructor, as can be the case with a non-user-provided default
631e988bdacSFariborz Jahanian   // constructor, emit the zero initialization now.
632e988bdacSFariborz Jahanian   // FIXME. Do I still need this for a copy ctor synthesis?
633e988bdacSFariborz Jahanian   if (E->requiresZeroInitialization())
634e988bdacSFariborz Jahanian     EmitNullInitialization(Dest, E->getType());
635e988bdacSFariborz Jahanian 
63699da11cfSChandler Carruth   assert(!getContext().getAsConstantArrayType(E->getType())
63799da11cfSChandler Carruth          && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
638525bf650SAlexey Samsonov   EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E);
639e988bdacSFariborz Jahanian }
640e988bdacSFariborz Jahanian 
6418ed55a54SJohn McCall static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
6428ed55a54SJohn McCall                                         const CXXNewExpr *E) {
64321122cf6SAnders Carlsson   if (!E->isArray())
6443eb55cfeSKen Dyck     return CharUnits::Zero();
64521122cf6SAnders Carlsson 
6467ec4b434SJohn McCall   // No cookie is required if the operator new[] being used is the
6477ec4b434SJohn McCall   // reserved placement operator new[].
6487ec4b434SJohn McCall   if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
6493eb55cfeSKen Dyck     return CharUnits::Zero();
650399f499fSAnders Carlsson 
651284c48ffSJohn McCall   return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
65259486a2dSAnders Carlsson }
65359486a2dSAnders Carlsson 
654036f2f6bSJohn McCall static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
655036f2f6bSJohn McCall                                         const CXXNewExpr *e,
656f862eb6aSSebastian Redl                                         unsigned minElements,
657036f2f6bSJohn McCall                                         llvm::Value *&numElements,
658036f2f6bSJohn McCall                                         llvm::Value *&sizeWithoutCookie) {
659036f2f6bSJohn McCall   QualType type = e->getAllocatedType();
66059486a2dSAnders Carlsson 
661036f2f6bSJohn McCall   if (!e->isArray()) {
662036f2f6bSJohn McCall     CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
663036f2f6bSJohn McCall     sizeWithoutCookie
664036f2f6bSJohn McCall       = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
665036f2f6bSJohn McCall     return sizeWithoutCookie;
66605fc5be3SDouglas Gregor   }
66759486a2dSAnders Carlsson 
668036f2f6bSJohn McCall   // The width of size_t.
669036f2f6bSJohn McCall   unsigned sizeWidth = CGF.SizeTy->getBitWidth();
670036f2f6bSJohn McCall 
6718ed55a54SJohn McCall   // Figure out the cookie size.
672036f2f6bSJohn McCall   llvm::APInt cookieSize(sizeWidth,
673036f2f6bSJohn McCall                          CalculateCookiePadding(CGF, e).getQuantity());
6748ed55a54SJohn McCall 
67559486a2dSAnders Carlsson   // Emit the array size expression.
6767648fb46SArgyrios Kyrtzidis   // We multiply the size of all dimensions for NumElements.
6777648fb46SArgyrios Kyrtzidis   // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
67807527621SNick Lewycky   numElements = CGF.CGM.EmitConstantExpr(e->getArraySize(),
67907527621SNick Lewycky                                          CGF.getContext().getSizeType(), &CGF);
68007527621SNick Lewycky   if (!numElements)
681036f2f6bSJohn McCall     numElements = CGF.EmitScalarExpr(e->getArraySize());
682036f2f6bSJohn McCall   assert(isa<llvm::IntegerType>(numElements->getType()));
6838ed55a54SJohn McCall 
684036f2f6bSJohn McCall   // The number of elements can be have an arbitrary integer type;
685036f2f6bSJohn McCall   // essentially, we need to multiply it by a constant factor, add a
686036f2f6bSJohn McCall   // cookie size, and verify that the result is representable as a
687036f2f6bSJohn McCall   // size_t.  That's just a gloss, though, and it's wrong in one
688036f2f6bSJohn McCall   // important way: if the count is negative, it's an error even if
689036f2f6bSJohn McCall   // the cookie size would bring the total size >= 0.
6906ab2fa8fSDouglas Gregor   bool isSigned
6916ab2fa8fSDouglas Gregor     = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
6922192fe50SChris Lattner   llvm::IntegerType *numElementsType
693036f2f6bSJohn McCall     = cast<llvm::IntegerType>(numElements->getType());
694036f2f6bSJohn McCall   unsigned numElementsWidth = numElementsType->getBitWidth();
695036f2f6bSJohn McCall 
696036f2f6bSJohn McCall   // Compute the constant factor.
697036f2f6bSJohn McCall   llvm::APInt arraySizeMultiplier(sizeWidth, 1);
6987648fb46SArgyrios Kyrtzidis   while (const ConstantArrayType *CAT
699036f2f6bSJohn McCall              = CGF.getContext().getAsConstantArrayType(type)) {
700036f2f6bSJohn McCall     type = CAT->getElementType();
701036f2f6bSJohn McCall     arraySizeMultiplier *= CAT->getSize();
7027648fb46SArgyrios Kyrtzidis   }
70359486a2dSAnders Carlsson 
704036f2f6bSJohn McCall   CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
705036f2f6bSJohn McCall   llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
706036f2f6bSJohn McCall   typeSizeMultiplier *= arraySizeMultiplier;
707036f2f6bSJohn McCall 
708036f2f6bSJohn McCall   // This will be a size_t.
709036f2f6bSJohn McCall   llvm::Value *size;
71032ac583dSChris Lattner 
71132ac583dSChris Lattner   // If someone is doing 'new int[42]' there is no need to do a dynamic check.
71232ac583dSChris Lattner   // Don't bloat the -O0 code.
713036f2f6bSJohn McCall   if (llvm::ConstantInt *numElementsC =
714036f2f6bSJohn McCall         dyn_cast<llvm::ConstantInt>(numElements)) {
715036f2f6bSJohn McCall     const llvm::APInt &count = numElementsC->getValue();
71632ac583dSChris Lattner 
717036f2f6bSJohn McCall     bool hasAnyOverflow = false;
71832ac583dSChris Lattner 
719036f2f6bSJohn McCall     // If 'count' was a negative number, it's an overflow.
720036f2f6bSJohn McCall     if (isSigned && count.isNegative())
721036f2f6bSJohn McCall       hasAnyOverflow = true;
7228ed55a54SJohn McCall 
723036f2f6bSJohn McCall     // We want to do all this arithmetic in size_t.  If numElements is
724036f2f6bSJohn McCall     // wider than that, check whether it's already too big, and if so,
725036f2f6bSJohn McCall     // overflow.
726036f2f6bSJohn McCall     else if (numElementsWidth > sizeWidth &&
727036f2f6bSJohn McCall              numElementsWidth - sizeWidth > count.countLeadingZeros())
728036f2f6bSJohn McCall       hasAnyOverflow = true;
729036f2f6bSJohn McCall 
730036f2f6bSJohn McCall     // Okay, compute a count at the right width.
731036f2f6bSJohn McCall     llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
732036f2f6bSJohn McCall 
733f862eb6aSSebastian Redl     // If there is a brace-initializer, we cannot allocate fewer elements than
734f862eb6aSSebastian Redl     // there are initializers. If we do, that's treated like an overflow.
735f862eb6aSSebastian Redl     if (adjustedCount.ult(minElements))
736f862eb6aSSebastian Redl       hasAnyOverflow = true;
737f862eb6aSSebastian Redl 
738036f2f6bSJohn McCall     // Scale numElements by that.  This might overflow, but we don't
739036f2f6bSJohn McCall     // care because it only overflows if allocationSize does, too, and
740036f2f6bSJohn McCall     // if that overflows then we shouldn't use this.
741036f2f6bSJohn McCall     numElements = llvm::ConstantInt::get(CGF.SizeTy,
742036f2f6bSJohn McCall                                          adjustedCount * arraySizeMultiplier);
743036f2f6bSJohn McCall 
744036f2f6bSJohn McCall     // Compute the size before cookie, and track whether it overflowed.
745036f2f6bSJohn McCall     bool overflow;
746036f2f6bSJohn McCall     llvm::APInt allocationSize
747036f2f6bSJohn McCall       = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
748036f2f6bSJohn McCall     hasAnyOverflow |= overflow;
749036f2f6bSJohn McCall 
750036f2f6bSJohn McCall     // Add in the cookie, and check whether it's overflowed.
751036f2f6bSJohn McCall     if (cookieSize != 0) {
752036f2f6bSJohn McCall       // Save the current size without a cookie.  This shouldn't be
753036f2f6bSJohn McCall       // used if there was overflow.
754036f2f6bSJohn McCall       sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
755036f2f6bSJohn McCall 
756036f2f6bSJohn McCall       allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
757036f2f6bSJohn McCall       hasAnyOverflow |= overflow;
7588ed55a54SJohn McCall     }
7598ed55a54SJohn McCall 
760036f2f6bSJohn McCall     // On overflow, produce a -1 so operator new will fail.
761455f42c9SAaron Ballman     if (hasAnyOverflow) {
762455f42c9SAaron Ballman       size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
763455f42c9SAaron Ballman     } else {
764036f2f6bSJohn McCall       size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
765455f42c9SAaron Ballman     }
76632ac583dSChris Lattner 
767036f2f6bSJohn McCall   // Otherwise, we might need to use the overflow intrinsics.
7688ed55a54SJohn McCall   } else {
769f862eb6aSSebastian Redl     // There are up to five conditions we need to test for:
770036f2f6bSJohn McCall     // 1) if isSigned, we need to check whether numElements is negative;
771036f2f6bSJohn McCall     // 2) if numElementsWidth > sizeWidth, we need to check whether
772036f2f6bSJohn McCall     //   numElements is larger than something representable in size_t;
773f862eb6aSSebastian Redl     // 3) if minElements > 0, we need to check whether numElements is smaller
774f862eb6aSSebastian Redl     //    than that.
775f862eb6aSSebastian Redl     // 4) we need to compute
776036f2f6bSJohn McCall     //      sizeWithoutCookie := numElements * typeSizeMultiplier
777036f2f6bSJohn McCall     //    and check whether it overflows; and
778f862eb6aSSebastian Redl     // 5) if we need a cookie, we need to compute
779036f2f6bSJohn McCall     //      size := sizeWithoutCookie + cookieSize
780036f2f6bSJohn McCall     //    and check whether it overflows.
7818ed55a54SJohn McCall 
7828a13c418SCraig Topper     llvm::Value *hasOverflow = nullptr;
7838ed55a54SJohn McCall 
784036f2f6bSJohn McCall     // If numElementsWidth > sizeWidth, then one way or another, we're
785036f2f6bSJohn McCall     // going to have to do a comparison for (2), and this happens to
786036f2f6bSJohn McCall     // take care of (1), too.
787036f2f6bSJohn McCall     if (numElementsWidth > sizeWidth) {
788036f2f6bSJohn McCall       llvm::APInt threshold(numElementsWidth, 1);
789036f2f6bSJohn McCall       threshold <<= sizeWidth;
7908ed55a54SJohn McCall 
791036f2f6bSJohn McCall       llvm::Value *thresholdV
792036f2f6bSJohn McCall         = llvm::ConstantInt::get(numElementsType, threshold);
793036f2f6bSJohn McCall 
794036f2f6bSJohn McCall       hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
795036f2f6bSJohn McCall       numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
796036f2f6bSJohn McCall 
797036f2f6bSJohn McCall     // Otherwise, if we're signed, we want to sext up to size_t.
798036f2f6bSJohn McCall     } else if (isSigned) {
799036f2f6bSJohn McCall       if (numElementsWidth < sizeWidth)
800036f2f6bSJohn McCall         numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
801036f2f6bSJohn McCall 
802036f2f6bSJohn McCall       // If there's a non-1 type size multiplier, then we can do the
803036f2f6bSJohn McCall       // signedness check at the same time as we do the multiply
804036f2f6bSJohn McCall       // because a negative number times anything will cause an
805f862eb6aSSebastian Redl       // unsigned overflow.  Otherwise, we have to do it here. But at least
806f862eb6aSSebastian Redl       // in this case, we can subsume the >= minElements check.
807036f2f6bSJohn McCall       if (typeSizeMultiplier == 1)
808036f2f6bSJohn McCall         hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
809f862eb6aSSebastian Redl                               llvm::ConstantInt::get(CGF.SizeTy, minElements));
810036f2f6bSJohn McCall 
811036f2f6bSJohn McCall     // Otherwise, zext up to size_t if necessary.
812036f2f6bSJohn McCall     } else if (numElementsWidth < sizeWidth) {
813036f2f6bSJohn McCall       numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
814036f2f6bSJohn McCall     }
815036f2f6bSJohn McCall 
816036f2f6bSJohn McCall     assert(numElements->getType() == CGF.SizeTy);
817036f2f6bSJohn McCall 
818f862eb6aSSebastian Redl     if (minElements) {
819f862eb6aSSebastian Redl       // Don't allow allocation of fewer elements than we have initializers.
820f862eb6aSSebastian Redl       if (!hasOverflow) {
821f862eb6aSSebastian Redl         hasOverflow = CGF.Builder.CreateICmpULT(numElements,
822f862eb6aSSebastian Redl                               llvm::ConstantInt::get(CGF.SizeTy, minElements));
823f862eb6aSSebastian Redl       } else if (numElementsWidth > sizeWidth) {
824f862eb6aSSebastian Redl         // The other existing overflow subsumes this check.
825f862eb6aSSebastian Redl         // We do an unsigned comparison, since any signed value < -1 is
826f862eb6aSSebastian Redl         // taken care of either above or below.
827f862eb6aSSebastian Redl         hasOverflow = CGF.Builder.CreateOr(hasOverflow,
828f862eb6aSSebastian Redl                           CGF.Builder.CreateICmpULT(numElements,
829f862eb6aSSebastian Redl                               llvm::ConstantInt::get(CGF.SizeTy, minElements)));
830f862eb6aSSebastian Redl       }
831f862eb6aSSebastian Redl     }
832f862eb6aSSebastian Redl 
833036f2f6bSJohn McCall     size = numElements;
834036f2f6bSJohn McCall 
835036f2f6bSJohn McCall     // Multiply by the type size if necessary.  This multiplier
836036f2f6bSJohn McCall     // includes all the factors for nested arrays.
8378ed55a54SJohn McCall     //
838036f2f6bSJohn McCall     // This step also causes numElements to be scaled up by the
839036f2f6bSJohn McCall     // nested-array factor if necessary.  Overflow on this computation
840036f2f6bSJohn McCall     // can be ignored because the result shouldn't be used if
841036f2f6bSJohn McCall     // allocation fails.
842036f2f6bSJohn McCall     if (typeSizeMultiplier != 1) {
843036f2f6bSJohn McCall       llvm::Value *umul_with_overflow
8448d375cefSBenjamin Kramer         = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
8458ed55a54SJohn McCall 
846036f2f6bSJohn McCall       llvm::Value *tsmV =
847036f2f6bSJohn McCall         llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
848036f2f6bSJohn McCall       llvm::Value *result =
84943f9bb73SDavid Blaikie           CGF.Builder.CreateCall(umul_with_overflow, {size, tsmV});
8508ed55a54SJohn McCall 
851036f2f6bSJohn McCall       llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
852036f2f6bSJohn McCall       if (hasOverflow)
853036f2f6bSJohn McCall         hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
8548ed55a54SJohn McCall       else
855036f2f6bSJohn McCall         hasOverflow = overflowed;
85659486a2dSAnders Carlsson 
857036f2f6bSJohn McCall       size = CGF.Builder.CreateExtractValue(result, 0);
858036f2f6bSJohn McCall 
859036f2f6bSJohn McCall       // Also scale up numElements by the array size multiplier.
860036f2f6bSJohn McCall       if (arraySizeMultiplier != 1) {
861036f2f6bSJohn McCall         // If the base element type size is 1, then we can re-use the
862036f2f6bSJohn McCall         // multiply we just did.
863036f2f6bSJohn McCall         if (typeSize.isOne()) {
864036f2f6bSJohn McCall           assert(arraySizeMultiplier == typeSizeMultiplier);
865036f2f6bSJohn McCall           numElements = size;
866036f2f6bSJohn McCall 
867036f2f6bSJohn McCall         // Otherwise we need a separate multiply.
868036f2f6bSJohn McCall         } else {
869036f2f6bSJohn McCall           llvm::Value *asmV =
870036f2f6bSJohn McCall             llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
871036f2f6bSJohn McCall           numElements = CGF.Builder.CreateMul(numElements, asmV);
872036f2f6bSJohn McCall         }
873036f2f6bSJohn McCall       }
874036f2f6bSJohn McCall     } else {
875036f2f6bSJohn McCall       // numElements doesn't need to be scaled.
876036f2f6bSJohn McCall       assert(arraySizeMultiplier == 1);
877036f2f6bSJohn McCall     }
878036f2f6bSJohn McCall 
879036f2f6bSJohn McCall     // Add in the cookie size if necessary.
880036f2f6bSJohn McCall     if (cookieSize != 0) {
881036f2f6bSJohn McCall       sizeWithoutCookie = size;
882036f2f6bSJohn McCall 
883036f2f6bSJohn McCall       llvm::Value *uadd_with_overflow
8848d375cefSBenjamin Kramer         = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
885036f2f6bSJohn McCall 
886036f2f6bSJohn McCall       llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
887036f2f6bSJohn McCall       llvm::Value *result =
88843f9bb73SDavid Blaikie           CGF.Builder.CreateCall(uadd_with_overflow, {size, cookieSizeV});
889036f2f6bSJohn McCall 
890036f2f6bSJohn McCall       llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
891036f2f6bSJohn McCall       if (hasOverflow)
892036f2f6bSJohn McCall         hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
893036f2f6bSJohn McCall       else
894036f2f6bSJohn McCall         hasOverflow = overflowed;
895036f2f6bSJohn McCall 
896036f2f6bSJohn McCall       size = CGF.Builder.CreateExtractValue(result, 0);
897036f2f6bSJohn McCall     }
898036f2f6bSJohn McCall 
899036f2f6bSJohn McCall     // If we had any possibility of dynamic overflow, make a select to
900036f2f6bSJohn McCall     // overwrite 'size' with an all-ones value, which should cause
901036f2f6bSJohn McCall     // operator new to throw.
902036f2f6bSJohn McCall     if (hasOverflow)
903455f42c9SAaron Ballman       size = CGF.Builder.CreateSelect(hasOverflow,
904455f42c9SAaron Ballman                                  llvm::Constant::getAllOnesValue(CGF.SizeTy),
905036f2f6bSJohn McCall                                       size);
906036f2f6bSJohn McCall   }
907036f2f6bSJohn McCall 
908036f2f6bSJohn McCall   if (cookieSize == 0)
909036f2f6bSJohn McCall     sizeWithoutCookie = size;
910036f2f6bSJohn McCall   else
911036f2f6bSJohn McCall     assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
912036f2f6bSJohn McCall 
913036f2f6bSJohn McCall   return size;
91459486a2dSAnders Carlsson }
91559486a2dSAnders Carlsson 
916f862eb6aSSebastian Redl static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
9177f416cc4SJohn McCall                                     QualType AllocType, Address NewPtr) {
9181c96bc5dSRichard Smith   // FIXME: Refactor with EmitExprAsInit.
91947fb9508SJohn McCall   switch (CGF.getEvaluationKind(AllocType)) {
92047fb9508SJohn McCall   case TEK_Scalar:
921a2c1124fSDavid Blaikie     CGF.EmitScalarInit(Init, nullptr,
9227f416cc4SJohn McCall                        CGF.MakeAddrLValue(NewPtr, AllocType), false);
92347fb9508SJohn McCall     return;
92447fb9508SJohn McCall   case TEK_Complex:
9257f416cc4SJohn McCall     CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType),
92647fb9508SJohn McCall                                   /*isInit*/ true);
92747fb9508SJohn McCall     return;
92847fb9508SJohn McCall   case TEK_Aggregate: {
9297a626f63SJohn McCall     AggValueSlot Slot
9307f416cc4SJohn McCall       = AggValueSlot::forAddr(NewPtr, AllocType.getQualifiers(),
9318d6fc958SJohn McCall                               AggValueSlot::IsDestructed,
93246759f4fSJohn McCall                               AggValueSlot::DoesNotNeedGCBarriers,
933615ed1a3SChad Rosier                               AggValueSlot::IsNotAliased);
9347a626f63SJohn McCall     CGF.EmitAggExpr(Init, Slot);
93547fb9508SJohn McCall     return;
9367a626f63SJohn McCall   }
937d5202e09SFariborz Jahanian   }
93847fb9508SJohn McCall   llvm_unreachable("bad evaluation kind");
93947fb9508SJohn McCall }
940d5202e09SFariborz Jahanian 
941fb901c7aSDavid Blaikie void CodeGenFunction::EmitNewArrayInitializer(
942fb901c7aSDavid Blaikie     const CXXNewExpr *E, QualType ElementType, llvm::Type *ElementTy,
9437f416cc4SJohn McCall     Address BeginPtr, llvm::Value *NumElements,
94406a67e2cSRichard Smith     llvm::Value *AllocSizeWithoutCookie) {
94506a67e2cSRichard Smith   // If we have a type with trivial initialization and no initializer,
94606a67e2cSRichard Smith   // there's nothing to do.
9476047f07eSSebastian Redl   if (!E->hasInitializer())
94806a67e2cSRichard Smith     return;
949b66b08efSFariborz Jahanian 
9507f416cc4SJohn McCall   Address CurPtr = BeginPtr;
951d5202e09SFariborz Jahanian 
95206a67e2cSRichard Smith   unsigned InitListElements = 0;
953f862eb6aSSebastian Redl 
954f862eb6aSSebastian Redl   const Expr *Init = E->getInitializer();
9557f416cc4SJohn McCall   Address EndOfInit = Address::invalid();
95606a67e2cSRichard Smith   QualType::DestructionKind DtorKind = ElementType.isDestructedType();
95706a67e2cSRichard Smith   EHScopeStack::stable_iterator Cleanup;
95806a67e2cSRichard Smith   llvm::Instruction *CleanupDominator = nullptr;
9591c96bc5dSRichard Smith 
9607f416cc4SJohn McCall   CharUnits ElementSize = getContext().getTypeSizeInChars(ElementType);
9617f416cc4SJohn McCall   CharUnits ElementAlign =
9627f416cc4SJohn McCall     BeginPtr.getAlignment().alignmentOfArrayElement(ElementSize);
9637f416cc4SJohn McCall 
9640511d23aSRichard Smith   // Attempt to perform zero-initialization using memset.
9650511d23aSRichard Smith   auto TryMemsetInitialization = [&]() -> bool {
9660511d23aSRichard Smith     // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
9670511d23aSRichard Smith     // we can initialize with a memset to -1.
9680511d23aSRichard Smith     if (!CGM.getTypes().isZeroInitializable(ElementType))
9690511d23aSRichard Smith       return false;
9700511d23aSRichard Smith 
9710511d23aSRichard Smith     // Optimization: since zero initialization will just set the memory
9720511d23aSRichard Smith     // to all zeroes, generate a single memset to do it in one shot.
9730511d23aSRichard Smith 
9740511d23aSRichard Smith     // Subtract out the size of any elements we've already initialized.
9750511d23aSRichard Smith     auto *RemainingSize = AllocSizeWithoutCookie;
9760511d23aSRichard Smith     if (InitListElements) {
9770511d23aSRichard Smith       // We know this can't overflow; we check this when doing the allocation.
9780511d23aSRichard Smith       auto *InitializedSize = llvm::ConstantInt::get(
9790511d23aSRichard Smith           RemainingSize->getType(),
9800511d23aSRichard Smith           getContext().getTypeSizeInChars(ElementType).getQuantity() *
9810511d23aSRichard Smith               InitListElements);
9820511d23aSRichard Smith       RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
9830511d23aSRichard Smith     }
9840511d23aSRichard Smith 
9850511d23aSRichard Smith     // Create the memset.
9860511d23aSRichard Smith     Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize, false);
9870511d23aSRichard Smith     return true;
9880511d23aSRichard Smith   };
9890511d23aSRichard Smith 
990f862eb6aSSebastian Redl   // If the initializer is an initializer list, first do the explicit elements.
991f862eb6aSSebastian Redl   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
9920511d23aSRichard Smith     // Initializing from a (braced) string literal is a special case; the init
9930511d23aSRichard Smith     // list element does not initialize a (single) array element.
9940511d23aSRichard Smith     if (ILE->isStringLiteralInit()) {
9950511d23aSRichard Smith       // Initialize the initial portion of length equal to that of the string
9960511d23aSRichard Smith       // literal. The allocation must be for at least this much; we emitted a
9970511d23aSRichard Smith       // check for that earlier.
9980511d23aSRichard Smith       AggValueSlot Slot =
9990511d23aSRichard Smith           AggValueSlot::forAddr(CurPtr, ElementType.getQualifiers(),
10000511d23aSRichard Smith                                 AggValueSlot::IsDestructed,
10010511d23aSRichard Smith                                 AggValueSlot::DoesNotNeedGCBarriers,
10020511d23aSRichard Smith                                 AggValueSlot::IsNotAliased);
10030511d23aSRichard Smith       EmitAggExpr(ILE->getInit(0), Slot);
10040511d23aSRichard Smith 
10050511d23aSRichard Smith       // Move past these elements.
10060511d23aSRichard Smith       InitListElements =
10070511d23aSRichard Smith           cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe())
10080511d23aSRichard Smith               ->getSize().getZExtValue();
10090511d23aSRichard Smith       CurPtr =
10100511d23aSRichard Smith           Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(),
10110511d23aSRichard Smith                                             Builder.getSize(InitListElements),
10120511d23aSRichard Smith                                             "string.init.end"),
10130511d23aSRichard Smith                   CurPtr.getAlignment().alignmentAtOffset(InitListElements *
10140511d23aSRichard Smith                                                           ElementSize));
10150511d23aSRichard Smith 
10160511d23aSRichard Smith       // Zero out the rest, if any remain.
10170511d23aSRichard Smith       llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
10180511d23aSRichard Smith       if (!ConstNum || !ConstNum->equalsInt(InitListElements)) {
10190511d23aSRichard Smith         bool OK = TryMemsetInitialization();
10200511d23aSRichard Smith         (void)OK;
10210511d23aSRichard Smith         assert(OK && "couldn't memset character type?");
10220511d23aSRichard Smith       }
10230511d23aSRichard Smith       return;
10240511d23aSRichard Smith     }
10250511d23aSRichard Smith 
102606a67e2cSRichard Smith     InitListElements = ILE->getNumInits();
1027f62290a1SChad Rosier 
10281c96bc5dSRichard Smith     // If this is a multi-dimensional array new, we will initialize multiple
10291c96bc5dSRichard Smith     // elements with each init list element.
10301c96bc5dSRichard Smith     QualType AllocType = E->getAllocatedType();
10311c96bc5dSRichard Smith     if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
10321c96bc5dSRichard Smith             AllocType->getAsArrayTypeUnsafe())) {
1033fb901c7aSDavid Blaikie       ElementTy = ConvertTypeForMem(AllocType);
10347f416cc4SJohn McCall       CurPtr = Builder.CreateElementBitCast(CurPtr, ElementTy);
103506a67e2cSRichard Smith       InitListElements *= getContext().getConstantArrayElementCount(CAT);
10361c96bc5dSRichard Smith     }
10371c96bc5dSRichard Smith 
103806a67e2cSRichard Smith     // Enter a partial-destruction Cleanup if necessary.
103906a67e2cSRichard Smith     if (needsEHCleanup(DtorKind)) {
104006a67e2cSRichard Smith       // In principle we could tell the Cleanup where we are more
1041f62290a1SChad Rosier       // directly, but the control flow can get so varied here that it
1042f62290a1SChad Rosier       // would actually be quite complex.  Therefore we go through an
1043f62290a1SChad Rosier       // alloca.
10447f416cc4SJohn McCall       EndOfInit = CreateTempAlloca(BeginPtr.getType(), getPointerAlign(),
10457f416cc4SJohn McCall                                    "array.init.end");
10467f416cc4SJohn McCall       CleanupDominator = Builder.CreateStore(BeginPtr.getPointer(), EndOfInit);
10477f416cc4SJohn McCall       pushIrregularPartialArrayCleanup(BeginPtr.getPointer(), EndOfInit,
10487f416cc4SJohn McCall                                        ElementType, ElementAlign,
104906a67e2cSRichard Smith                                        getDestroyer(DtorKind));
105006a67e2cSRichard Smith       Cleanup = EHStack.stable_begin();
1051f62290a1SChad Rosier     }
1052f62290a1SChad Rosier 
10537f416cc4SJohn McCall     CharUnits StartAlign = CurPtr.getAlignment();
1054f862eb6aSSebastian Redl     for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
1055f62290a1SChad Rosier       // Tell the cleanup that it needs to destroy up to this
1056f62290a1SChad Rosier       // element.  TODO: some of these stores can be trivially
1057f62290a1SChad Rosier       // observed to be unnecessary.
10587f416cc4SJohn McCall       if (EndOfInit.isValid()) {
10597f416cc4SJohn McCall         auto FinishedPtr =
10607f416cc4SJohn McCall           Builder.CreateBitCast(CurPtr.getPointer(), BeginPtr.getType());
10617f416cc4SJohn McCall         Builder.CreateStore(FinishedPtr, EndOfInit);
10627f416cc4SJohn McCall       }
106306a67e2cSRichard Smith       // FIXME: If the last initializer is an incomplete initializer list for
106406a67e2cSRichard Smith       // an array, and we have an array filler, we can fold together the two
106506a67e2cSRichard Smith       // initialization loops.
10661c96bc5dSRichard Smith       StoreAnyExprIntoOneUnit(*this, ILE->getInit(i),
106706a67e2cSRichard Smith                               ILE->getInit(i)->getType(), CurPtr);
10687f416cc4SJohn McCall       CurPtr = Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(),
10697f416cc4SJohn McCall                                                  Builder.getSize(1),
10707f416cc4SJohn McCall                                                  "array.exp.next"),
10717f416cc4SJohn McCall                        StartAlign.alignmentAtOffset((i + 1) * ElementSize));
1072f862eb6aSSebastian Redl     }
1073f862eb6aSSebastian Redl 
1074f862eb6aSSebastian Redl     // The remaining elements are filled with the array filler expression.
1075f862eb6aSSebastian Redl     Init = ILE->getArrayFiller();
10761c96bc5dSRichard Smith 
107706a67e2cSRichard Smith     // Extract the initializer for the individual array elements by pulling
107806a67e2cSRichard Smith     // out the array filler from all the nested initializer lists. This avoids
107906a67e2cSRichard Smith     // generating a nested loop for the initialization.
108006a67e2cSRichard Smith     while (Init && Init->getType()->isConstantArrayType()) {
108106a67e2cSRichard Smith       auto *SubILE = dyn_cast<InitListExpr>(Init);
108206a67e2cSRichard Smith       if (!SubILE)
108306a67e2cSRichard Smith         break;
108406a67e2cSRichard Smith       assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
108506a67e2cSRichard Smith       Init = SubILE->getArrayFiller();
1086f862eb6aSSebastian Redl     }
1087f862eb6aSSebastian Redl 
108806a67e2cSRichard Smith     // Switch back to initializing one base element at a time.
10897f416cc4SJohn McCall     CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr.getType());
1090f62290a1SChad Rosier   }
1091e6c980c4SChandler Carruth 
1092454a7cdfSRichard Smith   // If all elements have already been initialized, skip any further
1093454a7cdfSRichard Smith   // initialization.
1094454a7cdfSRichard Smith   llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
1095454a7cdfSRichard Smith   if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
1096454a7cdfSRichard Smith     // If there was a Cleanup, deactivate it.
1097454a7cdfSRichard Smith     if (CleanupDominator)
1098454a7cdfSRichard Smith       DeactivateCleanupBlock(Cleanup, CleanupDominator);
1099454a7cdfSRichard Smith     return;
1100454a7cdfSRichard Smith   }
1101454a7cdfSRichard Smith 
1102454a7cdfSRichard Smith   assert(Init && "have trailing elements to initialize but no initializer");
1103454a7cdfSRichard Smith 
110406a67e2cSRichard Smith   // If this is a constructor call, try to optimize it out, and failing that
110506a67e2cSRichard Smith   // emit a single loop to initialize all remaining elements.
1106454a7cdfSRichard Smith   if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
11076047f07eSSebastian Redl     CXXConstructorDecl *Ctor = CCE->getConstructor();
1108d153103cSDouglas Gregor     if (Ctor->isTrivial()) {
110905fc5be3SDouglas Gregor       // If new expression did not specify value-initialization, then there
111005fc5be3SDouglas Gregor       // is no initialization.
11116047f07eSSebastian Redl       if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
111205fc5be3SDouglas Gregor         return;
111305fc5be3SDouglas Gregor 
111406a67e2cSRichard Smith       if (TryMemsetInitialization())
11153a202f60SAnders Carlsson         return;
11163a202f60SAnders Carlsson     }
111705fc5be3SDouglas Gregor 
111806a67e2cSRichard Smith     // Store the new Cleanup position for irregular Cleanups.
111906a67e2cSRichard Smith     //
112006a67e2cSRichard Smith     // FIXME: Share this cleanup with the constructor call emission rather than
112106a67e2cSRichard Smith     // having it create a cleanup of its own.
11227f416cc4SJohn McCall     if (EndOfInit.isValid())
11237f416cc4SJohn McCall       Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
112406a67e2cSRichard Smith 
112506a67e2cSRichard Smith     // Emit a constructor call loop to initialize the remaining elements.
112606a67e2cSRichard Smith     if (InitListElements)
112706a67e2cSRichard Smith       NumElements = Builder.CreateSub(
112806a67e2cSRichard Smith           NumElements,
112906a67e2cSRichard Smith           llvm::ConstantInt::get(NumElements->getType(), InitListElements));
113070b9c01bSAlexey Samsonov     EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,
113148ddcf2cSEli Friedman                                CCE->requiresZeroInitialization());
113205fc5be3SDouglas Gregor     return;
11336047f07eSSebastian Redl   }
113406a67e2cSRichard Smith 
113506a67e2cSRichard Smith   // If this is value-initialization, we can usually use memset.
113606a67e2cSRichard Smith   ImplicitValueInitExpr IVIE(ElementType);
1137454a7cdfSRichard Smith   if (isa<ImplicitValueInitExpr>(Init)) {
113806a67e2cSRichard Smith     if (TryMemsetInitialization())
113906a67e2cSRichard Smith       return;
114006a67e2cSRichard Smith 
114106a67e2cSRichard Smith     // Switch to an ImplicitValueInitExpr for the element type. This handles
114206a67e2cSRichard Smith     // only one case: multidimensional array new of pointers to members. In
114306a67e2cSRichard Smith     // all other cases, we already have an initializer for the array element.
114406a67e2cSRichard Smith     Init = &IVIE;
114506a67e2cSRichard Smith   }
114606a67e2cSRichard Smith 
114706a67e2cSRichard Smith   // At this point we should have found an initializer for the individual
114806a67e2cSRichard Smith   // elements of the array.
114906a67e2cSRichard Smith   assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&
115006a67e2cSRichard Smith          "got wrong type of element to initialize");
115106a67e2cSRichard Smith 
1152454a7cdfSRichard Smith   // If we have an empty initializer list, we can usually use memset.
1153454a7cdfSRichard Smith   if (auto *ILE = dyn_cast<InitListExpr>(Init))
1154454a7cdfSRichard Smith     if (ILE->getNumInits() == 0 && TryMemsetInitialization())
1155d5202e09SFariborz Jahanian       return;
115659486a2dSAnders Carlsson 
1157cb77930dSYunzhong Gao   // If we have a struct whose every field is value-initialized, we can
1158cb77930dSYunzhong Gao   // usually use memset.
1159cb77930dSYunzhong Gao   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
1160cb77930dSYunzhong Gao     if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
1161cb77930dSYunzhong Gao       if (RType->getDecl()->isStruct()) {
1162872307e2SRichard Smith         unsigned NumElements = 0;
1163872307e2SRichard Smith         if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RType->getDecl()))
1164872307e2SRichard Smith           NumElements = CXXRD->getNumBases();
1165cb77930dSYunzhong Gao         for (auto *Field : RType->getDecl()->fields())
1166cb77930dSYunzhong Gao           if (!Field->isUnnamedBitfield())
1167872307e2SRichard Smith             ++NumElements;
1168872307e2SRichard Smith         // FIXME: Recurse into nested InitListExprs.
1169872307e2SRichard Smith         if (ILE->getNumInits() == NumElements)
1170cb77930dSYunzhong Gao           for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
1171cb77930dSYunzhong Gao             if (!isa<ImplicitValueInitExpr>(ILE->getInit(i)))
1172872307e2SRichard Smith               --NumElements;
1173872307e2SRichard Smith         if (ILE->getNumInits() == NumElements && TryMemsetInitialization())
1174cb77930dSYunzhong Gao           return;
1175cb77930dSYunzhong Gao       }
1176cb77930dSYunzhong Gao     }
1177cb77930dSYunzhong Gao   }
1178cb77930dSYunzhong Gao 
117906a67e2cSRichard Smith   // Create the loop blocks.
118006a67e2cSRichard Smith   llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
118106a67e2cSRichard Smith   llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
118206a67e2cSRichard Smith   llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
118359486a2dSAnders Carlsson 
118406a67e2cSRichard Smith   // Find the end of the array, hoisted out of the loop.
118506a67e2cSRichard Smith   llvm::Value *EndPtr =
11867f416cc4SJohn McCall     Builder.CreateInBoundsGEP(BeginPtr.getPointer(), NumElements, "array.end");
118706a67e2cSRichard Smith 
118806a67e2cSRichard Smith   // If the number of elements isn't constant, we have to now check if there is
118906a67e2cSRichard Smith   // anything left to initialize.
119006a67e2cSRichard Smith   if (!ConstNum) {
11917f416cc4SJohn McCall     llvm::Value *IsEmpty =
11927f416cc4SJohn McCall       Builder.CreateICmpEQ(CurPtr.getPointer(), EndPtr, "array.isempty");
119306a67e2cSRichard Smith     Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
119406a67e2cSRichard Smith   }
119506a67e2cSRichard Smith 
119606a67e2cSRichard Smith   // Enter the loop.
119706a67e2cSRichard Smith   EmitBlock(LoopBB);
119806a67e2cSRichard Smith 
119906a67e2cSRichard Smith   // Set up the current-element phi.
120006a67e2cSRichard Smith   llvm::PHINode *CurPtrPhi =
12017f416cc4SJohn McCall     Builder.CreatePHI(CurPtr.getType(), 2, "array.cur");
12027f416cc4SJohn McCall   CurPtrPhi->addIncoming(CurPtr.getPointer(), EntryBB);
12037f416cc4SJohn McCall 
12047f416cc4SJohn McCall   CurPtr = Address(CurPtrPhi, ElementAlign);
120506a67e2cSRichard Smith 
120606a67e2cSRichard Smith   // Store the new Cleanup position for irregular Cleanups.
12077f416cc4SJohn McCall   if (EndOfInit.isValid())
12087f416cc4SJohn McCall     Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
120906a67e2cSRichard Smith 
121006a67e2cSRichard Smith   // Enter a partial-destruction Cleanup if necessary.
121106a67e2cSRichard Smith   if (!CleanupDominator && needsEHCleanup(DtorKind)) {
12127f416cc4SJohn McCall     pushRegularPartialArrayCleanup(BeginPtr.getPointer(), CurPtr.getPointer(),
12137f416cc4SJohn McCall                                    ElementType, ElementAlign,
121406a67e2cSRichard Smith                                    getDestroyer(DtorKind));
121506a67e2cSRichard Smith     Cleanup = EHStack.stable_begin();
121606a67e2cSRichard Smith     CleanupDominator = Builder.CreateUnreachable();
121706a67e2cSRichard Smith   }
121806a67e2cSRichard Smith 
121906a67e2cSRichard Smith   // Emit the initializer into this element.
122006a67e2cSRichard Smith   StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr);
122106a67e2cSRichard Smith 
122206a67e2cSRichard Smith   // Leave the Cleanup if we entered one.
122306a67e2cSRichard Smith   if (CleanupDominator) {
122406a67e2cSRichard Smith     DeactivateCleanupBlock(Cleanup, CleanupDominator);
122506a67e2cSRichard Smith     CleanupDominator->eraseFromParent();
122606a67e2cSRichard Smith   }
122706a67e2cSRichard Smith 
122806a67e2cSRichard Smith   // Advance to the next element by adjusting the pointer type as necessary.
122906a67e2cSRichard Smith   llvm::Value *NextPtr =
12307f416cc4SJohn McCall     Builder.CreateConstInBoundsGEP1_32(ElementTy, CurPtr.getPointer(), 1,
12317f416cc4SJohn McCall                                        "array.next");
123206a67e2cSRichard Smith 
123306a67e2cSRichard Smith   // Check whether we've gotten to the end of the array and, if so,
123406a67e2cSRichard Smith   // exit the loop.
123506a67e2cSRichard Smith   llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
123606a67e2cSRichard Smith   Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
123706a67e2cSRichard Smith   CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
123806a67e2cSRichard Smith 
123906a67e2cSRichard Smith   EmitBlock(ContBB);
124006a67e2cSRichard Smith }
124106a67e2cSRichard Smith 
124206a67e2cSRichard Smith static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
1243fb901c7aSDavid Blaikie                                QualType ElementType, llvm::Type *ElementTy,
12447f416cc4SJohn McCall                                Address NewPtr, llvm::Value *NumElements,
124506a67e2cSRichard Smith                                llvm::Value *AllocSizeWithoutCookie) {
12469b479666SDavid Blaikie   ApplyDebugLocation DL(CGF, E);
124706a67e2cSRichard Smith   if (E->isArray())
1248fb901c7aSDavid Blaikie     CGF.EmitNewArrayInitializer(E, ElementType, ElementTy, NewPtr, NumElements,
124906a67e2cSRichard Smith                                 AllocSizeWithoutCookie);
125006a67e2cSRichard Smith   else if (const Expr *Init = E->getInitializer())
125166e4197fSDavid Blaikie     StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
125259486a2dSAnders Carlsson }
125359486a2dSAnders Carlsson 
12548d0dc31dSRichard Smith /// Emit a call to an operator new or operator delete function, as implicitly
12558d0dc31dSRichard Smith /// created by new-expressions and delete-expressions.
12568d0dc31dSRichard Smith static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
1257b92ab1afSJohn McCall                                 const FunctionDecl *CalleeDecl,
12588d0dc31dSRichard Smith                                 const FunctionProtoType *CalleeType,
12598d0dc31dSRichard Smith                                 const CallArgList &Args) {
12608d0dc31dSRichard Smith   llvm::Instruction *CallOrInvoke;
1261b92ab1afSJohn McCall   llvm::Constant *CalleePtr = CGF.CGM.GetAddrOfFunction(CalleeDecl);
1262b92ab1afSJohn McCall   CGCallee Callee = CGCallee::forDirect(CalleePtr, CalleeDecl);
12638d0dc31dSRichard Smith   RValue RV =
1264f770683fSPeter Collingbourne       CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(
1265f770683fSPeter Collingbourne                        Args, CalleeType, /*chainCall=*/false),
1266b92ab1afSJohn McCall                    Callee, ReturnValueSlot(), Args, &CallOrInvoke);
12678d0dc31dSRichard Smith 
12688d0dc31dSRichard Smith   /// C++1y [expr.new]p10:
12698d0dc31dSRichard Smith   ///   [In a new-expression,] an implementation is allowed to omit a call
12708d0dc31dSRichard Smith   ///   to a replaceable global allocation function.
12718d0dc31dSRichard Smith   ///
12728d0dc31dSRichard Smith   /// We model such elidable calls with the 'builtin' attribute.
1273b92ab1afSJohn McCall   llvm::Function *Fn = dyn_cast<llvm::Function>(CalleePtr);
1274b92ab1afSJohn McCall   if (CalleeDecl->isReplaceableGlobalAllocationFunction() &&
12756956d587SRafael Espindola       Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
12768d0dc31dSRichard Smith     // FIXME: Add addAttribute to CallSite.
12778d0dc31dSRichard Smith     if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(CallOrInvoke))
12788d0dc31dSRichard Smith       CI->addAttribute(llvm::AttributeSet::FunctionIndex,
12798d0dc31dSRichard Smith                        llvm::Attribute::Builtin);
12808d0dc31dSRichard Smith     else if (llvm::InvokeInst *II = dyn_cast<llvm::InvokeInst>(CallOrInvoke))
12818d0dc31dSRichard Smith       II->addAttribute(llvm::AttributeSet::FunctionIndex,
12828d0dc31dSRichard Smith                        llvm::Attribute::Builtin);
12838d0dc31dSRichard Smith     else
12848d0dc31dSRichard Smith       llvm_unreachable("unexpected kind of call instruction");
12858d0dc31dSRichard Smith   }
12868d0dc31dSRichard Smith 
12878d0dc31dSRichard Smith   return RV;
12888d0dc31dSRichard Smith }
12898d0dc31dSRichard Smith 
1290760520bcSRichard Smith RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
1291760520bcSRichard Smith                                                  const Expr *Arg,
1292760520bcSRichard Smith                                                  bool IsDelete) {
1293760520bcSRichard Smith   CallArgList Args;
1294760520bcSRichard Smith   const Stmt *ArgS = Arg;
1295f05779e2SDavid Blaikie   EmitCallArgs(Args, *Type->param_type_begin(), llvm::makeArrayRef(ArgS));
1296760520bcSRichard Smith   // Find the allocation or deallocation function that we're calling.
1297760520bcSRichard Smith   ASTContext &Ctx = getContext();
1298760520bcSRichard Smith   DeclarationName Name = Ctx.DeclarationNames
1299760520bcSRichard Smith       .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
1300760520bcSRichard Smith   for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
1301599bed75SRichard Smith     if (auto *FD = dyn_cast<FunctionDecl>(Decl))
1302599bed75SRichard Smith       if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
1303760520bcSRichard Smith         return EmitNewDeleteCall(*this, cast<FunctionDecl>(Decl), Type, Args);
1304760520bcSRichard Smith   llvm_unreachable("predeclared global operator new/delete is missing");
1305760520bcSRichard Smith }
1306760520bcSRichard Smith 
1307b2f0f057SRichard Smith static std::pair<bool, bool>
1308b2f0f057SRichard Smith shouldPassSizeAndAlignToUsualDelete(const FunctionProtoType *FPT) {
1309b2f0f057SRichard Smith   auto AI = FPT->param_type_begin(), AE = FPT->param_type_end();
1310e9abe648SDaniel Jasper 
1311b2f0f057SRichard Smith   // The first argument is always a void*.
1312b2f0f057SRichard Smith   ++AI;
1313b2f0f057SRichard Smith 
1314b2f0f057SRichard Smith   // Figure out what other parameters we should be implicitly passing.
1315b2f0f057SRichard Smith   bool PassSize = false;
1316b2f0f057SRichard Smith   bool PassAlignment = false;
1317b2f0f057SRichard Smith 
1318b2f0f057SRichard Smith   if (AI != AE && (*AI)->isIntegerType()) {
1319b2f0f057SRichard Smith     PassSize = true;
1320b2f0f057SRichard Smith     ++AI;
1321b2f0f057SRichard Smith   }
1322b2f0f057SRichard Smith 
1323b2f0f057SRichard Smith   if (AI != AE && (*AI)->isAlignValT()) {
1324b2f0f057SRichard Smith     PassAlignment = true;
1325b2f0f057SRichard Smith     ++AI;
1326b2f0f057SRichard Smith   }
1327b2f0f057SRichard Smith 
1328b2f0f057SRichard Smith   assert(AI == AE && "unexpected usual deallocation function parameter");
1329b2f0f057SRichard Smith   return {PassSize, PassAlignment};
1330b2f0f057SRichard Smith }
1331b2f0f057SRichard Smith 
1332b2f0f057SRichard Smith namespace {
1333b2f0f057SRichard Smith   /// A cleanup to call the given 'operator delete' function upon abnormal
1334b2f0f057SRichard Smith   /// exit from a new expression. Templated on a traits type that deals with
1335b2f0f057SRichard Smith   /// ensuring that the arguments dominate the cleanup if necessary.
1336b2f0f057SRichard Smith   template<typename Traits>
1337b2f0f057SRichard Smith   class CallDeleteDuringNew final : public EHScopeStack::Cleanup {
1338b2f0f057SRichard Smith     /// Type used to hold llvm::Value*s.
1339b2f0f057SRichard Smith     typedef typename Traits::ValueTy ValueTy;
1340b2f0f057SRichard Smith     /// Type used to hold RValues.
1341b2f0f057SRichard Smith     typedef typename Traits::RValueTy RValueTy;
1342b2f0f057SRichard Smith     struct PlacementArg {
1343b2f0f057SRichard Smith       RValueTy ArgValue;
1344b2f0f057SRichard Smith       QualType ArgType;
1345b2f0f057SRichard Smith     };
1346b2f0f057SRichard Smith 
1347b2f0f057SRichard Smith     unsigned NumPlacementArgs : 31;
1348b2f0f057SRichard Smith     unsigned PassAlignmentToPlacementDelete : 1;
1349b2f0f057SRichard Smith     const FunctionDecl *OperatorDelete;
1350b2f0f057SRichard Smith     ValueTy Ptr;
1351b2f0f057SRichard Smith     ValueTy AllocSize;
1352b2f0f057SRichard Smith     CharUnits AllocAlign;
1353b2f0f057SRichard Smith 
1354b2f0f057SRichard Smith     PlacementArg *getPlacementArgs() {
1355b2f0f057SRichard Smith       return reinterpret_cast<PlacementArg *>(this + 1);
1356b2f0f057SRichard Smith     }
1357e9abe648SDaniel Jasper 
1358e9abe648SDaniel Jasper   public:
1359e9abe648SDaniel Jasper     static size_t getExtraSize(size_t NumPlacementArgs) {
1360b2f0f057SRichard Smith       return NumPlacementArgs * sizeof(PlacementArg);
1361e9abe648SDaniel Jasper     }
1362e9abe648SDaniel Jasper 
1363e9abe648SDaniel Jasper     CallDeleteDuringNew(size_t NumPlacementArgs,
1364b2f0f057SRichard Smith                         const FunctionDecl *OperatorDelete, ValueTy Ptr,
1365b2f0f057SRichard Smith                         ValueTy AllocSize, bool PassAlignmentToPlacementDelete,
1366b2f0f057SRichard Smith                         CharUnits AllocAlign)
1367b2f0f057SRichard Smith       : NumPlacementArgs(NumPlacementArgs),
1368b2f0f057SRichard Smith         PassAlignmentToPlacementDelete(PassAlignmentToPlacementDelete),
1369b2f0f057SRichard Smith         OperatorDelete(OperatorDelete), Ptr(Ptr), AllocSize(AllocSize),
1370b2f0f057SRichard Smith         AllocAlign(AllocAlign) {}
1371e9abe648SDaniel Jasper 
1372b2f0f057SRichard Smith     void setPlacementArg(unsigned I, RValueTy Arg, QualType Type) {
1373e9abe648SDaniel Jasper       assert(I < NumPlacementArgs && "index out of range");
1374b2f0f057SRichard Smith       getPlacementArgs()[I] = {Arg, Type};
1375e9abe648SDaniel Jasper     }
1376e9abe648SDaniel Jasper 
1377e9abe648SDaniel Jasper     void Emit(CodeGenFunction &CGF, Flags flags) override {
1378b2f0f057SRichard Smith       const FunctionProtoType *FPT =
1379b2f0f057SRichard Smith           OperatorDelete->getType()->getAs<FunctionProtoType>();
1380e9abe648SDaniel Jasper       CallArgList DeleteArgs;
1381824c2f53SJohn McCall 
1382189e52fcSRichard Smith       // The first argument is always a void*.
1383b2f0f057SRichard Smith       DeleteArgs.add(Traits::get(CGF, Ptr), FPT->getParamType(0));
1384189e52fcSRichard Smith 
1385b2f0f057SRichard Smith       // Figure out what other parameters we should be implicitly passing.
1386b2f0f057SRichard Smith       bool PassSize = false;
1387b2f0f057SRichard Smith       bool PassAlignment = false;
1388b2f0f057SRichard Smith       if (NumPlacementArgs) {
1389b2f0f057SRichard Smith         // A placement deallocation function is implicitly passed an alignment
1390b2f0f057SRichard Smith         // if the placement allocation function was, but is never passed a size.
1391b2f0f057SRichard Smith         PassAlignment = PassAlignmentToPlacementDelete;
1392b2f0f057SRichard Smith       } else {
1393b2f0f057SRichard Smith         // For a non-placement new-expression, 'operator delete' can take a
1394b2f0f057SRichard Smith         // size and/or an alignment if it has the right parameters.
1395b2f0f057SRichard Smith         std::tie(PassSize, PassAlignment) =
1396b2f0f057SRichard Smith             shouldPassSizeAndAlignToUsualDelete(FPT);
1397189e52fcSRichard Smith       }
1398824c2f53SJohn McCall 
1399b2f0f057SRichard Smith       // The second argument can be a std::size_t (for non-placement delete).
1400b2f0f057SRichard Smith       if (PassSize)
1401b2f0f057SRichard Smith         DeleteArgs.add(Traits::get(CGF, AllocSize),
1402b2f0f057SRichard Smith                        CGF.getContext().getSizeType());
1403824c2f53SJohn McCall 
1404b2f0f057SRichard Smith       // The next (second or third) argument can be a std::align_val_t, which
1405b2f0f057SRichard Smith       // is an enum whose underlying type is std::size_t.
1406b2f0f057SRichard Smith       // FIXME: Use the right type as the parameter type. Note that in a call
1407b2f0f057SRichard Smith       // to operator delete(size_t, ...), we may not have it available.
1408b2f0f057SRichard Smith       if (PassAlignment)
1409b2f0f057SRichard Smith         DeleteArgs.add(RValue::get(llvm::ConstantInt::get(
1410b2f0f057SRichard Smith                            CGF.SizeTy, AllocAlign.getQuantity())),
1411b2f0f057SRichard Smith                        CGF.getContext().getSizeType());
14127f9c92a9SJohn McCall 
14137f9c92a9SJohn McCall       // Pass the rest of the arguments, which must match exactly.
14147f9c92a9SJohn McCall       for (unsigned I = 0; I != NumPlacementArgs; ++I) {
1415b2f0f057SRichard Smith         auto Arg = getPlacementArgs()[I];
1416b2f0f057SRichard Smith         DeleteArgs.add(Traits::get(CGF, Arg.ArgValue), Arg.ArgType);
14177f9c92a9SJohn McCall       }
14187f9c92a9SJohn McCall 
14197f9c92a9SJohn McCall       // Call 'operator delete'.
14208d0dc31dSRichard Smith       EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
14217f9c92a9SJohn McCall     }
14227f9c92a9SJohn McCall   };
1423ab9db510SAlexander Kornienko }
14247f9c92a9SJohn McCall 
14257f9c92a9SJohn McCall /// Enter a cleanup to call 'operator delete' if the initializer in a
14267f9c92a9SJohn McCall /// new-expression throws.
14277f9c92a9SJohn McCall static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
14287f9c92a9SJohn McCall                                   const CXXNewExpr *E,
14297f416cc4SJohn McCall                                   Address NewPtr,
14307f9c92a9SJohn McCall                                   llvm::Value *AllocSize,
1431b2f0f057SRichard Smith                                   CharUnits AllocAlign,
14327f9c92a9SJohn McCall                                   const CallArgList &NewArgs) {
1433b2f0f057SRichard Smith   unsigned NumNonPlacementArgs = E->passAlignment() ? 2 : 1;
1434b2f0f057SRichard Smith 
14357f9c92a9SJohn McCall   // If we're not inside a conditional branch, then the cleanup will
14367f9c92a9SJohn McCall   // dominate and we can do the easier (and more efficient) thing.
14377f9c92a9SJohn McCall   if (!CGF.isInConditionalBranch()) {
1438b2f0f057SRichard Smith     struct DirectCleanupTraits {
1439b2f0f057SRichard Smith       typedef llvm::Value *ValueTy;
1440b2f0f057SRichard Smith       typedef RValue RValueTy;
1441b2f0f057SRichard Smith       static RValue get(CodeGenFunction &, ValueTy V) { return RValue::get(V); }
1442b2f0f057SRichard Smith       static RValue get(CodeGenFunction &, RValueTy V) { return V; }
1443b2f0f057SRichard Smith     };
1444b2f0f057SRichard Smith 
1445b2f0f057SRichard Smith     typedef CallDeleteDuringNew<DirectCleanupTraits> DirectCleanup;
1446b2f0f057SRichard Smith 
1447b2f0f057SRichard Smith     DirectCleanup *Cleanup = CGF.EHStack
1448b2f0f057SRichard Smith       .pushCleanupWithExtra<DirectCleanup>(EHCleanup,
14497f9c92a9SJohn McCall                                            E->getNumPlacementArgs(),
14507f9c92a9SJohn McCall                                            E->getOperatorDelete(),
14517f416cc4SJohn McCall                                            NewPtr.getPointer(),
1452b2f0f057SRichard Smith                                            AllocSize,
1453b2f0f057SRichard Smith                                            E->passAlignment(),
1454b2f0f057SRichard Smith                                            AllocAlign);
1455b2f0f057SRichard Smith     for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
1456b2f0f057SRichard Smith       auto &Arg = NewArgs[I + NumNonPlacementArgs];
1457b2f0f057SRichard Smith       Cleanup->setPlacementArg(I, Arg.RV, Arg.Ty);
1458b2f0f057SRichard Smith     }
14597f9c92a9SJohn McCall 
14607f9c92a9SJohn McCall     return;
14617f9c92a9SJohn McCall   }
14627f9c92a9SJohn McCall 
14637f9c92a9SJohn McCall   // Otherwise, we need to save all this stuff.
1464cb5f77f0SJohn McCall   DominatingValue<RValue>::saved_type SavedNewPtr =
14657f416cc4SJohn McCall     DominatingValue<RValue>::save(CGF, RValue::get(NewPtr.getPointer()));
1466cb5f77f0SJohn McCall   DominatingValue<RValue>::saved_type SavedAllocSize =
1467cb5f77f0SJohn McCall     DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
14687f9c92a9SJohn McCall 
1469b2f0f057SRichard Smith   struct ConditionalCleanupTraits {
1470b2f0f057SRichard Smith     typedef DominatingValue<RValue>::saved_type ValueTy;
1471b2f0f057SRichard Smith     typedef DominatingValue<RValue>::saved_type RValueTy;
1472b2f0f057SRichard Smith     static RValue get(CodeGenFunction &CGF, ValueTy V) {
1473b2f0f057SRichard Smith       return V.restore(CGF);
1474b2f0f057SRichard Smith     }
1475b2f0f057SRichard Smith   };
1476b2f0f057SRichard Smith   typedef CallDeleteDuringNew<ConditionalCleanupTraits> ConditionalCleanup;
1477b2f0f057SRichard Smith 
1478b2f0f057SRichard Smith   ConditionalCleanup *Cleanup = CGF.EHStack
1479b2f0f057SRichard Smith     .pushCleanupWithExtra<ConditionalCleanup>(EHCleanup,
14807f9c92a9SJohn McCall                                               E->getNumPlacementArgs(),
14817f9c92a9SJohn McCall                                               E->getOperatorDelete(),
14827f9c92a9SJohn McCall                                               SavedNewPtr,
1483b2f0f057SRichard Smith                                               SavedAllocSize,
1484b2f0f057SRichard Smith                                               E->passAlignment(),
1485b2f0f057SRichard Smith                                               AllocAlign);
1486b2f0f057SRichard Smith   for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
1487b2f0f057SRichard Smith     auto &Arg = NewArgs[I + NumNonPlacementArgs];
1488b2f0f057SRichard Smith     Cleanup->setPlacementArg(I, DominatingValue<RValue>::save(CGF, Arg.RV),
1489b2f0f057SRichard Smith                              Arg.Ty);
1490b2f0f057SRichard Smith   }
14917f9c92a9SJohn McCall 
1492f4beacd0SJohn McCall   CGF.initFullExprCleanup();
1493824c2f53SJohn McCall }
1494824c2f53SJohn McCall 
149559486a2dSAnders Carlsson llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
149675f9498aSJohn McCall   // The element type being allocated.
149775f9498aSJohn McCall   QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
14988ed55a54SJohn McCall 
149975f9498aSJohn McCall   // 1. Build a call to the allocation function.
150075f9498aSJohn McCall   FunctionDecl *allocator = E->getOperatorNew();
150159486a2dSAnders Carlsson 
1502f862eb6aSSebastian Redl   // If there is a brace-initializer, cannot allocate fewer elements than inits.
1503f862eb6aSSebastian Redl   unsigned minElements = 0;
1504f862eb6aSSebastian Redl   if (E->isArray() && E->hasInitializer()) {
15050511d23aSRichard Smith     const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer());
15060511d23aSRichard Smith     if (ILE && ILE->isStringLiteralInit())
15070511d23aSRichard Smith       minElements =
15080511d23aSRichard Smith           cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe())
15090511d23aSRichard Smith               ->getSize().getZExtValue();
15100511d23aSRichard Smith     else if (ILE)
1511f862eb6aSSebastian Redl       minElements = ILE->getNumInits();
1512f862eb6aSSebastian Redl   }
1513f862eb6aSSebastian Redl 
15148a13c418SCraig Topper   llvm::Value *numElements = nullptr;
15158a13c418SCraig Topper   llvm::Value *allocSizeWithoutCookie = nullptr;
151675f9498aSJohn McCall   llvm::Value *allocSize =
1517f862eb6aSSebastian Redl     EmitCXXNewAllocSize(*this, E, minElements, numElements,
1518f862eb6aSSebastian Redl                         allocSizeWithoutCookie);
1519b2f0f057SRichard Smith   CharUnits allocAlign = getContext().getTypeAlignInChars(allocType);
152059486a2dSAnders Carlsson 
15217f416cc4SJohn McCall   // Emit the allocation call.  If the allocator is a global placement
15227f416cc4SJohn McCall   // operator, just "inline" it directly.
15237f416cc4SJohn McCall   Address allocation = Address::invalid();
15247f416cc4SJohn McCall   CallArgList allocatorArgs;
15257f416cc4SJohn McCall   if (allocator->isReservedGlobalPlacementOperator()) {
152653dcf94dSJohn McCall     assert(E->getNumPlacementArgs() == 1);
152753dcf94dSJohn McCall     const Expr *arg = *E->placement_arguments().begin();
152853dcf94dSJohn McCall 
15297f416cc4SJohn McCall     AlignmentSource alignSource;
153053dcf94dSJohn McCall     allocation = EmitPointerWithAlignment(arg, &alignSource);
15317f416cc4SJohn McCall 
15327f416cc4SJohn McCall     // The pointer expression will, in many cases, be an opaque void*.
15337f416cc4SJohn McCall     // In these cases, discard the computed alignment and use the
15347f416cc4SJohn McCall     // formal alignment of the allocated type.
1535b2f0f057SRichard Smith     if (alignSource != AlignmentSource::Decl)
1536b2f0f057SRichard Smith       allocation = Address(allocation.getPointer(), allocAlign);
15377f416cc4SJohn McCall 
153853dcf94dSJohn McCall     // Set up allocatorArgs for the call to operator delete if it's not
153953dcf94dSJohn McCall     // the reserved global operator.
154053dcf94dSJohn McCall     if (E->getOperatorDelete() &&
154153dcf94dSJohn McCall         !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
154253dcf94dSJohn McCall       allocatorArgs.add(RValue::get(allocSize), getContext().getSizeType());
154353dcf94dSJohn McCall       allocatorArgs.add(RValue::get(allocation.getPointer()), arg->getType());
154453dcf94dSJohn McCall     }
154553dcf94dSJohn McCall 
15467f416cc4SJohn McCall   } else {
15477f416cc4SJohn McCall     const FunctionProtoType *allocatorType =
15487f416cc4SJohn McCall       allocator->getType()->castAs<FunctionProtoType>();
1549b2f0f057SRichard Smith     unsigned ParamsToSkip = 0;
15507f416cc4SJohn McCall 
15517f416cc4SJohn McCall     // The allocation size is the first argument.
15527f416cc4SJohn McCall     QualType sizeType = getContext().getSizeType();
155343dca6a8SEli Friedman     allocatorArgs.add(RValue::get(allocSize), sizeType);
1554b2f0f057SRichard Smith     ++ParamsToSkip;
155559486a2dSAnders Carlsson 
1556b2f0f057SRichard Smith     if (allocSize != allocSizeWithoutCookie) {
1557b2f0f057SRichard Smith       CharUnits cookieAlign = getSizeAlign(); // FIXME: Ask the ABI.
1558b2f0f057SRichard Smith       allocAlign = std::max(allocAlign, cookieAlign);
1559b2f0f057SRichard Smith     }
1560b2f0f057SRichard Smith 
1561b2f0f057SRichard Smith     // The allocation alignment may be passed as the second argument.
1562b2f0f057SRichard Smith     if (E->passAlignment()) {
1563b2f0f057SRichard Smith       QualType AlignValT = sizeType;
1564b2f0f057SRichard Smith       if (allocatorType->getNumParams() > 1) {
1565b2f0f057SRichard Smith         AlignValT = allocatorType->getParamType(1);
1566b2f0f057SRichard Smith         assert(getContext().hasSameUnqualifiedType(
1567b2f0f057SRichard Smith                    AlignValT->castAs<EnumType>()->getDecl()->getIntegerType(),
1568b2f0f057SRichard Smith                    sizeType) &&
1569b2f0f057SRichard Smith                "wrong type for alignment parameter");
1570b2f0f057SRichard Smith         ++ParamsToSkip;
1571b2f0f057SRichard Smith       } else {
1572b2f0f057SRichard Smith         // Corner case, passing alignment to 'operator new(size_t, ...)'.
1573b2f0f057SRichard Smith         assert(allocator->isVariadic() && "can't pass alignment to allocator");
1574b2f0f057SRichard Smith       }
1575b2f0f057SRichard Smith       allocatorArgs.add(
1576b2f0f057SRichard Smith           RValue::get(llvm::ConstantInt::get(SizeTy, allocAlign.getQuantity())),
1577b2f0f057SRichard Smith           AlignValT);
1578b2f0f057SRichard Smith     }
1579b2f0f057SRichard Smith 
1580b2f0f057SRichard Smith     // FIXME: Why do we not pass a CalleeDecl here?
1581f05779e2SDavid Blaikie     EmitCallArgs(allocatorArgs, allocatorType, E->placement_arguments(),
1582*ed00ea08SVedant Kumar                  /*AC*/AbstractCallee(), /*ParamsToSkip*/ParamsToSkip);
158359486a2dSAnders Carlsson 
15847f416cc4SJohn McCall     RValue RV =
15857f416cc4SJohn McCall       EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
15867f416cc4SJohn McCall 
1587b2f0f057SRichard Smith     // If this was a call to a global replaceable allocation function that does
1588b2f0f057SRichard Smith     // not take an alignment argument, the allocator is known to produce
1589b2f0f057SRichard Smith     // storage that's suitably aligned for any object that fits, up to a known
1590b2f0f057SRichard Smith     // threshold. Otherwise assume it's suitably aligned for the allocated type.
1591b2f0f057SRichard Smith     CharUnits allocationAlign = allocAlign;
1592b2f0f057SRichard Smith     if (!E->passAlignment() &&
1593b2f0f057SRichard Smith         allocator->isReplaceableGlobalAllocationFunction()) {
1594b2f0f057SRichard Smith       unsigned AllocatorAlign = llvm::PowerOf2Floor(std::min<uint64_t>(
1595b2f0f057SRichard Smith           Target.getNewAlign(), getContext().getTypeSize(allocType)));
1596b2f0f057SRichard Smith       allocationAlign = std::max(
1597b2f0f057SRichard Smith           allocationAlign, getContext().toCharUnitsFromBits(AllocatorAlign));
15987f416cc4SJohn McCall     }
15997f416cc4SJohn McCall 
16007f416cc4SJohn McCall     allocation = Address(RV.getScalarVal(), allocationAlign);
16017ec4b434SJohn McCall   }
160259486a2dSAnders Carlsson 
160375f9498aSJohn McCall   // Emit a null check on the allocation result if the allocation
160475f9498aSJohn McCall   // function is allowed to return null (because it has a non-throwing
1605902a0238SRichard Smith   // exception spec or is the reserved placement new) and we have an
160675f9498aSJohn McCall   // interesting initializer.
1607902a0238SRichard Smith   bool nullCheck = E->shouldNullCheckAllocation(getContext()) &&
16086047f07eSSebastian Redl     (!allocType.isPODType(getContext()) || E->hasInitializer());
160959486a2dSAnders Carlsson 
16108a13c418SCraig Topper   llvm::BasicBlock *nullCheckBB = nullptr;
16118a13c418SCraig Topper   llvm::BasicBlock *contBB = nullptr;
161259486a2dSAnders Carlsson 
1613f7dcf320SJohn McCall   // The null-check means that the initializer is conditionally
1614f7dcf320SJohn McCall   // evaluated.
1615f7dcf320SJohn McCall   ConditionalEvaluation conditional(*this);
1616f7dcf320SJohn McCall 
161775f9498aSJohn McCall   if (nullCheck) {
1618f7dcf320SJohn McCall     conditional.begin(*this);
161975f9498aSJohn McCall 
162075f9498aSJohn McCall     nullCheckBB = Builder.GetInsertBlock();
162175f9498aSJohn McCall     llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
162275f9498aSJohn McCall     contBB = createBasicBlock("new.cont");
162375f9498aSJohn McCall 
16247f416cc4SJohn McCall     llvm::Value *isNull =
16257f416cc4SJohn McCall       Builder.CreateIsNull(allocation.getPointer(), "new.isnull");
162675f9498aSJohn McCall     Builder.CreateCondBr(isNull, contBB, notNullBB);
162775f9498aSJohn McCall     EmitBlock(notNullBB);
162859486a2dSAnders Carlsson   }
162959486a2dSAnders Carlsson 
1630824c2f53SJohn McCall   // If there's an operator delete, enter a cleanup to call it if an
1631824c2f53SJohn McCall   // exception is thrown.
163275f9498aSJohn McCall   EHScopeStack::stable_iterator operatorDeleteCleanup;
16338a13c418SCraig Topper   llvm::Instruction *cleanupDominator = nullptr;
16347ec4b434SJohn McCall   if (E->getOperatorDelete() &&
16357ec4b434SJohn McCall       !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
1636b2f0f057SRichard Smith     EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocAlign,
1637b2f0f057SRichard Smith                           allocatorArgs);
163875f9498aSJohn McCall     operatorDeleteCleanup = EHStack.stable_begin();
1639f4beacd0SJohn McCall     cleanupDominator = Builder.CreateUnreachable();
1640824c2f53SJohn McCall   }
1641824c2f53SJohn McCall 
1642cf9b1f65SEli Friedman   assert((allocSize == allocSizeWithoutCookie) ==
1643cf9b1f65SEli Friedman          CalculateCookiePadding(*this, E).isZero());
1644cf9b1f65SEli Friedman   if (allocSize != allocSizeWithoutCookie) {
1645cf9b1f65SEli Friedman     assert(E->isArray());
1646cf9b1f65SEli Friedman     allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1647cf9b1f65SEli Friedman                                                        numElements,
1648cf9b1f65SEli Friedman                                                        E, allocType);
1649cf9b1f65SEli Friedman   }
1650cf9b1f65SEli Friedman 
1651fb901c7aSDavid Blaikie   llvm::Type *elementTy = ConvertTypeForMem(allocType);
16527f416cc4SJohn McCall   Address result = Builder.CreateElementBitCast(allocation, elementTy);
1653824c2f53SJohn McCall 
1654338c9d0aSPiotr Padlewski   // Passing pointer through invariant.group.barrier to avoid propagation of
1655338c9d0aSPiotr Padlewski   // vptrs information which may be included in previous type.
1656338c9d0aSPiotr Padlewski   if (CGM.getCodeGenOpts().StrictVTablePointers &&
1657338c9d0aSPiotr Padlewski       CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1658338c9d0aSPiotr Padlewski       allocator->isReservedGlobalPlacementOperator())
1659338c9d0aSPiotr Padlewski     result = Address(Builder.CreateInvariantGroupBarrier(result.getPointer()),
1660338c9d0aSPiotr Padlewski                      result.getAlignment());
1661338c9d0aSPiotr Padlewski 
1662fb901c7aSDavid Blaikie   EmitNewInitializer(*this, E, allocType, elementTy, result, numElements,
166399210dc9SJohn McCall                      allocSizeWithoutCookie);
16648ed55a54SJohn McCall   if (E->isArray()) {
16658ed55a54SJohn McCall     // NewPtr is a pointer to the base element type.  If we're
16668ed55a54SJohn McCall     // allocating an array of arrays, we'll need to cast back to the
16678ed55a54SJohn McCall     // array pointer type.
16682192fe50SChris Lattner     llvm::Type *resultType = ConvertTypeForMem(E->getType());
16697f416cc4SJohn McCall     if (result.getType() != resultType)
167075f9498aSJohn McCall       result = Builder.CreateBitCast(result, resultType);
167147b4629bSFariborz Jahanian   }
167259486a2dSAnders Carlsson 
1673824c2f53SJohn McCall   // Deactivate the 'operator delete' cleanup if we finished
1674824c2f53SJohn McCall   // initialization.
1675f4beacd0SJohn McCall   if (operatorDeleteCleanup.isValid()) {
1676f4beacd0SJohn McCall     DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1677f4beacd0SJohn McCall     cleanupDominator->eraseFromParent();
1678f4beacd0SJohn McCall   }
1679824c2f53SJohn McCall 
16807f416cc4SJohn McCall   llvm::Value *resultPtr = result.getPointer();
168175f9498aSJohn McCall   if (nullCheck) {
1682f7dcf320SJohn McCall     conditional.end(*this);
1683f7dcf320SJohn McCall 
168475f9498aSJohn McCall     llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
168575f9498aSJohn McCall     EmitBlock(contBB);
168659486a2dSAnders Carlsson 
16877f416cc4SJohn McCall     llvm::PHINode *PHI = Builder.CreatePHI(resultPtr->getType(), 2);
16887f416cc4SJohn McCall     PHI->addIncoming(resultPtr, notNullBB);
16897f416cc4SJohn McCall     PHI->addIncoming(llvm::Constant::getNullValue(resultPtr->getType()),
169075f9498aSJohn McCall                      nullCheckBB);
169159486a2dSAnders Carlsson 
16927f416cc4SJohn McCall     resultPtr = PHI;
169359486a2dSAnders Carlsson   }
169459486a2dSAnders Carlsson 
16957f416cc4SJohn McCall   return resultPtr;
169659486a2dSAnders Carlsson }
169759486a2dSAnders Carlsson 
169859486a2dSAnders Carlsson void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1699b2f0f057SRichard Smith                                      llvm::Value *Ptr, QualType DeleteTy,
1700b2f0f057SRichard Smith                                      llvm::Value *NumElements,
1701b2f0f057SRichard Smith                                      CharUnits CookieSize) {
1702b2f0f057SRichard Smith   assert((!NumElements && CookieSize.isZero()) ||
1703b2f0f057SRichard Smith          DeleteFD->getOverloadedOperator() == OO_Array_Delete);
17048ed55a54SJohn McCall 
170559486a2dSAnders Carlsson   const FunctionProtoType *DeleteFTy =
170659486a2dSAnders Carlsson     DeleteFD->getType()->getAs<FunctionProtoType>();
170759486a2dSAnders Carlsson 
170859486a2dSAnders Carlsson   CallArgList DeleteArgs;
170959486a2dSAnders Carlsson 
1710b2f0f057SRichard Smith   std::pair<bool, bool> PassSizeAndAlign =
1711b2f0f057SRichard Smith       shouldPassSizeAndAlignToUsualDelete(DeleteFTy);
171221122cf6SAnders Carlsson 
1713b2f0f057SRichard Smith   auto ParamTypeIt = DeleteFTy->param_type_begin();
1714b2f0f057SRichard Smith 
1715b2f0f057SRichard Smith   // Pass the pointer itself.
1716b2f0f057SRichard Smith   QualType ArgTy = *ParamTypeIt++;
171759486a2dSAnders Carlsson   llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
171843dca6a8SEli Friedman   DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
171959486a2dSAnders Carlsson 
1720b2f0f057SRichard Smith   // Pass the size if the delete function has a size_t parameter.
1721b2f0f057SRichard Smith   if (PassSizeAndAlign.first) {
1722b2f0f057SRichard Smith     QualType SizeType = *ParamTypeIt++;
1723b2f0f057SRichard Smith     CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1724b2f0f057SRichard Smith     llvm::Value *Size = llvm::ConstantInt::get(ConvertType(SizeType),
1725b2f0f057SRichard Smith                                                DeleteTypeSize.getQuantity());
1726b2f0f057SRichard Smith 
1727b2f0f057SRichard Smith     // For array new, multiply by the number of elements.
1728b2f0f057SRichard Smith     if (NumElements)
1729b2f0f057SRichard Smith       Size = Builder.CreateMul(Size, NumElements);
1730b2f0f057SRichard Smith 
1731b2f0f057SRichard Smith     // If there is a cookie, add the cookie size.
1732b2f0f057SRichard Smith     if (!CookieSize.isZero())
1733b2f0f057SRichard Smith       Size = Builder.CreateAdd(
1734b2f0f057SRichard Smith           Size, llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity()));
1735b2f0f057SRichard Smith 
1736b2f0f057SRichard Smith     DeleteArgs.add(RValue::get(Size), SizeType);
1737b2f0f057SRichard Smith   }
1738b2f0f057SRichard Smith 
1739b2f0f057SRichard Smith   // Pass the alignment if the delete function has an align_val_t parameter.
1740b2f0f057SRichard Smith   if (PassSizeAndAlign.second) {
1741b2f0f057SRichard Smith     QualType AlignValType = *ParamTypeIt++;
1742b2f0f057SRichard Smith     CharUnits DeleteTypeAlign = getContext().toCharUnitsFromBits(
1743b2f0f057SRichard Smith         getContext().getTypeAlignIfKnown(DeleteTy));
1744b2f0f057SRichard Smith     llvm::Value *Align = llvm::ConstantInt::get(ConvertType(AlignValType),
1745b2f0f057SRichard Smith                                                 DeleteTypeAlign.getQuantity());
1746b2f0f057SRichard Smith     DeleteArgs.add(RValue::get(Align), AlignValType);
1747b2f0f057SRichard Smith   }
1748b2f0f057SRichard Smith 
1749b2f0f057SRichard Smith   assert(ParamTypeIt == DeleteFTy->param_type_end() &&
1750b2f0f057SRichard Smith          "unknown parameter to usual delete function");
175159486a2dSAnders Carlsson 
175259486a2dSAnders Carlsson   // Emit the call to delete.
17538d0dc31dSRichard Smith   EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
175459486a2dSAnders Carlsson }
175559486a2dSAnders Carlsson 
17568ed55a54SJohn McCall namespace {
17578ed55a54SJohn McCall   /// Calls the given 'operator delete' on a single object.
17587e70d680SDavid Blaikie   struct CallObjectDelete final : EHScopeStack::Cleanup {
17598ed55a54SJohn McCall     llvm::Value *Ptr;
17608ed55a54SJohn McCall     const FunctionDecl *OperatorDelete;
17618ed55a54SJohn McCall     QualType ElementType;
17628ed55a54SJohn McCall 
17638ed55a54SJohn McCall     CallObjectDelete(llvm::Value *Ptr,
17648ed55a54SJohn McCall                      const FunctionDecl *OperatorDelete,
17658ed55a54SJohn McCall                      QualType ElementType)
17668ed55a54SJohn McCall       : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
17678ed55a54SJohn McCall 
17684f12f10dSCraig Topper     void Emit(CodeGenFunction &CGF, Flags flags) override {
17698ed55a54SJohn McCall       CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
17708ed55a54SJohn McCall     }
17718ed55a54SJohn McCall   };
1772ab9db510SAlexander Kornienko }
17738ed55a54SJohn McCall 
17740c0b6d9aSDavid Majnemer void
17750c0b6d9aSDavid Majnemer CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
17760c0b6d9aSDavid Majnemer                                              llvm::Value *CompletePtr,
17770c0b6d9aSDavid Majnemer                                              QualType ElementType) {
17780c0b6d9aSDavid Majnemer   EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr,
17790c0b6d9aSDavid Majnemer                                         OperatorDelete, ElementType);
17800c0b6d9aSDavid Majnemer }
17810c0b6d9aSDavid Majnemer 
17828ed55a54SJohn McCall /// Emit the code for deleting a single object.
17838ed55a54SJohn McCall static void EmitObjectDelete(CodeGenFunction &CGF,
17840868137aSDavid Majnemer                              const CXXDeleteExpr *DE,
17857f416cc4SJohn McCall                              Address Ptr,
17860868137aSDavid Majnemer                              QualType ElementType) {
1787d98f5d78SIvan Krasin   // C++11 [expr.delete]p3:
1788d98f5d78SIvan Krasin   //   If the static type of the object to be deleted is different from its
1789d98f5d78SIvan Krasin   //   dynamic type, the static type shall be a base class of the dynamic type
1790d98f5d78SIvan Krasin   //   of the object to be deleted and the static type shall have a virtual
1791d98f5d78SIvan Krasin   //   destructor or the behavior is undefined.
1792d98f5d78SIvan Krasin   CGF.EmitTypeCheck(CodeGenFunction::TCK_MemberCall,
1793d98f5d78SIvan Krasin                     DE->getExprLoc(), Ptr.getPointer(),
1794d98f5d78SIvan Krasin                     ElementType);
1795d98f5d78SIvan Krasin 
17968ed55a54SJohn McCall   // Find the destructor for the type, if applicable.  If the
17978ed55a54SJohn McCall   // destructor is virtual, we'll just emit the vcall and return.
17988a13c418SCraig Topper   const CXXDestructorDecl *Dtor = nullptr;
17998ed55a54SJohn McCall   if (const RecordType *RT = ElementType->getAs<RecordType>()) {
18008ed55a54SJohn McCall     CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1801b23533dbSEli Friedman     if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
18028ed55a54SJohn McCall       Dtor = RD->getDestructor();
18038ed55a54SJohn McCall 
18048ed55a54SJohn McCall       if (Dtor->isVirtual()) {
18050868137aSDavid Majnemer         CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
18060868137aSDavid Majnemer                                                     Dtor);
18078ed55a54SJohn McCall         return;
18088ed55a54SJohn McCall       }
18098ed55a54SJohn McCall     }
18108ed55a54SJohn McCall   }
18118ed55a54SJohn McCall 
18128ed55a54SJohn McCall   // Make sure that we call delete even if the dtor throws.
1813e4df6c8dSJohn McCall   // This doesn't have to a conditional cleanup because we're going
1814e4df6c8dSJohn McCall   // to pop it off in a second.
18150868137aSDavid Majnemer   const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
18168ed55a54SJohn McCall   CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
18177f416cc4SJohn McCall                                             Ptr.getPointer(),
18187f416cc4SJohn McCall                                             OperatorDelete, ElementType);
18198ed55a54SJohn McCall 
18208ed55a54SJohn McCall   if (Dtor)
18218ed55a54SJohn McCall     CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
182261535005SDouglas Gregor                               /*ForVirtualBase=*/false,
182361535005SDouglas Gregor                               /*Delegating=*/false,
182461535005SDouglas Gregor                               Ptr);
1825460ce58fSJohn McCall   else if (auto Lifetime = ElementType.getObjCLifetime()) {
1826460ce58fSJohn McCall     switch (Lifetime) {
182731168b07SJohn McCall     case Qualifiers::OCL_None:
182831168b07SJohn McCall     case Qualifiers::OCL_ExplicitNone:
182931168b07SJohn McCall     case Qualifiers::OCL_Autoreleasing:
183031168b07SJohn McCall       break;
183131168b07SJohn McCall 
18327f416cc4SJohn McCall     case Qualifiers::OCL_Strong:
18337f416cc4SJohn McCall       CGF.EmitARCDestroyStrong(Ptr, ARCPreciseLifetime);
183431168b07SJohn McCall       break;
183531168b07SJohn McCall 
183631168b07SJohn McCall     case Qualifiers::OCL_Weak:
183731168b07SJohn McCall       CGF.EmitARCDestroyWeak(Ptr);
183831168b07SJohn McCall       break;
183931168b07SJohn McCall     }
184031168b07SJohn McCall   }
18418ed55a54SJohn McCall 
18428ed55a54SJohn McCall   CGF.PopCleanupBlock();
18438ed55a54SJohn McCall }
18448ed55a54SJohn McCall 
18458ed55a54SJohn McCall namespace {
18468ed55a54SJohn McCall   /// Calls the given 'operator delete' on an array of objects.
18477e70d680SDavid Blaikie   struct CallArrayDelete final : EHScopeStack::Cleanup {
18488ed55a54SJohn McCall     llvm::Value *Ptr;
18498ed55a54SJohn McCall     const FunctionDecl *OperatorDelete;
18508ed55a54SJohn McCall     llvm::Value *NumElements;
18518ed55a54SJohn McCall     QualType ElementType;
18528ed55a54SJohn McCall     CharUnits CookieSize;
18538ed55a54SJohn McCall 
18548ed55a54SJohn McCall     CallArrayDelete(llvm::Value *Ptr,
18558ed55a54SJohn McCall                     const FunctionDecl *OperatorDelete,
18568ed55a54SJohn McCall                     llvm::Value *NumElements,
18578ed55a54SJohn McCall                     QualType ElementType,
18588ed55a54SJohn McCall                     CharUnits CookieSize)
18598ed55a54SJohn McCall       : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
18608ed55a54SJohn McCall         ElementType(ElementType), CookieSize(CookieSize) {}
18618ed55a54SJohn McCall 
18624f12f10dSCraig Topper     void Emit(CodeGenFunction &CGF, Flags flags) override {
1863b2f0f057SRichard Smith       CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType, NumElements,
1864b2f0f057SRichard Smith                          CookieSize);
18658ed55a54SJohn McCall     }
18668ed55a54SJohn McCall   };
1867ab9db510SAlexander Kornienko }
18688ed55a54SJohn McCall 
18698ed55a54SJohn McCall /// Emit the code for deleting an array of objects.
18708ed55a54SJohn McCall static void EmitArrayDelete(CodeGenFunction &CGF,
1871284c48ffSJohn McCall                             const CXXDeleteExpr *E,
18727f416cc4SJohn McCall                             Address deletedPtr,
1873ca2c56f2SJohn McCall                             QualType elementType) {
18748a13c418SCraig Topper   llvm::Value *numElements = nullptr;
18758a13c418SCraig Topper   llvm::Value *allocatedPtr = nullptr;
1876ca2c56f2SJohn McCall   CharUnits cookieSize;
1877ca2c56f2SJohn McCall   CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1878ca2c56f2SJohn McCall                                       numElements, allocatedPtr, cookieSize);
18798ed55a54SJohn McCall 
1880ca2c56f2SJohn McCall   assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
18818ed55a54SJohn McCall 
18828ed55a54SJohn McCall   // Make sure that we call delete even if one of the dtors throws.
1883ca2c56f2SJohn McCall   const FunctionDecl *operatorDelete = E->getOperatorDelete();
18848ed55a54SJohn McCall   CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
1885ca2c56f2SJohn McCall                                            allocatedPtr, operatorDelete,
1886ca2c56f2SJohn McCall                                            numElements, elementType,
1887ca2c56f2SJohn McCall                                            cookieSize);
18888ed55a54SJohn McCall 
1889ca2c56f2SJohn McCall   // Destroy the elements.
1890ca2c56f2SJohn McCall   if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1891ca2c56f2SJohn McCall     assert(numElements && "no element count for a type with a destructor!");
189231168b07SJohn McCall 
18937f416cc4SJohn McCall     CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
18947f416cc4SJohn McCall     CharUnits elementAlign =
18957f416cc4SJohn McCall       deletedPtr.getAlignment().alignmentOfArrayElement(elementSize);
18967f416cc4SJohn McCall 
18977f416cc4SJohn McCall     llvm::Value *arrayBegin = deletedPtr.getPointer();
1898ca2c56f2SJohn McCall     llvm::Value *arrayEnd =
18997f416cc4SJohn McCall       CGF.Builder.CreateInBoundsGEP(arrayBegin, numElements, "delete.end");
190097eab0a2SJohn McCall 
190197eab0a2SJohn McCall     // Note that it is legal to allocate a zero-length array, and we
190297eab0a2SJohn McCall     // can never fold the check away because the length should always
190397eab0a2SJohn McCall     // come from a cookie.
19047f416cc4SJohn McCall     CGF.emitArrayDestroy(arrayBegin, arrayEnd, elementType, elementAlign,
1905ca2c56f2SJohn McCall                          CGF.getDestroyer(dtorKind),
190697eab0a2SJohn McCall                          /*checkZeroLength*/ true,
1907ca2c56f2SJohn McCall                          CGF.needsEHCleanup(dtorKind));
19088ed55a54SJohn McCall   }
19098ed55a54SJohn McCall 
1910ca2c56f2SJohn McCall   // Pop the cleanup block.
19118ed55a54SJohn McCall   CGF.PopCleanupBlock();
19128ed55a54SJohn McCall }
19138ed55a54SJohn McCall 
191459486a2dSAnders Carlsson void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
191559486a2dSAnders Carlsson   const Expr *Arg = E->getArgument();
19167f416cc4SJohn McCall   Address Ptr = EmitPointerWithAlignment(Arg);
191759486a2dSAnders Carlsson 
191859486a2dSAnders Carlsson   // Null check the pointer.
191959486a2dSAnders Carlsson   llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
192059486a2dSAnders Carlsson   llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
192159486a2dSAnders Carlsson 
19227f416cc4SJohn McCall   llvm::Value *IsNull = Builder.CreateIsNull(Ptr.getPointer(), "isnull");
192359486a2dSAnders Carlsson 
192459486a2dSAnders Carlsson   Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
192559486a2dSAnders Carlsson   EmitBlock(DeleteNotNull);
192659486a2dSAnders Carlsson 
19278ed55a54SJohn McCall   // We might be deleting a pointer to array.  If so, GEP down to the
19288ed55a54SJohn McCall   // first non-array element.
19298ed55a54SJohn McCall   // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
19308ed55a54SJohn McCall   QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
19318ed55a54SJohn McCall   if (DeleteTy->isConstantArrayType()) {
19328ed55a54SJohn McCall     llvm::Value *Zero = Builder.getInt32(0);
19330e62c1ccSChris Lattner     SmallVector<llvm::Value*,8> GEP;
193459486a2dSAnders Carlsson 
19358ed55a54SJohn McCall     GEP.push_back(Zero); // point at the outermost array
19368ed55a54SJohn McCall 
19378ed55a54SJohn McCall     // For each layer of array type we're pointing at:
19388ed55a54SJohn McCall     while (const ConstantArrayType *Arr
19398ed55a54SJohn McCall              = getContext().getAsConstantArrayType(DeleteTy)) {
19408ed55a54SJohn McCall       // 1. Unpeel the array type.
19418ed55a54SJohn McCall       DeleteTy = Arr->getElementType();
19428ed55a54SJohn McCall 
19438ed55a54SJohn McCall       // 2. GEP to the first element of the array.
19448ed55a54SJohn McCall       GEP.push_back(Zero);
19458ed55a54SJohn McCall     }
19468ed55a54SJohn McCall 
19477f416cc4SJohn McCall     Ptr = Address(Builder.CreateInBoundsGEP(Ptr.getPointer(), GEP, "del.first"),
19487f416cc4SJohn McCall                   Ptr.getAlignment());
19498ed55a54SJohn McCall   }
19508ed55a54SJohn McCall 
19517f416cc4SJohn McCall   assert(ConvertTypeForMem(DeleteTy) == Ptr.getElementType());
19528ed55a54SJohn McCall 
19537270ef57SReid Kleckner   if (E->isArrayForm()) {
19547270ef57SReid Kleckner     EmitArrayDelete(*this, E, Ptr, DeleteTy);
19557270ef57SReid Kleckner   } else {
19567270ef57SReid Kleckner     EmitObjectDelete(*this, E, Ptr, DeleteTy);
19577270ef57SReid Kleckner   }
195859486a2dSAnders Carlsson 
195959486a2dSAnders Carlsson   EmitBlock(DeleteEnd);
196059486a2dSAnders Carlsson }
196159486a2dSAnders Carlsson 
19621c3d95ebSDavid Majnemer static bool isGLValueFromPointerDeref(const Expr *E) {
19631c3d95ebSDavid Majnemer   E = E->IgnoreParens();
19641c3d95ebSDavid Majnemer 
19651c3d95ebSDavid Majnemer   if (const auto *CE = dyn_cast<CastExpr>(E)) {
19661c3d95ebSDavid Majnemer     if (!CE->getSubExpr()->isGLValue())
19671c3d95ebSDavid Majnemer       return false;
19681c3d95ebSDavid Majnemer     return isGLValueFromPointerDeref(CE->getSubExpr());
19691c3d95ebSDavid Majnemer   }
19701c3d95ebSDavid Majnemer 
19711c3d95ebSDavid Majnemer   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
19721c3d95ebSDavid Majnemer     return isGLValueFromPointerDeref(OVE->getSourceExpr());
19731c3d95ebSDavid Majnemer 
19741c3d95ebSDavid Majnemer   if (const auto *BO = dyn_cast<BinaryOperator>(E))
19751c3d95ebSDavid Majnemer     if (BO->getOpcode() == BO_Comma)
19761c3d95ebSDavid Majnemer       return isGLValueFromPointerDeref(BO->getRHS());
19771c3d95ebSDavid Majnemer 
19781c3d95ebSDavid Majnemer   if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E))
19791c3d95ebSDavid Majnemer     return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
19801c3d95ebSDavid Majnemer            isGLValueFromPointerDeref(ACO->getFalseExpr());
19811c3d95ebSDavid Majnemer 
19821c3d95ebSDavid Majnemer   // C++11 [expr.sub]p1:
19831c3d95ebSDavid Majnemer   //   The expression E1[E2] is identical (by definition) to *((E1)+(E2))
19841c3d95ebSDavid Majnemer   if (isa<ArraySubscriptExpr>(E))
19851c3d95ebSDavid Majnemer     return true;
19861c3d95ebSDavid Majnemer 
19871c3d95ebSDavid Majnemer   if (const auto *UO = dyn_cast<UnaryOperator>(E))
19881c3d95ebSDavid Majnemer     if (UO->getOpcode() == UO_Deref)
19891c3d95ebSDavid Majnemer       return true;
19901c3d95ebSDavid Majnemer 
19911c3d95ebSDavid Majnemer   return false;
19921c3d95ebSDavid Majnemer }
19931c3d95ebSDavid Majnemer 
1994747e301eSWarren Hunt static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
19952192fe50SChris Lattner                                          llvm::Type *StdTypeInfoPtrTy) {
1996940f02d2SAnders Carlsson   // Get the vtable pointer.
19977f416cc4SJohn McCall   Address ThisPtr = CGF.EmitLValue(E).getAddress();
1998940f02d2SAnders Carlsson 
1999940f02d2SAnders Carlsson   // C++ [expr.typeid]p2:
2000940f02d2SAnders Carlsson   //   If the glvalue expression is obtained by applying the unary * operator to
2001940f02d2SAnders Carlsson   //   a pointer and the pointer is a null pointer value, the typeid expression
2002940f02d2SAnders Carlsson   //   throws the std::bad_typeid exception.
20031c3d95ebSDavid Majnemer   //
20041c3d95ebSDavid Majnemer   // However, this paragraph's intent is not clear.  We choose a very generous
20051c3d95ebSDavid Majnemer   // interpretation which implores us to consider comma operators, conditional
20061c3d95ebSDavid Majnemer   // operators, parentheses and other such constructs.
20071162d25cSDavid Majnemer   QualType SrcRecordTy = E->getType();
20081c3d95ebSDavid Majnemer   if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(
20091c3d95ebSDavid Majnemer           isGLValueFromPointerDeref(E), SrcRecordTy)) {
2010940f02d2SAnders Carlsson     llvm::BasicBlock *BadTypeidBlock =
2011940f02d2SAnders Carlsson         CGF.createBasicBlock("typeid.bad_typeid");
20121162d25cSDavid Majnemer     llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
2013940f02d2SAnders Carlsson 
20147f416cc4SJohn McCall     llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr.getPointer());
2015940f02d2SAnders Carlsson     CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
2016940f02d2SAnders Carlsson 
2017940f02d2SAnders Carlsson     CGF.EmitBlock(BadTypeidBlock);
20181162d25cSDavid Majnemer     CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
2019940f02d2SAnders Carlsson     CGF.EmitBlock(EndBlock);
2020940f02d2SAnders Carlsson   }
2021940f02d2SAnders Carlsson 
20221162d25cSDavid Majnemer   return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
20231162d25cSDavid Majnemer                                         StdTypeInfoPtrTy);
2024940f02d2SAnders Carlsson }
2025940f02d2SAnders Carlsson 
202659486a2dSAnders Carlsson llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
20272192fe50SChris Lattner   llvm::Type *StdTypeInfoPtrTy =
2028940f02d2SAnders Carlsson     ConvertType(E->getType())->getPointerTo();
2029fd7dfeb7SAnders Carlsson 
20303f4336cbSAnders Carlsson   if (E->isTypeOperand()) {
20313f4336cbSAnders Carlsson     llvm::Constant *TypeInfo =
2032143c55eaSDavid Majnemer         CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
2033940f02d2SAnders Carlsson     return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
20343f4336cbSAnders Carlsson   }
2035fd7dfeb7SAnders Carlsson 
2036940f02d2SAnders Carlsson   // C++ [expr.typeid]p2:
2037940f02d2SAnders Carlsson   //   When typeid is applied to a glvalue expression whose type is a
2038940f02d2SAnders Carlsson   //   polymorphic class type, the result refers to a std::type_info object
2039940f02d2SAnders Carlsson   //   representing the type of the most derived object (that is, the dynamic
2040940f02d2SAnders Carlsson   //   type) to which the glvalue refers.
2041ef8bf436SRichard Smith   if (E->isPotentiallyEvaluated())
2042940f02d2SAnders Carlsson     return EmitTypeidFromVTable(*this, E->getExprOperand(),
2043940f02d2SAnders Carlsson                                 StdTypeInfoPtrTy);
2044940f02d2SAnders Carlsson 
2045940f02d2SAnders Carlsson   QualType OperandTy = E->getExprOperand()->getType();
2046940f02d2SAnders Carlsson   return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
2047940f02d2SAnders Carlsson                                StdTypeInfoPtrTy);
204859486a2dSAnders Carlsson }
204959486a2dSAnders Carlsson 
2050c1c9971cSAnders Carlsson static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
2051c1c9971cSAnders Carlsson                                           QualType DestTy) {
20522192fe50SChris Lattner   llvm::Type *DestLTy = CGF.ConvertType(DestTy);
2053c1c9971cSAnders Carlsson   if (DestTy->isPointerType())
2054c1c9971cSAnders Carlsson     return llvm::Constant::getNullValue(DestLTy);
2055c1c9971cSAnders Carlsson 
2056c1c9971cSAnders Carlsson   /// C++ [expr.dynamic.cast]p9:
2057c1c9971cSAnders Carlsson   ///   A failed cast to reference type throws std::bad_cast
20581162d25cSDavid Majnemer   if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
20591162d25cSDavid Majnemer     return nullptr;
2060c1c9971cSAnders Carlsson 
2061c1c9971cSAnders Carlsson   CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
2062c1c9971cSAnders Carlsson   return llvm::UndefValue::get(DestLTy);
2063c1c9971cSAnders Carlsson }
2064c1c9971cSAnders Carlsson 
20657f416cc4SJohn McCall llvm::Value *CodeGenFunction::EmitDynamicCast(Address ThisAddr,
206659486a2dSAnders Carlsson                                               const CXXDynamicCastExpr *DCE) {
20672bf9b4c0SAlexey Bataev   CGM.EmitExplicitCastExprType(DCE, this);
20683f4336cbSAnders Carlsson   QualType DestTy = DCE->getTypeAsWritten();
20693f4336cbSAnders Carlsson 
2070c1c9971cSAnders Carlsson   if (DCE->isAlwaysNull())
20711162d25cSDavid Majnemer     if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy))
20721162d25cSDavid Majnemer       return T;
2073c1c9971cSAnders Carlsson 
2074c1c9971cSAnders Carlsson   QualType SrcTy = DCE->getSubExpr()->getType();
2075c1c9971cSAnders Carlsson 
20761162d25cSDavid Majnemer   // C++ [expr.dynamic.cast]p7:
20771162d25cSDavid Majnemer   //   If T is "pointer to cv void," then the result is a pointer to the most
20781162d25cSDavid Majnemer   //   derived object pointed to by v.
20791162d25cSDavid Majnemer   const PointerType *DestPTy = DestTy->getAs<PointerType>();
20801162d25cSDavid Majnemer 
20811162d25cSDavid Majnemer   bool isDynamicCastToVoid;
20821162d25cSDavid Majnemer   QualType SrcRecordTy;
20831162d25cSDavid Majnemer   QualType DestRecordTy;
20841162d25cSDavid Majnemer   if (DestPTy) {
20851162d25cSDavid Majnemer     isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType();
20861162d25cSDavid Majnemer     SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
20871162d25cSDavid Majnemer     DestRecordTy = DestPTy->getPointeeType();
20881162d25cSDavid Majnemer   } else {
20891162d25cSDavid Majnemer     isDynamicCastToVoid = false;
20901162d25cSDavid Majnemer     SrcRecordTy = SrcTy;
20911162d25cSDavid Majnemer     DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
20921162d25cSDavid Majnemer   }
20931162d25cSDavid Majnemer 
20941162d25cSDavid Majnemer   assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
20951162d25cSDavid Majnemer 
2096882d790fSAnders Carlsson   // C++ [expr.dynamic.cast]p4:
2097882d790fSAnders Carlsson   //   If the value of v is a null pointer value in the pointer case, the result
2098882d790fSAnders Carlsson   //   is the null pointer value of type T.
20991162d25cSDavid Majnemer   bool ShouldNullCheckSrcValue =
21001162d25cSDavid Majnemer       CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(),
21011162d25cSDavid Majnemer                                                          SrcRecordTy);
210259486a2dSAnders Carlsson 
21038a13c418SCraig Topper   llvm::BasicBlock *CastNull = nullptr;
21048a13c418SCraig Topper   llvm::BasicBlock *CastNotNull = nullptr;
2105882d790fSAnders Carlsson   llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
2106fa8b4955SDouglas Gregor 
2107882d790fSAnders Carlsson   if (ShouldNullCheckSrcValue) {
2108882d790fSAnders Carlsson     CastNull = createBasicBlock("dynamic_cast.null");
2109882d790fSAnders Carlsson     CastNotNull = createBasicBlock("dynamic_cast.notnull");
2110882d790fSAnders Carlsson 
21117f416cc4SJohn McCall     llvm::Value *IsNull = Builder.CreateIsNull(ThisAddr.getPointer());
2112882d790fSAnders Carlsson     Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
2113882d790fSAnders Carlsson     EmitBlock(CastNotNull);
211459486a2dSAnders Carlsson   }
211559486a2dSAnders Carlsson 
21167f416cc4SJohn McCall   llvm::Value *Value;
21171162d25cSDavid Majnemer   if (isDynamicCastToVoid) {
21187f416cc4SJohn McCall     Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, ThisAddr, SrcRecordTy,
21191162d25cSDavid Majnemer                                                   DestTy);
21201162d25cSDavid Majnemer   } else {
21211162d25cSDavid Majnemer     assert(DestRecordTy->isRecordType() &&
21221162d25cSDavid Majnemer            "destination type must be a record type!");
21237f416cc4SJohn McCall     Value = CGM.getCXXABI().EmitDynamicCastCall(*this, ThisAddr, SrcRecordTy,
21241162d25cSDavid Majnemer                                                 DestTy, DestRecordTy, CastEnd);
212567528eaaSDavid Majnemer     CastNotNull = Builder.GetInsertBlock();
21261162d25cSDavid Majnemer   }
21273f4336cbSAnders Carlsson 
2128882d790fSAnders Carlsson   if (ShouldNullCheckSrcValue) {
2129882d790fSAnders Carlsson     EmitBranch(CastEnd);
213059486a2dSAnders Carlsson 
2131882d790fSAnders Carlsson     EmitBlock(CastNull);
2132882d790fSAnders Carlsson     EmitBranch(CastEnd);
213359486a2dSAnders Carlsson   }
213459486a2dSAnders Carlsson 
2135882d790fSAnders Carlsson   EmitBlock(CastEnd);
213659486a2dSAnders Carlsson 
2137882d790fSAnders Carlsson   if (ShouldNullCheckSrcValue) {
2138882d790fSAnders Carlsson     llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
2139882d790fSAnders Carlsson     PHI->addIncoming(Value, CastNotNull);
2140882d790fSAnders Carlsson     PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
214159486a2dSAnders Carlsson 
2142882d790fSAnders Carlsson     Value = PHI;
214359486a2dSAnders Carlsson   }
214459486a2dSAnders Carlsson 
2145882d790fSAnders Carlsson   return Value;
214659486a2dSAnders Carlsson }
2147c370a7eeSEli Friedman 
2148c370a7eeSEli Friedman void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
21498631f3e8SEli Friedman   RunCleanupsScope Scope(*this);
21507f416cc4SJohn McCall   LValue SlotLV = MakeAddrLValue(Slot.getAddress(), E->getType());
21518631f3e8SEli Friedman 
2152c370a7eeSEli Friedman   CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
215353c7616eSJames Y Knight   for (LambdaExpr::const_capture_init_iterator i = E->capture_init_begin(),
2154c370a7eeSEli Friedman                                                e = E->capture_init_end();
2155c370a7eeSEli Friedman        i != e; ++i, ++CurField) {
2156c370a7eeSEli Friedman     // Emit initialization
215740ed2973SDavid Blaikie     LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
215839c81e28SAlexey Bataev     if (CurField->hasCapturedVLAType()) {
215939c81e28SAlexey Bataev       auto VAT = CurField->getCapturedVLAType();
216039c81e28SAlexey Bataev       EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
216139c81e28SAlexey Bataev     } else {
216230e304e2SRichard Smith       EmitInitializerForField(*CurField, LV, *i);
2163c370a7eeSEli Friedman     }
2164c370a7eeSEli Friedman   }
216539c81e28SAlexey Bataev }
2166