159486a2dSAnders Carlsson //===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
259486a2dSAnders Carlsson //
359486a2dSAnders Carlsson //                     The LLVM Compiler Infrastructure
459486a2dSAnders Carlsson //
559486a2dSAnders Carlsson // This file is distributed under the University of Illinois Open Source
659486a2dSAnders Carlsson // License. See LICENSE.TXT for details.
759486a2dSAnders Carlsson //
859486a2dSAnders Carlsson //===----------------------------------------------------------------------===//
959486a2dSAnders Carlsson //
1059486a2dSAnders Carlsson // This contains code dealing with code generation of C++ expressions
1159486a2dSAnders Carlsson //
1259486a2dSAnders Carlsson //===----------------------------------------------------------------------===//
1359486a2dSAnders Carlsson 
1459486a2dSAnders Carlsson #include "CodeGenFunction.h"
15fe883422SPeter Collingbourne #include "CGCUDARuntime.h"
165d865c32SJohn McCall #include "CGCXXABI.h"
1791bbb554SDevang Patel #include "CGDebugInfo.h"
183a02247dSChandler Carruth #include "CGObjCRuntime.h"
19a8e7df36SMark Lacey #include "clang/CodeGen/CGFunctionInfo.h"
2010a4972aSSaleem Abdulrasool #include "clang/Frontend/CodeGenOptions.h"
21c80ceea9SChandler Carruth #include "llvm/IR/CallSite.h"
22ffd5551bSChandler Carruth #include "llvm/IR/Intrinsics.h"
23bbe277c4SAnders Carlsson 
2459486a2dSAnders Carlsson using namespace clang;
2559486a2dSAnders Carlsson using namespace CodeGen;
2659486a2dSAnders Carlsson 
27efa956ceSAlexey Samsonov static RequiredArgs
28efa956ceSAlexey Samsonov commonEmitCXXMemberOrOperatorCall(CodeGenFunction &CGF, const CXXMethodDecl *MD,
29efa956ceSAlexey Samsonov                                   llvm::Value *This, llvm::Value *ImplicitParam,
30efa956ceSAlexey Samsonov                                   QualType ImplicitParamTy, const CallExpr *CE,
31762672a7SRichard Smith                                   CallArgList &Args, CallArgList *RtlArgs) {
32a5bf76bdSAlexey Samsonov   assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) ||
33a5bf76bdSAlexey Samsonov          isa<CXXOperatorCallExpr>(CE));
3427da15baSAnders Carlsson   assert(MD->isInstance() &&
35a5bf76bdSAlexey Samsonov          "Trying to emit a member or operator call expr on a static method!");
36034e7270SReid Kleckner   ASTContext &C = CGF.getContext();
3727da15baSAnders Carlsson 
3869d0d262SRichard Smith   // C++11 [class.mfct.non-static]p2:
3969d0d262SRichard Smith   //   If a non-static member function of a class X is called for an object that
4069d0d262SRichard Smith   //   is not of type X, or of a type derived from X, the behavior is undefined.
41a5bf76bdSAlexey Samsonov   SourceLocation CallLoc;
42a5bf76bdSAlexey Samsonov   if (CE)
43a5bf76bdSAlexey Samsonov     CallLoc = CE->getExprLoc();
44034e7270SReid Kleckner   CGF.EmitTypeCheck(isa<CXXConstructorDecl>(MD)
45034e7270SReid Kleckner                         ? CodeGenFunction::TCK_ConstructorCall
460c0b6d9aSDavid Majnemer                         : CodeGenFunction::TCK_MemberCall,
47034e7270SReid Kleckner                     CallLoc, This, C.getRecordType(MD->getParent()));
4827da15baSAnders Carlsson 
4927da15baSAnders Carlsson   // Push the this ptr.
50034e7270SReid Kleckner   const CXXRecordDecl *RD =
51034e7270SReid Kleckner       CGF.CGM.getCXXABI().getThisArgumentTypeForMethod(MD);
52034e7270SReid Kleckner   Args.add(RValue::get(This),
53034e7270SReid Kleckner            RD ? C.getPointerType(C.getTypeDeclType(RD)) : C.VoidPtrTy);
5427da15baSAnders Carlsson 
55ee6bc533STimur Iskhodzhanov   // If there is an implicit parameter (e.g. VTT), emit it.
56ee6bc533STimur Iskhodzhanov   if (ImplicitParam) {
57ee6bc533STimur Iskhodzhanov     Args.add(RValue::get(ImplicitParam), ImplicitParamTy);
58e36a6b3eSAnders Carlsson   }
59e36a6b3eSAnders Carlsson 
60a729c62bSJohn McCall   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
61419996ccSGeorge Burgess IV   RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size(), MD);
62a729c62bSJohn McCall 
63a729c62bSJohn McCall   // And the rest of the call args.
64762672a7SRichard Smith   if (RtlArgs) {
65762672a7SRichard Smith     // Special case: if the caller emitted the arguments right-to-left already
66762672a7SRichard Smith     // (prior to emitting the *this argument), we're done. This happens for
67762672a7SRichard Smith     // assignment operators.
68762672a7SRichard Smith     Args.addFrom(*RtlArgs);
69762672a7SRichard Smith   } else if (CE) {
70a5bf76bdSAlexey Samsonov     // Special case: skip first argument of CXXOperatorCall (it is "this").
718e1162c7SAlexey Samsonov     unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0;
72f05779e2SDavid Blaikie     CGF.EmitCallArgs(Args, FPT, drop_begin(CE->arguments(), ArgsToSkip),
738e1162c7SAlexey Samsonov                      CE->getDirectCallee());
74a5bf76bdSAlexey Samsonov   } else {
758e1162c7SAlexey Samsonov     assert(
768e1162c7SAlexey Samsonov         FPT->getNumParams() == 0 &&
778e1162c7SAlexey Samsonov         "No CallExpr specified for function with non-zero number of arguments");
78a5bf76bdSAlexey Samsonov   }
790c0b6d9aSDavid Majnemer   return required;
800c0b6d9aSDavid Majnemer }
8127da15baSAnders Carlsson 
820c0b6d9aSDavid Majnemer RValue CodeGenFunction::EmitCXXMemberOrOperatorCall(
830c0b6d9aSDavid Majnemer     const CXXMethodDecl *MD, llvm::Value *Callee, ReturnValueSlot ReturnValue,
840c0b6d9aSDavid Majnemer     llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,
85762672a7SRichard Smith     const CallExpr *CE, CallArgList *RtlArgs) {
860c0b6d9aSDavid Majnemer   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
870c0b6d9aSDavid Majnemer   CallArgList Args;
880c0b6d9aSDavid Majnemer   RequiredArgs required = commonEmitCXXMemberOrOperatorCall(
89762672a7SRichard Smith       *this, MD, This, ImplicitParam, ImplicitParamTy, CE, Args, RtlArgs);
908dda7b27SJohn McCall   return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
91c50c27ccSRafael Espindola                   Callee, ReturnValue, Args, MD);
9227da15baSAnders Carlsson }
9327da15baSAnders Carlsson 
94ae81bbb4SAlexey Samsonov RValue CodeGenFunction::EmitCXXDestructorCall(
95ae81bbb4SAlexey Samsonov     const CXXDestructorDecl *DD, llvm::Value *Callee, llvm::Value *This,
96ae81bbb4SAlexey Samsonov     llvm::Value *ImplicitParam, QualType ImplicitParamTy, const CallExpr *CE,
97ae81bbb4SAlexey Samsonov     StructorType Type) {
980c0b6d9aSDavid Majnemer   CallArgList Args;
99ae81bbb4SAlexey Samsonov   commonEmitCXXMemberOrOperatorCall(*this, DD, This, ImplicitParam,
100762672a7SRichard Smith                                     ImplicitParamTy, CE, Args, nullptr);
101ae81bbb4SAlexey Samsonov   return EmitCall(CGM.getTypes().arrangeCXXStructorDeclaration(DD, Type),
102ae81bbb4SAlexey Samsonov                   Callee, ReturnValueSlot(), Args, DD);
1030c0b6d9aSDavid Majnemer }
1040c0b6d9aSDavid Majnemer 
1053b33c4ecSRafael Espindola static CXXRecordDecl *getCXXRecord(const Expr *E) {
1063b33c4ecSRafael Espindola   QualType T = E->getType();
1073b33c4ecSRafael Espindola   if (const PointerType *PTy = T->getAs<PointerType>())
1083b33c4ecSRafael Espindola     T = PTy->getPointeeType();
1093b33c4ecSRafael Espindola   const RecordType *Ty = T->castAs<RecordType>();
1103b33c4ecSRafael Espindola   return cast<CXXRecordDecl>(Ty->getDecl());
1113b33c4ecSRafael Espindola }
1123b33c4ecSRafael Espindola 
11364225794SFrancois Pichet // Note: This function also emit constructor calls to support a MSVC
11464225794SFrancois Pichet // extensions allowing explicit constructor function call.
11527da15baSAnders Carlsson RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
11627da15baSAnders Carlsson                                               ReturnValueSlot ReturnValue) {
1172d2e8707SJohn McCall   const Expr *callee = CE->getCallee()->IgnoreParens();
1182d2e8707SJohn McCall 
1192d2e8707SJohn McCall   if (isa<BinaryOperator>(callee))
12027da15baSAnders Carlsson     return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
12127da15baSAnders Carlsson 
1222d2e8707SJohn McCall   const MemberExpr *ME = cast<MemberExpr>(callee);
12327da15baSAnders Carlsson   const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
12427da15baSAnders Carlsson 
12527da15baSAnders Carlsson   if (MD->isStatic()) {
12627da15baSAnders Carlsson     // The method is static, emit it as we would a regular call.
12727da15baSAnders Carlsson     llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
12870b9c01bSAlexey Samsonov     return EmitCall(getContext().getPointerType(MD->getType()), Callee, CE,
12970b9c01bSAlexey Samsonov                     ReturnValue);
13027da15baSAnders Carlsson   }
13127da15baSAnders Carlsson 
132aad4af6dSNico Weber   bool HasQualifier = ME->hasQualifier();
133aad4af6dSNico Weber   NestedNameSpecifier *Qualifier = HasQualifier ? ME->getQualifier() : nullptr;
134aad4af6dSNico Weber   bool IsArrow = ME->isArrow();
135ecbe2e97SRafael Espindola   const Expr *Base = ME->getBase();
136aad4af6dSNico Weber 
137aad4af6dSNico Weber   return EmitCXXMemberOrOperatorMemberCallExpr(
138aad4af6dSNico Weber       CE, MD, ReturnValue, HasQualifier, Qualifier, IsArrow, Base);
139aad4af6dSNico Weber }
140aad4af6dSNico Weber 
141aad4af6dSNico Weber RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr(
142aad4af6dSNico Weber     const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue,
143aad4af6dSNico Weber     bool HasQualifier, NestedNameSpecifier *Qualifier, bool IsArrow,
144aad4af6dSNico Weber     const Expr *Base) {
145aad4af6dSNico Weber   assert(isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE));
146aad4af6dSNico Weber 
147aad4af6dSNico Weber   // Compute the object pointer.
148aad4af6dSNico Weber   bool CanUseVirtualCall = MD->isVirtual() && !HasQualifier;
149ecbe2e97SRafael Espindola 
1508a13c418SCraig Topper   const CXXMethodDecl *DevirtualizedMethod = nullptr;
1517463ed7cSBenjamin Kramer   if (CanUseVirtualCall && CanDevirtualizeMemberFunctionCall(Base, MD)) {
1523b33c4ecSRafael Espindola     const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
1533b33c4ecSRafael Espindola     DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
1543b33c4ecSRafael Espindola     assert(DevirtualizedMethod);
1553b33c4ecSRafael Espindola     const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
1563b33c4ecSRafael Espindola     const Expr *Inner = Base->ignoreParenBaseCasts();
1575bd68794SAlexey Bataev     if (DevirtualizedMethod->getReturnType().getCanonicalType() !=
1585bd68794SAlexey Bataev         MD->getReturnType().getCanonicalType())
1595bd68794SAlexey Bataev       // If the return types are not the same, this might be a case where more
1605bd68794SAlexey Bataev       // code needs to run to compensate for it. For example, the derived
1615bd68794SAlexey Bataev       // method might return a type that inherits form from the return
1625bd68794SAlexey Bataev       // type of MD and has a prefix.
1635bd68794SAlexey Bataev       // For now we just avoid devirtualizing these covariant cases.
1645bd68794SAlexey Bataev       DevirtualizedMethod = nullptr;
1655bd68794SAlexey Bataev     else if (getCXXRecord(Inner) == DevirtualizedClass)
1663b33c4ecSRafael Espindola       // If the class of the Inner expression is where the dynamic method
1673b33c4ecSRafael Espindola       // is defined, build the this pointer from it.
1683b33c4ecSRafael Espindola       Base = Inner;
1693b33c4ecSRafael Espindola     else if (getCXXRecord(Base) != DevirtualizedClass) {
1703b33c4ecSRafael Espindola       // If the method is defined in a class that is not the best dynamic
1713b33c4ecSRafael Espindola       // one or the one of the full expression, we would have to build
1723b33c4ecSRafael Espindola       // a derived-to-base cast to compute the correct this pointer, but
1733b33c4ecSRafael Espindola       // we don't have support for that yet, so do a virtual call.
1748a13c418SCraig Topper       DevirtualizedMethod = nullptr;
1753b33c4ecSRafael Espindola     }
1763b33c4ecSRafael Espindola   }
177ecbe2e97SRafael Espindola 
178762672a7SRichard Smith   // C++17 demands that we evaluate the RHS of a (possibly-compound) assignment
179762672a7SRichard Smith   // operator before the LHS.
180762672a7SRichard Smith   CallArgList RtlArgStorage;
181762672a7SRichard Smith   CallArgList *RtlArgs = nullptr;
182762672a7SRichard Smith   if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
183762672a7SRichard Smith     if (OCE->isAssignmentOp()) {
184762672a7SRichard Smith       RtlArgs = &RtlArgStorage;
185762672a7SRichard Smith       EmitCallArgs(*RtlArgs, MD->getType()->castAs<FunctionProtoType>(),
186762672a7SRichard Smith                    drop_begin(CE->arguments(), 1), CE->getDirectCallee(),
187*a560ccf2SRichard Smith                    /*ParamsToSkip*/0, EvaluationOrder::ForceRightToLeft);
188762672a7SRichard Smith     }
189762672a7SRichard Smith   }
190762672a7SRichard Smith 
1917f416cc4SJohn McCall   Address This = Address::invalid();
192aad4af6dSNico Weber   if (IsArrow)
1937f416cc4SJohn McCall     This = EmitPointerWithAlignment(Base);
194f93ac894SFariborz Jahanian   else
1953b33c4ecSRafael Espindola     This = EmitLValue(Base).getAddress();
196ecbe2e97SRafael Espindola 
19727da15baSAnders Carlsson 
198419bd094SRichard Smith   if (MD->isTrivial() || (MD->isDefaulted() && MD->getParent()->isUnion())) {
1998a13c418SCraig Topper     if (isa<CXXDestructorDecl>(MD)) return RValue::get(nullptr);
20064225794SFrancois Pichet     if (isa<CXXConstructorDecl>(MD) &&
20164225794SFrancois Pichet         cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
2028a13c418SCraig Topper       return RValue::get(nullptr);
2030d635f53SJohn McCall 
204aad4af6dSNico Weber     if (!MD->getParent()->mayInsertExtraPadding()) {
20522653bacSSebastian Redl       if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
20622653bacSSebastian Redl         // We don't like to generate the trivial copy/move assignment operator
20722653bacSSebastian Redl         // when it isn't necessary; just produce the proper effect here.
208762672a7SRichard Smith         LValue RHS = isa<CXXOperatorCallExpr>(CE)
209762672a7SRichard Smith                          ? MakeNaturalAlignAddrLValue(
210762672a7SRichard Smith                                (*RtlArgs)[0].RV.getScalarVal(),
211762672a7SRichard Smith                                (*(CE->arg_begin() + 1))->getType())
212762672a7SRichard Smith                          : EmitLValue(*CE->arg_begin());
213762672a7SRichard Smith         EmitAggregateAssign(This, RHS.getAddress(), CE->getType());
2147f416cc4SJohn McCall         return RValue::get(This.getPointer());
21527da15baSAnders Carlsson       }
21627da15baSAnders Carlsson 
21764225794SFrancois Pichet       if (isa<CXXConstructorDecl>(MD) &&
21822653bacSSebastian Redl           cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
21922653bacSSebastian Redl         // Trivial move and copy ctor are the same.
220525bf650SAlexey Samsonov         assert(CE->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
2217f416cc4SJohn McCall         Address RHS = EmitLValue(*CE->arg_begin()).getAddress();
222f48ee448SBenjamin Kramer         EmitAggregateCopy(This, RHS, (*CE->arg_begin())->getType());
2237f416cc4SJohn McCall         return RValue::get(This.getPointer());
22464225794SFrancois Pichet       }
22564225794SFrancois Pichet       llvm_unreachable("unknown trivial member function");
22664225794SFrancois Pichet     }
227aad4af6dSNico Weber   }
22864225794SFrancois Pichet 
2290d635f53SJohn McCall   // Compute the function type we're calling.
2303abfe958SNico Weber   const CXXMethodDecl *CalleeDecl =
2313abfe958SNico Weber       DevirtualizedMethod ? DevirtualizedMethod : MD;
2328a13c418SCraig Topper   const CGFunctionInfo *FInfo = nullptr;
2333abfe958SNico Weber   if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
2348d2a19b4SRafael Espindola     FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
2358d2a19b4SRafael Espindola         Dtor, StructorType::Complete);
2363abfe958SNico Weber   else if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(CalleeDecl))
2378d2a19b4SRafael Espindola     FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
2388d2a19b4SRafael Espindola         Ctor, StructorType::Complete);
23964225794SFrancois Pichet   else
240ade60977SEli Friedman     FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
2410d635f53SJohn McCall 
242e7de47efSReid Kleckner   llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
2430d635f53SJohn McCall 
24427da15baSAnders Carlsson   // C++ [class.virtual]p12:
24527da15baSAnders Carlsson   //   Explicit qualification with the scope operator (5.1) suppresses the
24627da15baSAnders Carlsson   //   virtual call mechanism.
24727da15baSAnders Carlsson   //
24827da15baSAnders Carlsson   // We also don't emit a virtual call if the base expression has a record type
24927da15baSAnders Carlsson   // because then we know what the type is.
2503b33c4ecSRafael Espindola   bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
25119cee187SStephen Lin   llvm::Value *Callee;
2529dc6eef7SStephen Lin 
2530d635f53SJohn McCall   if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
25419cee187SStephen Lin     assert(CE->arg_begin() == CE->arg_end() &&
2559dc6eef7SStephen Lin            "Destructor shouldn't have explicit parameters");
2569dc6eef7SStephen Lin     assert(ReturnValue.isNull() && "Destructor shouldn't have return value");
2579dc6eef7SStephen Lin     if (UseVirtualCall) {
258aad4af6dSNico Weber       CGM.getCXXABI().EmitVirtualDestructorCall(
259aad4af6dSNico Weber           *this, Dtor, Dtor_Complete, This, cast<CXXMemberCallExpr>(CE));
26027da15baSAnders Carlsson     } else {
261aad4af6dSNico Weber       if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
262aad4af6dSNico Weber         Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
2633b33c4ecSRafael Espindola       else if (!DevirtualizedMethod)
2641ac0ec86SRafael Espindola         Callee =
2651ac0ec86SRafael Espindola             CGM.getAddrOfCXXStructor(Dtor, StructorType::Complete, FInfo, Ty);
26649e860b2SRafael Espindola       else {
2673b33c4ecSRafael Espindola         const CXXDestructorDecl *DDtor =
2683b33c4ecSRafael Espindola           cast<CXXDestructorDecl>(DevirtualizedMethod);
26949e860b2SRafael Espindola         Callee = CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty);
27049e860b2SRafael Espindola       }
2717f416cc4SJohn McCall       EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This.getPointer(),
272762672a7SRichard Smith                                   /*ImplicitParam=*/nullptr, QualType(), CE,
273762672a7SRichard Smith                                   nullptr);
27427da15baSAnders Carlsson     }
2758a13c418SCraig Topper     return RValue::get(nullptr);
2769dc6eef7SStephen Lin   }
2779dc6eef7SStephen Lin 
2789dc6eef7SStephen Lin   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
27964225794SFrancois Pichet     Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
2800d635f53SJohn McCall   } else if (UseVirtualCall) {
2816708c4a1SPeter Collingbourne     Callee = CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, Ty,
2826708c4a1SPeter Collingbourne                                                        CE->getLocStart());
28327da15baSAnders Carlsson   } else {
2841a7488afSPeter Collingbourne     if (SanOpts.has(SanitizerKind::CFINVCall) &&
2851a7488afSPeter Collingbourne         MD->getParent()->isDynamicClass()) {
2864b1ac72cSPiotr Padlewski       llvm::Value *VTable = GetVTablePtr(This, Int8PtrTy, MD->getParent());
287fb532b9aSPeter Collingbourne       EmitVTablePtrCheckForCall(MD->getParent(), VTable, CFITCK_NVCall,
288fb532b9aSPeter Collingbourne                                 CE->getLocStart());
2891a7488afSPeter Collingbourne     }
2901a7488afSPeter Collingbourne 
291aad4af6dSNico Weber     if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
292aad4af6dSNico Weber       Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
2933b33c4ecSRafael Espindola     else if (!DevirtualizedMethod)
294727a771aSRafael Espindola       Callee = CGM.GetAddrOfFunction(MD, Ty);
29549e860b2SRafael Espindola     else {
2963b33c4ecSRafael Espindola       Callee = CGM.GetAddrOfFunction(DevirtualizedMethod, Ty);
29749e860b2SRafael Espindola     }
29827da15baSAnders Carlsson   }
29927da15baSAnders Carlsson 
300f1749427STimur Iskhodzhanov   if (MD->isVirtual()) {
301f1749427STimur Iskhodzhanov     This = CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
3024b60f30aSReid Kleckner         *this, CalleeDecl, This, UseVirtualCall);
303f1749427STimur Iskhodzhanov   }
30488fd439aSTimur Iskhodzhanov 
3057f416cc4SJohn McCall   return EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This.getPointer(),
306762672a7SRichard Smith                                      /*ImplicitParam=*/nullptr, QualType(), CE,
307762672a7SRichard Smith                                      RtlArgs);
30827da15baSAnders Carlsson }
30927da15baSAnders Carlsson 
31027da15baSAnders Carlsson RValue
31127da15baSAnders Carlsson CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
31227da15baSAnders Carlsson                                               ReturnValueSlot ReturnValue) {
31327da15baSAnders Carlsson   const BinaryOperator *BO =
31427da15baSAnders Carlsson       cast<BinaryOperator>(E->getCallee()->IgnoreParens());
31527da15baSAnders Carlsson   const Expr *BaseExpr = BO->getLHS();
31627da15baSAnders Carlsson   const Expr *MemFnExpr = BO->getRHS();
31727da15baSAnders Carlsson 
31827da15baSAnders Carlsson   const MemberPointerType *MPT =
3190009fcc3SJohn McCall     MemFnExpr->getType()->castAs<MemberPointerType>();
320475999dcSJohn McCall 
32127da15baSAnders Carlsson   const FunctionProtoType *FPT =
3220009fcc3SJohn McCall     MPT->getPointeeType()->castAs<FunctionProtoType>();
32327da15baSAnders Carlsson   const CXXRecordDecl *RD =
32427da15baSAnders Carlsson     cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
32527da15baSAnders Carlsson 
32627da15baSAnders Carlsson   // Emit the 'this' pointer.
3277f416cc4SJohn McCall   Address This = Address::invalid();
328e302792bSJohn McCall   if (BO->getOpcode() == BO_PtrMemI)
3297f416cc4SJohn McCall     This = EmitPointerWithAlignment(BaseExpr);
33027da15baSAnders Carlsson   else
33127da15baSAnders Carlsson     This = EmitLValue(BaseExpr).getAddress();
33227da15baSAnders Carlsson 
3337f416cc4SJohn McCall   EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This.getPointer(),
334e30752c9SRichard Smith                 QualType(MPT->getClass(), 0));
33569d0d262SRichard Smith 
336bde62d78SRichard Smith   // Get the member function pointer.
337bde62d78SRichard Smith   llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
338bde62d78SRichard Smith 
339475999dcSJohn McCall   // Ask the ABI to load the callee.  Note that This is modified.
3407f416cc4SJohn McCall   llvm::Value *ThisPtrForCall = nullptr;
341475999dcSJohn McCall   llvm::Value *Callee =
3427f416cc4SJohn McCall     CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This,
3437f416cc4SJohn McCall                                              ThisPtrForCall, MemFnPtr, MPT);
34427da15baSAnders Carlsson 
34527da15baSAnders Carlsson   CallArgList Args;
34627da15baSAnders Carlsson 
34727da15baSAnders Carlsson   QualType ThisType =
34827da15baSAnders Carlsson     getContext().getPointerType(getContext().getTagDeclType(RD));
34927da15baSAnders Carlsson 
35027da15baSAnders Carlsson   // Push the this ptr.
3517f416cc4SJohn McCall   Args.add(RValue::get(ThisPtrForCall), ThisType);
35227da15baSAnders Carlsson 
353419996ccSGeorge Burgess IV   RequiredArgs required =
354419996ccSGeorge Burgess IV       RequiredArgs::forPrototypePlus(FPT, 1, /*FD=*/nullptr);
3558dda7b27SJohn McCall 
35627da15baSAnders Carlsson   // And the rest of the call args
357419996ccSGeorge Burgess IV   EmitCallArgs(Args, FPT, E->arguments());
3585fa40c3bSNick Lewycky   return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
3595fa40c3bSNick Lewycky                   Callee, ReturnValue, Args);
36027da15baSAnders Carlsson }
36127da15baSAnders Carlsson 
36227da15baSAnders Carlsson RValue
36327da15baSAnders Carlsson CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
36427da15baSAnders Carlsson                                                const CXXMethodDecl *MD,
36527da15baSAnders Carlsson                                                ReturnValueSlot ReturnValue) {
36627da15baSAnders Carlsson   assert(MD->isInstance() &&
36727da15baSAnders Carlsson          "Trying to emit a member call expr on a static method!");
368aad4af6dSNico Weber   return EmitCXXMemberOrOperatorMemberCallExpr(
369aad4af6dSNico Weber       E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr,
370aad4af6dSNico Weber       /*IsArrow=*/false, E->getArg(0));
37127da15baSAnders Carlsson }
37227da15baSAnders Carlsson 
373fe883422SPeter Collingbourne RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
374fe883422SPeter Collingbourne                                                ReturnValueSlot ReturnValue) {
375fe883422SPeter Collingbourne   return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
376fe883422SPeter Collingbourne }
377fe883422SPeter Collingbourne 
378fde961dbSEli Friedman static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
3797f416cc4SJohn McCall                                             Address DestPtr,
380fde961dbSEli Friedman                                             const CXXRecordDecl *Base) {
381fde961dbSEli Friedman   if (Base->isEmpty())
382fde961dbSEli Friedman     return;
383fde961dbSEli Friedman 
3847f416cc4SJohn McCall   DestPtr = CGF.Builder.CreateElementBitCast(DestPtr, CGF.Int8Ty);
385fde961dbSEli Friedman 
386fde961dbSEli Friedman   const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
3878671c6e0SDavid Majnemer   CharUnits NVSize = Layout.getNonVirtualSize();
3888671c6e0SDavid Majnemer 
3898671c6e0SDavid Majnemer   // We cannot simply zero-initialize the entire base sub-object if vbptrs are
3908671c6e0SDavid Majnemer   // present, they are initialized by the most derived class before calling the
3918671c6e0SDavid Majnemer   // constructor.
3928671c6e0SDavid Majnemer   SmallVector<std::pair<CharUnits, CharUnits>, 1> Stores;
3938671c6e0SDavid Majnemer   Stores.emplace_back(CharUnits::Zero(), NVSize);
3948671c6e0SDavid Majnemer 
3958671c6e0SDavid Majnemer   // Each store is split by the existence of a vbptr.
3968671c6e0SDavid Majnemer   CharUnits VBPtrWidth = CGF.getPointerSize();
3978671c6e0SDavid Majnemer   std::vector<CharUnits> VBPtrOffsets =
3988671c6e0SDavid Majnemer       CGF.CGM.getCXXABI().getVBPtrOffsets(Base);
3998671c6e0SDavid Majnemer   for (CharUnits VBPtrOffset : VBPtrOffsets) {
4007f980d84SDavid Majnemer     // Stop before we hit any virtual base pointers located in virtual bases.
4017f980d84SDavid Majnemer     if (VBPtrOffset >= NVSize)
4027f980d84SDavid Majnemer       break;
4038671c6e0SDavid Majnemer     std::pair<CharUnits, CharUnits> LastStore = Stores.pop_back_val();
4048671c6e0SDavid Majnemer     CharUnits LastStoreOffset = LastStore.first;
4058671c6e0SDavid Majnemer     CharUnits LastStoreSize = LastStore.second;
4068671c6e0SDavid Majnemer 
4078671c6e0SDavid Majnemer     CharUnits SplitBeforeOffset = LastStoreOffset;
4088671c6e0SDavid Majnemer     CharUnits SplitBeforeSize = VBPtrOffset - SplitBeforeOffset;
4098671c6e0SDavid Majnemer     assert(!SplitBeforeSize.isNegative() && "negative store size!");
4108671c6e0SDavid Majnemer     if (!SplitBeforeSize.isZero())
4118671c6e0SDavid Majnemer       Stores.emplace_back(SplitBeforeOffset, SplitBeforeSize);
4128671c6e0SDavid Majnemer 
4138671c6e0SDavid Majnemer     CharUnits SplitAfterOffset = VBPtrOffset + VBPtrWidth;
4148671c6e0SDavid Majnemer     CharUnits SplitAfterSize = LastStoreSize - SplitAfterOffset;
4158671c6e0SDavid Majnemer     assert(!SplitAfterSize.isNegative() && "negative store size!");
4168671c6e0SDavid Majnemer     if (!SplitAfterSize.isZero())
4178671c6e0SDavid Majnemer       Stores.emplace_back(SplitAfterOffset, SplitAfterSize);
4188671c6e0SDavid Majnemer   }
419fde961dbSEli Friedman 
420fde961dbSEli Friedman   // If the type contains a pointer to data member we can't memset it to zero.
421fde961dbSEli Friedman   // Instead, create a null constant and copy it to the destination.
422fde961dbSEli Friedman   // TODO: there are other patterns besides zero that we can usefully memset,
423fde961dbSEli Friedman   // like -1, which happens to be the pattern used by member-pointers.
424fde961dbSEli Friedman   // TODO: isZeroInitializable can be over-conservative in the case where a
425fde961dbSEli Friedman   // virtual base contains a member pointer.
4268671c6e0SDavid Majnemer   llvm::Constant *NullConstantForBase = CGF.CGM.EmitNullConstantForBase(Base);
4278671c6e0SDavid Majnemer   if (!NullConstantForBase->isNullValue()) {
4288671c6e0SDavid Majnemer     llvm::GlobalVariable *NullVariable = new llvm::GlobalVariable(
4298671c6e0SDavid Majnemer         CGF.CGM.getModule(), NullConstantForBase->getType(),
4308671c6e0SDavid Majnemer         /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage,
4318671c6e0SDavid Majnemer         NullConstantForBase, Twine());
4327f416cc4SJohn McCall 
4337f416cc4SJohn McCall     CharUnits Align = std::max(Layout.getNonVirtualAlignment(),
4347f416cc4SJohn McCall                                DestPtr.getAlignment());
435fde961dbSEli Friedman     NullVariable->setAlignment(Align.getQuantity());
4367f416cc4SJohn McCall 
4377f416cc4SJohn McCall     Address SrcPtr = Address(CGF.EmitCastToVoidPtr(NullVariable), Align);
438fde961dbSEli Friedman 
439fde961dbSEli Friedman     // Get and call the appropriate llvm.memcpy overload.
4408671c6e0SDavid Majnemer     for (std::pair<CharUnits, CharUnits> Store : Stores) {
4418671c6e0SDavid Majnemer       CharUnits StoreOffset = Store.first;
4428671c6e0SDavid Majnemer       CharUnits StoreSize = Store.second;
4438671c6e0SDavid Majnemer       llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
4448671c6e0SDavid Majnemer       CGF.Builder.CreateMemCpy(
4458671c6e0SDavid Majnemer           CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
4468671c6e0SDavid Majnemer           CGF.Builder.CreateConstInBoundsByteGEP(SrcPtr, StoreOffset),
4478671c6e0SDavid Majnemer           StoreSizeVal);
448fde961dbSEli Friedman     }
449fde961dbSEli Friedman 
450fde961dbSEli Friedman   // Otherwise, just memset the whole thing to zero.  This is legal
451fde961dbSEli Friedman   // because in LLVM, all default initializers (other than the ones we just
452fde961dbSEli Friedman   // handled above) are guaranteed to have a bit pattern of all zeros.
4538671c6e0SDavid Majnemer   } else {
4548671c6e0SDavid Majnemer     for (std::pair<CharUnits, CharUnits> Store : Stores) {
4558671c6e0SDavid Majnemer       CharUnits StoreOffset = Store.first;
4568671c6e0SDavid Majnemer       CharUnits StoreSize = Store.second;
4578671c6e0SDavid Majnemer       llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
4588671c6e0SDavid Majnemer       CGF.Builder.CreateMemSet(
4598671c6e0SDavid Majnemer           CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
4608671c6e0SDavid Majnemer           CGF.Builder.getInt8(0), StoreSizeVal);
4618671c6e0SDavid Majnemer     }
4628671c6e0SDavid Majnemer   }
463fde961dbSEli Friedman }
464fde961dbSEli Friedman 
46527da15baSAnders Carlsson void
4667a626f63SJohn McCall CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
4677a626f63SJohn McCall                                       AggValueSlot Dest) {
4687a626f63SJohn McCall   assert(!Dest.isIgnored() && "Must have a destination!");
46927da15baSAnders Carlsson   const CXXConstructorDecl *CD = E->getConstructor();
470630c76efSDouglas Gregor 
471630c76efSDouglas Gregor   // If we require zero initialization before (or instead of) calling the
472630c76efSDouglas Gregor   // constructor, as can be the case with a non-user-provided default
47303535265SArgyrios Kyrtzidis   // constructor, emit the zero initialization now, unless destination is
47403535265SArgyrios Kyrtzidis   // already zeroed.
475fde961dbSEli Friedman   if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
476fde961dbSEli Friedman     switch (E->getConstructionKind()) {
477fde961dbSEli Friedman     case CXXConstructExpr::CK_Delegating:
478fde961dbSEli Friedman     case CXXConstructExpr::CK_Complete:
4797f416cc4SJohn McCall       EmitNullInitialization(Dest.getAddress(), E->getType());
480fde961dbSEli Friedman       break;
481fde961dbSEli Friedman     case CXXConstructExpr::CK_VirtualBase:
482fde961dbSEli Friedman     case CXXConstructExpr::CK_NonVirtualBase:
4837f416cc4SJohn McCall       EmitNullBaseClassInitialization(*this, Dest.getAddress(),
4847f416cc4SJohn McCall                                       CD->getParent());
485fde961dbSEli Friedman       break;
486fde961dbSEli Friedman     }
487fde961dbSEli Friedman   }
488630c76efSDouglas Gregor 
489630c76efSDouglas Gregor   // If this is a call to a trivial default constructor, do nothing.
490630c76efSDouglas Gregor   if (CD->isTrivial() && CD->isDefaultConstructor())
49127da15baSAnders Carlsson     return;
492630c76efSDouglas Gregor 
4938ea46b66SJohn McCall   // Elide the constructor if we're constructing from a temporary.
4948ea46b66SJohn McCall   // The temporary check is required because Sema sets this on NRVO
4958ea46b66SJohn McCall   // returns.
4969c6890a7SRichard Smith   if (getLangOpts().ElideConstructors && E->isElidable()) {
4978ea46b66SJohn McCall     assert(getContext().hasSameUnqualifiedType(E->getType(),
4988ea46b66SJohn McCall                                                E->getArg(0)->getType()));
4997a626f63SJohn McCall     if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
5007a626f63SJohn McCall       EmitAggExpr(E->getArg(0), Dest);
50127da15baSAnders Carlsson       return;
50227da15baSAnders Carlsson     }
503222cf0efSDouglas Gregor   }
504630c76efSDouglas Gregor 
505e7545b33SAlexey Bataev   if (const ArrayType *arrayType
506e7545b33SAlexey Bataev         = getContext().getAsArrayType(E->getType())) {
5077f416cc4SJohn McCall     EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddress(), E);
508f677a8e9SJohn McCall   } else {
509bceca20aSCameron Esfahani     CXXCtorType Type = Ctor_Complete;
510271c3681SAlexis Hunt     bool ForVirtualBase = false;
51161535005SDouglas Gregor     bool Delegating = false;
512271c3681SAlexis Hunt 
513271c3681SAlexis Hunt     switch (E->getConstructionKind()) {
514271c3681SAlexis Hunt      case CXXConstructExpr::CK_Delegating:
51561bc1737SAlexis Hunt       // We should be emitting a constructor; GlobalDecl will assert this
51661bc1737SAlexis Hunt       Type = CurGD.getCtorType();
51761535005SDouglas Gregor       Delegating = true;
518271c3681SAlexis Hunt       break;
51961bc1737SAlexis Hunt 
520271c3681SAlexis Hunt      case CXXConstructExpr::CK_Complete:
521271c3681SAlexis Hunt       Type = Ctor_Complete;
522271c3681SAlexis Hunt       break;
523271c3681SAlexis Hunt 
524271c3681SAlexis Hunt      case CXXConstructExpr::CK_VirtualBase:
525271c3681SAlexis Hunt       ForVirtualBase = true;
526271c3681SAlexis Hunt       // fall-through
527271c3681SAlexis Hunt 
528271c3681SAlexis Hunt      case CXXConstructExpr::CK_NonVirtualBase:
529271c3681SAlexis Hunt       Type = Ctor_Base;
530271c3681SAlexis Hunt     }
531e11f9ce9SAnders Carlsson 
53227da15baSAnders Carlsson     // Call the constructor.
5337f416cc4SJohn McCall     EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating,
5347f416cc4SJohn McCall                            Dest.getAddress(), E);
53527da15baSAnders Carlsson   }
536e11f9ce9SAnders Carlsson }
53727da15baSAnders Carlsson 
5387f416cc4SJohn McCall void CodeGenFunction::EmitSynthesizedCXXCopyCtor(Address Dest, Address Src,
53950198098SFariborz Jahanian                                                  const Expr *Exp) {
5405d413781SJohn McCall   if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
541e988bdacSFariborz Jahanian     Exp = E->getSubExpr();
542e988bdacSFariborz Jahanian   assert(isa<CXXConstructExpr>(Exp) &&
543e988bdacSFariborz Jahanian          "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
544e988bdacSFariborz Jahanian   const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
545e988bdacSFariborz Jahanian   const CXXConstructorDecl *CD = E->getConstructor();
546e988bdacSFariborz Jahanian   RunCleanupsScope Scope(*this);
547e988bdacSFariborz Jahanian 
548e988bdacSFariborz Jahanian   // If we require zero initialization before (or instead of) calling the
549e988bdacSFariborz Jahanian   // constructor, as can be the case with a non-user-provided default
550e988bdacSFariborz Jahanian   // constructor, emit the zero initialization now.
551e988bdacSFariborz Jahanian   // FIXME. Do I still need this for a copy ctor synthesis?
552e988bdacSFariborz Jahanian   if (E->requiresZeroInitialization())
553e988bdacSFariborz Jahanian     EmitNullInitialization(Dest, E->getType());
554e988bdacSFariborz Jahanian 
55599da11cfSChandler Carruth   assert(!getContext().getAsConstantArrayType(E->getType())
55699da11cfSChandler Carruth          && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
557525bf650SAlexey Samsonov   EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E);
558e988bdacSFariborz Jahanian }
559e988bdacSFariborz Jahanian 
5608ed55a54SJohn McCall static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
5618ed55a54SJohn McCall                                         const CXXNewExpr *E) {
56221122cf6SAnders Carlsson   if (!E->isArray())
5633eb55cfeSKen Dyck     return CharUnits::Zero();
56421122cf6SAnders Carlsson 
5657ec4b434SJohn McCall   // No cookie is required if the operator new[] being used is the
5667ec4b434SJohn McCall   // reserved placement operator new[].
5677ec4b434SJohn McCall   if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
5683eb55cfeSKen Dyck     return CharUnits::Zero();
569399f499fSAnders Carlsson 
570284c48ffSJohn McCall   return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
57159486a2dSAnders Carlsson }
57259486a2dSAnders Carlsson 
573036f2f6bSJohn McCall static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
574036f2f6bSJohn McCall                                         const CXXNewExpr *e,
575f862eb6aSSebastian Redl                                         unsigned minElements,
576036f2f6bSJohn McCall                                         llvm::Value *&numElements,
577036f2f6bSJohn McCall                                         llvm::Value *&sizeWithoutCookie) {
578036f2f6bSJohn McCall   QualType type = e->getAllocatedType();
57959486a2dSAnders Carlsson 
580036f2f6bSJohn McCall   if (!e->isArray()) {
581036f2f6bSJohn McCall     CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
582036f2f6bSJohn McCall     sizeWithoutCookie
583036f2f6bSJohn McCall       = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
584036f2f6bSJohn McCall     return sizeWithoutCookie;
58505fc5be3SDouglas Gregor   }
58659486a2dSAnders Carlsson 
587036f2f6bSJohn McCall   // The width of size_t.
588036f2f6bSJohn McCall   unsigned sizeWidth = CGF.SizeTy->getBitWidth();
589036f2f6bSJohn McCall 
5908ed55a54SJohn McCall   // Figure out the cookie size.
591036f2f6bSJohn McCall   llvm::APInt cookieSize(sizeWidth,
592036f2f6bSJohn McCall                          CalculateCookiePadding(CGF, e).getQuantity());
5938ed55a54SJohn McCall 
59459486a2dSAnders Carlsson   // Emit the array size expression.
5957648fb46SArgyrios Kyrtzidis   // We multiply the size of all dimensions for NumElements.
5967648fb46SArgyrios Kyrtzidis   // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
597036f2f6bSJohn McCall   numElements = CGF.EmitScalarExpr(e->getArraySize());
598036f2f6bSJohn McCall   assert(isa<llvm::IntegerType>(numElements->getType()));
5998ed55a54SJohn McCall 
600036f2f6bSJohn McCall   // The number of elements can be have an arbitrary integer type;
601036f2f6bSJohn McCall   // essentially, we need to multiply it by a constant factor, add a
602036f2f6bSJohn McCall   // cookie size, and verify that the result is representable as a
603036f2f6bSJohn McCall   // size_t.  That's just a gloss, though, and it's wrong in one
604036f2f6bSJohn McCall   // important way: if the count is negative, it's an error even if
605036f2f6bSJohn McCall   // the cookie size would bring the total size >= 0.
6066ab2fa8fSDouglas Gregor   bool isSigned
6076ab2fa8fSDouglas Gregor     = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
6082192fe50SChris Lattner   llvm::IntegerType *numElementsType
609036f2f6bSJohn McCall     = cast<llvm::IntegerType>(numElements->getType());
610036f2f6bSJohn McCall   unsigned numElementsWidth = numElementsType->getBitWidth();
611036f2f6bSJohn McCall 
612036f2f6bSJohn McCall   // Compute the constant factor.
613036f2f6bSJohn McCall   llvm::APInt arraySizeMultiplier(sizeWidth, 1);
6147648fb46SArgyrios Kyrtzidis   while (const ConstantArrayType *CAT
615036f2f6bSJohn McCall              = CGF.getContext().getAsConstantArrayType(type)) {
616036f2f6bSJohn McCall     type = CAT->getElementType();
617036f2f6bSJohn McCall     arraySizeMultiplier *= CAT->getSize();
6187648fb46SArgyrios Kyrtzidis   }
61959486a2dSAnders Carlsson 
620036f2f6bSJohn McCall   CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
621036f2f6bSJohn McCall   llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
622036f2f6bSJohn McCall   typeSizeMultiplier *= arraySizeMultiplier;
623036f2f6bSJohn McCall 
624036f2f6bSJohn McCall   // This will be a size_t.
625036f2f6bSJohn McCall   llvm::Value *size;
62632ac583dSChris Lattner 
62732ac583dSChris Lattner   // If someone is doing 'new int[42]' there is no need to do a dynamic check.
62832ac583dSChris Lattner   // Don't bloat the -O0 code.
629036f2f6bSJohn McCall   if (llvm::ConstantInt *numElementsC =
630036f2f6bSJohn McCall         dyn_cast<llvm::ConstantInt>(numElements)) {
631036f2f6bSJohn McCall     const llvm::APInt &count = numElementsC->getValue();
63232ac583dSChris Lattner 
633036f2f6bSJohn McCall     bool hasAnyOverflow = false;
63432ac583dSChris Lattner 
635036f2f6bSJohn McCall     // If 'count' was a negative number, it's an overflow.
636036f2f6bSJohn McCall     if (isSigned && count.isNegative())
637036f2f6bSJohn McCall       hasAnyOverflow = true;
6388ed55a54SJohn McCall 
639036f2f6bSJohn McCall     // We want to do all this arithmetic in size_t.  If numElements is
640036f2f6bSJohn McCall     // wider than that, check whether it's already too big, and if so,
641036f2f6bSJohn McCall     // overflow.
642036f2f6bSJohn McCall     else if (numElementsWidth > sizeWidth &&
643036f2f6bSJohn McCall              numElementsWidth - sizeWidth > count.countLeadingZeros())
644036f2f6bSJohn McCall       hasAnyOverflow = true;
645036f2f6bSJohn McCall 
646036f2f6bSJohn McCall     // Okay, compute a count at the right width.
647036f2f6bSJohn McCall     llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
648036f2f6bSJohn McCall 
649f862eb6aSSebastian Redl     // If there is a brace-initializer, we cannot allocate fewer elements than
650f862eb6aSSebastian Redl     // there are initializers. If we do, that's treated like an overflow.
651f862eb6aSSebastian Redl     if (adjustedCount.ult(minElements))
652f862eb6aSSebastian Redl       hasAnyOverflow = true;
653f862eb6aSSebastian Redl 
654036f2f6bSJohn McCall     // Scale numElements by that.  This might overflow, but we don't
655036f2f6bSJohn McCall     // care because it only overflows if allocationSize does, too, and
656036f2f6bSJohn McCall     // if that overflows then we shouldn't use this.
657036f2f6bSJohn McCall     numElements = llvm::ConstantInt::get(CGF.SizeTy,
658036f2f6bSJohn McCall                                          adjustedCount * arraySizeMultiplier);
659036f2f6bSJohn McCall 
660036f2f6bSJohn McCall     // Compute the size before cookie, and track whether it overflowed.
661036f2f6bSJohn McCall     bool overflow;
662036f2f6bSJohn McCall     llvm::APInt allocationSize
663036f2f6bSJohn McCall       = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
664036f2f6bSJohn McCall     hasAnyOverflow |= overflow;
665036f2f6bSJohn McCall 
666036f2f6bSJohn McCall     // Add in the cookie, and check whether it's overflowed.
667036f2f6bSJohn McCall     if (cookieSize != 0) {
668036f2f6bSJohn McCall       // Save the current size without a cookie.  This shouldn't be
669036f2f6bSJohn McCall       // used if there was overflow.
670036f2f6bSJohn McCall       sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
671036f2f6bSJohn McCall 
672036f2f6bSJohn McCall       allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
673036f2f6bSJohn McCall       hasAnyOverflow |= overflow;
6748ed55a54SJohn McCall     }
6758ed55a54SJohn McCall 
676036f2f6bSJohn McCall     // On overflow, produce a -1 so operator new will fail.
677455f42c9SAaron Ballman     if (hasAnyOverflow) {
678455f42c9SAaron Ballman       size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
679455f42c9SAaron Ballman     } else {
680036f2f6bSJohn McCall       size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
681455f42c9SAaron Ballman     }
68232ac583dSChris Lattner 
683036f2f6bSJohn McCall   // Otherwise, we might need to use the overflow intrinsics.
6848ed55a54SJohn McCall   } else {
685f862eb6aSSebastian Redl     // There are up to five conditions we need to test for:
686036f2f6bSJohn McCall     // 1) if isSigned, we need to check whether numElements is negative;
687036f2f6bSJohn McCall     // 2) if numElementsWidth > sizeWidth, we need to check whether
688036f2f6bSJohn McCall     //   numElements is larger than something representable in size_t;
689f862eb6aSSebastian Redl     // 3) if minElements > 0, we need to check whether numElements is smaller
690f862eb6aSSebastian Redl     //    than that.
691f862eb6aSSebastian Redl     // 4) we need to compute
692036f2f6bSJohn McCall     //      sizeWithoutCookie := numElements * typeSizeMultiplier
693036f2f6bSJohn McCall     //    and check whether it overflows; and
694f862eb6aSSebastian Redl     // 5) if we need a cookie, we need to compute
695036f2f6bSJohn McCall     //      size := sizeWithoutCookie + cookieSize
696036f2f6bSJohn McCall     //    and check whether it overflows.
6978ed55a54SJohn McCall 
6988a13c418SCraig Topper     llvm::Value *hasOverflow = nullptr;
6998ed55a54SJohn McCall 
700036f2f6bSJohn McCall     // If numElementsWidth > sizeWidth, then one way or another, we're
701036f2f6bSJohn McCall     // going to have to do a comparison for (2), and this happens to
702036f2f6bSJohn McCall     // take care of (1), too.
703036f2f6bSJohn McCall     if (numElementsWidth > sizeWidth) {
704036f2f6bSJohn McCall       llvm::APInt threshold(numElementsWidth, 1);
705036f2f6bSJohn McCall       threshold <<= sizeWidth;
7068ed55a54SJohn McCall 
707036f2f6bSJohn McCall       llvm::Value *thresholdV
708036f2f6bSJohn McCall         = llvm::ConstantInt::get(numElementsType, threshold);
709036f2f6bSJohn McCall 
710036f2f6bSJohn McCall       hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
711036f2f6bSJohn McCall       numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
712036f2f6bSJohn McCall 
713036f2f6bSJohn McCall     // Otherwise, if we're signed, we want to sext up to size_t.
714036f2f6bSJohn McCall     } else if (isSigned) {
715036f2f6bSJohn McCall       if (numElementsWidth < sizeWidth)
716036f2f6bSJohn McCall         numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
717036f2f6bSJohn McCall 
718036f2f6bSJohn McCall       // If there's a non-1 type size multiplier, then we can do the
719036f2f6bSJohn McCall       // signedness check at the same time as we do the multiply
720036f2f6bSJohn McCall       // because a negative number times anything will cause an
721f862eb6aSSebastian Redl       // unsigned overflow.  Otherwise, we have to do it here. But at least
722f862eb6aSSebastian Redl       // in this case, we can subsume the >= minElements check.
723036f2f6bSJohn McCall       if (typeSizeMultiplier == 1)
724036f2f6bSJohn McCall         hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
725f862eb6aSSebastian Redl                               llvm::ConstantInt::get(CGF.SizeTy, minElements));
726036f2f6bSJohn McCall 
727036f2f6bSJohn McCall     // Otherwise, zext up to size_t if necessary.
728036f2f6bSJohn McCall     } else if (numElementsWidth < sizeWidth) {
729036f2f6bSJohn McCall       numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
730036f2f6bSJohn McCall     }
731036f2f6bSJohn McCall 
732036f2f6bSJohn McCall     assert(numElements->getType() == CGF.SizeTy);
733036f2f6bSJohn McCall 
734f862eb6aSSebastian Redl     if (minElements) {
735f862eb6aSSebastian Redl       // Don't allow allocation of fewer elements than we have initializers.
736f862eb6aSSebastian Redl       if (!hasOverflow) {
737f862eb6aSSebastian Redl         hasOverflow = CGF.Builder.CreateICmpULT(numElements,
738f862eb6aSSebastian Redl                               llvm::ConstantInt::get(CGF.SizeTy, minElements));
739f862eb6aSSebastian Redl       } else if (numElementsWidth > sizeWidth) {
740f862eb6aSSebastian Redl         // The other existing overflow subsumes this check.
741f862eb6aSSebastian Redl         // We do an unsigned comparison, since any signed value < -1 is
742f862eb6aSSebastian Redl         // taken care of either above or below.
743f862eb6aSSebastian Redl         hasOverflow = CGF.Builder.CreateOr(hasOverflow,
744f862eb6aSSebastian Redl                           CGF.Builder.CreateICmpULT(numElements,
745f862eb6aSSebastian Redl                               llvm::ConstantInt::get(CGF.SizeTy, minElements)));
746f862eb6aSSebastian Redl       }
747f862eb6aSSebastian Redl     }
748f862eb6aSSebastian Redl 
749036f2f6bSJohn McCall     size = numElements;
750036f2f6bSJohn McCall 
751036f2f6bSJohn McCall     // Multiply by the type size if necessary.  This multiplier
752036f2f6bSJohn McCall     // includes all the factors for nested arrays.
7538ed55a54SJohn McCall     //
754036f2f6bSJohn McCall     // This step also causes numElements to be scaled up by the
755036f2f6bSJohn McCall     // nested-array factor if necessary.  Overflow on this computation
756036f2f6bSJohn McCall     // can be ignored because the result shouldn't be used if
757036f2f6bSJohn McCall     // allocation fails.
758036f2f6bSJohn McCall     if (typeSizeMultiplier != 1) {
759036f2f6bSJohn McCall       llvm::Value *umul_with_overflow
7608d375cefSBenjamin Kramer         = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
7618ed55a54SJohn McCall 
762036f2f6bSJohn McCall       llvm::Value *tsmV =
763036f2f6bSJohn McCall         llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
764036f2f6bSJohn McCall       llvm::Value *result =
76543f9bb73SDavid Blaikie           CGF.Builder.CreateCall(umul_with_overflow, {size, tsmV});
7668ed55a54SJohn McCall 
767036f2f6bSJohn McCall       llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
768036f2f6bSJohn McCall       if (hasOverflow)
769036f2f6bSJohn McCall         hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
7708ed55a54SJohn McCall       else
771036f2f6bSJohn McCall         hasOverflow = overflowed;
77259486a2dSAnders Carlsson 
773036f2f6bSJohn McCall       size = CGF.Builder.CreateExtractValue(result, 0);
774036f2f6bSJohn McCall 
775036f2f6bSJohn McCall       // Also scale up numElements by the array size multiplier.
776036f2f6bSJohn McCall       if (arraySizeMultiplier != 1) {
777036f2f6bSJohn McCall         // If the base element type size is 1, then we can re-use the
778036f2f6bSJohn McCall         // multiply we just did.
779036f2f6bSJohn McCall         if (typeSize.isOne()) {
780036f2f6bSJohn McCall           assert(arraySizeMultiplier == typeSizeMultiplier);
781036f2f6bSJohn McCall           numElements = size;
782036f2f6bSJohn McCall 
783036f2f6bSJohn McCall         // Otherwise we need a separate multiply.
784036f2f6bSJohn McCall         } else {
785036f2f6bSJohn McCall           llvm::Value *asmV =
786036f2f6bSJohn McCall             llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
787036f2f6bSJohn McCall           numElements = CGF.Builder.CreateMul(numElements, asmV);
788036f2f6bSJohn McCall         }
789036f2f6bSJohn McCall       }
790036f2f6bSJohn McCall     } else {
791036f2f6bSJohn McCall       // numElements doesn't need to be scaled.
792036f2f6bSJohn McCall       assert(arraySizeMultiplier == 1);
793036f2f6bSJohn McCall     }
794036f2f6bSJohn McCall 
795036f2f6bSJohn McCall     // Add in the cookie size if necessary.
796036f2f6bSJohn McCall     if (cookieSize != 0) {
797036f2f6bSJohn McCall       sizeWithoutCookie = size;
798036f2f6bSJohn McCall 
799036f2f6bSJohn McCall       llvm::Value *uadd_with_overflow
8008d375cefSBenjamin Kramer         = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
801036f2f6bSJohn McCall 
802036f2f6bSJohn McCall       llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
803036f2f6bSJohn McCall       llvm::Value *result =
80443f9bb73SDavid Blaikie           CGF.Builder.CreateCall(uadd_with_overflow, {size, cookieSizeV});
805036f2f6bSJohn McCall 
806036f2f6bSJohn McCall       llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
807036f2f6bSJohn McCall       if (hasOverflow)
808036f2f6bSJohn McCall         hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
809036f2f6bSJohn McCall       else
810036f2f6bSJohn McCall         hasOverflow = overflowed;
811036f2f6bSJohn McCall 
812036f2f6bSJohn McCall       size = CGF.Builder.CreateExtractValue(result, 0);
813036f2f6bSJohn McCall     }
814036f2f6bSJohn McCall 
815036f2f6bSJohn McCall     // If we had any possibility of dynamic overflow, make a select to
816036f2f6bSJohn McCall     // overwrite 'size' with an all-ones value, which should cause
817036f2f6bSJohn McCall     // operator new to throw.
818036f2f6bSJohn McCall     if (hasOverflow)
819455f42c9SAaron Ballman       size = CGF.Builder.CreateSelect(hasOverflow,
820455f42c9SAaron Ballman                                  llvm::Constant::getAllOnesValue(CGF.SizeTy),
821036f2f6bSJohn McCall                                       size);
822036f2f6bSJohn McCall   }
823036f2f6bSJohn McCall 
824036f2f6bSJohn McCall   if (cookieSize == 0)
825036f2f6bSJohn McCall     sizeWithoutCookie = size;
826036f2f6bSJohn McCall   else
827036f2f6bSJohn McCall     assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
828036f2f6bSJohn McCall 
829036f2f6bSJohn McCall   return size;
83059486a2dSAnders Carlsson }
83159486a2dSAnders Carlsson 
832f862eb6aSSebastian Redl static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
8337f416cc4SJohn McCall                                     QualType AllocType, Address NewPtr) {
8341c96bc5dSRichard Smith   // FIXME: Refactor with EmitExprAsInit.
83547fb9508SJohn McCall   switch (CGF.getEvaluationKind(AllocType)) {
83647fb9508SJohn McCall   case TEK_Scalar:
837a2c1124fSDavid Blaikie     CGF.EmitScalarInit(Init, nullptr,
8387f416cc4SJohn McCall                        CGF.MakeAddrLValue(NewPtr, AllocType), false);
83947fb9508SJohn McCall     return;
84047fb9508SJohn McCall   case TEK_Complex:
8417f416cc4SJohn McCall     CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType),
84247fb9508SJohn McCall                                   /*isInit*/ true);
84347fb9508SJohn McCall     return;
84447fb9508SJohn McCall   case TEK_Aggregate: {
8457a626f63SJohn McCall     AggValueSlot Slot
8467f416cc4SJohn McCall       = AggValueSlot::forAddr(NewPtr, AllocType.getQualifiers(),
8478d6fc958SJohn McCall                               AggValueSlot::IsDestructed,
84846759f4fSJohn McCall                               AggValueSlot::DoesNotNeedGCBarriers,
849615ed1a3SChad Rosier                               AggValueSlot::IsNotAliased);
8507a626f63SJohn McCall     CGF.EmitAggExpr(Init, Slot);
85147fb9508SJohn McCall     return;
8527a626f63SJohn McCall   }
853d5202e09SFariborz Jahanian   }
85447fb9508SJohn McCall   llvm_unreachable("bad evaluation kind");
85547fb9508SJohn McCall }
856d5202e09SFariborz Jahanian 
857fb901c7aSDavid Blaikie void CodeGenFunction::EmitNewArrayInitializer(
858fb901c7aSDavid Blaikie     const CXXNewExpr *E, QualType ElementType, llvm::Type *ElementTy,
8597f416cc4SJohn McCall     Address BeginPtr, llvm::Value *NumElements,
86006a67e2cSRichard Smith     llvm::Value *AllocSizeWithoutCookie) {
86106a67e2cSRichard Smith   // If we have a type with trivial initialization and no initializer,
86206a67e2cSRichard Smith   // there's nothing to do.
8636047f07eSSebastian Redl   if (!E->hasInitializer())
86406a67e2cSRichard Smith     return;
865b66b08efSFariborz Jahanian 
8667f416cc4SJohn McCall   Address CurPtr = BeginPtr;
867d5202e09SFariborz Jahanian 
86806a67e2cSRichard Smith   unsigned InitListElements = 0;
869f862eb6aSSebastian Redl 
870f862eb6aSSebastian Redl   const Expr *Init = E->getInitializer();
8717f416cc4SJohn McCall   Address EndOfInit = Address::invalid();
87206a67e2cSRichard Smith   QualType::DestructionKind DtorKind = ElementType.isDestructedType();
87306a67e2cSRichard Smith   EHScopeStack::stable_iterator Cleanup;
87406a67e2cSRichard Smith   llvm::Instruction *CleanupDominator = nullptr;
8751c96bc5dSRichard Smith 
8767f416cc4SJohn McCall   CharUnits ElementSize = getContext().getTypeSizeInChars(ElementType);
8777f416cc4SJohn McCall   CharUnits ElementAlign =
8787f416cc4SJohn McCall     BeginPtr.getAlignment().alignmentOfArrayElement(ElementSize);
8797f416cc4SJohn McCall 
880f862eb6aSSebastian Redl   // If the initializer is an initializer list, first do the explicit elements.
881f862eb6aSSebastian Redl   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
88206a67e2cSRichard Smith     InitListElements = ILE->getNumInits();
883f62290a1SChad Rosier 
8841c96bc5dSRichard Smith     // If this is a multi-dimensional array new, we will initialize multiple
8851c96bc5dSRichard Smith     // elements with each init list element.
8861c96bc5dSRichard Smith     QualType AllocType = E->getAllocatedType();
8871c96bc5dSRichard Smith     if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
8881c96bc5dSRichard Smith             AllocType->getAsArrayTypeUnsafe())) {
889fb901c7aSDavid Blaikie       ElementTy = ConvertTypeForMem(AllocType);
8907f416cc4SJohn McCall       CurPtr = Builder.CreateElementBitCast(CurPtr, ElementTy);
89106a67e2cSRichard Smith       InitListElements *= getContext().getConstantArrayElementCount(CAT);
8921c96bc5dSRichard Smith     }
8931c96bc5dSRichard Smith 
89406a67e2cSRichard Smith     // Enter a partial-destruction Cleanup if necessary.
89506a67e2cSRichard Smith     if (needsEHCleanup(DtorKind)) {
89606a67e2cSRichard Smith       // In principle we could tell the Cleanup where we are more
897f62290a1SChad Rosier       // directly, but the control flow can get so varied here that it
898f62290a1SChad Rosier       // would actually be quite complex.  Therefore we go through an
899f62290a1SChad Rosier       // alloca.
9007f416cc4SJohn McCall       EndOfInit = CreateTempAlloca(BeginPtr.getType(), getPointerAlign(),
9017f416cc4SJohn McCall                                    "array.init.end");
9027f416cc4SJohn McCall       CleanupDominator = Builder.CreateStore(BeginPtr.getPointer(), EndOfInit);
9037f416cc4SJohn McCall       pushIrregularPartialArrayCleanup(BeginPtr.getPointer(), EndOfInit,
9047f416cc4SJohn McCall                                        ElementType, ElementAlign,
90506a67e2cSRichard Smith                                        getDestroyer(DtorKind));
90606a67e2cSRichard Smith       Cleanup = EHStack.stable_begin();
907f62290a1SChad Rosier     }
908f62290a1SChad Rosier 
9097f416cc4SJohn McCall     CharUnits StartAlign = CurPtr.getAlignment();
910f862eb6aSSebastian Redl     for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
911f62290a1SChad Rosier       // Tell the cleanup that it needs to destroy up to this
912f62290a1SChad Rosier       // element.  TODO: some of these stores can be trivially
913f62290a1SChad Rosier       // observed to be unnecessary.
9147f416cc4SJohn McCall       if (EndOfInit.isValid()) {
9157f416cc4SJohn McCall         auto FinishedPtr =
9167f416cc4SJohn McCall           Builder.CreateBitCast(CurPtr.getPointer(), BeginPtr.getType());
9177f416cc4SJohn McCall         Builder.CreateStore(FinishedPtr, EndOfInit);
9187f416cc4SJohn McCall       }
91906a67e2cSRichard Smith       // FIXME: If the last initializer is an incomplete initializer list for
92006a67e2cSRichard Smith       // an array, and we have an array filler, we can fold together the two
92106a67e2cSRichard Smith       // initialization loops.
9221c96bc5dSRichard Smith       StoreAnyExprIntoOneUnit(*this, ILE->getInit(i),
92306a67e2cSRichard Smith                               ILE->getInit(i)->getType(), CurPtr);
9247f416cc4SJohn McCall       CurPtr = Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(),
9257f416cc4SJohn McCall                                                  Builder.getSize(1),
9267f416cc4SJohn McCall                                                  "array.exp.next"),
9277f416cc4SJohn McCall                        StartAlign.alignmentAtOffset((i + 1) * ElementSize));
928f862eb6aSSebastian Redl     }
929f862eb6aSSebastian Redl 
930f862eb6aSSebastian Redl     // The remaining elements are filled with the array filler expression.
931f862eb6aSSebastian Redl     Init = ILE->getArrayFiller();
9321c96bc5dSRichard Smith 
93306a67e2cSRichard Smith     // Extract the initializer for the individual array elements by pulling
93406a67e2cSRichard Smith     // out the array filler from all the nested initializer lists. This avoids
93506a67e2cSRichard Smith     // generating a nested loop for the initialization.
93606a67e2cSRichard Smith     while (Init && Init->getType()->isConstantArrayType()) {
93706a67e2cSRichard Smith       auto *SubILE = dyn_cast<InitListExpr>(Init);
93806a67e2cSRichard Smith       if (!SubILE)
93906a67e2cSRichard Smith         break;
94006a67e2cSRichard Smith       assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
94106a67e2cSRichard Smith       Init = SubILE->getArrayFiller();
942f862eb6aSSebastian Redl     }
943f862eb6aSSebastian Redl 
94406a67e2cSRichard Smith     // Switch back to initializing one base element at a time.
9457f416cc4SJohn McCall     CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr.getType());
946f62290a1SChad Rosier   }
947e6c980c4SChandler Carruth 
94806a67e2cSRichard Smith   // Attempt to perform zero-initialization using memset.
94906a67e2cSRichard Smith   auto TryMemsetInitialization = [&]() -> bool {
95006a67e2cSRichard Smith     // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
95106a67e2cSRichard Smith     // we can initialize with a memset to -1.
95206a67e2cSRichard Smith     if (!CGM.getTypes().isZeroInitializable(ElementType))
95306a67e2cSRichard Smith       return false;
954e6c980c4SChandler Carruth 
95506a67e2cSRichard Smith     // Optimization: since zero initialization will just set the memory
95606a67e2cSRichard Smith     // to all zeroes, generate a single memset to do it in one shot.
95706a67e2cSRichard Smith 
95806a67e2cSRichard Smith     // Subtract out the size of any elements we've already initialized.
95906a67e2cSRichard Smith     auto *RemainingSize = AllocSizeWithoutCookie;
96006a67e2cSRichard Smith     if (InitListElements) {
96106a67e2cSRichard Smith       // We know this can't overflow; we check this when doing the allocation.
96206a67e2cSRichard Smith       auto *InitializedSize = llvm::ConstantInt::get(
96306a67e2cSRichard Smith           RemainingSize->getType(),
96406a67e2cSRichard Smith           getContext().getTypeSizeInChars(ElementType).getQuantity() *
96506a67e2cSRichard Smith               InitListElements);
96606a67e2cSRichard Smith       RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
96799210dc9SJohn McCall     }
968d5202e09SFariborz Jahanian 
96906a67e2cSRichard Smith     // Create the memset.
9707f416cc4SJohn McCall     Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize, false);
97106a67e2cSRichard Smith     return true;
97206a67e2cSRichard Smith   };
97305fc5be3SDouglas Gregor 
974454a7cdfSRichard Smith   // If all elements have already been initialized, skip any further
975454a7cdfSRichard Smith   // initialization.
976454a7cdfSRichard Smith   llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
977454a7cdfSRichard Smith   if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
978454a7cdfSRichard Smith     // If there was a Cleanup, deactivate it.
979454a7cdfSRichard Smith     if (CleanupDominator)
980454a7cdfSRichard Smith       DeactivateCleanupBlock(Cleanup, CleanupDominator);
981454a7cdfSRichard Smith     return;
982454a7cdfSRichard Smith   }
983454a7cdfSRichard Smith 
984454a7cdfSRichard Smith   assert(Init && "have trailing elements to initialize but no initializer");
985454a7cdfSRichard Smith 
98606a67e2cSRichard Smith   // If this is a constructor call, try to optimize it out, and failing that
98706a67e2cSRichard Smith   // emit a single loop to initialize all remaining elements.
988454a7cdfSRichard Smith   if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
9896047f07eSSebastian Redl     CXXConstructorDecl *Ctor = CCE->getConstructor();
990d153103cSDouglas Gregor     if (Ctor->isTrivial()) {
99105fc5be3SDouglas Gregor       // If new expression did not specify value-initialization, then there
99205fc5be3SDouglas Gregor       // is no initialization.
9936047f07eSSebastian Redl       if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
99405fc5be3SDouglas Gregor         return;
99505fc5be3SDouglas Gregor 
99606a67e2cSRichard Smith       if (TryMemsetInitialization())
9973a202f60SAnders Carlsson         return;
9983a202f60SAnders Carlsson     }
99905fc5be3SDouglas Gregor 
100006a67e2cSRichard Smith     // Store the new Cleanup position for irregular Cleanups.
100106a67e2cSRichard Smith     //
100206a67e2cSRichard Smith     // FIXME: Share this cleanup with the constructor call emission rather than
100306a67e2cSRichard Smith     // having it create a cleanup of its own.
10047f416cc4SJohn McCall     if (EndOfInit.isValid())
10057f416cc4SJohn McCall       Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
100606a67e2cSRichard Smith 
100706a67e2cSRichard Smith     // Emit a constructor call loop to initialize the remaining elements.
100806a67e2cSRichard Smith     if (InitListElements)
100906a67e2cSRichard Smith       NumElements = Builder.CreateSub(
101006a67e2cSRichard Smith           NumElements,
101106a67e2cSRichard Smith           llvm::ConstantInt::get(NumElements->getType(), InitListElements));
101270b9c01bSAlexey Samsonov     EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,
101348ddcf2cSEli Friedman                                CCE->requiresZeroInitialization());
101405fc5be3SDouglas Gregor     return;
10156047f07eSSebastian Redl   }
101606a67e2cSRichard Smith 
101706a67e2cSRichard Smith   // If this is value-initialization, we can usually use memset.
101806a67e2cSRichard Smith   ImplicitValueInitExpr IVIE(ElementType);
1019454a7cdfSRichard Smith   if (isa<ImplicitValueInitExpr>(Init)) {
102006a67e2cSRichard Smith     if (TryMemsetInitialization())
102106a67e2cSRichard Smith       return;
102206a67e2cSRichard Smith 
102306a67e2cSRichard Smith     // Switch to an ImplicitValueInitExpr for the element type. This handles
102406a67e2cSRichard Smith     // only one case: multidimensional array new of pointers to members. In
102506a67e2cSRichard Smith     // all other cases, we already have an initializer for the array element.
102606a67e2cSRichard Smith     Init = &IVIE;
102706a67e2cSRichard Smith   }
102806a67e2cSRichard Smith 
102906a67e2cSRichard Smith   // At this point we should have found an initializer for the individual
103006a67e2cSRichard Smith   // elements of the array.
103106a67e2cSRichard Smith   assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&
103206a67e2cSRichard Smith          "got wrong type of element to initialize");
103306a67e2cSRichard Smith 
1034454a7cdfSRichard Smith   // If we have an empty initializer list, we can usually use memset.
1035454a7cdfSRichard Smith   if (auto *ILE = dyn_cast<InitListExpr>(Init))
1036454a7cdfSRichard Smith     if (ILE->getNumInits() == 0 && TryMemsetInitialization())
1037d5202e09SFariborz Jahanian       return;
103859486a2dSAnders Carlsson 
1039cb77930dSYunzhong Gao   // If we have a struct whose every field is value-initialized, we can
1040cb77930dSYunzhong Gao   // usually use memset.
1041cb77930dSYunzhong Gao   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
1042cb77930dSYunzhong Gao     if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
1043cb77930dSYunzhong Gao       if (RType->getDecl()->isStruct()) {
1044872307e2SRichard Smith         unsigned NumElements = 0;
1045872307e2SRichard Smith         if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RType->getDecl()))
1046872307e2SRichard Smith           NumElements = CXXRD->getNumBases();
1047cb77930dSYunzhong Gao         for (auto *Field : RType->getDecl()->fields())
1048cb77930dSYunzhong Gao           if (!Field->isUnnamedBitfield())
1049872307e2SRichard Smith             ++NumElements;
1050872307e2SRichard Smith         // FIXME: Recurse into nested InitListExprs.
1051872307e2SRichard Smith         if (ILE->getNumInits() == NumElements)
1052cb77930dSYunzhong Gao           for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
1053cb77930dSYunzhong Gao             if (!isa<ImplicitValueInitExpr>(ILE->getInit(i)))
1054872307e2SRichard Smith               --NumElements;
1055872307e2SRichard Smith         if (ILE->getNumInits() == NumElements && TryMemsetInitialization())
1056cb77930dSYunzhong Gao           return;
1057cb77930dSYunzhong Gao       }
1058cb77930dSYunzhong Gao     }
1059cb77930dSYunzhong Gao   }
1060cb77930dSYunzhong Gao 
106106a67e2cSRichard Smith   // Create the loop blocks.
106206a67e2cSRichard Smith   llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
106306a67e2cSRichard Smith   llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
106406a67e2cSRichard Smith   llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
106559486a2dSAnders Carlsson 
106606a67e2cSRichard Smith   // Find the end of the array, hoisted out of the loop.
106706a67e2cSRichard Smith   llvm::Value *EndPtr =
10687f416cc4SJohn McCall     Builder.CreateInBoundsGEP(BeginPtr.getPointer(), NumElements, "array.end");
106906a67e2cSRichard Smith 
107006a67e2cSRichard Smith   // If the number of elements isn't constant, we have to now check if there is
107106a67e2cSRichard Smith   // anything left to initialize.
107206a67e2cSRichard Smith   if (!ConstNum) {
10737f416cc4SJohn McCall     llvm::Value *IsEmpty =
10747f416cc4SJohn McCall       Builder.CreateICmpEQ(CurPtr.getPointer(), EndPtr, "array.isempty");
107506a67e2cSRichard Smith     Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
107606a67e2cSRichard Smith   }
107706a67e2cSRichard Smith 
107806a67e2cSRichard Smith   // Enter the loop.
107906a67e2cSRichard Smith   EmitBlock(LoopBB);
108006a67e2cSRichard Smith 
108106a67e2cSRichard Smith   // Set up the current-element phi.
108206a67e2cSRichard Smith   llvm::PHINode *CurPtrPhi =
10837f416cc4SJohn McCall     Builder.CreatePHI(CurPtr.getType(), 2, "array.cur");
10847f416cc4SJohn McCall   CurPtrPhi->addIncoming(CurPtr.getPointer(), EntryBB);
10857f416cc4SJohn McCall 
10867f416cc4SJohn McCall   CurPtr = Address(CurPtrPhi, ElementAlign);
108706a67e2cSRichard Smith 
108806a67e2cSRichard Smith   // Store the new Cleanup position for irregular Cleanups.
10897f416cc4SJohn McCall   if (EndOfInit.isValid())
10907f416cc4SJohn McCall     Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
109106a67e2cSRichard Smith 
109206a67e2cSRichard Smith   // Enter a partial-destruction Cleanup if necessary.
109306a67e2cSRichard Smith   if (!CleanupDominator && needsEHCleanup(DtorKind)) {
10947f416cc4SJohn McCall     pushRegularPartialArrayCleanup(BeginPtr.getPointer(), CurPtr.getPointer(),
10957f416cc4SJohn McCall                                    ElementType, ElementAlign,
109606a67e2cSRichard Smith                                    getDestroyer(DtorKind));
109706a67e2cSRichard Smith     Cleanup = EHStack.stable_begin();
109806a67e2cSRichard Smith     CleanupDominator = Builder.CreateUnreachable();
109906a67e2cSRichard Smith   }
110006a67e2cSRichard Smith 
110106a67e2cSRichard Smith   // Emit the initializer into this element.
110206a67e2cSRichard Smith   StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr);
110306a67e2cSRichard Smith 
110406a67e2cSRichard Smith   // Leave the Cleanup if we entered one.
110506a67e2cSRichard Smith   if (CleanupDominator) {
110606a67e2cSRichard Smith     DeactivateCleanupBlock(Cleanup, CleanupDominator);
110706a67e2cSRichard Smith     CleanupDominator->eraseFromParent();
110806a67e2cSRichard Smith   }
110906a67e2cSRichard Smith 
111006a67e2cSRichard Smith   // Advance to the next element by adjusting the pointer type as necessary.
111106a67e2cSRichard Smith   llvm::Value *NextPtr =
11127f416cc4SJohn McCall     Builder.CreateConstInBoundsGEP1_32(ElementTy, CurPtr.getPointer(), 1,
11137f416cc4SJohn McCall                                        "array.next");
111406a67e2cSRichard Smith 
111506a67e2cSRichard Smith   // Check whether we've gotten to the end of the array and, if so,
111606a67e2cSRichard Smith   // exit the loop.
111706a67e2cSRichard Smith   llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
111806a67e2cSRichard Smith   Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
111906a67e2cSRichard Smith   CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
112006a67e2cSRichard Smith 
112106a67e2cSRichard Smith   EmitBlock(ContBB);
112206a67e2cSRichard Smith }
112306a67e2cSRichard Smith 
112406a67e2cSRichard Smith static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
1125fb901c7aSDavid Blaikie                                QualType ElementType, llvm::Type *ElementTy,
11267f416cc4SJohn McCall                                Address NewPtr, llvm::Value *NumElements,
112706a67e2cSRichard Smith                                llvm::Value *AllocSizeWithoutCookie) {
11289b479666SDavid Blaikie   ApplyDebugLocation DL(CGF, E);
112906a67e2cSRichard Smith   if (E->isArray())
1130fb901c7aSDavid Blaikie     CGF.EmitNewArrayInitializer(E, ElementType, ElementTy, NewPtr, NumElements,
113106a67e2cSRichard Smith                                 AllocSizeWithoutCookie);
113206a67e2cSRichard Smith   else if (const Expr *Init = E->getInitializer())
113366e4197fSDavid Blaikie     StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
113459486a2dSAnders Carlsson }
113559486a2dSAnders Carlsson 
11368d0dc31dSRichard Smith /// Emit a call to an operator new or operator delete function, as implicitly
11378d0dc31dSRichard Smith /// created by new-expressions and delete-expressions.
11388d0dc31dSRichard Smith static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
11398d0dc31dSRichard Smith                                 const FunctionDecl *Callee,
11408d0dc31dSRichard Smith                                 const FunctionProtoType *CalleeType,
11418d0dc31dSRichard Smith                                 const CallArgList &Args) {
11428d0dc31dSRichard Smith   llvm::Instruction *CallOrInvoke;
11431235a8daSRichard Smith   llvm::Value *CalleeAddr = CGF.CGM.GetAddrOfFunction(Callee);
11448d0dc31dSRichard Smith   RValue RV =
1145f770683fSPeter Collingbourne       CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(
1146f770683fSPeter Collingbourne                        Args, CalleeType, /*chainCall=*/false),
1147f770683fSPeter Collingbourne                    CalleeAddr, ReturnValueSlot(), Args, Callee, &CallOrInvoke);
11488d0dc31dSRichard Smith 
11498d0dc31dSRichard Smith   /// C++1y [expr.new]p10:
11508d0dc31dSRichard Smith   ///   [In a new-expression,] an implementation is allowed to omit a call
11518d0dc31dSRichard Smith   ///   to a replaceable global allocation function.
11528d0dc31dSRichard Smith   ///
11538d0dc31dSRichard Smith   /// We model such elidable calls with the 'builtin' attribute.
11546956d587SRafael Espindola   llvm::Function *Fn = dyn_cast<llvm::Function>(CalleeAddr);
11551235a8daSRichard Smith   if (Callee->isReplaceableGlobalAllocationFunction() &&
11566956d587SRafael Espindola       Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
11578d0dc31dSRichard Smith     // FIXME: Add addAttribute to CallSite.
11588d0dc31dSRichard Smith     if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(CallOrInvoke))
11598d0dc31dSRichard Smith       CI->addAttribute(llvm::AttributeSet::FunctionIndex,
11608d0dc31dSRichard Smith                        llvm::Attribute::Builtin);
11618d0dc31dSRichard Smith     else if (llvm::InvokeInst *II = dyn_cast<llvm::InvokeInst>(CallOrInvoke))
11628d0dc31dSRichard Smith       II->addAttribute(llvm::AttributeSet::FunctionIndex,
11638d0dc31dSRichard Smith                        llvm::Attribute::Builtin);
11648d0dc31dSRichard Smith     else
11658d0dc31dSRichard Smith       llvm_unreachable("unexpected kind of call instruction");
11668d0dc31dSRichard Smith   }
11678d0dc31dSRichard Smith 
11688d0dc31dSRichard Smith   return RV;
11698d0dc31dSRichard Smith }
11708d0dc31dSRichard Smith 
1171760520bcSRichard Smith RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
1172760520bcSRichard Smith                                                  const Expr *Arg,
1173760520bcSRichard Smith                                                  bool IsDelete) {
1174760520bcSRichard Smith   CallArgList Args;
1175760520bcSRichard Smith   const Stmt *ArgS = Arg;
1176f05779e2SDavid Blaikie   EmitCallArgs(Args, *Type->param_type_begin(), llvm::makeArrayRef(ArgS));
1177760520bcSRichard Smith   // Find the allocation or deallocation function that we're calling.
1178760520bcSRichard Smith   ASTContext &Ctx = getContext();
1179760520bcSRichard Smith   DeclarationName Name = Ctx.DeclarationNames
1180760520bcSRichard Smith       .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
1181760520bcSRichard Smith   for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
1182599bed75SRichard Smith     if (auto *FD = dyn_cast<FunctionDecl>(Decl))
1183599bed75SRichard Smith       if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
1184760520bcSRichard Smith         return EmitNewDeleteCall(*this, cast<FunctionDecl>(Decl), Type, Args);
1185760520bcSRichard Smith   llvm_unreachable("predeclared global operator new/delete is missing");
1186760520bcSRichard Smith }
1187760520bcSRichard Smith 
1188824c2f53SJohn McCall namespace {
1189824c2f53SJohn McCall   /// A cleanup to call the given 'operator delete' function upon
1190824c2f53SJohn McCall   /// abnormal exit from a new expression.
11917e70d680SDavid Blaikie   class CallDeleteDuringNew final : public EHScopeStack::Cleanup {
1192824c2f53SJohn McCall     size_t NumPlacementArgs;
1193824c2f53SJohn McCall     const FunctionDecl *OperatorDelete;
1194824c2f53SJohn McCall     llvm::Value *Ptr;
1195824c2f53SJohn McCall     llvm::Value *AllocSize;
1196824c2f53SJohn McCall 
1197824c2f53SJohn McCall     RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
1198824c2f53SJohn McCall 
1199824c2f53SJohn McCall   public:
1200824c2f53SJohn McCall     static size_t getExtraSize(size_t NumPlacementArgs) {
1201824c2f53SJohn McCall       return NumPlacementArgs * sizeof(RValue);
1202824c2f53SJohn McCall     }
1203824c2f53SJohn McCall 
1204824c2f53SJohn McCall     CallDeleteDuringNew(size_t NumPlacementArgs,
1205824c2f53SJohn McCall                         const FunctionDecl *OperatorDelete,
1206824c2f53SJohn McCall                         llvm::Value *Ptr,
1207824c2f53SJohn McCall                         llvm::Value *AllocSize)
1208824c2f53SJohn McCall       : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1209824c2f53SJohn McCall         Ptr(Ptr), AllocSize(AllocSize) {}
1210824c2f53SJohn McCall 
1211824c2f53SJohn McCall     void setPlacementArg(unsigned I, RValue Arg) {
1212824c2f53SJohn McCall       assert(I < NumPlacementArgs && "index out of range");
1213824c2f53SJohn McCall       getPlacementArgs()[I] = Arg;
1214824c2f53SJohn McCall     }
1215824c2f53SJohn McCall 
12164f12f10dSCraig Topper     void Emit(CodeGenFunction &CGF, Flags flags) override {
1217824c2f53SJohn McCall       const FunctionProtoType *FPT
1218824c2f53SJohn McCall         = OperatorDelete->getType()->getAs<FunctionProtoType>();
12199cacbabdSAlp Toker       assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
12209cacbabdSAlp Toker              (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
1221824c2f53SJohn McCall 
1222824c2f53SJohn McCall       CallArgList DeleteArgs;
1223824c2f53SJohn McCall 
1224824c2f53SJohn McCall       // The first argument is always a void*.
12259cacbabdSAlp Toker       FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
122643dca6a8SEli Friedman       DeleteArgs.add(RValue::get(Ptr), *AI++);
1227824c2f53SJohn McCall 
1228824c2f53SJohn McCall       // A member 'operator delete' can take an extra 'size_t' argument.
12299cacbabdSAlp Toker       if (FPT->getNumParams() == NumPlacementArgs + 2)
123043dca6a8SEli Friedman         DeleteArgs.add(RValue::get(AllocSize), *AI++);
1231824c2f53SJohn McCall 
1232824c2f53SJohn McCall       // Pass the rest of the arguments, which must match exactly.
1233824c2f53SJohn McCall       for (unsigned I = 0; I != NumPlacementArgs; ++I)
123443dca6a8SEli Friedman         DeleteArgs.add(getPlacementArgs()[I], *AI++);
1235824c2f53SJohn McCall 
1236824c2f53SJohn McCall       // Call 'operator delete'.
12378d0dc31dSRichard Smith       EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
1238824c2f53SJohn McCall     }
1239824c2f53SJohn McCall   };
12407f9c92a9SJohn McCall 
12417f9c92a9SJohn McCall   /// A cleanup to call the given 'operator delete' function upon
12427f9c92a9SJohn McCall   /// abnormal exit from a new expression when the new expression is
12437f9c92a9SJohn McCall   /// conditional.
12447e70d680SDavid Blaikie   class CallDeleteDuringConditionalNew final : public EHScopeStack::Cleanup {
12457f9c92a9SJohn McCall     size_t NumPlacementArgs;
12467f9c92a9SJohn McCall     const FunctionDecl *OperatorDelete;
1247cb5f77f0SJohn McCall     DominatingValue<RValue>::saved_type Ptr;
1248cb5f77f0SJohn McCall     DominatingValue<RValue>::saved_type AllocSize;
12497f9c92a9SJohn McCall 
1250cb5f77f0SJohn McCall     DominatingValue<RValue>::saved_type *getPlacementArgs() {
1251cb5f77f0SJohn McCall       return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
12527f9c92a9SJohn McCall     }
12537f9c92a9SJohn McCall 
12547f9c92a9SJohn McCall   public:
12557f9c92a9SJohn McCall     static size_t getExtraSize(size_t NumPlacementArgs) {
1256cb5f77f0SJohn McCall       return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
12577f9c92a9SJohn McCall     }
12587f9c92a9SJohn McCall 
12597f9c92a9SJohn McCall     CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
12607f9c92a9SJohn McCall                                    const FunctionDecl *OperatorDelete,
1261cb5f77f0SJohn McCall                                    DominatingValue<RValue>::saved_type Ptr,
1262cb5f77f0SJohn McCall                               DominatingValue<RValue>::saved_type AllocSize)
12637f9c92a9SJohn McCall       : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
12647f9c92a9SJohn McCall         Ptr(Ptr), AllocSize(AllocSize) {}
12657f9c92a9SJohn McCall 
1266cb5f77f0SJohn McCall     void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
12677f9c92a9SJohn McCall       assert(I < NumPlacementArgs && "index out of range");
12687f9c92a9SJohn McCall       getPlacementArgs()[I] = Arg;
12697f9c92a9SJohn McCall     }
12707f9c92a9SJohn McCall 
12714f12f10dSCraig Topper     void Emit(CodeGenFunction &CGF, Flags flags) override {
12727f9c92a9SJohn McCall       const FunctionProtoType *FPT
12737f9c92a9SJohn McCall         = OperatorDelete->getType()->getAs<FunctionProtoType>();
12749cacbabdSAlp Toker       assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
12759cacbabdSAlp Toker              (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
12767f9c92a9SJohn McCall 
12777f9c92a9SJohn McCall       CallArgList DeleteArgs;
12787f9c92a9SJohn McCall 
12797f9c92a9SJohn McCall       // The first argument is always a void*.
12809cacbabdSAlp Toker       FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
128143dca6a8SEli Friedman       DeleteArgs.add(Ptr.restore(CGF), *AI++);
12827f9c92a9SJohn McCall 
12837f9c92a9SJohn McCall       // A member 'operator delete' can take an extra 'size_t' argument.
12849cacbabdSAlp Toker       if (FPT->getNumParams() == NumPlacementArgs + 2) {
1285cb5f77f0SJohn McCall         RValue RV = AllocSize.restore(CGF);
128643dca6a8SEli Friedman         DeleteArgs.add(RV, *AI++);
12877f9c92a9SJohn McCall       }
12887f9c92a9SJohn McCall 
12897f9c92a9SJohn McCall       // Pass the rest of the arguments, which must match exactly.
12907f9c92a9SJohn McCall       for (unsigned I = 0; I != NumPlacementArgs; ++I) {
1291cb5f77f0SJohn McCall         RValue RV = getPlacementArgs()[I].restore(CGF);
129243dca6a8SEli Friedman         DeleteArgs.add(RV, *AI++);
12937f9c92a9SJohn McCall       }
12947f9c92a9SJohn McCall 
12957f9c92a9SJohn McCall       // Call 'operator delete'.
12968d0dc31dSRichard Smith       EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
12977f9c92a9SJohn McCall     }
12987f9c92a9SJohn McCall   };
1299ab9db510SAlexander Kornienko }
13007f9c92a9SJohn McCall 
13017f9c92a9SJohn McCall /// Enter a cleanup to call 'operator delete' if the initializer in a
13027f9c92a9SJohn McCall /// new-expression throws.
13037f9c92a9SJohn McCall static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
13047f9c92a9SJohn McCall                                   const CXXNewExpr *E,
13057f416cc4SJohn McCall                                   Address NewPtr,
13067f9c92a9SJohn McCall                                   llvm::Value *AllocSize,
13077f9c92a9SJohn McCall                                   const CallArgList &NewArgs) {
13087f9c92a9SJohn McCall   // If we're not inside a conditional branch, then the cleanup will
13097f9c92a9SJohn McCall   // dominate and we can do the easier (and more efficient) thing.
13107f9c92a9SJohn McCall   if (!CGF.isInConditionalBranch()) {
13117f9c92a9SJohn McCall     CallDeleteDuringNew *Cleanup = CGF.EHStack
13127f9c92a9SJohn McCall       .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
13137f9c92a9SJohn McCall                                                  E->getNumPlacementArgs(),
13147f9c92a9SJohn McCall                                                  E->getOperatorDelete(),
13157f416cc4SJohn McCall                                                  NewPtr.getPointer(),
13167f416cc4SJohn McCall                                                  AllocSize);
13177f9c92a9SJohn McCall     for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1318f4258eb4SEli Friedman       Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
13197f9c92a9SJohn McCall 
13207f9c92a9SJohn McCall     return;
13217f9c92a9SJohn McCall   }
13227f9c92a9SJohn McCall 
13237f9c92a9SJohn McCall   // Otherwise, we need to save all this stuff.
1324cb5f77f0SJohn McCall   DominatingValue<RValue>::saved_type SavedNewPtr =
13257f416cc4SJohn McCall     DominatingValue<RValue>::save(CGF, RValue::get(NewPtr.getPointer()));
1326cb5f77f0SJohn McCall   DominatingValue<RValue>::saved_type SavedAllocSize =
1327cb5f77f0SJohn McCall     DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
13287f9c92a9SJohn McCall 
13297f9c92a9SJohn McCall   CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
1330f4beacd0SJohn McCall     .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(EHCleanup,
13317f9c92a9SJohn McCall                                                  E->getNumPlacementArgs(),
13327f9c92a9SJohn McCall                                                  E->getOperatorDelete(),
13337f9c92a9SJohn McCall                                                  SavedNewPtr,
13347f9c92a9SJohn McCall                                                  SavedAllocSize);
13357f9c92a9SJohn McCall   for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1336cb5f77f0SJohn McCall     Cleanup->setPlacementArg(I,
1337f4258eb4SEli Friedman                      DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
13387f9c92a9SJohn McCall 
1339f4beacd0SJohn McCall   CGF.initFullExprCleanup();
1340824c2f53SJohn McCall }
1341824c2f53SJohn McCall 
134259486a2dSAnders Carlsson llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
134375f9498aSJohn McCall   // The element type being allocated.
134475f9498aSJohn McCall   QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
13458ed55a54SJohn McCall 
134675f9498aSJohn McCall   // 1. Build a call to the allocation function.
134775f9498aSJohn McCall   FunctionDecl *allocator = E->getOperatorNew();
134859486a2dSAnders Carlsson 
1349f862eb6aSSebastian Redl   // If there is a brace-initializer, cannot allocate fewer elements than inits.
1350f862eb6aSSebastian Redl   unsigned minElements = 0;
1351f862eb6aSSebastian Redl   if (E->isArray() && E->hasInitializer()) {
1352f862eb6aSSebastian Redl     if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer()))
1353f862eb6aSSebastian Redl       minElements = ILE->getNumInits();
1354f862eb6aSSebastian Redl   }
1355f862eb6aSSebastian Redl 
13568a13c418SCraig Topper   llvm::Value *numElements = nullptr;
13578a13c418SCraig Topper   llvm::Value *allocSizeWithoutCookie = nullptr;
135875f9498aSJohn McCall   llvm::Value *allocSize =
1359f862eb6aSSebastian Redl     EmitCXXNewAllocSize(*this, E, minElements, numElements,
1360f862eb6aSSebastian Redl                         allocSizeWithoutCookie);
136159486a2dSAnders Carlsson 
13627f416cc4SJohn McCall   // Emit the allocation call.  If the allocator is a global placement
13637f416cc4SJohn McCall   // operator, just "inline" it directly.
13647f416cc4SJohn McCall   Address allocation = Address::invalid();
13657f416cc4SJohn McCall   CallArgList allocatorArgs;
13667f416cc4SJohn McCall   if (allocator->isReservedGlobalPlacementOperator()) {
136753dcf94dSJohn McCall     assert(E->getNumPlacementArgs() == 1);
136853dcf94dSJohn McCall     const Expr *arg = *E->placement_arguments().begin();
136953dcf94dSJohn McCall 
13707f416cc4SJohn McCall     AlignmentSource alignSource;
137153dcf94dSJohn McCall     allocation = EmitPointerWithAlignment(arg, &alignSource);
13727f416cc4SJohn McCall 
13737f416cc4SJohn McCall     // The pointer expression will, in many cases, be an opaque void*.
13747f416cc4SJohn McCall     // In these cases, discard the computed alignment and use the
13757f416cc4SJohn McCall     // formal alignment of the allocated type.
13767f416cc4SJohn McCall     if (alignSource != AlignmentSource::Decl) {
13777f416cc4SJohn McCall       allocation = Address(allocation.getPointer(),
13787f416cc4SJohn McCall                            getContext().getTypeAlignInChars(allocType));
13797f416cc4SJohn McCall     }
13807f416cc4SJohn McCall 
138153dcf94dSJohn McCall     // Set up allocatorArgs for the call to operator delete if it's not
138253dcf94dSJohn McCall     // the reserved global operator.
138353dcf94dSJohn McCall     if (E->getOperatorDelete() &&
138453dcf94dSJohn McCall         !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
138553dcf94dSJohn McCall       allocatorArgs.add(RValue::get(allocSize), getContext().getSizeType());
138653dcf94dSJohn McCall       allocatorArgs.add(RValue::get(allocation.getPointer()), arg->getType());
138753dcf94dSJohn McCall     }
138853dcf94dSJohn McCall 
13897f416cc4SJohn McCall   } else {
13907f416cc4SJohn McCall     const FunctionProtoType *allocatorType =
13917f416cc4SJohn McCall       allocator->getType()->castAs<FunctionProtoType>();
13927f416cc4SJohn McCall 
13937f416cc4SJohn McCall     // The allocation size is the first argument.
13947f416cc4SJohn McCall     QualType sizeType = getContext().getSizeType();
139543dca6a8SEli Friedman     allocatorArgs.add(RValue::get(allocSize), sizeType);
139659486a2dSAnders Carlsson 
139759486a2dSAnders Carlsson     // We start at 1 here because the first argument (the allocation size)
139859486a2dSAnders Carlsson     // has already been emitted.
1399f05779e2SDavid Blaikie     EmitCallArgs(allocatorArgs, allocatorType, E->placement_arguments(),
1400f05779e2SDavid Blaikie                  /* CalleeDecl */ nullptr,
14018e1162c7SAlexey Samsonov                  /*ParamsToSkip*/ 1);
140259486a2dSAnders Carlsson 
14037f416cc4SJohn McCall     RValue RV =
14047f416cc4SJohn McCall       EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
14057f416cc4SJohn McCall 
14067f416cc4SJohn McCall     // For now, only assume that the allocation function returns
14077f416cc4SJohn McCall     // something satisfactorily aligned for the element type, plus
14087f416cc4SJohn McCall     // the cookie if we have one.
14097f416cc4SJohn McCall     CharUnits allocationAlign =
14107f416cc4SJohn McCall       getContext().getTypeAlignInChars(allocType);
14117f416cc4SJohn McCall     if (allocSize != allocSizeWithoutCookie) {
14127f416cc4SJohn McCall       CharUnits cookieAlign = getSizeAlign(); // FIXME?
14137f416cc4SJohn McCall       allocationAlign = std::max(allocationAlign, cookieAlign);
14147f416cc4SJohn McCall     }
14157f416cc4SJohn McCall 
14167f416cc4SJohn McCall     allocation = Address(RV.getScalarVal(), allocationAlign);
14177ec4b434SJohn McCall   }
141859486a2dSAnders Carlsson 
141975f9498aSJohn McCall   // Emit a null check on the allocation result if the allocation
142075f9498aSJohn McCall   // function is allowed to return null (because it has a non-throwing
1421902a0238SRichard Smith   // exception spec or is the reserved placement new) and we have an
142275f9498aSJohn McCall   // interesting initializer.
1423902a0238SRichard Smith   bool nullCheck = E->shouldNullCheckAllocation(getContext()) &&
14246047f07eSSebastian Redl     (!allocType.isPODType(getContext()) || E->hasInitializer());
142559486a2dSAnders Carlsson 
14268a13c418SCraig Topper   llvm::BasicBlock *nullCheckBB = nullptr;
14278a13c418SCraig Topper   llvm::BasicBlock *contBB = nullptr;
142859486a2dSAnders Carlsson 
1429f7dcf320SJohn McCall   // The null-check means that the initializer is conditionally
1430f7dcf320SJohn McCall   // evaluated.
1431f7dcf320SJohn McCall   ConditionalEvaluation conditional(*this);
1432f7dcf320SJohn McCall 
143375f9498aSJohn McCall   if (nullCheck) {
1434f7dcf320SJohn McCall     conditional.begin(*this);
143575f9498aSJohn McCall 
143675f9498aSJohn McCall     nullCheckBB = Builder.GetInsertBlock();
143775f9498aSJohn McCall     llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
143875f9498aSJohn McCall     contBB = createBasicBlock("new.cont");
143975f9498aSJohn McCall 
14407f416cc4SJohn McCall     llvm::Value *isNull =
14417f416cc4SJohn McCall       Builder.CreateIsNull(allocation.getPointer(), "new.isnull");
144275f9498aSJohn McCall     Builder.CreateCondBr(isNull, contBB, notNullBB);
144375f9498aSJohn McCall     EmitBlock(notNullBB);
144459486a2dSAnders Carlsson   }
144559486a2dSAnders Carlsson 
1446824c2f53SJohn McCall   // If there's an operator delete, enter a cleanup to call it if an
1447824c2f53SJohn McCall   // exception is thrown.
144875f9498aSJohn McCall   EHScopeStack::stable_iterator operatorDeleteCleanup;
14498a13c418SCraig Topper   llvm::Instruction *cleanupDominator = nullptr;
14507ec4b434SJohn McCall   if (E->getOperatorDelete() &&
14517ec4b434SJohn McCall       !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
145275f9498aSJohn McCall     EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
145375f9498aSJohn McCall     operatorDeleteCleanup = EHStack.stable_begin();
1454f4beacd0SJohn McCall     cleanupDominator = Builder.CreateUnreachable();
1455824c2f53SJohn McCall   }
1456824c2f53SJohn McCall 
1457cf9b1f65SEli Friedman   assert((allocSize == allocSizeWithoutCookie) ==
1458cf9b1f65SEli Friedman          CalculateCookiePadding(*this, E).isZero());
1459cf9b1f65SEli Friedman   if (allocSize != allocSizeWithoutCookie) {
1460cf9b1f65SEli Friedman     assert(E->isArray());
1461cf9b1f65SEli Friedman     allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1462cf9b1f65SEli Friedman                                                        numElements,
1463cf9b1f65SEli Friedman                                                        E, allocType);
1464cf9b1f65SEli Friedman   }
1465cf9b1f65SEli Friedman 
1466fb901c7aSDavid Blaikie   llvm::Type *elementTy = ConvertTypeForMem(allocType);
14677f416cc4SJohn McCall   Address result = Builder.CreateElementBitCast(allocation, elementTy);
1468824c2f53SJohn McCall 
1469338c9d0aSPiotr Padlewski   // Passing pointer through invariant.group.barrier to avoid propagation of
1470338c9d0aSPiotr Padlewski   // vptrs information which may be included in previous type.
1471338c9d0aSPiotr Padlewski   if (CGM.getCodeGenOpts().StrictVTablePointers &&
1472338c9d0aSPiotr Padlewski       CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1473338c9d0aSPiotr Padlewski       allocator->isReservedGlobalPlacementOperator())
1474338c9d0aSPiotr Padlewski     result = Address(Builder.CreateInvariantGroupBarrier(result.getPointer()),
1475338c9d0aSPiotr Padlewski                      result.getAlignment());
1476338c9d0aSPiotr Padlewski 
1477fb901c7aSDavid Blaikie   EmitNewInitializer(*this, E, allocType, elementTy, result, numElements,
147899210dc9SJohn McCall                      allocSizeWithoutCookie);
14798ed55a54SJohn McCall   if (E->isArray()) {
14808ed55a54SJohn McCall     // NewPtr is a pointer to the base element type.  If we're
14818ed55a54SJohn McCall     // allocating an array of arrays, we'll need to cast back to the
14828ed55a54SJohn McCall     // array pointer type.
14832192fe50SChris Lattner     llvm::Type *resultType = ConvertTypeForMem(E->getType());
14847f416cc4SJohn McCall     if (result.getType() != resultType)
148575f9498aSJohn McCall       result = Builder.CreateBitCast(result, resultType);
148647b4629bSFariborz Jahanian   }
148759486a2dSAnders Carlsson 
1488824c2f53SJohn McCall   // Deactivate the 'operator delete' cleanup if we finished
1489824c2f53SJohn McCall   // initialization.
1490f4beacd0SJohn McCall   if (operatorDeleteCleanup.isValid()) {
1491f4beacd0SJohn McCall     DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1492f4beacd0SJohn McCall     cleanupDominator->eraseFromParent();
1493f4beacd0SJohn McCall   }
1494824c2f53SJohn McCall 
14957f416cc4SJohn McCall   llvm::Value *resultPtr = result.getPointer();
149675f9498aSJohn McCall   if (nullCheck) {
1497f7dcf320SJohn McCall     conditional.end(*this);
1498f7dcf320SJohn McCall 
149975f9498aSJohn McCall     llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
150075f9498aSJohn McCall     EmitBlock(contBB);
150159486a2dSAnders Carlsson 
15027f416cc4SJohn McCall     llvm::PHINode *PHI = Builder.CreatePHI(resultPtr->getType(), 2);
15037f416cc4SJohn McCall     PHI->addIncoming(resultPtr, notNullBB);
15047f416cc4SJohn McCall     PHI->addIncoming(llvm::Constant::getNullValue(resultPtr->getType()),
150575f9498aSJohn McCall                      nullCheckBB);
150659486a2dSAnders Carlsson 
15077f416cc4SJohn McCall     resultPtr = PHI;
150859486a2dSAnders Carlsson   }
150959486a2dSAnders Carlsson 
15107f416cc4SJohn McCall   return resultPtr;
151159486a2dSAnders Carlsson }
151259486a2dSAnders Carlsson 
151359486a2dSAnders Carlsson void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
151459486a2dSAnders Carlsson                                      llvm::Value *Ptr,
151559486a2dSAnders Carlsson                                      QualType DeleteTy) {
15168ed55a54SJohn McCall   assert(DeleteFD->getOverloadedOperator() == OO_Delete);
15178ed55a54SJohn McCall 
151859486a2dSAnders Carlsson   const FunctionProtoType *DeleteFTy =
151959486a2dSAnders Carlsson     DeleteFD->getType()->getAs<FunctionProtoType>();
152059486a2dSAnders Carlsson 
152159486a2dSAnders Carlsson   CallArgList DeleteArgs;
152259486a2dSAnders Carlsson 
152321122cf6SAnders Carlsson   // Check if we need to pass the size to the delete operator.
15248a13c418SCraig Topper   llvm::Value *Size = nullptr;
152521122cf6SAnders Carlsson   QualType SizeTy;
15269cacbabdSAlp Toker   if (DeleteFTy->getNumParams() == 2) {
15279cacbabdSAlp Toker     SizeTy = DeleteFTy->getParamType(1);
15287df3cbebSKen Dyck     CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
15297df3cbebSKen Dyck     Size = llvm::ConstantInt::get(ConvertType(SizeTy),
15307df3cbebSKen Dyck                                   DeleteTypeSize.getQuantity());
153121122cf6SAnders Carlsson   }
153221122cf6SAnders Carlsson 
15339cacbabdSAlp Toker   QualType ArgTy = DeleteFTy->getParamType(0);
153459486a2dSAnders Carlsson   llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
153543dca6a8SEli Friedman   DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
153659486a2dSAnders Carlsson 
153721122cf6SAnders Carlsson   if (Size)
153843dca6a8SEli Friedman     DeleteArgs.add(RValue::get(Size), SizeTy);
153959486a2dSAnders Carlsson 
154059486a2dSAnders Carlsson   // Emit the call to delete.
15418d0dc31dSRichard Smith   EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
154259486a2dSAnders Carlsson }
154359486a2dSAnders Carlsson 
15448ed55a54SJohn McCall namespace {
15458ed55a54SJohn McCall   /// Calls the given 'operator delete' on a single object.
15467e70d680SDavid Blaikie   struct CallObjectDelete final : EHScopeStack::Cleanup {
15478ed55a54SJohn McCall     llvm::Value *Ptr;
15488ed55a54SJohn McCall     const FunctionDecl *OperatorDelete;
15498ed55a54SJohn McCall     QualType ElementType;
15508ed55a54SJohn McCall 
15518ed55a54SJohn McCall     CallObjectDelete(llvm::Value *Ptr,
15528ed55a54SJohn McCall                      const FunctionDecl *OperatorDelete,
15538ed55a54SJohn McCall                      QualType ElementType)
15548ed55a54SJohn McCall       : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
15558ed55a54SJohn McCall 
15564f12f10dSCraig Topper     void Emit(CodeGenFunction &CGF, Flags flags) override {
15578ed55a54SJohn McCall       CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
15588ed55a54SJohn McCall     }
15598ed55a54SJohn McCall   };
1560ab9db510SAlexander Kornienko }
15618ed55a54SJohn McCall 
15620c0b6d9aSDavid Majnemer void
15630c0b6d9aSDavid Majnemer CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
15640c0b6d9aSDavid Majnemer                                              llvm::Value *CompletePtr,
15650c0b6d9aSDavid Majnemer                                              QualType ElementType) {
15660c0b6d9aSDavid Majnemer   EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr,
15670c0b6d9aSDavid Majnemer                                         OperatorDelete, ElementType);
15680c0b6d9aSDavid Majnemer }
15690c0b6d9aSDavid Majnemer 
15708ed55a54SJohn McCall /// Emit the code for deleting a single object.
15718ed55a54SJohn McCall static void EmitObjectDelete(CodeGenFunction &CGF,
15720868137aSDavid Majnemer                              const CXXDeleteExpr *DE,
15737f416cc4SJohn McCall                              Address Ptr,
15740868137aSDavid Majnemer                              QualType ElementType) {
15758ed55a54SJohn McCall   // Find the destructor for the type, if applicable.  If the
15768ed55a54SJohn McCall   // destructor is virtual, we'll just emit the vcall and return.
15778a13c418SCraig Topper   const CXXDestructorDecl *Dtor = nullptr;
15788ed55a54SJohn McCall   if (const RecordType *RT = ElementType->getAs<RecordType>()) {
15798ed55a54SJohn McCall     CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1580b23533dbSEli Friedman     if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
15818ed55a54SJohn McCall       Dtor = RD->getDestructor();
15828ed55a54SJohn McCall 
15838ed55a54SJohn McCall       if (Dtor->isVirtual()) {
15840868137aSDavid Majnemer         CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
15850868137aSDavid Majnemer                                                     Dtor);
15868ed55a54SJohn McCall         return;
15878ed55a54SJohn McCall       }
15888ed55a54SJohn McCall     }
15898ed55a54SJohn McCall   }
15908ed55a54SJohn McCall 
15918ed55a54SJohn McCall   // Make sure that we call delete even if the dtor throws.
1592e4df6c8dSJohn McCall   // This doesn't have to a conditional cleanup because we're going
1593e4df6c8dSJohn McCall   // to pop it off in a second.
15940868137aSDavid Majnemer   const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
15958ed55a54SJohn McCall   CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
15967f416cc4SJohn McCall                                             Ptr.getPointer(),
15977f416cc4SJohn McCall                                             OperatorDelete, ElementType);
15988ed55a54SJohn McCall 
15998ed55a54SJohn McCall   if (Dtor)
16008ed55a54SJohn McCall     CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
160161535005SDouglas Gregor                               /*ForVirtualBase=*/false,
160261535005SDouglas Gregor                               /*Delegating=*/false,
160361535005SDouglas Gregor                               Ptr);
1604460ce58fSJohn McCall   else if (auto Lifetime = ElementType.getObjCLifetime()) {
1605460ce58fSJohn McCall     switch (Lifetime) {
160631168b07SJohn McCall     case Qualifiers::OCL_None:
160731168b07SJohn McCall     case Qualifiers::OCL_ExplicitNone:
160831168b07SJohn McCall     case Qualifiers::OCL_Autoreleasing:
160931168b07SJohn McCall       break;
161031168b07SJohn McCall 
16117f416cc4SJohn McCall     case Qualifiers::OCL_Strong:
16127f416cc4SJohn McCall       CGF.EmitARCDestroyStrong(Ptr, ARCPreciseLifetime);
161331168b07SJohn McCall       break;
161431168b07SJohn McCall 
161531168b07SJohn McCall     case Qualifiers::OCL_Weak:
161631168b07SJohn McCall       CGF.EmitARCDestroyWeak(Ptr);
161731168b07SJohn McCall       break;
161831168b07SJohn McCall     }
161931168b07SJohn McCall   }
16208ed55a54SJohn McCall 
16218ed55a54SJohn McCall   CGF.PopCleanupBlock();
16228ed55a54SJohn McCall }
16238ed55a54SJohn McCall 
16248ed55a54SJohn McCall namespace {
16258ed55a54SJohn McCall   /// Calls the given 'operator delete' on an array of objects.
16267e70d680SDavid Blaikie   struct CallArrayDelete final : EHScopeStack::Cleanup {
16278ed55a54SJohn McCall     llvm::Value *Ptr;
16288ed55a54SJohn McCall     const FunctionDecl *OperatorDelete;
16298ed55a54SJohn McCall     llvm::Value *NumElements;
16308ed55a54SJohn McCall     QualType ElementType;
16318ed55a54SJohn McCall     CharUnits CookieSize;
16328ed55a54SJohn McCall 
16338ed55a54SJohn McCall     CallArrayDelete(llvm::Value *Ptr,
16348ed55a54SJohn McCall                     const FunctionDecl *OperatorDelete,
16358ed55a54SJohn McCall                     llvm::Value *NumElements,
16368ed55a54SJohn McCall                     QualType ElementType,
16378ed55a54SJohn McCall                     CharUnits CookieSize)
16388ed55a54SJohn McCall       : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
16398ed55a54SJohn McCall         ElementType(ElementType), CookieSize(CookieSize) {}
16408ed55a54SJohn McCall 
16414f12f10dSCraig Topper     void Emit(CodeGenFunction &CGF, Flags flags) override {
16428ed55a54SJohn McCall       const FunctionProtoType *DeleteFTy =
16438ed55a54SJohn McCall         OperatorDelete->getType()->getAs<FunctionProtoType>();
16449cacbabdSAlp Toker       assert(DeleteFTy->getNumParams() == 1 || DeleteFTy->getNumParams() == 2);
16458ed55a54SJohn McCall 
16468ed55a54SJohn McCall       CallArgList Args;
16478ed55a54SJohn McCall 
16488ed55a54SJohn McCall       // Pass the pointer as the first argument.
16499cacbabdSAlp Toker       QualType VoidPtrTy = DeleteFTy->getParamType(0);
16508ed55a54SJohn McCall       llvm::Value *DeletePtr
16518ed55a54SJohn McCall         = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
165243dca6a8SEli Friedman       Args.add(RValue::get(DeletePtr), VoidPtrTy);
16538ed55a54SJohn McCall 
16548ed55a54SJohn McCall       // Pass the original requested size as the second argument.
16559cacbabdSAlp Toker       if (DeleteFTy->getNumParams() == 2) {
16569cacbabdSAlp Toker         QualType size_t = DeleteFTy->getParamType(1);
16572192fe50SChris Lattner         llvm::IntegerType *SizeTy
16588ed55a54SJohn McCall           = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
16598ed55a54SJohn McCall 
16608ed55a54SJohn McCall         CharUnits ElementTypeSize =
16618ed55a54SJohn McCall           CGF.CGM.getContext().getTypeSizeInChars(ElementType);
16628ed55a54SJohn McCall 
16638ed55a54SJohn McCall         // The size of an element, multiplied by the number of elements.
16648ed55a54SJohn McCall         llvm::Value *Size
16658ed55a54SJohn McCall           = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1666149e6031SDavid Majnemer         if (NumElements)
16678ed55a54SJohn McCall           Size = CGF.Builder.CreateMul(Size, NumElements);
16688ed55a54SJohn McCall 
16698ed55a54SJohn McCall         // Plus the size of the cookie if applicable.
16708ed55a54SJohn McCall         if (!CookieSize.isZero()) {
16718ed55a54SJohn McCall           llvm::Value *CookieSizeV
16728ed55a54SJohn McCall             = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
16738ed55a54SJohn McCall           Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
16748ed55a54SJohn McCall         }
16758ed55a54SJohn McCall 
167643dca6a8SEli Friedman         Args.add(RValue::get(Size), size_t);
16778ed55a54SJohn McCall       }
16788ed55a54SJohn McCall 
16798ed55a54SJohn McCall       // Emit the call to delete.
16808d0dc31dSRichard Smith       EmitNewDeleteCall(CGF, OperatorDelete, DeleteFTy, Args);
16818ed55a54SJohn McCall     }
16828ed55a54SJohn McCall   };
1683ab9db510SAlexander Kornienko }
16848ed55a54SJohn McCall 
16858ed55a54SJohn McCall /// Emit the code for deleting an array of objects.
16868ed55a54SJohn McCall static void EmitArrayDelete(CodeGenFunction &CGF,
1687284c48ffSJohn McCall                             const CXXDeleteExpr *E,
16887f416cc4SJohn McCall                             Address deletedPtr,
1689ca2c56f2SJohn McCall                             QualType elementType) {
16908a13c418SCraig Topper   llvm::Value *numElements = nullptr;
16918a13c418SCraig Topper   llvm::Value *allocatedPtr = nullptr;
1692ca2c56f2SJohn McCall   CharUnits cookieSize;
1693ca2c56f2SJohn McCall   CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1694ca2c56f2SJohn McCall                                       numElements, allocatedPtr, cookieSize);
16958ed55a54SJohn McCall 
1696ca2c56f2SJohn McCall   assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
16978ed55a54SJohn McCall 
16988ed55a54SJohn McCall   // Make sure that we call delete even if one of the dtors throws.
1699ca2c56f2SJohn McCall   const FunctionDecl *operatorDelete = E->getOperatorDelete();
17008ed55a54SJohn McCall   CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
1701ca2c56f2SJohn McCall                                            allocatedPtr, operatorDelete,
1702ca2c56f2SJohn McCall                                            numElements, elementType,
1703ca2c56f2SJohn McCall                                            cookieSize);
17048ed55a54SJohn McCall 
1705ca2c56f2SJohn McCall   // Destroy the elements.
1706ca2c56f2SJohn McCall   if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1707ca2c56f2SJohn McCall     assert(numElements && "no element count for a type with a destructor!");
170831168b07SJohn McCall 
17097f416cc4SJohn McCall     CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
17107f416cc4SJohn McCall     CharUnits elementAlign =
17117f416cc4SJohn McCall       deletedPtr.getAlignment().alignmentOfArrayElement(elementSize);
17127f416cc4SJohn McCall 
17137f416cc4SJohn McCall     llvm::Value *arrayBegin = deletedPtr.getPointer();
1714ca2c56f2SJohn McCall     llvm::Value *arrayEnd =
17157f416cc4SJohn McCall       CGF.Builder.CreateInBoundsGEP(arrayBegin, numElements, "delete.end");
171697eab0a2SJohn McCall 
171797eab0a2SJohn McCall     // Note that it is legal to allocate a zero-length array, and we
171897eab0a2SJohn McCall     // can never fold the check away because the length should always
171997eab0a2SJohn McCall     // come from a cookie.
17207f416cc4SJohn McCall     CGF.emitArrayDestroy(arrayBegin, arrayEnd, elementType, elementAlign,
1721ca2c56f2SJohn McCall                          CGF.getDestroyer(dtorKind),
172297eab0a2SJohn McCall                          /*checkZeroLength*/ true,
1723ca2c56f2SJohn McCall                          CGF.needsEHCleanup(dtorKind));
17248ed55a54SJohn McCall   }
17258ed55a54SJohn McCall 
1726ca2c56f2SJohn McCall   // Pop the cleanup block.
17278ed55a54SJohn McCall   CGF.PopCleanupBlock();
17288ed55a54SJohn McCall }
17298ed55a54SJohn McCall 
173059486a2dSAnders Carlsson void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
173159486a2dSAnders Carlsson   const Expr *Arg = E->getArgument();
17327f416cc4SJohn McCall   Address Ptr = EmitPointerWithAlignment(Arg);
173359486a2dSAnders Carlsson 
173459486a2dSAnders Carlsson   // Null check the pointer.
173559486a2dSAnders Carlsson   llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
173659486a2dSAnders Carlsson   llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
173759486a2dSAnders Carlsson 
17387f416cc4SJohn McCall   llvm::Value *IsNull = Builder.CreateIsNull(Ptr.getPointer(), "isnull");
173959486a2dSAnders Carlsson 
174059486a2dSAnders Carlsson   Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
174159486a2dSAnders Carlsson   EmitBlock(DeleteNotNull);
174259486a2dSAnders Carlsson 
17438ed55a54SJohn McCall   // We might be deleting a pointer to array.  If so, GEP down to the
17448ed55a54SJohn McCall   // first non-array element.
17458ed55a54SJohn McCall   // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
17468ed55a54SJohn McCall   QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
17478ed55a54SJohn McCall   if (DeleteTy->isConstantArrayType()) {
17488ed55a54SJohn McCall     llvm::Value *Zero = Builder.getInt32(0);
17490e62c1ccSChris Lattner     SmallVector<llvm::Value*,8> GEP;
175059486a2dSAnders Carlsson 
17518ed55a54SJohn McCall     GEP.push_back(Zero); // point at the outermost array
17528ed55a54SJohn McCall 
17538ed55a54SJohn McCall     // For each layer of array type we're pointing at:
17548ed55a54SJohn McCall     while (const ConstantArrayType *Arr
17558ed55a54SJohn McCall              = getContext().getAsConstantArrayType(DeleteTy)) {
17568ed55a54SJohn McCall       // 1. Unpeel the array type.
17578ed55a54SJohn McCall       DeleteTy = Arr->getElementType();
17588ed55a54SJohn McCall 
17598ed55a54SJohn McCall       // 2. GEP to the first element of the array.
17608ed55a54SJohn McCall       GEP.push_back(Zero);
17618ed55a54SJohn McCall     }
17628ed55a54SJohn McCall 
17637f416cc4SJohn McCall     Ptr = Address(Builder.CreateInBoundsGEP(Ptr.getPointer(), GEP, "del.first"),
17647f416cc4SJohn McCall                   Ptr.getAlignment());
17658ed55a54SJohn McCall   }
17668ed55a54SJohn McCall 
17677f416cc4SJohn McCall   assert(ConvertTypeForMem(DeleteTy) == Ptr.getElementType());
17688ed55a54SJohn McCall 
17697270ef57SReid Kleckner   if (E->isArrayForm()) {
17707270ef57SReid Kleckner     EmitArrayDelete(*this, E, Ptr, DeleteTy);
17717270ef57SReid Kleckner   } else {
17727270ef57SReid Kleckner     EmitObjectDelete(*this, E, Ptr, DeleteTy);
17737270ef57SReid Kleckner   }
177459486a2dSAnders Carlsson 
177559486a2dSAnders Carlsson   EmitBlock(DeleteEnd);
177659486a2dSAnders Carlsson }
177759486a2dSAnders Carlsson 
17781c3d95ebSDavid Majnemer static bool isGLValueFromPointerDeref(const Expr *E) {
17791c3d95ebSDavid Majnemer   E = E->IgnoreParens();
17801c3d95ebSDavid Majnemer 
17811c3d95ebSDavid Majnemer   if (const auto *CE = dyn_cast<CastExpr>(E)) {
17821c3d95ebSDavid Majnemer     if (!CE->getSubExpr()->isGLValue())
17831c3d95ebSDavid Majnemer       return false;
17841c3d95ebSDavid Majnemer     return isGLValueFromPointerDeref(CE->getSubExpr());
17851c3d95ebSDavid Majnemer   }
17861c3d95ebSDavid Majnemer 
17871c3d95ebSDavid Majnemer   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
17881c3d95ebSDavid Majnemer     return isGLValueFromPointerDeref(OVE->getSourceExpr());
17891c3d95ebSDavid Majnemer 
17901c3d95ebSDavid Majnemer   if (const auto *BO = dyn_cast<BinaryOperator>(E))
17911c3d95ebSDavid Majnemer     if (BO->getOpcode() == BO_Comma)
17921c3d95ebSDavid Majnemer       return isGLValueFromPointerDeref(BO->getRHS());
17931c3d95ebSDavid Majnemer 
17941c3d95ebSDavid Majnemer   if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E))
17951c3d95ebSDavid Majnemer     return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
17961c3d95ebSDavid Majnemer            isGLValueFromPointerDeref(ACO->getFalseExpr());
17971c3d95ebSDavid Majnemer 
17981c3d95ebSDavid Majnemer   // C++11 [expr.sub]p1:
17991c3d95ebSDavid Majnemer   //   The expression E1[E2] is identical (by definition) to *((E1)+(E2))
18001c3d95ebSDavid Majnemer   if (isa<ArraySubscriptExpr>(E))
18011c3d95ebSDavid Majnemer     return true;
18021c3d95ebSDavid Majnemer 
18031c3d95ebSDavid Majnemer   if (const auto *UO = dyn_cast<UnaryOperator>(E))
18041c3d95ebSDavid Majnemer     if (UO->getOpcode() == UO_Deref)
18051c3d95ebSDavid Majnemer       return true;
18061c3d95ebSDavid Majnemer 
18071c3d95ebSDavid Majnemer   return false;
18081c3d95ebSDavid Majnemer }
18091c3d95ebSDavid Majnemer 
1810747e301eSWarren Hunt static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
18112192fe50SChris Lattner                                          llvm::Type *StdTypeInfoPtrTy) {
1812940f02d2SAnders Carlsson   // Get the vtable pointer.
18137f416cc4SJohn McCall   Address ThisPtr = CGF.EmitLValue(E).getAddress();
1814940f02d2SAnders Carlsson 
1815940f02d2SAnders Carlsson   // C++ [expr.typeid]p2:
1816940f02d2SAnders Carlsson   //   If the glvalue expression is obtained by applying the unary * operator to
1817940f02d2SAnders Carlsson   //   a pointer and the pointer is a null pointer value, the typeid expression
1818940f02d2SAnders Carlsson   //   throws the std::bad_typeid exception.
18191c3d95ebSDavid Majnemer   //
18201c3d95ebSDavid Majnemer   // However, this paragraph's intent is not clear.  We choose a very generous
18211c3d95ebSDavid Majnemer   // interpretation which implores us to consider comma operators, conditional
18221c3d95ebSDavid Majnemer   // operators, parentheses and other such constructs.
18231162d25cSDavid Majnemer   QualType SrcRecordTy = E->getType();
18241c3d95ebSDavid Majnemer   if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(
18251c3d95ebSDavid Majnemer           isGLValueFromPointerDeref(E), SrcRecordTy)) {
1826940f02d2SAnders Carlsson     llvm::BasicBlock *BadTypeidBlock =
1827940f02d2SAnders Carlsson         CGF.createBasicBlock("typeid.bad_typeid");
18281162d25cSDavid Majnemer     llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
1829940f02d2SAnders Carlsson 
18307f416cc4SJohn McCall     llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr.getPointer());
1831940f02d2SAnders Carlsson     CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
1832940f02d2SAnders Carlsson 
1833940f02d2SAnders Carlsson     CGF.EmitBlock(BadTypeidBlock);
18341162d25cSDavid Majnemer     CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
1835940f02d2SAnders Carlsson     CGF.EmitBlock(EndBlock);
1836940f02d2SAnders Carlsson   }
1837940f02d2SAnders Carlsson 
18381162d25cSDavid Majnemer   return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
18391162d25cSDavid Majnemer                                         StdTypeInfoPtrTy);
1840940f02d2SAnders Carlsson }
1841940f02d2SAnders Carlsson 
184259486a2dSAnders Carlsson llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
18432192fe50SChris Lattner   llvm::Type *StdTypeInfoPtrTy =
1844940f02d2SAnders Carlsson     ConvertType(E->getType())->getPointerTo();
1845fd7dfeb7SAnders Carlsson 
18463f4336cbSAnders Carlsson   if (E->isTypeOperand()) {
18473f4336cbSAnders Carlsson     llvm::Constant *TypeInfo =
1848143c55eaSDavid Majnemer         CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
1849940f02d2SAnders Carlsson     return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
18503f4336cbSAnders Carlsson   }
1851fd7dfeb7SAnders Carlsson 
1852940f02d2SAnders Carlsson   // C++ [expr.typeid]p2:
1853940f02d2SAnders Carlsson   //   When typeid is applied to a glvalue expression whose type is a
1854940f02d2SAnders Carlsson   //   polymorphic class type, the result refers to a std::type_info object
1855940f02d2SAnders Carlsson   //   representing the type of the most derived object (that is, the dynamic
1856940f02d2SAnders Carlsson   //   type) to which the glvalue refers.
1857ef8bf436SRichard Smith   if (E->isPotentiallyEvaluated())
1858940f02d2SAnders Carlsson     return EmitTypeidFromVTable(*this, E->getExprOperand(),
1859940f02d2SAnders Carlsson                                 StdTypeInfoPtrTy);
1860940f02d2SAnders Carlsson 
1861940f02d2SAnders Carlsson   QualType OperandTy = E->getExprOperand()->getType();
1862940f02d2SAnders Carlsson   return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1863940f02d2SAnders Carlsson                                StdTypeInfoPtrTy);
186459486a2dSAnders Carlsson }
186559486a2dSAnders Carlsson 
1866c1c9971cSAnders Carlsson static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1867c1c9971cSAnders Carlsson                                           QualType DestTy) {
18682192fe50SChris Lattner   llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1869c1c9971cSAnders Carlsson   if (DestTy->isPointerType())
1870c1c9971cSAnders Carlsson     return llvm::Constant::getNullValue(DestLTy);
1871c1c9971cSAnders Carlsson 
1872c1c9971cSAnders Carlsson   /// C++ [expr.dynamic.cast]p9:
1873c1c9971cSAnders Carlsson   ///   A failed cast to reference type throws std::bad_cast
18741162d25cSDavid Majnemer   if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
18751162d25cSDavid Majnemer     return nullptr;
1876c1c9971cSAnders Carlsson 
1877c1c9971cSAnders Carlsson   CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1878c1c9971cSAnders Carlsson   return llvm::UndefValue::get(DestLTy);
1879c1c9971cSAnders Carlsson }
1880c1c9971cSAnders Carlsson 
18817f416cc4SJohn McCall llvm::Value *CodeGenFunction::EmitDynamicCast(Address ThisAddr,
188259486a2dSAnders Carlsson                                               const CXXDynamicCastExpr *DCE) {
18832bf9b4c0SAlexey Bataev   CGM.EmitExplicitCastExprType(DCE, this);
18843f4336cbSAnders Carlsson   QualType DestTy = DCE->getTypeAsWritten();
18853f4336cbSAnders Carlsson 
1886c1c9971cSAnders Carlsson   if (DCE->isAlwaysNull())
18871162d25cSDavid Majnemer     if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy))
18881162d25cSDavid Majnemer       return T;
1889c1c9971cSAnders Carlsson 
1890c1c9971cSAnders Carlsson   QualType SrcTy = DCE->getSubExpr()->getType();
1891c1c9971cSAnders Carlsson 
18921162d25cSDavid Majnemer   // C++ [expr.dynamic.cast]p7:
18931162d25cSDavid Majnemer   //   If T is "pointer to cv void," then the result is a pointer to the most
18941162d25cSDavid Majnemer   //   derived object pointed to by v.
18951162d25cSDavid Majnemer   const PointerType *DestPTy = DestTy->getAs<PointerType>();
18961162d25cSDavid Majnemer 
18971162d25cSDavid Majnemer   bool isDynamicCastToVoid;
18981162d25cSDavid Majnemer   QualType SrcRecordTy;
18991162d25cSDavid Majnemer   QualType DestRecordTy;
19001162d25cSDavid Majnemer   if (DestPTy) {
19011162d25cSDavid Majnemer     isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType();
19021162d25cSDavid Majnemer     SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
19031162d25cSDavid Majnemer     DestRecordTy = DestPTy->getPointeeType();
19041162d25cSDavid Majnemer   } else {
19051162d25cSDavid Majnemer     isDynamicCastToVoid = false;
19061162d25cSDavid Majnemer     SrcRecordTy = SrcTy;
19071162d25cSDavid Majnemer     DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
19081162d25cSDavid Majnemer   }
19091162d25cSDavid Majnemer 
19101162d25cSDavid Majnemer   assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
19111162d25cSDavid Majnemer 
1912882d790fSAnders Carlsson   // C++ [expr.dynamic.cast]p4:
1913882d790fSAnders Carlsson   //   If the value of v is a null pointer value in the pointer case, the result
1914882d790fSAnders Carlsson   //   is the null pointer value of type T.
19151162d25cSDavid Majnemer   bool ShouldNullCheckSrcValue =
19161162d25cSDavid Majnemer       CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(),
19171162d25cSDavid Majnemer                                                          SrcRecordTy);
191859486a2dSAnders Carlsson 
19198a13c418SCraig Topper   llvm::BasicBlock *CastNull = nullptr;
19208a13c418SCraig Topper   llvm::BasicBlock *CastNotNull = nullptr;
1921882d790fSAnders Carlsson   llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
1922fa8b4955SDouglas Gregor 
1923882d790fSAnders Carlsson   if (ShouldNullCheckSrcValue) {
1924882d790fSAnders Carlsson     CastNull = createBasicBlock("dynamic_cast.null");
1925882d790fSAnders Carlsson     CastNotNull = createBasicBlock("dynamic_cast.notnull");
1926882d790fSAnders Carlsson 
19277f416cc4SJohn McCall     llvm::Value *IsNull = Builder.CreateIsNull(ThisAddr.getPointer());
1928882d790fSAnders Carlsson     Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1929882d790fSAnders Carlsson     EmitBlock(CastNotNull);
193059486a2dSAnders Carlsson   }
193159486a2dSAnders Carlsson 
19327f416cc4SJohn McCall   llvm::Value *Value;
19331162d25cSDavid Majnemer   if (isDynamicCastToVoid) {
19347f416cc4SJohn McCall     Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, ThisAddr, SrcRecordTy,
19351162d25cSDavid Majnemer                                                   DestTy);
19361162d25cSDavid Majnemer   } else {
19371162d25cSDavid Majnemer     assert(DestRecordTy->isRecordType() &&
19381162d25cSDavid Majnemer            "destination type must be a record type!");
19397f416cc4SJohn McCall     Value = CGM.getCXXABI().EmitDynamicCastCall(*this, ThisAddr, SrcRecordTy,
19401162d25cSDavid Majnemer                                                 DestTy, DestRecordTy, CastEnd);
194167528eaaSDavid Majnemer     CastNotNull = Builder.GetInsertBlock();
19421162d25cSDavid Majnemer   }
19433f4336cbSAnders Carlsson 
1944882d790fSAnders Carlsson   if (ShouldNullCheckSrcValue) {
1945882d790fSAnders Carlsson     EmitBranch(CastEnd);
194659486a2dSAnders Carlsson 
1947882d790fSAnders Carlsson     EmitBlock(CastNull);
1948882d790fSAnders Carlsson     EmitBranch(CastEnd);
194959486a2dSAnders Carlsson   }
195059486a2dSAnders Carlsson 
1951882d790fSAnders Carlsson   EmitBlock(CastEnd);
195259486a2dSAnders Carlsson 
1953882d790fSAnders Carlsson   if (ShouldNullCheckSrcValue) {
1954882d790fSAnders Carlsson     llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1955882d790fSAnders Carlsson     PHI->addIncoming(Value, CastNotNull);
1956882d790fSAnders Carlsson     PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
195759486a2dSAnders Carlsson 
1958882d790fSAnders Carlsson     Value = PHI;
195959486a2dSAnders Carlsson   }
196059486a2dSAnders Carlsson 
1961882d790fSAnders Carlsson   return Value;
196259486a2dSAnders Carlsson }
1963c370a7eeSEli Friedman 
1964c370a7eeSEli Friedman void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
19658631f3e8SEli Friedman   RunCleanupsScope Scope(*this);
19667f416cc4SJohn McCall   LValue SlotLV = MakeAddrLValue(Slot.getAddress(), E->getType());
19678631f3e8SEli Friedman 
1968c370a7eeSEli Friedman   CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
196953c7616eSJames Y Knight   for (LambdaExpr::const_capture_init_iterator i = E->capture_init_begin(),
1970c370a7eeSEli Friedman                                                e = E->capture_init_end();
1971c370a7eeSEli Friedman        i != e; ++i, ++CurField) {
1972c370a7eeSEli Friedman     // Emit initialization
197340ed2973SDavid Blaikie     LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
197439c81e28SAlexey Bataev     if (CurField->hasCapturedVLAType()) {
197539c81e28SAlexey Bataev       auto VAT = CurField->getCapturedVLAType();
197639c81e28SAlexey Bataev       EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
197739c81e28SAlexey Bataev     } else {
19785f1a04ffSEli Friedman       ArrayRef<VarDecl *> ArrayIndexes;
19795f1a04ffSEli Friedman       if (CurField->getType()->isArrayType())
19805f1a04ffSEli Friedman         ArrayIndexes = E->getCaptureInitIndexVars(i);
198140ed2973SDavid Blaikie       EmitInitializerForField(*CurField, LV, *i, ArrayIndexes);
1982c370a7eeSEli Friedman     }
1983c370a7eeSEli Friedman   }
198439c81e28SAlexey Bataev }
1985