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(),
187a560ccf2SRichard 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 
244*018f266bSVedant Kumar   // FIXME: Uses of 'MD' past this point need to be audited. We may need to use
245*018f266bSVedant Kumar   // 'CalleeDecl' instead.
246*018f266bSVedant Kumar 
24727da15baSAnders Carlsson   // C++ [class.virtual]p12:
24827da15baSAnders Carlsson   //   Explicit qualification with the scope operator (5.1) suppresses the
24927da15baSAnders Carlsson   //   virtual call mechanism.
25027da15baSAnders Carlsson   //
25127da15baSAnders Carlsson   // We also don't emit a virtual call if the base expression has a record type
25227da15baSAnders Carlsson   // because then we know what the type is.
2533b33c4ecSRafael Espindola   bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
25419cee187SStephen Lin   llvm::Value *Callee;
2559dc6eef7SStephen Lin 
2560d635f53SJohn McCall   if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
25719cee187SStephen Lin     assert(CE->arg_begin() == CE->arg_end() &&
2589dc6eef7SStephen Lin            "Destructor shouldn't have explicit parameters");
2599dc6eef7SStephen Lin     assert(ReturnValue.isNull() && "Destructor shouldn't have return value");
2609dc6eef7SStephen Lin     if (UseVirtualCall) {
261aad4af6dSNico Weber       CGM.getCXXABI().EmitVirtualDestructorCall(
262aad4af6dSNico Weber           *this, Dtor, Dtor_Complete, This, cast<CXXMemberCallExpr>(CE));
26327da15baSAnders Carlsson     } else {
264aad4af6dSNico Weber       if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
265aad4af6dSNico Weber         Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
2663b33c4ecSRafael Espindola       else if (!DevirtualizedMethod)
2671ac0ec86SRafael Espindola         Callee =
2681ac0ec86SRafael Espindola             CGM.getAddrOfCXXStructor(Dtor, StructorType::Complete, FInfo, Ty);
26949e860b2SRafael Espindola       else {
2703b33c4ecSRafael Espindola         const CXXDestructorDecl *DDtor =
2713b33c4ecSRafael Espindola           cast<CXXDestructorDecl>(DevirtualizedMethod);
27249e860b2SRafael Espindola         Callee = CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty);
27349e860b2SRafael Espindola       }
274*018f266bSVedant Kumar       EmitCXXMemberOrOperatorCall(
275*018f266bSVedant Kumar           CalleeDecl, Callee, ReturnValue, This.getPointer(),
276*018f266bSVedant Kumar           /*ImplicitParam=*/nullptr, QualType(), CE, nullptr);
27727da15baSAnders Carlsson     }
2788a13c418SCraig Topper     return RValue::get(nullptr);
2799dc6eef7SStephen Lin   }
2809dc6eef7SStephen Lin 
2819dc6eef7SStephen Lin   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
28264225794SFrancois Pichet     Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
2830d635f53SJohn McCall   } else if (UseVirtualCall) {
2846708c4a1SPeter Collingbourne     Callee = CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, Ty,
2856708c4a1SPeter Collingbourne                                                        CE->getLocStart());
28627da15baSAnders Carlsson   } else {
2871a7488afSPeter Collingbourne     if (SanOpts.has(SanitizerKind::CFINVCall) &&
2881a7488afSPeter Collingbourne         MD->getParent()->isDynamicClass()) {
2894b1ac72cSPiotr Padlewski       llvm::Value *VTable = GetVTablePtr(This, Int8PtrTy, MD->getParent());
290fb532b9aSPeter Collingbourne       EmitVTablePtrCheckForCall(MD->getParent(), VTable, CFITCK_NVCall,
291fb532b9aSPeter Collingbourne                                 CE->getLocStart());
2921a7488afSPeter Collingbourne     }
2931a7488afSPeter Collingbourne 
294aad4af6dSNico Weber     if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
295aad4af6dSNico Weber       Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
2963b33c4ecSRafael Espindola     else if (!DevirtualizedMethod)
297727a771aSRafael Espindola       Callee = CGM.GetAddrOfFunction(MD, Ty);
29849e860b2SRafael Espindola     else {
2993b33c4ecSRafael Espindola       Callee = CGM.GetAddrOfFunction(DevirtualizedMethod, Ty);
30049e860b2SRafael Espindola     }
30127da15baSAnders Carlsson   }
30227da15baSAnders Carlsson 
303f1749427STimur Iskhodzhanov   if (MD->isVirtual()) {
304f1749427STimur Iskhodzhanov     This = CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
3054b60f30aSReid Kleckner         *this, CalleeDecl, This, UseVirtualCall);
306f1749427STimur Iskhodzhanov   }
30788fd439aSTimur Iskhodzhanov 
308*018f266bSVedant Kumar   return EmitCXXMemberOrOperatorCall(
309*018f266bSVedant Kumar       CalleeDecl, Callee, ReturnValue, This.getPointer(),
310*018f266bSVedant Kumar       /*ImplicitParam=*/nullptr, QualType(), CE, RtlArgs);
31127da15baSAnders Carlsson }
31227da15baSAnders Carlsson 
31327da15baSAnders Carlsson RValue
31427da15baSAnders Carlsson CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
31527da15baSAnders Carlsson                                               ReturnValueSlot ReturnValue) {
31627da15baSAnders Carlsson   const BinaryOperator *BO =
31727da15baSAnders Carlsson       cast<BinaryOperator>(E->getCallee()->IgnoreParens());
31827da15baSAnders Carlsson   const Expr *BaseExpr = BO->getLHS();
31927da15baSAnders Carlsson   const Expr *MemFnExpr = BO->getRHS();
32027da15baSAnders Carlsson 
32127da15baSAnders Carlsson   const MemberPointerType *MPT =
3220009fcc3SJohn McCall     MemFnExpr->getType()->castAs<MemberPointerType>();
323475999dcSJohn McCall 
32427da15baSAnders Carlsson   const FunctionProtoType *FPT =
3250009fcc3SJohn McCall     MPT->getPointeeType()->castAs<FunctionProtoType>();
32627da15baSAnders Carlsson   const CXXRecordDecl *RD =
32727da15baSAnders Carlsson     cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
32827da15baSAnders Carlsson 
32927da15baSAnders Carlsson   // Emit the 'this' pointer.
3307f416cc4SJohn McCall   Address This = Address::invalid();
331e302792bSJohn McCall   if (BO->getOpcode() == BO_PtrMemI)
3327f416cc4SJohn McCall     This = EmitPointerWithAlignment(BaseExpr);
33327da15baSAnders Carlsson   else
33427da15baSAnders Carlsson     This = EmitLValue(BaseExpr).getAddress();
33527da15baSAnders Carlsson 
3367f416cc4SJohn McCall   EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This.getPointer(),
337e30752c9SRichard Smith                 QualType(MPT->getClass(), 0));
33869d0d262SRichard Smith 
339bde62d78SRichard Smith   // Get the member function pointer.
340bde62d78SRichard Smith   llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
341bde62d78SRichard Smith 
342475999dcSJohn McCall   // Ask the ABI to load the callee.  Note that This is modified.
3437f416cc4SJohn McCall   llvm::Value *ThisPtrForCall = nullptr;
344475999dcSJohn McCall   llvm::Value *Callee =
3457f416cc4SJohn McCall     CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This,
3467f416cc4SJohn McCall                                              ThisPtrForCall, MemFnPtr, MPT);
34727da15baSAnders Carlsson 
34827da15baSAnders Carlsson   CallArgList Args;
34927da15baSAnders Carlsson 
35027da15baSAnders Carlsson   QualType ThisType =
35127da15baSAnders Carlsson     getContext().getPointerType(getContext().getTagDeclType(RD));
35227da15baSAnders Carlsson 
35327da15baSAnders Carlsson   // Push the this ptr.
3547f416cc4SJohn McCall   Args.add(RValue::get(ThisPtrForCall), ThisType);
35527da15baSAnders Carlsson 
356419996ccSGeorge Burgess IV   RequiredArgs required =
357419996ccSGeorge Burgess IV       RequiredArgs::forPrototypePlus(FPT, 1, /*FD=*/nullptr);
3588dda7b27SJohn McCall 
35927da15baSAnders Carlsson   // And the rest of the call args
360419996ccSGeorge Burgess IV   EmitCallArgs(Args, FPT, E->arguments());
3615fa40c3bSNick Lewycky   return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
3625fa40c3bSNick Lewycky                   Callee, ReturnValue, Args);
36327da15baSAnders Carlsson }
36427da15baSAnders Carlsson 
36527da15baSAnders Carlsson RValue
36627da15baSAnders Carlsson CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
36727da15baSAnders Carlsson                                                const CXXMethodDecl *MD,
36827da15baSAnders Carlsson                                                ReturnValueSlot ReturnValue) {
36927da15baSAnders Carlsson   assert(MD->isInstance() &&
37027da15baSAnders Carlsson          "Trying to emit a member call expr on a static method!");
371aad4af6dSNico Weber   return EmitCXXMemberOrOperatorMemberCallExpr(
372aad4af6dSNico Weber       E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr,
373aad4af6dSNico Weber       /*IsArrow=*/false, E->getArg(0));
37427da15baSAnders Carlsson }
37527da15baSAnders Carlsson 
376fe883422SPeter Collingbourne RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
377fe883422SPeter Collingbourne                                                ReturnValueSlot ReturnValue) {
378fe883422SPeter Collingbourne   return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
379fe883422SPeter Collingbourne }
380fe883422SPeter Collingbourne 
381fde961dbSEli Friedman static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
3827f416cc4SJohn McCall                                             Address DestPtr,
383fde961dbSEli Friedman                                             const CXXRecordDecl *Base) {
384fde961dbSEli Friedman   if (Base->isEmpty())
385fde961dbSEli Friedman     return;
386fde961dbSEli Friedman 
3877f416cc4SJohn McCall   DestPtr = CGF.Builder.CreateElementBitCast(DestPtr, CGF.Int8Ty);
388fde961dbSEli Friedman 
389fde961dbSEli Friedman   const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
3908671c6e0SDavid Majnemer   CharUnits NVSize = Layout.getNonVirtualSize();
3918671c6e0SDavid Majnemer 
3928671c6e0SDavid Majnemer   // We cannot simply zero-initialize the entire base sub-object if vbptrs are
3938671c6e0SDavid Majnemer   // present, they are initialized by the most derived class before calling the
3948671c6e0SDavid Majnemer   // constructor.
3958671c6e0SDavid Majnemer   SmallVector<std::pair<CharUnits, CharUnits>, 1> Stores;
3968671c6e0SDavid Majnemer   Stores.emplace_back(CharUnits::Zero(), NVSize);
3978671c6e0SDavid Majnemer 
3988671c6e0SDavid Majnemer   // Each store is split by the existence of a vbptr.
3998671c6e0SDavid Majnemer   CharUnits VBPtrWidth = CGF.getPointerSize();
4008671c6e0SDavid Majnemer   std::vector<CharUnits> VBPtrOffsets =
4018671c6e0SDavid Majnemer       CGF.CGM.getCXXABI().getVBPtrOffsets(Base);
4028671c6e0SDavid Majnemer   for (CharUnits VBPtrOffset : VBPtrOffsets) {
4037f980d84SDavid Majnemer     // Stop before we hit any virtual base pointers located in virtual bases.
4047f980d84SDavid Majnemer     if (VBPtrOffset >= NVSize)
4057f980d84SDavid Majnemer       break;
4068671c6e0SDavid Majnemer     std::pair<CharUnits, CharUnits> LastStore = Stores.pop_back_val();
4078671c6e0SDavid Majnemer     CharUnits LastStoreOffset = LastStore.first;
4088671c6e0SDavid Majnemer     CharUnits LastStoreSize = LastStore.second;
4098671c6e0SDavid Majnemer 
4108671c6e0SDavid Majnemer     CharUnits SplitBeforeOffset = LastStoreOffset;
4118671c6e0SDavid Majnemer     CharUnits SplitBeforeSize = VBPtrOffset - SplitBeforeOffset;
4128671c6e0SDavid Majnemer     assert(!SplitBeforeSize.isNegative() && "negative store size!");
4138671c6e0SDavid Majnemer     if (!SplitBeforeSize.isZero())
4148671c6e0SDavid Majnemer       Stores.emplace_back(SplitBeforeOffset, SplitBeforeSize);
4158671c6e0SDavid Majnemer 
4168671c6e0SDavid Majnemer     CharUnits SplitAfterOffset = VBPtrOffset + VBPtrWidth;
4178671c6e0SDavid Majnemer     CharUnits SplitAfterSize = LastStoreSize - SplitAfterOffset;
4188671c6e0SDavid Majnemer     assert(!SplitAfterSize.isNegative() && "negative store size!");
4198671c6e0SDavid Majnemer     if (!SplitAfterSize.isZero())
4208671c6e0SDavid Majnemer       Stores.emplace_back(SplitAfterOffset, SplitAfterSize);
4218671c6e0SDavid Majnemer   }
422fde961dbSEli Friedman 
423fde961dbSEli Friedman   // If the type contains a pointer to data member we can't memset it to zero.
424fde961dbSEli Friedman   // Instead, create a null constant and copy it to the destination.
425fde961dbSEli Friedman   // TODO: there are other patterns besides zero that we can usefully memset,
426fde961dbSEli Friedman   // like -1, which happens to be the pattern used by member-pointers.
427fde961dbSEli Friedman   // TODO: isZeroInitializable can be over-conservative in the case where a
428fde961dbSEli Friedman   // virtual base contains a member pointer.
4298671c6e0SDavid Majnemer   llvm::Constant *NullConstantForBase = CGF.CGM.EmitNullConstantForBase(Base);
4308671c6e0SDavid Majnemer   if (!NullConstantForBase->isNullValue()) {
4318671c6e0SDavid Majnemer     llvm::GlobalVariable *NullVariable = new llvm::GlobalVariable(
4328671c6e0SDavid Majnemer         CGF.CGM.getModule(), NullConstantForBase->getType(),
4338671c6e0SDavid Majnemer         /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage,
4348671c6e0SDavid Majnemer         NullConstantForBase, Twine());
4357f416cc4SJohn McCall 
4367f416cc4SJohn McCall     CharUnits Align = std::max(Layout.getNonVirtualAlignment(),
4377f416cc4SJohn McCall                                DestPtr.getAlignment());
438fde961dbSEli Friedman     NullVariable->setAlignment(Align.getQuantity());
4397f416cc4SJohn McCall 
4407f416cc4SJohn McCall     Address SrcPtr = Address(CGF.EmitCastToVoidPtr(NullVariable), Align);
441fde961dbSEli Friedman 
442fde961dbSEli Friedman     // Get and call the appropriate llvm.memcpy overload.
4438671c6e0SDavid Majnemer     for (std::pair<CharUnits, CharUnits> Store : Stores) {
4448671c6e0SDavid Majnemer       CharUnits StoreOffset = Store.first;
4458671c6e0SDavid Majnemer       CharUnits StoreSize = Store.second;
4468671c6e0SDavid Majnemer       llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
4478671c6e0SDavid Majnemer       CGF.Builder.CreateMemCpy(
4488671c6e0SDavid Majnemer           CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
4498671c6e0SDavid Majnemer           CGF.Builder.CreateConstInBoundsByteGEP(SrcPtr, StoreOffset),
4508671c6e0SDavid Majnemer           StoreSizeVal);
451fde961dbSEli Friedman     }
452fde961dbSEli Friedman 
453fde961dbSEli Friedman   // Otherwise, just memset the whole thing to zero.  This is legal
454fde961dbSEli Friedman   // because in LLVM, all default initializers (other than the ones we just
455fde961dbSEli Friedman   // handled above) are guaranteed to have a bit pattern of all zeros.
4568671c6e0SDavid Majnemer   } else {
4578671c6e0SDavid Majnemer     for (std::pair<CharUnits, CharUnits> Store : Stores) {
4588671c6e0SDavid Majnemer       CharUnits StoreOffset = Store.first;
4598671c6e0SDavid Majnemer       CharUnits StoreSize = Store.second;
4608671c6e0SDavid Majnemer       llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
4618671c6e0SDavid Majnemer       CGF.Builder.CreateMemSet(
4628671c6e0SDavid Majnemer           CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
4638671c6e0SDavid Majnemer           CGF.Builder.getInt8(0), StoreSizeVal);
4648671c6e0SDavid Majnemer     }
4658671c6e0SDavid Majnemer   }
466fde961dbSEli Friedman }
467fde961dbSEli Friedman 
46827da15baSAnders Carlsson void
4697a626f63SJohn McCall CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
4707a626f63SJohn McCall                                       AggValueSlot Dest) {
4717a626f63SJohn McCall   assert(!Dest.isIgnored() && "Must have a destination!");
47227da15baSAnders Carlsson   const CXXConstructorDecl *CD = E->getConstructor();
473630c76efSDouglas Gregor 
474630c76efSDouglas Gregor   // If we require zero initialization before (or instead of) calling the
475630c76efSDouglas Gregor   // constructor, as can be the case with a non-user-provided default
47603535265SArgyrios Kyrtzidis   // constructor, emit the zero initialization now, unless destination is
47703535265SArgyrios Kyrtzidis   // already zeroed.
478fde961dbSEli Friedman   if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
479fde961dbSEli Friedman     switch (E->getConstructionKind()) {
480fde961dbSEli Friedman     case CXXConstructExpr::CK_Delegating:
481fde961dbSEli Friedman     case CXXConstructExpr::CK_Complete:
4827f416cc4SJohn McCall       EmitNullInitialization(Dest.getAddress(), E->getType());
483fde961dbSEli Friedman       break;
484fde961dbSEli Friedman     case CXXConstructExpr::CK_VirtualBase:
485fde961dbSEli Friedman     case CXXConstructExpr::CK_NonVirtualBase:
4867f416cc4SJohn McCall       EmitNullBaseClassInitialization(*this, Dest.getAddress(),
4877f416cc4SJohn McCall                                       CD->getParent());
488fde961dbSEli Friedman       break;
489fde961dbSEli Friedman     }
490fde961dbSEli Friedman   }
491630c76efSDouglas Gregor 
492630c76efSDouglas Gregor   // If this is a call to a trivial default constructor, do nothing.
493630c76efSDouglas Gregor   if (CD->isTrivial() && CD->isDefaultConstructor())
49427da15baSAnders Carlsson     return;
495630c76efSDouglas Gregor 
4968ea46b66SJohn McCall   // Elide the constructor if we're constructing from a temporary.
4978ea46b66SJohn McCall   // The temporary check is required because Sema sets this on NRVO
4988ea46b66SJohn McCall   // returns.
4999c6890a7SRichard Smith   if (getLangOpts().ElideConstructors && E->isElidable()) {
5008ea46b66SJohn McCall     assert(getContext().hasSameUnqualifiedType(E->getType(),
5018ea46b66SJohn McCall                                                E->getArg(0)->getType()));
5027a626f63SJohn McCall     if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
5037a626f63SJohn McCall       EmitAggExpr(E->getArg(0), Dest);
50427da15baSAnders Carlsson       return;
50527da15baSAnders Carlsson     }
506222cf0efSDouglas Gregor   }
507630c76efSDouglas Gregor 
508e7545b33SAlexey Bataev   if (const ArrayType *arrayType
509e7545b33SAlexey Bataev         = getContext().getAsArrayType(E->getType())) {
5107f416cc4SJohn McCall     EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddress(), E);
511f677a8e9SJohn McCall   } else {
512bceca20aSCameron Esfahani     CXXCtorType Type = Ctor_Complete;
513271c3681SAlexis Hunt     bool ForVirtualBase = false;
51461535005SDouglas Gregor     bool Delegating = false;
515271c3681SAlexis Hunt 
516271c3681SAlexis Hunt     switch (E->getConstructionKind()) {
517271c3681SAlexis Hunt      case CXXConstructExpr::CK_Delegating:
51861bc1737SAlexis Hunt       // We should be emitting a constructor; GlobalDecl will assert this
51961bc1737SAlexis Hunt       Type = CurGD.getCtorType();
52061535005SDouglas Gregor       Delegating = true;
521271c3681SAlexis Hunt       break;
52261bc1737SAlexis Hunt 
523271c3681SAlexis Hunt      case CXXConstructExpr::CK_Complete:
524271c3681SAlexis Hunt       Type = Ctor_Complete;
525271c3681SAlexis Hunt       break;
526271c3681SAlexis Hunt 
527271c3681SAlexis Hunt      case CXXConstructExpr::CK_VirtualBase:
528271c3681SAlexis Hunt       ForVirtualBase = true;
529271c3681SAlexis Hunt       // fall-through
530271c3681SAlexis Hunt 
531271c3681SAlexis Hunt      case CXXConstructExpr::CK_NonVirtualBase:
532271c3681SAlexis Hunt       Type = Ctor_Base;
533271c3681SAlexis Hunt     }
534e11f9ce9SAnders Carlsson 
53527da15baSAnders Carlsson     // Call the constructor.
5367f416cc4SJohn McCall     EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating,
5377f416cc4SJohn McCall                            Dest.getAddress(), E);
53827da15baSAnders Carlsson   }
539e11f9ce9SAnders Carlsson }
54027da15baSAnders Carlsson 
5417f416cc4SJohn McCall void CodeGenFunction::EmitSynthesizedCXXCopyCtor(Address Dest, Address Src,
54250198098SFariborz Jahanian                                                  const Expr *Exp) {
5435d413781SJohn McCall   if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
544e988bdacSFariborz Jahanian     Exp = E->getSubExpr();
545e988bdacSFariborz Jahanian   assert(isa<CXXConstructExpr>(Exp) &&
546e988bdacSFariborz Jahanian          "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
547e988bdacSFariborz Jahanian   const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
548e988bdacSFariborz Jahanian   const CXXConstructorDecl *CD = E->getConstructor();
549e988bdacSFariborz Jahanian   RunCleanupsScope Scope(*this);
550e988bdacSFariborz Jahanian 
551e988bdacSFariborz Jahanian   // If we require zero initialization before (or instead of) calling the
552e988bdacSFariborz Jahanian   // constructor, as can be the case with a non-user-provided default
553e988bdacSFariborz Jahanian   // constructor, emit the zero initialization now.
554e988bdacSFariborz Jahanian   // FIXME. Do I still need this for a copy ctor synthesis?
555e988bdacSFariborz Jahanian   if (E->requiresZeroInitialization())
556e988bdacSFariborz Jahanian     EmitNullInitialization(Dest, E->getType());
557e988bdacSFariborz Jahanian 
55899da11cfSChandler Carruth   assert(!getContext().getAsConstantArrayType(E->getType())
55999da11cfSChandler Carruth          && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
560525bf650SAlexey Samsonov   EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E);
561e988bdacSFariborz Jahanian }
562e988bdacSFariborz Jahanian 
5638ed55a54SJohn McCall static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
5648ed55a54SJohn McCall                                         const CXXNewExpr *E) {
56521122cf6SAnders Carlsson   if (!E->isArray())
5663eb55cfeSKen Dyck     return CharUnits::Zero();
56721122cf6SAnders Carlsson 
5687ec4b434SJohn McCall   // No cookie is required if the operator new[] being used is the
5697ec4b434SJohn McCall   // reserved placement operator new[].
5707ec4b434SJohn McCall   if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
5713eb55cfeSKen Dyck     return CharUnits::Zero();
572399f499fSAnders Carlsson 
573284c48ffSJohn McCall   return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
57459486a2dSAnders Carlsson }
57559486a2dSAnders Carlsson 
576036f2f6bSJohn McCall static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
577036f2f6bSJohn McCall                                         const CXXNewExpr *e,
578f862eb6aSSebastian Redl                                         unsigned minElements,
579036f2f6bSJohn McCall                                         llvm::Value *&numElements,
580036f2f6bSJohn McCall                                         llvm::Value *&sizeWithoutCookie) {
581036f2f6bSJohn McCall   QualType type = e->getAllocatedType();
58259486a2dSAnders Carlsson 
583036f2f6bSJohn McCall   if (!e->isArray()) {
584036f2f6bSJohn McCall     CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
585036f2f6bSJohn McCall     sizeWithoutCookie
586036f2f6bSJohn McCall       = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
587036f2f6bSJohn McCall     return sizeWithoutCookie;
58805fc5be3SDouglas Gregor   }
58959486a2dSAnders Carlsson 
590036f2f6bSJohn McCall   // The width of size_t.
591036f2f6bSJohn McCall   unsigned sizeWidth = CGF.SizeTy->getBitWidth();
592036f2f6bSJohn McCall 
5938ed55a54SJohn McCall   // Figure out the cookie size.
594036f2f6bSJohn McCall   llvm::APInt cookieSize(sizeWidth,
595036f2f6bSJohn McCall                          CalculateCookiePadding(CGF, e).getQuantity());
5968ed55a54SJohn McCall 
59759486a2dSAnders Carlsson   // Emit the array size expression.
5987648fb46SArgyrios Kyrtzidis   // We multiply the size of all dimensions for NumElements.
5997648fb46SArgyrios Kyrtzidis   // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
600036f2f6bSJohn McCall   numElements = CGF.EmitScalarExpr(e->getArraySize());
601036f2f6bSJohn McCall   assert(isa<llvm::IntegerType>(numElements->getType()));
6028ed55a54SJohn McCall 
603036f2f6bSJohn McCall   // The number of elements can be have an arbitrary integer type;
604036f2f6bSJohn McCall   // essentially, we need to multiply it by a constant factor, add a
605036f2f6bSJohn McCall   // cookie size, and verify that the result is representable as a
606036f2f6bSJohn McCall   // size_t.  That's just a gloss, though, and it's wrong in one
607036f2f6bSJohn McCall   // important way: if the count is negative, it's an error even if
608036f2f6bSJohn McCall   // the cookie size would bring the total size >= 0.
6096ab2fa8fSDouglas Gregor   bool isSigned
6106ab2fa8fSDouglas Gregor     = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
6112192fe50SChris Lattner   llvm::IntegerType *numElementsType
612036f2f6bSJohn McCall     = cast<llvm::IntegerType>(numElements->getType());
613036f2f6bSJohn McCall   unsigned numElementsWidth = numElementsType->getBitWidth();
614036f2f6bSJohn McCall 
615036f2f6bSJohn McCall   // Compute the constant factor.
616036f2f6bSJohn McCall   llvm::APInt arraySizeMultiplier(sizeWidth, 1);
6177648fb46SArgyrios Kyrtzidis   while (const ConstantArrayType *CAT
618036f2f6bSJohn McCall              = CGF.getContext().getAsConstantArrayType(type)) {
619036f2f6bSJohn McCall     type = CAT->getElementType();
620036f2f6bSJohn McCall     arraySizeMultiplier *= CAT->getSize();
6217648fb46SArgyrios Kyrtzidis   }
62259486a2dSAnders Carlsson 
623036f2f6bSJohn McCall   CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
624036f2f6bSJohn McCall   llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
625036f2f6bSJohn McCall   typeSizeMultiplier *= arraySizeMultiplier;
626036f2f6bSJohn McCall 
627036f2f6bSJohn McCall   // This will be a size_t.
628036f2f6bSJohn McCall   llvm::Value *size;
62932ac583dSChris Lattner 
63032ac583dSChris Lattner   // If someone is doing 'new int[42]' there is no need to do a dynamic check.
63132ac583dSChris Lattner   // Don't bloat the -O0 code.
632036f2f6bSJohn McCall   if (llvm::ConstantInt *numElementsC =
633036f2f6bSJohn McCall         dyn_cast<llvm::ConstantInt>(numElements)) {
634036f2f6bSJohn McCall     const llvm::APInt &count = numElementsC->getValue();
63532ac583dSChris Lattner 
636036f2f6bSJohn McCall     bool hasAnyOverflow = false;
63732ac583dSChris Lattner 
638036f2f6bSJohn McCall     // If 'count' was a negative number, it's an overflow.
639036f2f6bSJohn McCall     if (isSigned && count.isNegative())
640036f2f6bSJohn McCall       hasAnyOverflow = true;
6418ed55a54SJohn McCall 
642036f2f6bSJohn McCall     // We want to do all this arithmetic in size_t.  If numElements is
643036f2f6bSJohn McCall     // wider than that, check whether it's already too big, and if so,
644036f2f6bSJohn McCall     // overflow.
645036f2f6bSJohn McCall     else if (numElementsWidth > sizeWidth &&
646036f2f6bSJohn McCall              numElementsWidth - sizeWidth > count.countLeadingZeros())
647036f2f6bSJohn McCall       hasAnyOverflow = true;
648036f2f6bSJohn McCall 
649036f2f6bSJohn McCall     // Okay, compute a count at the right width.
650036f2f6bSJohn McCall     llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
651036f2f6bSJohn McCall 
652f862eb6aSSebastian Redl     // If there is a brace-initializer, we cannot allocate fewer elements than
653f862eb6aSSebastian Redl     // there are initializers. If we do, that's treated like an overflow.
654f862eb6aSSebastian Redl     if (adjustedCount.ult(minElements))
655f862eb6aSSebastian Redl       hasAnyOverflow = true;
656f862eb6aSSebastian Redl 
657036f2f6bSJohn McCall     // Scale numElements by that.  This might overflow, but we don't
658036f2f6bSJohn McCall     // care because it only overflows if allocationSize does, too, and
659036f2f6bSJohn McCall     // if that overflows then we shouldn't use this.
660036f2f6bSJohn McCall     numElements = llvm::ConstantInt::get(CGF.SizeTy,
661036f2f6bSJohn McCall                                          adjustedCount * arraySizeMultiplier);
662036f2f6bSJohn McCall 
663036f2f6bSJohn McCall     // Compute the size before cookie, and track whether it overflowed.
664036f2f6bSJohn McCall     bool overflow;
665036f2f6bSJohn McCall     llvm::APInt allocationSize
666036f2f6bSJohn McCall       = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
667036f2f6bSJohn McCall     hasAnyOverflow |= overflow;
668036f2f6bSJohn McCall 
669036f2f6bSJohn McCall     // Add in the cookie, and check whether it's overflowed.
670036f2f6bSJohn McCall     if (cookieSize != 0) {
671036f2f6bSJohn McCall       // Save the current size without a cookie.  This shouldn't be
672036f2f6bSJohn McCall       // used if there was overflow.
673036f2f6bSJohn McCall       sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
674036f2f6bSJohn McCall 
675036f2f6bSJohn McCall       allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
676036f2f6bSJohn McCall       hasAnyOverflow |= overflow;
6778ed55a54SJohn McCall     }
6788ed55a54SJohn McCall 
679036f2f6bSJohn McCall     // On overflow, produce a -1 so operator new will fail.
680455f42c9SAaron Ballman     if (hasAnyOverflow) {
681455f42c9SAaron Ballman       size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
682455f42c9SAaron Ballman     } else {
683036f2f6bSJohn McCall       size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
684455f42c9SAaron Ballman     }
68532ac583dSChris Lattner 
686036f2f6bSJohn McCall   // Otherwise, we might need to use the overflow intrinsics.
6878ed55a54SJohn McCall   } else {
688f862eb6aSSebastian Redl     // There are up to five conditions we need to test for:
689036f2f6bSJohn McCall     // 1) if isSigned, we need to check whether numElements is negative;
690036f2f6bSJohn McCall     // 2) if numElementsWidth > sizeWidth, we need to check whether
691036f2f6bSJohn McCall     //   numElements is larger than something representable in size_t;
692f862eb6aSSebastian Redl     // 3) if minElements > 0, we need to check whether numElements is smaller
693f862eb6aSSebastian Redl     //    than that.
694f862eb6aSSebastian Redl     // 4) we need to compute
695036f2f6bSJohn McCall     //      sizeWithoutCookie := numElements * typeSizeMultiplier
696036f2f6bSJohn McCall     //    and check whether it overflows; and
697f862eb6aSSebastian Redl     // 5) if we need a cookie, we need to compute
698036f2f6bSJohn McCall     //      size := sizeWithoutCookie + cookieSize
699036f2f6bSJohn McCall     //    and check whether it overflows.
7008ed55a54SJohn McCall 
7018a13c418SCraig Topper     llvm::Value *hasOverflow = nullptr;
7028ed55a54SJohn McCall 
703036f2f6bSJohn McCall     // If numElementsWidth > sizeWidth, then one way or another, we're
704036f2f6bSJohn McCall     // going to have to do a comparison for (2), and this happens to
705036f2f6bSJohn McCall     // take care of (1), too.
706036f2f6bSJohn McCall     if (numElementsWidth > sizeWidth) {
707036f2f6bSJohn McCall       llvm::APInt threshold(numElementsWidth, 1);
708036f2f6bSJohn McCall       threshold <<= sizeWidth;
7098ed55a54SJohn McCall 
710036f2f6bSJohn McCall       llvm::Value *thresholdV
711036f2f6bSJohn McCall         = llvm::ConstantInt::get(numElementsType, threshold);
712036f2f6bSJohn McCall 
713036f2f6bSJohn McCall       hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
714036f2f6bSJohn McCall       numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
715036f2f6bSJohn McCall 
716036f2f6bSJohn McCall     // Otherwise, if we're signed, we want to sext up to size_t.
717036f2f6bSJohn McCall     } else if (isSigned) {
718036f2f6bSJohn McCall       if (numElementsWidth < sizeWidth)
719036f2f6bSJohn McCall         numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
720036f2f6bSJohn McCall 
721036f2f6bSJohn McCall       // If there's a non-1 type size multiplier, then we can do the
722036f2f6bSJohn McCall       // signedness check at the same time as we do the multiply
723036f2f6bSJohn McCall       // because a negative number times anything will cause an
724f862eb6aSSebastian Redl       // unsigned overflow.  Otherwise, we have to do it here. But at least
725f862eb6aSSebastian Redl       // in this case, we can subsume the >= minElements check.
726036f2f6bSJohn McCall       if (typeSizeMultiplier == 1)
727036f2f6bSJohn McCall         hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
728f862eb6aSSebastian Redl                               llvm::ConstantInt::get(CGF.SizeTy, minElements));
729036f2f6bSJohn McCall 
730036f2f6bSJohn McCall     // Otherwise, zext up to size_t if necessary.
731036f2f6bSJohn McCall     } else if (numElementsWidth < sizeWidth) {
732036f2f6bSJohn McCall       numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
733036f2f6bSJohn McCall     }
734036f2f6bSJohn McCall 
735036f2f6bSJohn McCall     assert(numElements->getType() == CGF.SizeTy);
736036f2f6bSJohn McCall 
737f862eb6aSSebastian Redl     if (minElements) {
738f862eb6aSSebastian Redl       // Don't allow allocation of fewer elements than we have initializers.
739f862eb6aSSebastian Redl       if (!hasOverflow) {
740f862eb6aSSebastian Redl         hasOverflow = CGF.Builder.CreateICmpULT(numElements,
741f862eb6aSSebastian Redl                               llvm::ConstantInt::get(CGF.SizeTy, minElements));
742f862eb6aSSebastian Redl       } else if (numElementsWidth > sizeWidth) {
743f862eb6aSSebastian Redl         // The other existing overflow subsumes this check.
744f862eb6aSSebastian Redl         // We do an unsigned comparison, since any signed value < -1 is
745f862eb6aSSebastian Redl         // taken care of either above or below.
746f862eb6aSSebastian Redl         hasOverflow = CGF.Builder.CreateOr(hasOverflow,
747f862eb6aSSebastian Redl                           CGF.Builder.CreateICmpULT(numElements,
748f862eb6aSSebastian Redl                               llvm::ConstantInt::get(CGF.SizeTy, minElements)));
749f862eb6aSSebastian Redl       }
750f862eb6aSSebastian Redl     }
751f862eb6aSSebastian Redl 
752036f2f6bSJohn McCall     size = numElements;
753036f2f6bSJohn McCall 
754036f2f6bSJohn McCall     // Multiply by the type size if necessary.  This multiplier
755036f2f6bSJohn McCall     // includes all the factors for nested arrays.
7568ed55a54SJohn McCall     //
757036f2f6bSJohn McCall     // This step also causes numElements to be scaled up by the
758036f2f6bSJohn McCall     // nested-array factor if necessary.  Overflow on this computation
759036f2f6bSJohn McCall     // can be ignored because the result shouldn't be used if
760036f2f6bSJohn McCall     // allocation fails.
761036f2f6bSJohn McCall     if (typeSizeMultiplier != 1) {
762036f2f6bSJohn McCall       llvm::Value *umul_with_overflow
7638d375cefSBenjamin Kramer         = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
7648ed55a54SJohn McCall 
765036f2f6bSJohn McCall       llvm::Value *tsmV =
766036f2f6bSJohn McCall         llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
767036f2f6bSJohn McCall       llvm::Value *result =
76843f9bb73SDavid Blaikie           CGF.Builder.CreateCall(umul_with_overflow, {size, tsmV});
7698ed55a54SJohn McCall 
770036f2f6bSJohn McCall       llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
771036f2f6bSJohn McCall       if (hasOverflow)
772036f2f6bSJohn McCall         hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
7738ed55a54SJohn McCall       else
774036f2f6bSJohn McCall         hasOverflow = overflowed;
77559486a2dSAnders Carlsson 
776036f2f6bSJohn McCall       size = CGF.Builder.CreateExtractValue(result, 0);
777036f2f6bSJohn McCall 
778036f2f6bSJohn McCall       // Also scale up numElements by the array size multiplier.
779036f2f6bSJohn McCall       if (arraySizeMultiplier != 1) {
780036f2f6bSJohn McCall         // If the base element type size is 1, then we can re-use the
781036f2f6bSJohn McCall         // multiply we just did.
782036f2f6bSJohn McCall         if (typeSize.isOne()) {
783036f2f6bSJohn McCall           assert(arraySizeMultiplier == typeSizeMultiplier);
784036f2f6bSJohn McCall           numElements = size;
785036f2f6bSJohn McCall 
786036f2f6bSJohn McCall         // Otherwise we need a separate multiply.
787036f2f6bSJohn McCall         } else {
788036f2f6bSJohn McCall           llvm::Value *asmV =
789036f2f6bSJohn McCall             llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
790036f2f6bSJohn McCall           numElements = CGF.Builder.CreateMul(numElements, asmV);
791036f2f6bSJohn McCall         }
792036f2f6bSJohn McCall       }
793036f2f6bSJohn McCall     } else {
794036f2f6bSJohn McCall       // numElements doesn't need to be scaled.
795036f2f6bSJohn McCall       assert(arraySizeMultiplier == 1);
796036f2f6bSJohn McCall     }
797036f2f6bSJohn McCall 
798036f2f6bSJohn McCall     // Add in the cookie size if necessary.
799036f2f6bSJohn McCall     if (cookieSize != 0) {
800036f2f6bSJohn McCall       sizeWithoutCookie = size;
801036f2f6bSJohn McCall 
802036f2f6bSJohn McCall       llvm::Value *uadd_with_overflow
8038d375cefSBenjamin Kramer         = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
804036f2f6bSJohn McCall 
805036f2f6bSJohn McCall       llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
806036f2f6bSJohn McCall       llvm::Value *result =
80743f9bb73SDavid Blaikie           CGF.Builder.CreateCall(uadd_with_overflow, {size, cookieSizeV});
808036f2f6bSJohn McCall 
809036f2f6bSJohn McCall       llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
810036f2f6bSJohn McCall       if (hasOverflow)
811036f2f6bSJohn McCall         hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
812036f2f6bSJohn McCall       else
813036f2f6bSJohn McCall         hasOverflow = overflowed;
814036f2f6bSJohn McCall 
815036f2f6bSJohn McCall       size = CGF.Builder.CreateExtractValue(result, 0);
816036f2f6bSJohn McCall     }
817036f2f6bSJohn McCall 
818036f2f6bSJohn McCall     // If we had any possibility of dynamic overflow, make a select to
819036f2f6bSJohn McCall     // overwrite 'size' with an all-ones value, which should cause
820036f2f6bSJohn McCall     // operator new to throw.
821036f2f6bSJohn McCall     if (hasOverflow)
822455f42c9SAaron Ballman       size = CGF.Builder.CreateSelect(hasOverflow,
823455f42c9SAaron Ballman                                  llvm::Constant::getAllOnesValue(CGF.SizeTy),
824036f2f6bSJohn McCall                                       size);
825036f2f6bSJohn McCall   }
826036f2f6bSJohn McCall 
827036f2f6bSJohn McCall   if (cookieSize == 0)
828036f2f6bSJohn McCall     sizeWithoutCookie = size;
829036f2f6bSJohn McCall   else
830036f2f6bSJohn McCall     assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
831036f2f6bSJohn McCall 
832036f2f6bSJohn McCall   return size;
83359486a2dSAnders Carlsson }
83459486a2dSAnders Carlsson 
835f862eb6aSSebastian Redl static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
8367f416cc4SJohn McCall                                     QualType AllocType, Address NewPtr) {
8371c96bc5dSRichard Smith   // FIXME: Refactor with EmitExprAsInit.
83847fb9508SJohn McCall   switch (CGF.getEvaluationKind(AllocType)) {
83947fb9508SJohn McCall   case TEK_Scalar:
840a2c1124fSDavid Blaikie     CGF.EmitScalarInit(Init, nullptr,
8417f416cc4SJohn McCall                        CGF.MakeAddrLValue(NewPtr, AllocType), false);
84247fb9508SJohn McCall     return;
84347fb9508SJohn McCall   case TEK_Complex:
8447f416cc4SJohn McCall     CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType),
84547fb9508SJohn McCall                                   /*isInit*/ true);
84647fb9508SJohn McCall     return;
84747fb9508SJohn McCall   case TEK_Aggregate: {
8487a626f63SJohn McCall     AggValueSlot Slot
8497f416cc4SJohn McCall       = AggValueSlot::forAddr(NewPtr, AllocType.getQualifiers(),
8508d6fc958SJohn McCall                               AggValueSlot::IsDestructed,
85146759f4fSJohn McCall                               AggValueSlot::DoesNotNeedGCBarriers,
852615ed1a3SChad Rosier                               AggValueSlot::IsNotAliased);
8537a626f63SJohn McCall     CGF.EmitAggExpr(Init, Slot);
85447fb9508SJohn McCall     return;
8557a626f63SJohn McCall   }
856d5202e09SFariborz Jahanian   }
85747fb9508SJohn McCall   llvm_unreachable("bad evaluation kind");
85847fb9508SJohn McCall }
859d5202e09SFariborz Jahanian 
860fb901c7aSDavid Blaikie void CodeGenFunction::EmitNewArrayInitializer(
861fb901c7aSDavid Blaikie     const CXXNewExpr *E, QualType ElementType, llvm::Type *ElementTy,
8627f416cc4SJohn McCall     Address BeginPtr, llvm::Value *NumElements,
86306a67e2cSRichard Smith     llvm::Value *AllocSizeWithoutCookie) {
86406a67e2cSRichard Smith   // If we have a type with trivial initialization and no initializer,
86506a67e2cSRichard Smith   // there's nothing to do.
8666047f07eSSebastian Redl   if (!E->hasInitializer())
86706a67e2cSRichard Smith     return;
868b66b08efSFariborz Jahanian 
8697f416cc4SJohn McCall   Address CurPtr = BeginPtr;
870d5202e09SFariborz Jahanian 
87106a67e2cSRichard Smith   unsigned InitListElements = 0;
872f862eb6aSSebastian Redl 
873f862eb6aSSebastian Redl   const Expr *Init = E->getInitializer();
8747f416cc4SJohn McCall   Address EndOfInit = Address::invalid();
87506a67e2cSRichard Smith   QualType::DestructionKind DtorKind = ElementType.isDestructedType();
87606a67e2cSRichard Smith   EHScopeStack::stable_iterator Cleanup;
87706a67e2cSRichard Smith   llvm::Instruction *CleanupDominator = nullptr;
8781c96bc5dSRichard Smith 
8797f416cc4SJohn McCall   CharUnits ElementSize = getContext().getTypeSizeInChars(ElementType);
8807f416cc4SJohn McCall   CharUnits ElementAlign =
8817f416cc4SJohn McCall     BeginPtr.getAlignment().alignmentOfArrayElement(ElementSize);
8827f416cc4SJohn McCall 
8830511d23aSRichard Smith   // Attempt to perform zero-initialization using memset.
8840511d23aSRichard Smith   auto TryMemsetInitialization = [&]() -> bool {
8850511d23aSRichard Smith     // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
8860511d23aSRichard Smith     // we can initialize with a memset to -1.
8870511d23aSRichard Smith     if (!CGM.getTypes().isZeroInitializable(ElementType))
8880511d23aSRichard Smith       return false;
8890511d23aSRichard Smith 
8900511d23aSRichard Smith     // Optimization: since zero initialization will just set the memory
8910511d23aSRichard Smith     // to all zeroes, generate a single memset to do it in one shot.
8920511d23aSRichard Smith 
8930511d23aSRichard Smith     // Subtract out the size of any elements we've already initialized.
8940511d23aSRichard Smith     auto *RemainingSize = AllocSizeWithoutCookie;
8950511d23aSRichard Smith     if (InitListElements) {
8960511d23aSRichard Smith       // We know this can't overflow; we check this when doing the allocation.
8970511d23aSRichard Smith       auto *InitializedSize = llvm::ConstantInt::get(
8980511d23aSRichard Smith           RemainingSize->getType(),
8990511d23aSRichard Smith           getContext().getTypeSizeInChars(ElementType).getQuantity() *
9000511d23aSRichard Smith               InitListElements);
9010511d23aSRichard Smith       RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
9020511d23aSRichard Smith     }
9030511d23aSRichard Smith 
9040511d23aSRichard Smith     // Create the memset.
9050511d23aSRichard Smith     Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize, false);
9060511d23aSRichard Smith     return true;
9070511d23aSRichard Smith   };
9080511d23aSRichard Smith 
909f862eb6aSSebastian Redl   // If the initializer is an initializer list, first do the explicit elements.
910f862eb6aSSebastian Redl   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
9110511d23aSRichard Smith     // Initializing from a (braced) string literal is a special case; the init
9120511d23aSRichard Smith     // list element does not initialize a (single) array element.
9130511d23aSRichard Smith     if (ILE->isStringLiteralInit()) {
9140511d23aSRichard Smith       // Initialize the initial portion of length equal to that of the string
9150511d23aSRichard Smith       // literal. The allocation must be for at least this much; we emitted a
9160511d23aSRichard Smith       // check for that earlier.
9170511d23aSRichard Smith       AggValueSlot Slot =
9180511d23aSRichard Smith           AggValueSlot::forAddr(CurPtr, ElementType.getQualifiers(),
9190511d23aSRichard Smith                                 AggValueSlot::IsDestructed,
9200511d23aSRichard Smith                                 AggValueSlot::DoesNotNeedGCBarriers,
9210511d23aSRichard Smith                                 AggValueSlot::IsNotAliased);
9220511d23aSRichard Smith       EmitAggExpr(ILE->getInit(0), Slot);
9230511d23aSRichard Smith 
9240511d23aSRichard Smith       // Move past these elements.
9250511d23aSRichard Smith       InitListElements =
9260511d23aSRichard Smith           cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe())
9270511d23aSRichard Smith               ->getSize().getZExtValue();
9280511d23aSRichard Smith       CurPtr =
9290511d23aSRichard Smith           Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(),
9300511d23aSRichard Smith                                             Builder.getSize(InitListElements),
9310511d23aSRichard Smith                                             "string.init.end"),
9320511d23aSRichard Smith                   CurPtr.getAlignment().alignmentAtOffset(InitListElements *
9330511d23aSRichard Smith                                                           ElementSize));
9340511d23aSRichard Smith 
9350511d23aSRichard Smith       // Zero out the rest, if any remain.
9360511d23aSRichard Smith       llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
9370511d23aSRichard Smith       if (!ConstNum || !ConstNum->equalsInt(InitListElements)) {
9380511d23aSRichard Smith         bool OK = TryMemsetInitialization();
9390511d23aSRichard Smith         (void)OK;
9400511d23aSRichard Smith         assert(OK && "couldn't memset character type?");
9410511d23aSRichard Smith       }
9420511d23aSRichard Smith       return;
9430511d23aSRichard Smith     }
9440511d23aSRichard Smith 
94506a67e2cSRichard Smith     InitListElements = ILE->getNumInits();
946f62290a1SChad Rosier 
9471c96bc5dSRichard Smith     // If this is a multi-dimensional array new, we will initialize multiple
9481c96bc5dSRichard Smith     // elements with each init list element.
9491c96bc5dSRichard Smith     QualType AllocType = E->getAllocatedType();
9501c96bc5dSRichard Smith     if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
9511c96bc5dSRichard Smith             AllocType->getAsArrayTypeUnsafe())) {
952fb901c7aSDavid Blaikie       ElementTy = ConvertTypeForMem(AllocType);
9537f416cc4SJohn McCall       CurPtr = Builder.CreateElementBitCast(CurPtr, ElementTy);
95406a67e2cSRichard Smith       InitListElements *= getContext().getConstantArrayElementCount(CAT);
9551c96bc5dSRichard Smith     }
9561c96bc5dSRichard Smith 
95706a67e2cSRichard Smith     // Enter a partial-destruction Cleanup if necessary.
95806a67e2cSRichard Smith     if (needsEHCleanup(DtorKind)) {
95906a67e2cSRichard Smith       // In principle we could tell the Cleanup where we are more
960f62290a1SChad Rosier       // directly, but the control flow can get so varied here that it
961f62290a1SChad Rosier       // would actually be quite complex.  Therefore we go through an
962f62290a1SChad Rosier       // alloca.
9637f416cc4SJohn McCall       EndOfInit = CreateTempAlloca(BeginPtr.getType(), getPointerAlign(),
9647f416cc4SJohn McCall                                    "array.init.end");
9657f416cc4SJohn McCall       CleanupDominator = Builder.CreateStore(BeginPtr.getPointer(), EndOfInit);
9667f416cc4SJohn McCall       pushIrregularPartialArrayCleanup(BeginPtr.getPointer(), EndOfInit,
9677f416cc4SJohn McCall                                        ElementType, ElementAlign,
96806a67e2cSRichard Smith                                        getDestroyer(DtorKind));
96906a67e2cSRichard Smith       Cleanup = EHStack.stable_begin();
970f62290a1SChad Rosier     }
971f62290a1SChad Rosier 
9727f416cc4SJohn McCall     CharUnits StartAlign = CurPtr.getAlignment();
973f862eb6aSSebastian Redl     for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
974f62290a1SChad Rosier       // Tell the cleanup that it needs to destroy up to this
975f62290a1SChad Rosier       // element.  TODO: some of these stores can be trivially
976f62290a1SChad Rosier       // observed to be unnecessary.
9777f416cc4SJohn McCall       if (EndOfInit.isValid()) {
9787f416cc4SJohn McCall         auto FinishedPtr =
9797f416cc4SJohn McCall           Builder.CreateBitCast(CurPtr.getPointer(), BeginPtr.getType());
9807f416cc4SJohn McCall         Builder.CreateStore(FinishedPtr, EndOfInit);
9817f416cc4SJohn McCall       }
98206a67e2cSRichard Smith       // FIXME: If the last initializer is an incomplete initializer list for
98306a67e2cSRichard Smith       // an array, and we have an array filler, we can fold together the two
98406a67e2cSRichard Smith       // initialization loops.
9851c96bc5dSRichard Smith       StoreAnyExprIntoOneUnit(*this, ILE->getInit(i),
98606a67e2cSRichard Smith                               ILE->getInit(i)->getType(), CurPtr);
9877f416cc4SJohn McCall       CurPtr = Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(),
9887f416cc4SJohn McCall                                                  Builder.getSize(1),
9897f416cc4SJohn McCall                                                  "array.exp.next"),
9907f416cc4SJohn McCall                        StartAlign.alignmentAtOffset((i + 1) * ElementSize));
991f862eb6aSSebastian Redl     }
992f862eb6aSSebastian Redl 
993f862eb6aSSebastian Redl     // The remaining elements are filled with the array filler expression.
994f862eb6aSSebastian Redl     Init = ILE->getArrayFiller();
9951c96bc5dSRichard Smith 
99606a67e2cSRichard Smith     // Extract the initializer for the individual array elements by pulling
99706a67e2cSRichard Smith     // out the array filler from all the nested initializer lists. This avoids
99806a67e2cSRichard Smith     // generating a nested loop for the initialization.
99906a67e2cSRichard Smith     while (Init && Init->getType()->isConstantArrayType()) {
100006a67e2cSRichard Smith       auto *SubILE = dyn_cast<InitListExpr>(Init);
100106a67e2cSRichard Smith       if (!SubILE)
100206a67e2cSRichard Smith         break;
100306a67e2cSRichard Smith       assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
100406a67e2cSRichard Smith       Init = SubILE->getArrayFiller();
1005f862eb6aSSebastian Redl     }
1006f862eb6aSSebastian Redl 
100706a67e2cSRichard Smith     // Switch back to initializing one base element at a time.
10087f416cc4SJohn McCall     CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr.getType());
1009f62290a1SChad Rosier   }
1010e6c980c4SChandler Carruth 
1011454a7cdfSRichard Smith   // If all elements have already been initialized, skip any further
1012454a7cdfSRichard Smith   // initialization.
1013454a7cdfSRichard Smith   llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
1014454a7cdfSRichard Smith   if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
1015454a7cdfSRichard Smith     // If there was a Cleanup, deactivate it.
1016454a7cdfSRichard Smith     if (CleanupDominator)
1017454a7cdfSRichard Smith       DeactivateCleanupBlock(Cleanup, CleanupDominator);
1018454a7cdfSRichard Smith     return;
1019454a7cdfSRichard Smith   }
1020454a7cdfSRichard Smith 
1021454a7cdfSRichard Smith   assert(Init && "have trailing elements to initialize but no initializer");
1022454a7cdfSRichard Smith 
102306a67e2cSRichard Smith   // If this is a constructor call, try to optimize it out, and failing that
102406a67e2cSRichard Smith   // emit a single loop to initialize all remaining elements.
1025454a7cdfSRichard Smith   if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
10266047f07eSSebastian Redl     CXXConstructorDecl *Ctor = CCE->getConstructor();
1027d153103cSDouglas Gregor     if (Ctor->isTrivial()) {
102805fc5be3SDouglas Gregor       // If new expression did not specify value-initialization, then there
102905fc5be3SDouglas Gregor       // is no initialization.
10306047f07eSSebastian Redl       if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
103105fc5be3SDouglas Gregor         return;
103205fc5be3SDouglas Gregor 
103306a67e2cSRichard Smith       if (TryMemsetInitialization())
10343a202f60SAnders Carlsson         return;
10353a202f60SAnders Carlsson     }
103605fc5be3SDouglas Gregor 
103706a67e2cSRichard Smith     // Store the new Cleanup position for irregular Cleanups.
103806a67e2cSRichard Smith     //
103906a67e2cSRichard Smith     // FIXME: Share this cleanup with the constructor call emission rather than
104006a67e2cSRichard Smith     // having it create a cleanup of its own.
10417f416cc4SJohn McCall     if (EndOfInit.isValid())
10427f416cc4SJohn McCall       Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
104306a67e2cSRichard Smith 
104406a67e2cSRichard Smith     // Emit a constructor call loop to initialize the remaining elements.
104506a67e2cSRichard Smith     if (InitListElements)
104606a67e2cSRichard Smith       NumElements = Builder.CreateSub(
104706a67e2cSRichard Smith           NumElements,
104806a67e2cSRichard Smith           llvm::ConstantInt::get(NumElements->getType(), InitListElements));
104970b9c01bSAlexey Samsonov     EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,
105048ddcf2cSEli Friedman                                CCE->requiresZeroInitialization());
105105fc5be3SDouglas Gregor     return;
10526047f07eSSebastian Redl   }
105306a67e2cSRichard Smith 
105406a67e2cSRichard Smith   // If this is value-initialization, we can usually use memset.
105506a67e2cSRichard Smith   ImplicitValueInitExpr IVIE(ElementType);
1056454a7cdfSRichard Smith   if (isa<ImplicitValueInitExpr>(Init)) {
105706a67e2cSRichard Smith     if (TryMemsetInitialization())
105806a67e2cSRichard Smith       return;
105906a67e2cSRichard Smith 
106006a67e2cSRichard Smith     // Switch to an ImplicitValueInitExpr for the element type. This handles
106106a67e2cSRichard Smith     // only one case: multidimensional array new of pointers to members. In
106206a67e2cSRichard Smith     // all other cases, we already have an initializer for the array element.
106306a67e2cSRichard Smith     Init = &IVIE;
106406a67e2cSRichard Smith   }
106506a67e2cSRichard Smith 
106606a67e2cSRichard Smith   // At this point we should have found an initializer for the individual
106706a67e2cSRichard Smith   // elements of the array.
106806a67e2cSRichard Smith   assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&
106906a67e2cSRichard Smith          "got wrong type of element to initialize");
107006a67e2cSRichard Smith 
1071454a7cdfSRichard Smith   // If we have an empty initializer list, we can usually use memset.
1072454a7cdfSRichard Smith   if (auto *ILE = dyn_cast<InitListExpr>(Init))
1073454a7cdfSRichard Smith     if (ILE->getNumInits() == 0 && TryMemsetInitialization())
1074d5202e09SFariborz Jahanian       return;
107559486a2dSAnders Carlsson 
1076cb77930dSYunzhong Gao   // If we have a struct whose every field is value-initialized, we can
1077cb77930dSYunzhong Gao   // usually use memset.
1078cb77930dSYunzhong Gao   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
1079cb77930dSYunzhong Gao     if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
1080cb77930dSYunzhong Gao       if (RType->getDecl()->isStruct()) {
1081872307e2SRichard Smith         unsigned NumElements = 0;
1082872307e2SRichard Smith         if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RType->getDecl()))
1083872307e2SRichard Smith           NumElements = CXXRD->getNumBases();
1084cb77930dSYunzhong Gao         for (auto *Field : RType->getDecl()->fields())
1085cb77930dSYunzhong Gao           if (!Field->isUnnamedBitfield())
1086872307e2SRichard Smith             ++NumElements;
1087872307e2SRichard Smith         // FIXME: Recurse into nested InitListExprs.
1088872307e2SRichard Smith         if (ILE->getNumInits() == NumElements)
1089cb77930dSYunzhong Gao           for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
1090cb77930dSYunzhong Gao             if (!isa<ImplicitValueInitExpr>(ILE->getInit(i)))
1091872307e2SRichard Smith               --NumElements;
1092872307e2SRichard Smith         if (ILE->getNumInits() == NumElements && TryMemsetInitialization())
1093cb77930dSYunzhong Gao           return;
1094cb77930dSYunzhong Gao       }
1095cb77930dSYunzhong Gao     }
1096cb77930dSYunzhong Gao   }
1097cb77930dSYunzhong Gao 
109806a67e2cSRichard Smith   // Create the loop blocks.
109906a67e2cSRichard Smith   llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
110006a67e2cSRichard Smith   llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
110106a67e2cSRichard Smith   llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
110259486a2dSAnders Carlsson 
110306a67e2cSRichard Smith   // Find the end of the array, hoisted out of the loop.
110406a67e2cSRichard Smith   llvm::Value *EndPtr =
11057f416cc4SJohn McCall     Builder.CreateInBoundsGEP(BeginPtr.getPointer(), NumElements, "array.end");
110606a67e2cSRichard Smith 
110706a67e2cSRichard Smith   // If the number of elements isn't constant, we have to now check if there is
110806a67e2cSRichard Smith   // anything left to initialize.
110906a67e2cSRichard Smith   if (!ConstNum) {
11107f416cc4SJohn McCall     llvm::Value *IsEmpty =
11117f416cc4SJohn McCall       Builder.CreateICmpEQ(CurPtr.getPointer(), EndPtr, "array.isempty");
111206a67e2cSRichard Smith     Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
111306a67e2cSRichard Smith   }
111406a67e2cSRichard Smith 
111506a67e2cSRichard Smith   // Enter the loop.
111606a67e2cSRichard Smith   EmitBlock(LoopBB);
111706a67e2cSRichard Smith 
111806a67e2cSRichard Smith   // Set up the current-element phi.
111906a67e2cSRichard Smith   llvm::PHINode *CurPtrPhi =
11207f416cc4SJohn McCall     Builder.CreatePHI(CurPtr.getType(), 2, "array.cur");
11217f416cc4SJohn McCall   CurPtrPhi->addIncoming(CurPtr.getPointer(), EntryBB);
11227f416cc4SJohn McCall 
11237f416cc4SJohn McCall   CurPtr = Address(CurPtrPhi, ElementAlign);
112406a67e2cSRichard Smith 
112506a67e2cSRichard Smith   // Store the new Cleanup position for irregular Cleanups.
11267f416cc4SJohn McCall   if (EndOfInit.isValid())
11277f416cc4SJohn McCall     Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
112806a67e2cSRichard Smith 
112906a67e2cSRichard Smith   // Enter a partial-destruction Cleanup if necessary.
113006a67e2cSRichard Smith   if (!CleanupDominator && needsEHCleanup(DtorKind)) {
11317f416cc4SJohn McCall     pushRegularPartialArrayCleanup(BeginPtr.getPointer(), CurPtr.getPointer(),
11327f416cc4SJohn McCall                                    ElementType, ElementAlign,
113306a67e2cSRichard Smith                                    getDestroyer(DtorKind));
113406a67e2cSRichard Smith     Cleanup = EHStack.stable_begin();
113506a67e2cSRichard Smith     CleanupDominator = Builder.CreateUnreachable();
113606a67e2cSRichard Smith   }
113706a67e2cSRichard Smith 
113806a67e2cSRichard Smith   // Emit the initializer into this element.
113906a67e2cSRichard Smith   StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr);
114006a67e2cSRichard Smith 
114106a67e2cSRichard Smith   // Leave the Cleanup if we entered one.
114206a67e2cSRichard Smith   if (CleanupDominator) {
114306a67e2cSRichard Smith     DeactivateCleanupBlock(Cleanup, CleanupDominator);
114406a67e2cSRichard Smith     CleanupDominator->eraseFromParent();
114506a67e2cSRichard Smith   }
114606a67e2cSRichard Smith 
114706a67e2cSRichard Smith   // Advance to the next element by adjusting the pointer type as necessary.
114806a67e2cSRichard Smith   llvm::Value *NextPtr =
11497f416cc4SJohn McCall     Builder.CreateConstInBoundsGEP1_32(ElementTy, CurPtr.getPointer(), 1,
11507f416cc4SJohn McCall                                        "array.next");
115106a67e2cSRichard Smith 
115206a67e2cSRichard Smith   // Check whether we've gotten to the end of the array and, if so,
115306a67e2cSRichard Smith   // exit the loop.
115406a67e2cSRichard Smith   llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
115506a67e2cSRichard Smith   Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
115606a67e2cSRichard Smith   CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
115706a67e2cSRichard Smith 
115806a67e2cSRichard Smith   EmitBlock(ContBB);
115906a67e2cSRichard Smith }
116006a67e2cSRichard Smith 
116106a67e2cSRichard Smith static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
1162fb901c7aSDavid Blaikie                                QualType ElementType, llvm::Type *ElementTy,
11637f416cc4SJohn McCall                                Address NewPtr, llvm::Value *NumElements,
116406a67e2cSRichard Smith                                llvm::Value *AllocSizeWithoutCookie) {
11659b479666SDavid Blaikie   ApplyDebugLocation DL(CGF, E);
116606a67e2cSRichard Smith   if (E->isArray())
1167fb901c7aSDavid Blaikie     CGF.EmitNewArrayInitializer(E, ElementType, ElementTy, NewPtr, NumElements,
116806a67e2cSRichard Smith                                 AllocSizeWithoutCookie);
116906a67e2cSRichard Smith   else if (const Expr *Init = E->getInitializer())
117066e4197fSDavid Blaikie     StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
117159486a2dSAnders Carlsson }
117259486a2dSAnders Carlsson 
11738d0dc31dSRichard Smith /// Emit a call to an operator new or operator delete function, as implicitly
11748d0dc31dSRichard Smith /// created by new-expressions and delete-expressions.
11758d0dc31dSRichard Smith static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
11768d0dc31dSRichard Smith                                 const FunctionDecl *Callee,
11778d0dc31dSRichard Smith                                 const FunctionProtoType *CalleeType,
11788d0dc31dSRichard Smith                                 const CallArgList &Args) {
11798d0dc31dSRichard Smith   llvm::Instruction *CallOrInvoke;
11801235a8daSRichard Smith   llvm::Value *CalleeAddr = CGF.CGM.GetAddrOfFunction(Callee);
11818d0dc31dSRichard Smith   RValue RV =
1182f770683fSPeter Collingbourne       CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(
1183f770683fSPeter Collingbourne                        Args, CalleeType, /*chainCall=*/false),
1184f770683fSPeter Collingbourne                    CalleeAddr, ReturnValueSlot(), Args, Callee, &CallOrInvoke);
11858d0dc31dSRichard Smith 
11868d0dc31dSRichard Smith   /// C++1y [expr.new]p10:
11878d0dc31dSRichard Smith   ///   [In a new-expression,] an implementation is allowed to omit a call
11888d0dc31dSRichard Smith   ///   to a replaceable global allocation function.
11898d0dc31dSRichard Smith   ///
11908d0dc31dSRichard Smith   /// We model such elidable calls with the 'builtin' attribute.
11916956d587SRafael Espindola   llvm::Function *Fn = dyn_cast<llvm::Function>(CalleeAddr);
11921235a8daSRichard Smith   if (Callee->isReplaceableGlobalAllocationFunction() &&
11936956d587SRafael Espindola       Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
11948d0dc31dSRichard Smith     // FIXME: Add addAttribute to CallSite.
11958d0dc31dSRichard Smith     if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(CallOrInvoke))
11968d0dc31dSRichard Smith       CI->addAttribute(llvm::AttributeSet::FunctionIndex,
11978d0dc31dSRichard Smith                        llvm::Attribute::Builtin);
11988d0dc31dSRichard Smith     else if (llvm::InvokeInst *II = dyn_cast<llvm::InvokeInst>(CallOrInvoke))
11998d0dc31dSRichard Smith       II->addAttribute(llvm::AttributeSet::FunctionIndex,
12008d0dc31dSRichard Smith                        llvm::Attribute::Builtin);
12018d0dc31dSRichard Smith     else
12028d0dc31dSRichard Smith       llvm_unreachable("unexpected kind of call instruction");
12038d0dc31dSRichard Smith   }
12048d0dc31dSRichard Smith 
12058d0dc31dSRichard Smith   return RV;
12068d0dc31dSRichard Smith }
12078d0dc31dSRichard Smith 
1208760520bcSRichard Smith RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
1209760520bcSRichard Smith                                                  const Expr *Arg,
1210760520bcSRichard Smith                                                  bool IsDelete) {
1211760520bcSRichard Smith   CallArgList Args;
1212760520bcSRichard Smith   const Stmt *ArgS = Arg;
1213f05779e2SDavid Blaikie   EmitCallArgs(Args, *Type->param_type_begin(), llvm::makeArrayRef(ArgS));
1214760520bcSRichard Smith   // Find the allocation or deallocation function that we're calling.
1215760520bcSRichard Smith   ASTContext &Ctx = getContext();
1216760520bcSRichard Smith   DeclarationName Name = Ctx.DeclarationNames
1217760520bcSRichard Smith       .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
1218760520bcSRichard Smith   for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
1219599bed75SRichard Smith     if (auto *FD = dyn_cast<FunctionDecl>(Decl))
1220599bed75SRichard Smith       if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
1221760520bcSRichard Smith         return EmitNewDeleteCall(*this, cast<FunctionDecl>(Decl), Type, Args);
1222760520bcSRichard Smith   llvm_unreachable("predeclared global operator new/delete is missing");
1223760520bcSRichard Smith }
1224760520bcSRichard Smith 
1225b2f0f057SRichard Smith static std::pair<bool, bool>
1226b2f0f057SRichard Smith shouldPassSizeAndAlignToUsualDelete(const FunctionProtoType *FPT) {
1227b2f0f057SRichard Smith   auto AI = FPT->param_type_begin(), AE = FPT->param_type_end();
1228e9abe648SDaniel Jasper 
1229b2f0f057SRichard Smith   // The first argument is always a void*.
1230b2f0f057SRichard Smith   ++AI;
1231b2f0f057SRichard Smith 
1232b2f0f057SRichard Smith   // Figure out what other parameters we should be implicitly passing.
1233b2f0f057SRichard Smith   bool PassSize = false;
1234b2f0f057SRichard Smith   bool PassAlignment = false;
1235b2f0f057SRichard Smith 
1236b2f0f057SRichard Smith   if (AI != AE && (*AI)->isIntegerType()) {
1237b2f0f057SRichard Smith     PassSize = true;
1238b2f0f057SRichard Smith     ++AI;
1239b2f0f057SRichard Smith   }
1240b2f0f057SRichard Smith 
1241b2f0f057SRichard Smith   if (AI != AE && (*AI)->isAlignValT()) {
1242b2f0f057SRichard Smith     PassAlignment = true;
1243b2f0f057SRichard Smith     ++AI;
1244b2f0f057SRichard Smith   }
1245b2f0f057SRichard Smith 
1246b2f0f057SRichard Smith   assert(AI == AE && "unexpected usual deallocation function parameter");
1247b2f0f057SRichard Smith   return {PassSize, PassAlignment};
1248b2f0f057SRichard Smith }
1249b2f0f057SRichard Smith 
1250b2f0f057SRichard Smith namespace {
1251b2f0f057SRichard Smith   /// A cleanup to call the given 'operator delete' function upon abnormal
1252b2f0f057SRichard Smith   /// exit from a new expression. Templated on a traits type that deals with
1253b2f0f057SRichard Smith   /// ensuring that the arguments dominate the cleanup if necessary.
1254b2f0f057SRichard Smith   template<typename Traits>
1255b2f0f057SRichard Smith   class CallDeleteDuringNew final : public EHScopeStack::Cleanup {
1256b2f0f057SRichard Smith     /// Type used to hold llvm::Value*s.
1257b2f0f057SRichard Smith     typedef typename Traits::ValueTy ValueTy;
1258b2f0f057SRichard Smith     /// Type used to hold RValues.
1259b2f0f057SRichard Smith     typedef typename Traits::RValueTy RValueTy;
1260b2f0f057SRichard Smith     struct PlacementArg {
1261b2f0f057SRichard Smith       RValueTy ArgValue;
1262b2f0f057SRichard Smith       QualType ArgType;
1263b2f0f057SRichard Smith     };
1264b2f0f057SRichard Smith 
1265b2f0f057SRichard Smith     unsigned NumPlacementArgs : 31;
1266b2f0f057SRichard Smith     unsigned PassAlignmentToPlacementDelete : 1;
1267b2f0f057SRichard Smith     const FunctionDecl *OperatorDelete;
1268b2f0f057SRichard Smith     ValueTy Ptr;
1269b2f0f057SRichard Smith     ValueTy AllocSize;
1270b2f0f057SRichard Smith     CharUnits AllocAlign;
1271b2f0f057SRichard Smith 
1272b2f0f057SRichard Smith     PlacementArg *getPlacementArgs() {
1273b2f0f057SRichard Smith       return reinterpret_cast<PlacementArg *>(this + 1);
1274b2f0f057SRichard Smith     }
1275e9abe648SDaniel Jasper 
1276e9abe648SDaniel Jasper   public:
1277e9abe648SDaniel Jasper     static size_t getExtraSize(size_t NumPlacementArgs) {
1278b2f0f057SRichard Smith       return NumPlacementArgs * sizeof(PlacementArg);
1279e9abe648SDaniel Jasper     }
1280e9abe648SDaniel Jasper 
1281e9abe648SDaniel Jasper     CallDeleteDuringNew(size_t NumPlacementArgs,
1282b2f0f057SRichard Smith                         const FunctionDecl *OperatorDelete, ValueTy Ptr,
1283b2f0f057SRichard Smith                         ValueTy AllocSize, bool PassAlignmentToPlacementDelete,
1284b2f0f057SRichard Smith                         CharUnits AllocAlign)
1285b2f0f057SRichard Smith       : NumPlacementArgs(NumPlacementArgs),
1286b2f0f057SRichard Smith         PassAlignmentToPlacementDelete(PassAlignmentToPlacementDelete),
1287b2f0f057SRichard Smith         OperatorDelete(OperatorDelete), Ptr(Ptr), AllocSize(AllocSize),
1288b2f0f057SRichard Smith         AllocAlign(AllocAlign) {}
1289e9abe648SDaniel Jasper 
1290b2f0f057SRichard Smith     void setPlacementArg(unsigned I, RValueTy Arg, QualType Type) {
1291e9abe648SDaniel Jasper       assert(I < NumPlacementArgs && "index out of range");
1292b2f0f057SRichard Smith       getPlacementArgs()[I] = {Arg, Type};
1293e9abe648SDaniel Jasper     }
1294e9abe648SDaniel Jasper 
1295e9abe648SDaniel Jasper     void Emit(CodeGenFunction &CGF, Flags flags) override {
1296b2f0f057SRichard Smith       const FunctionProtoType *FPT =
1297b2f0f057SRichard Smith           OperatorDelete->getType()->getAs<FunctionProtoType>();
1298e9abe648SDaniel Jasper       CallArgList DeleteArgs;
1299824c2f53SJohn McCall 
1300189e52fcSRichard Smith       // The first argument is always a void*.
1301b2f0f057SRichard Smith       DeleteArgs.add(Traits::get(CGF, Ptr), FPT->getParamType(0));
1302189e52fcSRichard Smith 
1303b2f0f057SRichard Smith       // Figure out what other parameters we should be implicitly passing.
1304b2f0f057SRichard Smith       bool PassSize = false;
1305b2f0f057SRichard Smith       bool PassAlignment = false;
1306b2f0f057SRichard Smith       if (NumPlacementArgs) {
1307b2f0f057SRichard Smith         // A placement deallocation function is implicitly passed an alignment
1308b2f0f057SRichard Smith         // if the placement allocation function was, but is never passed a size.
1309b2f0f057SRichard Smith         PassAlignment = PassAlignmentToPlacementDelete;
1310b2f0f057SRichard Smith       } else {
1311b2f0f057SRichard Smith         // For a non-placement new-expression, 'operator delete' can take a
1312b2f0f057SRichard Smith         // size and/or an alignment if it has the right parameters.
1313b2f0f057SRichard Smith         std::tie(PassSize, PassAlignment) =
1314b2f0f057SRichard Smith             shouldPassSizeAndAlignToUsualDelete(FPT);
1315189e52fcSRichard Smith       }
1316824c2f53SJohn McCall 
1317b2f0f057SRichard Smith       // The second argument can be a std::size_t (for non-placement delete).
1318b2f0f057SRichard Smith       if (PassSize)
1319b2f0f057SRichard Smith         DeleteArgs.add(Traits::get(CGF, AllocSize),
1320b2f0f057SRichard Smith                        CGF.getContext().getSizeType());
1321824c2f53SJohn McCall 
1322b2f0f057SRichard Smith       // The next (second or third) argument can be a std::align_val_t, which
1323b2f0f057SRichard Smith       // is an enum whose underlying type is std::size_t.
1324b2f0f057SRichard Smith       // FIXME: Use the right type as the parameter type. Note that in a call
1325b2f0f057SRichard Smith       // to operator delete(size_t, ...), we may not have it available.
1326b2f0f057SRichard Smith       if (PassAlignment)
1327b2f0f057SRichard Smith         DeleteArgs.add(RValue::get(llvm::ConstantInt::get(
1328b2f0f057SRichard Smith                            CGF.SizeTy, AllocAlign.getQuantity())),
1329b2f0f057SRichard Smith                        CGF.getContext().getSizeType());
13307f9c92a9SJohn McCall 
13317f9c92a9SJohn McCall       // Pass the rest of the arguments, which must match exactly.
13327f9c92a9SJohn McCall       for (unsigned I = 0; I != NumPlacementArgs; ++I) {
1333b2f0f057SRichard Smith         auto Arg = getPlacementArgs()[I];
1334b2f0f057SRichard Smith         DeleteArgs.add(Traits::get(CGF, Arg.ArgValue), Arg.ArgType);
13357f9c92a9SJohn McCall       }
13367f9c92a9SJohn McCall 
13377f9c92a9SJohn McCall       // Call 'operator delete'.
13388d0dc31dSRichard Smith       EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
13397f9c92a9SJohn McCall     }
13407f9c92a9SJohn McCall   };
1341ab9db510SAlexander Kornienko }
13427f9c92a9SJohn McCall 
13437f9c92a9SJohn McCall /// Enter a cleanup to call 'operator delete' if the initializer in a
13447f9c92a9SJohn McCall /// new-expression throws.
13457f9c92a9SJohn McCall static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
13467f9c92a9SJohn McCall                                   const CXXNewExpr *E,
13477f416cc4SJohn McCall                                   Address NewPtr,
13487f9c92a9SJohn McCall                                   llvm::Value *AllocSize,
1349b2f0f057SRichard Smith                                   CharUnits AllocAlign,
13507f9c92a9SJohn McCall                                   const CallArgList &NewArgs) {
1351b2f0f057SRichard Smith   unsigned NumNonPlacementArgs = E->passAlignment() ? 2 : 1;
1352b2f0f057SRichard Smith 
13537f9c92a9SJohn McCall   // If we're not inside a conditional branch, then the cleanup will
13547f9c92a9SJohn McCall   // dominate and we can do the easier (and more efficient) thing.
13557f9c92a9SJohn McCall   if (!CGF.isInConditionalBranch()) {
1356b2f0f057SRichard Smith     struct DirectCleanupTraits {
1357b2f0f057SRichard Smith       typedef llvm::Value *ValueTy;
1358b2f0f057SRichard Smith       typedef RValue RValueTy;
1359b2f0f057SRichard Smith       static RValue get(CodeGenFunction &, ValueTy V) { return RValue::get(V); }
1360b2f0f057SRichard Smith       static RValue get(CodeGenFunction &, RValueTy V) { return V; }
1361b2f0f057SRichard Smith     };
1362b2f0f057SRichard Smith 
1363b2f0f057SRichard Smith     typedef CallDeleteDuringNew<DirectCleanupTraits> DirectCleanup;
1364b2f0f057SRichard Smith 
1365b2f0f057SRichard Smith     DirectCleanup *Cleanup = CGF.EHStack
1366b2f0f057SRichard Smith       .pushCleanupWithExtra<DirectCleanup>(EHCleanup,
13677f9c92a9SJohn McCall                                            E->getNumPlacementArgs(),
13687f9c92a9SJohn McCall                                            E->getOperatorDelete(),
13697f416cc4SJohn McCall                                            NewPtr.getPointer(),
1370b2f0f057SRichard Smith                                            AllocSize,
1371b2f0f057SRichard Smith                                            E->passAlignment(),
1372b2f0f057SRichard Smith                                            AllocAlign);
1373b2f0f057SRichard Smith     for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
1374b2f0f057SRichard Smith       auto &Arg = NewArgs[I + NumNonPlacementArgs];
1375b2f0f057SRichard Smith       Cleanup->setPlacementArg(I, Arg.RV, Arg.Ty);
1376b2f0f057SRichard Smith     }
13777f9c92a9SJohn McCall 
13787f9c92a9SJohn McCall     return;
13797f9c92a9SJohn McCall   }
13807f9c92a9SJohn McCall 
13817f9c92a9SJohn McCall   // Otherwise, we need to save all this stuff.
1382cb5f77f0SJohn McCall   DominatingValue<RValue>::saved_type SavedNewPtr =
13837f416cc4SJohn McCall     DominatingValue<RValue>::save(CGF, RValue::get(NewPtr.getPointer()));
1384cb5f77f0SJohn McCall   DominatingValue<RValue>::saved_type SavedAllocSize =
1385cb5f77f0SJohn McCall     DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
13867f9c92a9SJohn McCall 
1387b2f0f057SRichard Smith   struct ConditionalCleanupTraits {
1388b2f0f057SRichard Smith     typedef DominatingValue<RValue>::saved_type ValueTy;
1389b2f0f057SRichard Smith     typedef DominatingValue<RValue>::saved_type RValueTy;
1390b2f0f057SRichard Smith     static RValue get(CodeGenFunction &CGF, ValueTy V) {
1391b2f0f057SRichard Smith       return V.restore(CGF);
1392b2f0f057SRichard Smith     }
1393b2f0f057SRichard Smith   };
1394b2f0f057SRichard Smith   typedef CallDeleteDuringNew<ConditionalCleanupTraits> ConditionalCleanup;
1395b2f0f057SRichard Smith 
1396b2f0f057SRichard Smith   ConditionalCleanup *Cleanup = CGF.EHStack
1397b2f0f057SRichard Smith     .pushCleanupWithExtra<ConditionalCleanup>(EHCleanup,
13987f9c92a9SJohn McCall                                               E->getNumPlacementArgs(),
13997f9c92a9SJohn McCall                                               E->getOperatorDelete(),
14007f9c92a9SJohn McCall                                               SavedNewPtr,
1401b2f0f057SRichard Smith                                               SavedAllocSize,
1402b2f0f057SRichard Smith                                               E->passAlignment(),
1403b2f0f057SRichard Smith                                               AllocAlign);
1404b2f0f057SRichard Smith   for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
1405b2f0f057SRichard Smith     auto &Arg = NewArgs[I + NumNonPlacementArgs];
1406b2f0f057SRichard Smith     Cleanup->setPlacementArg(I, DominatingValue<RValue>::save(CGF, Arg.RV),
1407b2f0f057SRichard Smith                              Arg.Ty);
1408b2f0f057SRichard Smith   }
14097f9c92a9SJohn McCall 
1410f4beacd0SJohn McCall   CGF.initFullExprCleanup();
1411824c2f53SJohn McCall }
1412824c2f53SJohn McCall 
141359486a2dSAnders Carlsson llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
141475f9498aSJohn McCall   // The element type being allocated.
141575f9498aSJohn McCall   QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
14168ed55a54SJohn McCall 
141775f9498aSJohn McCall   // 1. Build a call to the allocation function.
141875f9498aSJohn McCall   FunctionDecl *allocator = E->getOperatorNew();
141959486a2dSAnders Carlsson 
1420f862eb6aSSebastian Redl   // If there is a brace-initializer, cannot allocate fewer elements than inits.
1421f862eb6aSSebastian Redl   unsigned minElements = 0;
1422f862eb6aSSebastian Redl   if (E->isArray() && E->hasInitializer()) {
14230511d23aSRichard Smith     const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer());
14240511d23aSRichard Smith     if (ILE && ILE->isStringLiteralInit())
14250511d23aSRichard Smith       minElements =
14260511d23aSRichard Smith           cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe())
14270511d23aSRichard Smith               ->getSize().getZExtValue();
14280511d23aSRichard Smith     else if (ILE)
1429f862eb6aSSebastian Redl       minElements = ILE->getNumInits();
1430f862eb6aSSebastian Redl   }
1431f862eb6aSSebastian Redl 
14328a13c418SCraig Topper   llvm::Value *numElements = nullptr;
14338a13c418SCraig Topper   llvm::Value *allocSizeWithoutCookie = nullptr;
143475f9498aSJohn McCall   llvm::Value *allocSize =
1435f862eb6aSSebastian Redl     EmitCXXNewAllocSize(*this, E, minElements, numElements,
1436f862eb6aSSebastian Redl                         allocSizeWithoutCookie);
1437b2f0f057SRichard Smith   CharUnits allocAlign = getContext().getTypeAlignInChars(allocType);
143859486a2dSAnders Carlsson 
14397f416cc4SJohn McCall   // Emit the allocation call.  If the allocator is a global placement
14407f416cc4SJohn McCall   // operator, just "inline" it directly.
14417f416cc4SJohn McCall   Address allocation = Address::invalid();
14427f416cc4SJohn McCall   CallArgList allocatorArgs;
14437f416cc4SJohn McCall   if (allocator->isReservedGlobalPlacementOperator()) {
144453dcf94dSJohn McCall     assert(E->getNumPlacementArgs() == 1);
144553dcf94dSJohn McCall     const Expr *arg = *E->placement_arguments().begin();
144653dcf94dSJohn McCall 
14477f416cc4SJohn McCall     AlignmentSource alignSource;
144853dcf94dSJohn McCall     allocation = EmitPointerWithAlignment(arg, &alignSource);
14497f416cc4SJohn McCall 
14507f416cc4SJohn McCall     // The pointer expression will, in many cases, be an opaque void*.
14517f416cc4SJohn McCall     // In these cases, discard the computed alignment and use the
14527f416cc4SJohn McCall     // formal alignment of the allocated type.
1453b2f0f057SRichard Smith     if (alignSource != AlignmentSource::Decl)
1454b2f0f057SRichard Smith       allocation = Address(allocation.getPointer(), allocAlign);
14557f416cc4SJohn McCall 
145653dcf94dSJohn McCall     // Set up allocatorArgs for the call to operator delete if it's not
145753dcf94dSJohn McCall     // the reserved global operator.
145853dcf94dSJohn McCall     if (E->getOperatorDelete() &&
145953dcf94dSJohn McCall         !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
146053dcf94dSJohn McCall       allocatorArgs.add(RValue::get(allocSize), getContext().getSizeType());
146153dcf94dSJohn McCall       allocatorArgs.add(RValue::get(allocation.getPointer()), arg->getType());
146253dcf94dSJohn McCall     }
146353dcf94dSJohn McCall 
14647f416cc4SJohn McCall   } else {
14657f416cc4SJohn McCall     const FunctionProtoType *allocatorType =
14667f416cc4SJohn McCall       allocator->getType()->castAs<FunctionProtoType>();
1467b2f0f057SRichard Smith     unsigned ParamsToSkip = 0;
14687f416cc4SJohn McCall 
14697f416cc4SJohn McCall     // The allocation size is the first argument.
14707f416cc4SJohn McCall     QualType sizeType = getContext().getSizeType();
147143dca6a8SEli Friedman     allocatorArgs.add(RValue::get(allocSize), sizeType);
1472b2f0f057SRichard Smith     ++ParamsToSkip;
147359486a2dSAnders Carlsson 
1474b2f0f057SRichard Smith     if (allocSize != allocSizeWithoutCookie) {
1475b2f0f057SRichard Smith       CharUnits cookieAlign = getSizeAlign(); // FIXME: Ask the ABI.
1476b2f0f057SRichard Smith       allocAlign = std::max(allocAlign, cookieAlign);
1477b2f0f057SRichard Smith     }
1478b2f0f057SRichard Smith 
1479b2f0f057SRichard Smith     // The allocation alignment may be passed as the second argument.
1480b2f0f057SRichard Smith     if (E->passAlignment()) {
1481b2f0f057SRichard Smith       QualType AlignValT = sizeType;
1482b2f0f057SRichard Smith       if (allocatorType->getNumParams() > 1) {
1483b2f0f057SRichard Smith         AlignValT = allocatorType->getParamType(1);
1484b2f0f057SRichard Smith         assert(getContext().hasSameUnqualifiedType(
1485b2f0f057SRichard Smith                    AlignValT->castAs<EnumType>()->getDecl()->getIntegerType(),
1486b2f0f057SRichard Smith                    sizeType) &&
1487b2f0f057SRichard Smith                "wrong type for alignment parameter");
1488b2f0f057SRichard Smith         ++ParamsToSkip;
1489b2f0f057SRichard Smith       } else {
1490b2f0f057SRichard Smith         // Corner case, passing alignment to 'operator new(size_t, ...)'.
1491b2f0f057SRichard Smith         assert(allocator->isVariadic() && "can't pass alignment to allocator");
1492b2f0f057SRichard Smith       }
1493b2f0f057SRichard Smith       allocatorArgs.add(
1494b2f0f057SRichard Smith           RValue::get(llvm::ConstantInt::get(SizeTy, allocAlign.getQuantity())),
1495b2f0f057SRichard Smith           AlignValT);
1496b2f0f057SRichard Smith     }
1497b2f0f057SRichard Smith 
1498b2f0f057SRichard Smith     // FIXME: Why do we not pass a CalleeDecl here?
1499f05779e2SDavid Blaikie     EmitCallArgs(allocatorArgs, allocatorType, E->placement_arguments(),
1500b2f0f057SRichard Smith                  /*CalleeDecl*/nullptr, /*ParamsToSkip*/ParamsToSkip);
150159486a2dSAnders Carlsson 
15027f416cc4SJohn McCall     RValue RV =
15037f416cc4SJohn McCall       EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
15047f416cc4SJohn McCall 
1505b2f0f057SRichard Smith     // If this was a call to a global replaceable allocation function that does
1506b2f0f057SRichard Smith     // not take an alignment argument, the allocator is known to produce
1507b2f0f057SRichard Smith     // storage that's suitably aligned for any object that fits, up to a known
1508b2f0f057SRichard Smith     // threshold. Otherwise assume it's suitably aligned for the allocated type.
1509b2f0f057SRichard Smith     CharUnits allocationAlign = allocAlign;
1510b2f0f057SRichard Smith     if (!E->passAlignment() &&
1511b2f0f057SRichard Smith         allocator->isReplaceableGlobalAllocationFunction()) {
1512b2f0f057SRichard Smith       unsigned AllocatorAlign = llvm::PowerOf2Floor(std::min<uint64_t>(
1513b2f0f057SRichard Smith           Target.getNewAlign(), getContext().getTypeSize(allocType)));
1514b2f0f057SRichard Smith       allocationAlign = std::max(
1515b2f0f057SRichard Smith           allocationAlign, getContext().toCharUnitsFromBits(AllocatorAlign));
15167f416cc4SJohn McCall     }
15177f416cc4SJohn McCall 
15187f416cc4SJohn McCall     allocation = Address(RV.getScalarVal(), allocationAlign);
15197ec4b434SJohn McCall   }
152059486a2dSAnders Carlsson 
152175f9498aSJohn McCall   // Emit a null check on the allocation result if the allocation
152275f9498aSJohn McCall   // function is allowed to return null (because it has a non-throwing
1523902a0238SRichard Smith   // exception spec or is the reserved placement new) and we have an
152475f9498aSJohn McCall   // interesting initializer.
1525902a0238SRichard Smith   bool nullCheck = E->shouldNullCheckAllocation(getContext()) &&
15266047f07eSSebastian Redl     (!allocType.isPODType(getContext()) || E->hasInitializer());
152759486a2dSAnders Carlsson 
15288a13c418SCraig Topper   llvm::BasicBlock *nullCheckBB = nullptr;
15298a13c418SCraig Topper   llvm::BasicBlock *contBB = nullptr;
153059486a2dSAnders Carlsson 
1531f7dcf320SJohn McCall   // The null-check means that the initializer is conditionally
1532f7dcf320SJohn McCall   // evaluated.
1533f7dcf320SJohn McCall   ConditionalEvaluation conditional(*this);
1534f7dcf320SJohn McCall 
153575f9498aSJohn McCall   if (nullCheck) {
1536f7dcf320SJohn McCall     conditional.begin(*this);
153775f9498aSJohn McCall 
153875f9498aSJohn McCall     nullCheckBB = Builder.GetInsertBlock();
153975f9498aSJohn McCall     llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
154075f9498aSJohn McCall     contBB = createBasicBlock("new.cont");
154175f9498aSJohn McCall 
15427f416cc4SJohn McCall     llvm::Value *isNull =
15437f416cc4SJohn McCall       Builder.CreateIsNull(allocation.getPointer(), "new.isnull");
154475f9498aSJohn McCall     Builder.CreateCondBr(isNull, contBB, notNullBB);
154575f9498aSJohn McCall     EmitBlock(notNullBB);
154659486a2dSAnders Carlsson   }
154759486a2dSAnders Carlsson 
1548824c2f53SJohn McCall   // If there's an operator delete, enter a cleanup to call it if an
1549824c2f53SJohn McCall   // exception is thrown.
155075f9498aSJohn McCall   EHScopeStack::stable_iterator operatorDeleteCleanup;
15518a13c418SCraig Topper   llvm::Instruction *cleanupDominator = nullptr;
15527ec4b434SJohn McCall   if (E->getOperatorDelete() &&
15537ec4b434SJohn McCall       !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
1554b2f0f057SRichard Smith     EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocAlign,
1555b2f0f057SRichard Smith                           allocatorArgs);
155675f9498aSJohn McCall     operatorDeleteCleanup = EHStack.stable_begin();
1557f4beacd0SJohn McCall     cleanupDominator = Builder.CreateUnreachable();
1558824c2f53SJohn McCall   }
1559824c2f53SJohn McCall 
1560cf9b1f65SEli Friedman   assert((allocSize == allocSizeWithoutCookie) ==
1561cf9b1f65SEli Friedman          CalculateCookiePadding(*this, E).isZero());
1562cf9b1f65SEli Friedman   if (allocSize != allocSizeWithoutCookie) {
1563cf9b1f65SEli Friedman     assert(E->isArray());
1564cf9b1f65SEli Friedman     allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1565cf9b1f65SEli Friedman                                                        numElements,
1566cf9b1f65SEli Friedman                                                        E, allocType);
1567cf9b1f65SEli Friedman   }
1568cf9b1f65SEli Friedman 
1569fb901c7aSDavid Blaikie   llvm::Type *elementTy = ConvertTypeForMem(allocType);
15707f416cc4SJohn McCall   Address result = Builder.CreateElementBitCast(allocation, elementTy);
1571824c2f53SJohn McCall 
1572338c9d0aSPiotr Padlewski   // Passing pointer through invariant.group.barrier to avoid propagation of
1573338c9d0aSPiotr Padlewski   // vptrs information which may be included in previous type.
1574338c9d0aSPiotr Padlewski   if (CGM.getCodeGenOpts().StrictVTablePointers &&
1575338c9d0aSPiotr Padlewski       CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1576338c9d0aSPiotr Padlewski       allocator->isReservedGlobalPlacementOperator())
1577338c9d0aSPiotr Padlewski     result = Address(Builder.CreateInvariantGroupBarrier(result.getPointer()),
1578338c9d0aSPiotr Padlewski                      result.getAlignment());
1579338c9d0aSPiotr Padlewski 
1580fb901c7aSDavid Blaikie   EmitNewInitializer(*this, E, allocType, elementTy, result, numElements,
158199210dc9SJohn McCall                      allocSizeWithoutCookie);
15828ed55a54SJohn McCall   if (E->isArray()) {
15838ed55a54SJohn McCall     // NewPtr is a pointer to the base element type.  If we're
15848ed55a54SJohn McCall     // allocating an array of arrays, we'll need to cast back to the
15858ed55a54SJohn McCall     // array pointer type.
15862192fe50SChris Lattner     llvm::Type *resultType = ConvertTypeForMem(E->getType());
15877f416cc4SJohn McCall     if (result.getType() != resultType)
158875f9498aSJohn McCall       result = Builder.CreateBitCast(result, resultType);
158947b4629bSFariborz Jahanian   }
159059486a2dSAnders Carlsson 
1591824c2f53SJohn McCall   // Deactivate the 'operator delete' cleanup if we finished
1592824c2f53SJohn McCall   // initialization.
1593f4beacd0SJohn McCall   if (operatorDeleteCleanup.isValid()) {
1594f4beacd0SJohn McCall     DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1595f4beacd0SJohn McCall     cleanupDominator->eraseFromParent();
1596f4beacd0SJohn McCall   }
1597824c2f53SJohn McCall 
15987f416cc4SJohn McCall   llvm::Value *resultPtr = result.getPointer();
159975f9498aSJohn McCall   if (nullCheck) {
1600f7dcf320SJohn McCall     conditional.end(*this);
1601f7dcf320SJohn McCall 
160275f9498aSJohn McCall     llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
160375f9498aSJohn McCall     EmitBlock(contBB);
160459486a2dSAnders Carlsson 
16057f416cc4SJohn McCall     llvm::PHINode *PHI = Builder.CreatePHI(resultPtr->getType(), 2);
16067f416cc4SJohn McCall     PHI->addIncoming(resultPtr, notNullBB);
16077f416cc4SJohn McCall     PHI->addIncoming(llvm::Constant::getNullValue(resultPtr->getType()),
160875f9498aSJohn McCall                      nullCheckBB);
160959486a2dSAnders Carlsson 
16107f416cc4SJohn McCall     resultPtr = PHI;
161159486a2dSAnders Carlsson   }
161259486a2dSAnders Carlsson 
16137f416cc4SJohn McCall   return resultPtr;
161459486a2dSAnders Carlsson }
161559486a2dSAnders Carlsson 
161659486a2dSAnders Carlsson void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1617b2f0f057SRichard Smith                                      llvm::Value *Ptr, QualType DeleteTy,
1618b2f0f057SRichard Smith                                      llvm::Value *NumElements,
1619b2f0f057SRichard Smith                                      CharUnits CookieSize) {
1620b2f0f057SRichard Smith   assert((!NumElements && CookieSize.isZero()) ||
1621b2f0f057SRichard Smith          DeleteFD->getOverloadedOperator() == OO_Array_Delete);
16228ed55a54SJohn McCall 
162359486a2dSAnders Carlsson   const FunctionProtoType *DeleteFTy =
162459486a2dSAnders Carlsson     DeleteFD->getType()->getAs<FunctionProtoType>();
162559486a2dSAnders Carlsson 
162659486a2dSAnders Carlsson   CallArgList DeleteArgs;
162759486a2dSAnders Carlsson 
1628b2f0f057SRichard Smith   std::pair<bool, bool> PassSizeAndAlign =
1629b2f0f057SRichard Smith       shouldPassSizeAndAlignToUsualDelete(DeleteFTy);
163021122cf6SAnders Carlsson 
1631b2f0f057SRichard Smith   auto ParamTypeIt = DeleteFTy->param_type_begin();
1632b2f0f057SRichard Smith 
1633b2f0f057SRichard Smith   // Pass the pointer itself.
1634b2f0f057SRichard Smith   QualType ArgTy = *ParamTypeIt++;
163559486a2dSAnders Carlsson   llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
163643dca6a8SEli Friedman   DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
163759486a2dSAnders Carlsson 
1638b2f0f057SRichard Smith   // Pass the size if the delete function has a size_t parameter.
1639b2f0f057SRichard Smith   if (PassSizeAndAlign.first) {
1640b2f0f057SRichard Smith     QualType SizeType = *ParamTypeIt++;
1641b2f0f057SRichard Smith     CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1642b2f0f057SRichard Smith     llvm::Value *Size = llvm::ConstantInt::get(ConvertType(SizeType),
1643b2f0f057SRichard Smith                                                DeleteTypeSize.getQuantity());
1644b2f0f057SRichard Smith 
1645b2f0f057SRichard Smith     // For array new, multiply by the number of elements.
1646b2f0f057SRichard Smith     if (NumElements)
1647b2f0f057SRichard Smith       Size = Builder.CreateMul(Size, NumElements);
1648b2f0f057SRichard Smith 
1649b2f0f057SRichard Smith     // If there is a cookie, add the cookie size.
1650b2f0f057SRichard Smith     if (!CookieSize.isZero())
1651b2f0f057SRichard Smith       Size = Builder.CreateAdd(
1652b2f0f057SRichard Smith           Size, llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity()));
1653b2f0f057SRichard Smith 
1654b2f0f057SRichard Smith     DeleteArgs.add(RValue::get(Size), SizeType);
1655b2f0f057SRichard Smith   }
1656b2f0f057SRichard Smith 
1657b2f0f057SRichard Smith   // Pass the alignment if the delete function has an align_val_t parameter.
1658b2f0f057SRichard Smith   if (PassSizeAndAlign.second) {
1659b2f0f057SRichard Smith     QualType AlignValType = *ParamTypeIt++;
1660b2f0f057SRichard Smith     CharUnits DeleteTypeAlign = getContext().toCharUnitsFromBits(
1661b2f0f057SRichard Smith         getContext().getTypeAlignIfKnown(DeleteTy));
1662b2f0f057SRichard Smith     llvm::Value *Align = llvm::ConstantInt::get(ConvertType(AlignValType),
1663b2f0f057SRichard Smith                                                 DeleteTypeAlign.getQuantity());
1664b2f0f057SRichard Smith     DeleteArgs.add(RValue::get(Align), AlignValType);
1665b2f0f057SRichard Smith   }
1666b2f0f057SRichard Smith 
1667b2f0f057SRichard Smith   assert(ParamTypeIt == DeleteFTy->param_type_end() &&
1668b2f0f057SRichard Smith          "unknown parameter to usual delete function");
166959486a2dSAnders Carlsson 
167059486a2dSAnders Carlsson   // Emit the call to delete.
16718d0dc31dSRichard Smith   EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
167259486a2dSAnders Carlsson }
167359486a2dSAnders Carlsson 
16748ed55a54SJohn McCall namespace {
16758ed55a54SJohn McCall   /// Calls the given 'operator delete' on a single object.
16767e70d680SDavid Blaikie   struct CallObjectDelete final : EHScopeStack::Cleanup {
16778ed55a54SJohn McCall     llvm::Value *Ptr;
16788ed55a54SJohn McCall     const FunctionDecl *OperatorDelete;
16798ed55a54SJohn McCall     QualType ElementType;
16808ed55a54SJohn McCall 
16818ed55a54SJohn McCall     CallObjectDelete(llvm::Value *Ptr,
16828ed55a54SJohn McCall                      const FunctionDecl *OperatorDelete,
16838ed55a54SJohn McCall                      QualType ElementType)
16848ed55a54SJohn McCall       : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
16858ed55a54SJohn McCall 
16864f12f10dSCraig Topper     void Emit(CodeGenFunction &CGF, Flags flags) override {
16878ed55a54SJohn McCall       CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
16888ed55a54SJohn McCall     }
16898ed55a54SJohn McCall   };
1690ab9db510SAlexander Kornienko }
16918ed55a54SJohn McCall 
16920c0b6d9aSDavid Majnemer void
16930c0b6d9aSDavid Majnemer CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
16940c0b6d9aSDavid Majnemer                                              llvm::Value *CompletePtr,
16950c0b6d9aSDavid Majnemer                                              QualType ElementType) {
16960c0b6d9aSDavid Majnemer   EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr,
16970c0b6d9aSDavid Majnemer                                         OperatorDelete, ElementType);
16980c0b6d9aSDavid Majnemer }
16990c0b6d9aSDavid Majnemer 
17008ed55a54SJohn McCall /// Emit the code for deleting a single object.
17018ed55a54SJohn McCall static void EmitObjectDelete(CodeGenFunction &CGF,
17020868137aSDavid Majnemer                              const CXXDeleteExpr *DE,
17037f416cc4SJohn McCall                              Address Ptr,
17040868137aSDavid Majnemer                              QualType ElementType) {
17058ed55a54SJohn McCall   // Find the destructor for the type, if applicable.  If the
17068ed55a54SJohn McCall   // destructor is virtual, we'll just emit the vcall and return.
17078a13c418SCraig Topper   const CXXDestructorDecl *Dtor = nullptr;
17088ed55a54SJohn McCall   if (const RecordType *RT = ElementType->getAs<RecordType>()) {
17098ed55a54SJohn McCall     CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1710b23533dbSEli Friedman     if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
17118ed55a54SJohn McCall       Dtor = RD->getDestructor();
17128ed55a54SJohn McCall 
17138ed55a54SJohn McCall       if (Dtor->isVirtual()) {
17140868137aSDavid Majnemer         CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
17150868137aSDavid Majnemer                                                     Dtor);
17168ed55a54SJohn McCall         return;
17178ed55a54SJohn McCall       }
17188ed55a54SJohn McCall     }
17198ed55a54SJohn McCall   }
17208ed55a54SJohn McCall 
17218ed55a54SJohn McCall   // Make sure that we call delete even if the dtor throws.
1722e4df6c8dSJohn McCall   // This doesn't have to a conditional cleanup because we're going
1723e4df6c8dSJohn McCall   // to pop it off in a second.
17240868137aSDavid Majnemer   const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
17258ed55a54SJohn McCall   CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
17267f416cc4SJohn McCall                                             Ptr.getPointer(),
17277f416cc4SJohn McCall                                             OperatorDelete, ElementType);
17288ed55a54SJohn McCall 
17298ed55a54SJohn McCall   if (Dtor)
17308ed55a54SJohn McCall     CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
173161535005SDouglas Gregor                               /*ForVirtualBase=*/false,
173261535005SDouglas Gregor                               /*Delegating=*/false,
173361535005SDouglas Gregor                               Ptr);
1734460ce58fSJohn McCall   else if (auto Lifetime = ElementType.getObjCLifetime()) {
1735460ce58fSJohn McCall     switch (Lifetime) {
173631168b07SJohn McCall     case Qualifiers::OCL_None:
173731168b07SJohn McCall     case Qualifiers::OCL_ExplicitNone:
173831168b07SJohn McCall     case Qualifiers::OCL_Autoreleasing:
173931168b07SJohn McCall       break;
174031168b07SJohn McCall 
17417f416cc4SJohn McCall     case Qualifiers::OCL_Strong:
17427f416cc4SJohn McCall       CGF.EmitARCDestroyStrong(Ptr, ARCPreciseLifetime);
174331168b07SJohn McCall       break;
174431168b07SJohn McCall 
174531168b07SJohn McCall     case Qualifiers::OCL_Weak:
174631168b07SJohn McCall       CGF.EmitARCDestroyWeak(Ptr);
174731168b07SJohn McCall       break;
174831168b07SJohn McCall     }
174931168b07SJohn McCall   }
17508ed55a54SJohn McCall 
17518ed55a54SJohn McCall   CGF.PopCleanupBlock();
17528ed55a54SJohn McCall }
17538ed55a54SJohn McCall 
17548ed55a54SJohn McCall namespace {
17558ed55a54SJohn McCall   /// Calls the given 'operator delete' on an array of objects.
17567e70d680SDavid Blaikie   struct CallArrayDelete final : EHScopeStack::Cleanup {
17578ed55a54SJohn McCall     llvm::Value *Ptr;
17588ed55a54SJohn McCall     const FunctionDecl *OperatorDelete;
17598ed55a54SJohn McCall     llvm::Value *NumElements;
17608ed55a54SJohn McCall     QualType ElementType;
17618ed55a54SJohn McCall     CharUnits CookieSize;
17628ed55a54SJohn McCall 
17638ed55a54SJohn McCall     CallArrayDelete(llvm::Value *Ptr,
17648ed55a54SJohn McCall                     const FunctionDecl *OperatorDelete,
17658ed55a54SJohn McCall                     llvm::Value *NumElements,
17668ed55a54SJohn McCall                     QualType ElementType,
17678ed55a54SJohn McCall                     CharUnits CookieSize)
17688ed55a54SJohn McCall       : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
17698ed55a54SJohn McCall         ElementType(ElementType), CookieSize(CookieSize) {}
17708ed55a54SJohn McCall 
17714f12f10dSCraig Topper     void Emit(CodeGenFunction &CGF, Flags flags) override {
1772b2f0f057SRichard Smith       CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType, NumElements,
1773b2f0f057SRichard Smith                          CookieSize);
17748ed55a54SJohn McCall     }
17758ed55a54SJohn McCall   };
1776ab9db510SAlexander Kornienko }
17778ed55a54SJohn McCall 
17788ed55a54SJohn McCall /// Emit the code for deleting an array of objects.
17798ed55a54SJohn McCall static void EmitArrayDelete(CodeGenFunction &CGF,
1780284c48ffSJohn McCall                             const CXXDeleteExpr *E,
17817f416cc4SJohn McCall                             Address deletedPtr,
1782ca2c56f2SJohn McCall                             QualType elementType) {
17838a13c418SCraig Topper   llvm::Value *numElements = nullptr;
17848a13c418SCraig Topper   llvm::Value *allocatedPtr = nullptr;
1785ca2c56f2SJohn McCall   CharUnits cookieSize;
1786ca2c56f2SJohn McCall   CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1787ca2c56f2SJohn McCall                                       numElements, allocatedPtr, cookieSize);
17888ed55a54SJohn McCall 
1789ca2c56f2SJohn McCall   assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
17908ed55a54SJohn McCall 
17918ed55a54SJohn McCall   // Make sure that we call delete even if one of the dtors throws.
1792ca2c56f2SJohn McCall   const FunctionDecl *operatorDelete = E->getOperatorDelete();
17938ed55a54SJohn McCall   CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
1794ca2c56f2SJohn McCall                                            allocatedPtr, operatorDelete,
1795ca2c56f2SJohn McCall                                            numElements, elementType,
1796ca2c56f2SJohn McCall                                            cookieSize);
17978ed55a54SJohn McCall 
1798ca2c56f2SJohn McCall   // Destroy the elements.
1799ca2c56f2SJohn McCall   if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1800ca2c56f2SJohn McCall     assert(numElements && "no element count for a type with a destructor!");
180131168b07SJohn McCall 
18027f416cc4SJohn McCall     CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
18037f416cc4SJohn McCall     CharUnits elementAlign =
18047f416cc4SJohn McCall       deletedPtr.getAlignment().alignmentOfArrayElement(elementSize);
18057f416cc4SJohn McCall 
18067f416cc4SJohn McCall     llvm::Value *arrayBegin = deletedPtr.getPointer();
1807ca2c56f2SJohn McCall     llvm::Value *arrayEnd =
18087f416cc4SJohn McCall       CGF.Builder.CreateInBoundsGEP(arrayBegin, numElements, "delete.end");
180997eab0a2SJohn McCall 
181097eab0a2SJohn McCall     // Note that it is legal to allocate a zero-length array, and we
181197eab0a2SJohn McCall     // can never fold the check away because the length should always
181297eab0a2SJohn McCall     // come from a cookie.
18137f416cc4SJohn McCall     CGF.emitArrayDestroy(arrayBegin, arrayEnd, elementType, elementAlign,
1814ca2c56f2SJohn McCall                          CGF.getDestroyer(dtorKind),
181597eab0a2SJohn McCall                          /*checkZeroLength*/ true,
1816ca2c56f2SJohn McCall                          CGF.needsEHCleanup(dtorKind));
18178ed55a54SJohn McCall   }
18188ed55a54SJohn McCall 
1819ca2c56f2SJohn McCall   // Pop the cleanup block.
18208ed55a54SJohn McCall   CGF.PopCleanupBlock();
18218ed55a54SJohn McCall }
18228ed55a54SJohn McCall 
182359486a2dSAnders Carlsson void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
182459486a2dSAnders Carlsson   const Expr *Arg = E->getArgument();
18257f416cc4SJohn McCall   Address Ptr = EmitPointerWithAlignment(Arg);
182659486a2dSAnders Carlsson 
182759486a2dSAnders Carlsson   // Null check the pointer.
182859486a2dSAnders Carlsson   llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
182959486a2dSAnders Carlsson   llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
183059486a2dSAnders Carlsson 
18317f416cc4SJohn McCall   llvm::Value *IsNull = Builder.CreateIsNull(Ptr.getPointer(), "isnull");
183259486a2dSAnders Carlsson 
183359486a2dSAnders Carlsson   Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
183459486a2dSAnders Carlsson   EmitBlock(DeleteNotNull);
183559486a2dSAnders Carlsson 
18368ed55a54SJohn McCall   // We might be deleting a pointer to array.  If so, GEP down to the
18378ed55a54SJohn McCall   // first non-array element.
18388ed55a54SJohn McCall   // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
18398ed55a54SJohn McCall   QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
18408ed55a54SJohn McCall   if (DeleteTy->isConstantArrayType()) {
18418ed55a54SJohn McCall     llvm::Value *Zero = Builder.getInt32(0);
18420e62c1ccSChris Lattner     SmallVector<llvm::Value*,8> GEP;
184359486a2dSAnders Carlsson 
18448ed55a54SJohn McCall     GEP.push_back(Zero); // point at the outermost array
18458ed55a54SJohn McCall 
18468ed55a54SJohn McCall     // For each layer of array type we're pointing at:
18478ed55a54SJohn McCall     while (const ConstantArrayType *Arr
18488ed55a54SJohn McCall              = getContext().getAsConstantArrayType(DeleteTy)) {
18498ed55a54SJohn McCall       // 1. Unpeel the array type.
18508ed55a54SJohn McCall       DeleteTy = Arr->getElementType();
18518ed55a54SJohn McCall 
18528ed55a54SJohn McCall       // 2. GEP to the first element of the array.
18538ed55a54SJohn McCall       GEP.push_back(Zero);
18548ed55a54SJohn McCall     }
18558ed55a54SJohn McCall 
18567f416cc4SJohn McCall     Ptr = Address(Builder.CreateInBoundsGEP(Ptr.getPointer(), GEP, "del.first"),
18577f416cc4SJohn McCall                   Ptr.getAlignment());
18588ed55a54SJohn McCall   }
18598ed55a54SJohn McCall 
18607f416cc4SJohn McCall   assert(ConvertTypeForMem(DeleteTy) == Ptr.getElementType());
18618ed55a54SJohn McCall 
18627270ef57SReid Kleckner   if (E->isArrayForm()) {
18637270ef57SReid Kleckner     EmitArrayDelete(*this, E, Ptr, DeleteTy);
18647270ef57SReid Kleckner   } else {
18657270ef57SReid Kleckner     EmitObjectDelete(*this, E, Ptr, DeleteTy);
18667270ef57SReid Kleckner   }
186759486a2dSAnders Carlsson 
186859486a2dSAnders Carlsson   EmitBlock(DeleteEnd);
186959486a2dSAnders Carlsson }
187059486a2dSAnders Carlsson 
18711c3d95ebSDavid Majnemer static bool isGLValueFromPointerDeref(const Expr *E) {
18721c3d95ebSDavid Majnemer   E = E->IgnoreParens();
18731c3d95ebSDavid Majnemer 
18741c3d95ebSDavid Majnemer   if (const auto *CE = dyn_cast<CastExpr>(E)) {
18751c3d95ebSDavid Majnemer     if (!CE->getSubExpr()->isGLValue())
18761c3d95ebSDavid Majnemer       return false;
18771c3d95ebSDavid Majnemer     return isGLValueFromPointerDeref(CE->getSubExpr());
18781c3d95ebSDavid Majnemer   }
18791c3d95ebSDavid Majnemer 
18801c3d95ebSDavid Majnemer   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
18811c3d95ebSDavid Majnemer     return isGLValueFromPointerDeref(OVE->getSourceExpr());
18821c3d95ebSDavid Majnemer 
18831c3d95ebSDavid Majnemer   if (const auto *BO = dyn_cast<BinaryOperator>(E))
18841c3d95ebSDavid Majnemer     if (BO->getOpcode() == BO_Comma)
18851c3d95ebSDavid Majnemer       return isGLValueFromPointerDeref(BO->getRHS());
18861c3d95ebSDavid Majnemer 
18871c3d95ebSDavid Majnemer   if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E))
18881c3d95ebSDavid Majnemer     return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
18891c3d95ebSDavid Majnemer            isGLValueFromPointerDeref(ACO->getFalseExpr());
18901c3d95ebSDavid Majnemer 
18911c3d95ebSDavid Majnemer   // C++11 [expr.sub]p1:
18921c3d95ebSDavid Majnemer   //   The expression E1[E2] is identical (by definition) to *((E1)+(E2))
18931c3d95ebSDavid Majnemer   if (isa<ArraySubscriptExpr>(E))
18941c3d95ebSDavid Majnemer     return true;
18951c3d95ebSDavid Majnemer 
18961c3d95ebSDavid Majnemer   if (const auto *UO = dyn_cast<UnaryOperator>(E))
18971c3d95ebSDavid Majnemer     if (UO->getOpcode() == UO_Deref)
18981c3d95ebSDavid Majnemer       return true;
18991c3d95ebSDavid Majnemer 
19001c3d95ebSDavid Majnemer   return false;
19011c3d95ebSDavid Majnemer }
19021c3d95ebSDavid Majnemer 
1903747e301eSWarren Hunt static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
19042192fe50SChris Lattner                                          llvm::Type *StdTypeInfoPtrTy) {
1905940f02d2SAnders Carlsson   // Get the vtable pointer.
19067f416cc4SJohn McCall   Address ThisPtr = CGF.EmitLValue(E).getAddress();
1907940f02d2SAnders Carlsson 
1908940f02d2SAnders Carlsson   // C++ [expr.typeid]p2:
1909940f02d2SAnders Carlsson   //   If the glvalue expression is obtained by applying the unary * operator to
1910940f02d2SAnders Carlsson   //   a pointer and the pointer is a null pointer value, the typeid expression
1911940f02d2SAnders Carlsson   //   throws the std::bad_typeid exception.
19121c3d95ebSDavid Majnemer   //
19131c3d95ebSDavid Majnemer   // However, this paragraph's intent is not clear.  We choose a very generous
19141c3d95ebSDavid Majnemer   // interpretation which implores us to consider comma operators, conditional
19151c3d95ebSDavid Majnemer   // operators, parentheses and other such constructs.
19161162d25cSDavid Majnemer   QualType SrcRecordTy = E->getType();
19171c3d95ebSDavid Majnemer   if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(
19181c3d95ebSDavid Majnemer           isGLValueFromPointerDeref(E), SrcRecordTy)) {
1919940f02d2SAnders Carlsson     llvm::BasicBlock *BadTypeidBlock =
1920940f02d2SAnders Carlsson         CGF.createBasicBlock("typeid.bad_typeid");
19211162d25cSDavid Majnemer     llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
1922940f02d2SAnders Carlsson 
19237f416cc4SJohn McCall     llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr.getPointer());
1924940f02d2SAnders Carlsson     CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
1925940f02d2SAnders Carlsson 
1926940f02d2SAnders Carlsson     CGF.EmitBlock(BadTypeidBlock);
19271162d25cSDavid Majnemer     CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
1928940f02d2SAnders Carlsson     CGF.EmitBlock(EndBlock);
1929940f02d2SAnders Carlsson   }
1930940f02d2SAnders Carlsson 
19311162d25cSDavid Majnemer   return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
19321162d25cSDavid Majnemer                                         StdTypeInfoPtrTy);
1933940f02d2SAnders Carlsson }
1934940f02d2SAnders Carlsson 
193559486a2dSAnders Carlsson llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
19362192fe50SChris Lattner   llvm::Type *StdTypeInfoPtrTy =
1937940f02d2SAnders Carlsson     ConvertType(E->getType())->getPointerTo();
1938fd7dfeb7SAnders Carlsson 
19393f4336cbSAnders Carlsson   if (E->isTypeOperand()) {
19403f4336cbSAnders Carlsson     llvm::Constant *TypeInfo =
1941143c55eaSDavid Majnemer         CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
1942940f02d2SAnders Carlsson     return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
19433f4336cbSAnders Carlsson   }
1944fd7dfeb7SAnders Carlsson 
1945940f02d2SAnders Carlsson   // C++ [expr.typeid]p2:
1946940f02d2SAnders Carlsson   //   When typeid is applied to a glvalue expression whose type is a
1947940f02d2SAnders Carlsson   //   polymorphic class type, the result refers to a std::type_info object
1948940f02d2SAnders Carlsson   //   representing the type of the most derived object (that is, the dynamic
1949940f02d2SAnders Carlsson   //   type) to which the glvalue refers.
1950ef8bf436SRichard Smith   if (E->isPotentiallyEvaluated())
1951940f02d2SAnders Carlsson     return EmitTypeidFromVTable(*this, E->getExprOperand(),
1952940f02d2SAnders Carlsson                                 StdTypeInfoPtrTy);
1953940f02d2SAnders Carlsson 
1954940f02d2SAnders Carlsson   QualType OperandTy = E->getExprOperand()->getType();
1955940f02d2SAnders Carlsson   return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1956940f02d2SAnders Carlsson                                StdTypeInfoPtrTy);
195759486a2dSAnders Carlsson }
195859486a2dSAnders Carlsson 
1959c1c9971cSAnders Carlsson static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1960c1c9971cSAnders Carlsson                                           QualType DestTy) {
19612192fe50SChris Lattner   llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1962c1c9971cSAnders Carlsson   if (DestTy->isPointerType())
1963c1c9971cSAnders Carlsson     return llvm::Constant::getNullValue(DestLTy);
1964c1c9971cSAnders Carlsson 
1965c1c9971cSAnders Carlsson   /// C++ [expr.dynamic.cast]p9:
1966c1c9971cSAnders Carlsson   ///   A failed cast to reference type throws std::bad_cast
19671162d25cSDavid Majnemer   if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
19681162d25cSDavid Majnemer     return nullptr;
1969c1c9971cSAnders Carlsson 
1970c1c9971cSAnders Carlsson   CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1971c1c9971cSAnders Carlsson   return llvm::UndefValue::get(DestLTy);
1972c1c9971cSAnders Carlsson }
1973c1c9971cSAnders Carlsson 
19747f416cc4SJohn McCall llvm::Value *CodeGenFunction::EmitDynamicCast(Address ThisAddr,
197559486a2dSAnders Carlsson                                               const CXXDynamicCastExpr *DCE) {
19762bf9b4c0SAlexey Bataev   CGM.EmitExplicitCastExprType(DCE, this);
19773f4336cbSAnders Carlsson   QualType DestTy = DCE->getTypeAsWritten();
19783f4336cbSAnders Carlsson 
1979c1c9971cSAnders Carlsson   if (DCE->isAlwaysNull())
19801162d25cSDavid Majnemer     if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy))
19811162d25cSDavid Majnemer       return T;
1982c1c9971cSAnders Carlsson 
1983c1c9971cSAnders Carlsson   QualType SrcTy = DCE->getSubExpr()->getType();
1984c1c9971cSAnders Carlsson 
19851162d25cSDavid Majnemer   // C++ [expr.dynamic.cast]p7:
19861162d25cSDavid Majnemer   //   If T is "pointer to cv void," then the result is a pointer to the most
19871162d25cSDavid Majnemer   //   derived object pointed to by v.
19881162d25cSDavid Majnemer   const PointerType *DestPTy = DestTy->getAs<PointerType>();
19891162d25cSDavid Majnemer 
19901162d25cSDavid Majnemer   bool isDynamicCastToVoid;
19911162d25cSDavid Majnemer   QualType SrcRecordTy;
19921162d25cSDavid Majnemer   QualType DestRecordTy;
19931162d25cSDavid Majnemer   if (DestPTy) {
19941162d25cSDavid Majnemer     isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType();
19951162d25cSDavid Majnemer     SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
19961162d25cSDavid Majnemer     DestRecordTy = DestPTy->getPointeeType();
19971162d25cSDavid Majnemer   } else {
19981162d25cSDavid Majnemer     isDynamicCastToVoid = false;
19991162d25cSDavid Majnemer     SrcRecordTy = SrcTy;
20001162d25cSDavid Majnemer     DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
20011162d25cSDavid Majnemer   }
20021162d25cSDavid Majnemer 
20031162d25cSDavid Majnemer   assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
20041162d25cSDavid Majnemer 
2005882d790fSAnders Carlsson   // C++ [expr.dynamic.cast]p4:
2006882d790fSAnders Carlsson   //   If the value of v is a null pointer value in the pointer case, the result
2007882d790fSAnders Carlsson   //   is the null pointer value of type T.
20081162d25cSDavid Majnemer   bool ShouldNullCheckSrcValue =
20091162d25cSDavid Majnemer       CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(),
20101162d25cSDavid Majnemer                                                          SrcRecordTy);
201159486a2dSAnders Carlsson 
20128a13c418SCraig Topper   llvm::BasicBlock *CastNull = nullptr;
20138a13c418SCraig Topper   llvm::BasicBlock *CastNotNull = nullptr;
2014882d790fSAnders Carlsson   llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
2015fa8b4955SDouglas Gregor 
2016882d790fSAnders Carlsson   if (ShouldNullCheckSrcValue) {
2017882d790fSAnders Carlsson     CastNull = createBasicBlock("dynamic_cast.null");
2018882d790fSAnders Carlsson     CastNotNull = createBasicBlock("dynamic_cast.notnull");
2019882d790fSAnders Carlsson 
20207f416cc4SJohn McCall     llvm::Value *IsNull = Builder.CreateIsNull(ThisAddr.getPointer());
2021882d790fSAnders Carlsson     Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
2022882d790fSAnders Carlsson     EmitBlock(CastNotNull);
202359486a2dSAnders Carlsson   }
202459486a2dSAnders Carlsson 
20257f416cc4SJohn McCall   llvm::Value *Value;
20261162d25cSDavid Majnemer   if (isDynamicCastToVoid) {
20277f416cc4SJohn McCall     Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, ThisAddr, SrcRecordTy,
20281162d25cSDavid Majnemer                                                   DestTy);
20291162d25cSDavid Majnemer   } else {
20301162d25cSDavid Majnemer     assert(DestRecordTy->isRecordType() &&
20311162d25cSDavid Majnemer            "destination type must be a record type!");
20327f416cc4SJohn McCall     Value = CGM.getCXXABI().EmitDynamicCastCall(*this, ThisAddr, SrcRecordTy,
20331162d25cSDavid Majnemer                                                 DestTy, DestRecordTy, CastEnd);
203467528eaaSDavid Majnemer     CastNotNull = Builder.GetInsertBlock();
20351162d25cSDavid Majnemer   }
20363f4336cbSAnders Carlsson 
2037882d790fSAnders Carlsson   if (ShouldNullCheckSrcValue) {
2038882d790fSAnders Carlsson     EmitBranch(CastEnd);
203959486a2dSAnders Carlsson 
2040882d790fSAnders Carlsson     EmitBlock(CastNull);
2041882d790fSAnders Carlsson     EmitBranch(CastEnd);
204259486a2dSAnders Carlsson   }
204359486a2dSAnders Carlsson 
2044882d790fSAnders Carlsson   EmitBlock(CastEnd);
204559486a2dSAnders Carlsson 
2046882d790fSAnders Carlsson   if (ShouldNullCheckSrcValue) {
2047882d790fSAnders Carlsson     llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
2048882d790fSAnders Carlsson     PHI->addIncoming(Value, CastNotNull);
2049882d790fSAnders Carlsson     PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
205059486a2dSAnders Carlsson 
2051882d790fSAnders Carlsson     Value = PHI;
205259486a2dSAnders Carlsson   }
205359486a2dSAnders Carlsson 
2054882d790fSAnders Carlsson   return Value;
205559486a2dSAnders Carlsson }
2056c370a7eeSEli Friedman 
2057c370a7eeSEli Friedman void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
20588631f3e8SEli Friedman   RunCleanupsScope Scope(*this);
20597f416cc4SJohn McCall   LValue SlotLV = MakeAddrLValue(Slot.getAddress(), E->getType());
20608631f3e8SEli Friedman 
2061c370a7eeSEli Friedman   CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
206253c7616eSJames Y Knight   for (LambdaExpr::const_capture_init_iterator i = E->capture_init_begin(),
2063c370a7eeSEli Friedman                                                e = E->capture_init_end();
2064c370a7eeSEli Friedman        i != e; ++i, ++CurField) {
2065c370a7eeSEli Friedman     // Emit initialization
206640ed2973SDavid Blaikie     LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
206739c81e28SAlexey Bataev     if (CurField->hasCapturedVLAType()) {
206839c81e28SAlexey Bataev       auto VAT = CurField->getCapturedVLAType();
206939c81e28SAlexey Bataev       EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
207039c81e28SAlexey Bataev     } else {
20715f1a04ffSEli Friedman       ArrayRef<VarDecl *> ArrayIndexes;
20725f1a04ffSEli Friedman       if (CurField->getType()->isArrayType())
20735f1a04ffSEli Friedman         ArrayIndexes = E->getCaptureInitIndexVars(i);
207440ed2973SDavid Blaikie       EmitInitializerForField(*CurField, LV, *i, ArrayIndexes);
2075c370a7eeSEli Friedman     }
2076c370a7eeSEli Friedman   }
207739c81e28SAlexey Bataev }
2078