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"
19de0fe07eSJohn McCall #include "ConstantEmitter.h"
20a8e7df36SMark Lacey #include "clang/CodeGen/CGFunctionInfo.h"
2110a4972aSSaleem Abdulrasool #include "clang/Frontend/CodeGenOptions.h"
22c80ceea9SChandler Carruth #include "llvm/IR/CallSite.h"
23ffd5551bSChandler Carruth #include "llvm/IR/Intrinsics.h"
24bbe277c4SAnders Carlsson 
2559486a2dSAnders Carlsson using namespace clang;
2659486a2dSAnders Carlsson using namespace CodeGen;
2759486a2dSAnders Carlsson 
28d0a9e807SGeorge Burgess IV namespace {
29d0a9e807SGeorge Burgess IV struct MemberCallInfo {
30d0a9e807SGeorge Burgess IV   RequiredArgs ReqArgs;
31d0a9e807SGeorge Burgess IV   // Number of prefix arguments for the call. Ignores the `this` pointer.
32d0a9e807SGeorge Burgess IV   unsigned PrefixSize;
33d0a9e807SGeorge Burgess IV };
34d0a9e807SGeorge Burgess IV }
35d0a9e807SGeorge Burgess IV 
36d0a9e807SGeorge Burgess IV static MemberCallInfo
37efa956ceSAlexey Samsonov commonEmitCXXMemberOrOperatorCall(CodeGenFunction &CGF, const CXXMethodDecl *MD,
38efa956ceSAlexey Samsonov                                   llvm::Value *This, llvm::Value *ImplicitParam,
39efa956ceSAlexey Samsonov                                   QualType ImplicitParamTy, const CallExpr *CE,
40762672a7SRichard Smith                                   CallArgList &Args, CallArgList *RtlArgs) {
41a5bf76bdSAlexey Samsonov   assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) ||
42a5bf76bdSAlexey Samsonov          isa<CXXOperatorCallExpr>(CE));
4327da15baSAnders Carlsson   assert(MD->isInstance() &&
44a5bf76bdSAlexey Samsonov          "Trying to emit a member or operator call expr on a static method!");
45034e7270SReid Kleckner   ASTContext &C = CGF.getContext();
4627da15baSAnders Carlsson 
4727da15baSAnders Carlsson   // Push the this ptr.
48034e7270SReid Kleckner   const CXXRecordDecl *RD =
49034e7270SReid Kleckner       CGF.CGM.getCXXABI().getThisArgumentTypeForMethod(MD);
50034e7270SReid Kleckner   Args.add(RValue::get(This),
51034e7270SReid Kleckner            RD ? C.getPointerType(C.getTypeDeclType(RD)) : C.VoidPtrTy);
5227da15baSAnders Carlsson 
53ee6bc533STimur Iskhodzhanov   // If there is an implicit parameter (e.g. VTT), emit it.
54ee6bc533STimur Iskhodzhanov   if (ImplicitParam) {
55ee6bc533STimur Iskhodzhanov     Args.add(RValue::get(ImplicitParam), ImplicitParamTy);
56e36a6b3eSAnders Carlsson   }
57e36a6b3eSAnders Carlsson 
58a729c62bSJohn McCall   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
59419996ccSGeorge Burgess IV   RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size(), MD);
60d0a9e807SGeorge Burgess IV   unsigned PrefixSize = Args.size() - 1;
61a729c62bSJohn McCall 
62a729c62bSJohn McCall   // And the rest of the call args.
63762672a7SRichard Smith   if (RtlArgs) {
64762672a7SRichard Smith     // Special case: if the caller emitted the arguments right-to-left already
65762672a7SRichard Smith     // (prior to emitting the *this argument), we're done. This happens for
66762672a7SRichard Smith     // assignment operators.
67762672a7SRichard Smith     Args.addFrom(*RtlArgs);
68762672a7SRichard Smith   } else if (CE) {
69a5bf76bdSAlexey Samsonov     // Special case: skip first argument of CXXOperatorCall (it is "this").
708e1162c7SAlexey Samsonov     unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0;
71f05779e2SDavid Blaikie     CGF.EmitCallArgs(Args, FPT, drop_begin(CE->arguments(), ArgsToSkip),
728e1162c7SAlexey Samsonov                      CE->getDirectCallee());
73a5bf76bdSAlexey Samsonov   } else {
748e1162c7SAlexey Samsonov     assert(
758e1162c7SAlexey Samsonov         FPT->getNumParams() == 0 &&
768e1162c7SAlexey Samsonov         "No CallExpr specified for function with non-zero number of arguments");
77a5bf76bdSAlexey Samsonov   }
78d0a9e807SGeorge Burgess IV   return {required, PrefixSize};
790c0b6d9aSDavid Majnemer }
8027da15baSAnders Carlsson 
810c0b6d9aSDavid Majnemer RValue CodeGenFunction::EmitCXXMemberOrOperatorCall(
82b92ab1afSJohn McCall     const CXXMethodDecl *MD, const CGCallee &Callee,
83b92ab1afSJohn McCall     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;
88d0a9e807SGeorge Burgess IV   MemberCallInfo CallInfo = commonEmitCXXMemberOrOperatorCall(
89762672a7SRichard Smith       *this, MD, This, ImplicitParam, ImplicitParamTy, CE, Args, RtlArgs);
90d0a9e807SGeorge Burgess IV   auto &FnInfo = CGM.getTypes().arrangeCXXMethodCall(
91d0a9e807SGeorge Burgess IV       Args, FPT, CallInfo.ReqArgs, CallInfo.PrefixSize);
92b92ab1afSJohn McCall   return EmitCall(FnInfo, Callee, ReturnValue, Args);
9327da15baSAnders Carlsson }
9427da15baSAnders Carlsson 
95ae81bbb4SAlexey Samsonov RValue CodeGenFunction::EmitCXXDestructorCall(
96b92ab1afSJohn McCall     const CXXDestructorDecl *DD, const CGCallee &Callee, llvm::Value *This,
97ae81bbb4SAlexey Samsonov     llvm::Value *ImplicitParam, QualType ImplicitParamTy, const CallExpr *CE,
98ae81bbb4SAlexey Samsonov     StructorType Type) {
990c0b6d9aSDavid Majnemer   CallArgList Args;
100ae81bbb4SAlexey Samsonov   commonEmitCXXMemberOrOperatorCall(*this, DD, This, ImplicitParam,
101762672a7SRichard Smith                                     ImplicitParamTy, CE, Args, nullptr);
102ae81bbb4SAlexey Samsonov   return EmitCall(CGM.getTypes().arrangeCXXStructorDeclaration(DD, Type),
103b92ab1afSJohn McCall                   Callee, ReturnValueSlot(), Args);
104b92ab1afSJohn McCall }
105b92ab1afSJohn McCall 
106b92ab1afSJohn McCall RValue CodeGenFunction::EmitCXXPseudoDestructorExpr(
107b92ab1afSJohn McCall                                             const CXXPseudoDestructorExpr *E) {
108b92ab1afSJohn McCall   QualType DestroyedType = E->getDestroyedType();
109b92ab1afSJohn McCall   if (DestroyedType.hasStrongOrWeakObjCLifetime()) {
110b92ab1afSJohn McCall     // Automatic Reference Counting:
111b92ab1afSJohn McCall     //   If the pseudo-expression names a retainable object with weak or
112b92ab1afSJohn McCall     //   strong lifetime, the object shall be released.
113b92ab1afSJohn McCall     Expr *BaseExpr = E->getBase();
114b92ab1afSJohn McCall     Address BaseValue = Address::invalid();
115b92ab1afSJohn McCall     Qualifiers BaseQuals;
116b92ab1afSJohn McCall 
117b92ab1afSJohn McCall     // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
118b92ab1afSJohn McCall     if (E->isArrow()) {
119b92ab1afSJohn McCall       BaseValue = EmitPointerWithAlignment(BaseExpr);
120b92ab1afSJohn McCall       const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>();
121b92ab1afSJohn McCall       BaseQuals = PTy->getPointeeType().getQualifiers();
122b92ab1afSJohn McCall     } else {
123b92ab1afSJohn McCall       LValue BaseLV = EmitLValue(BaseExpr);
124b92ab1afSJohn McCall       BaseValue = BaseLV.getAddress();
125b92ab1afSJohn McCall       QualType BaseTy = BaseExpr->getType();
126b92ab1afSJohn McCall       BaseQuals = BaseTy.getQualifiers();
127b92ab1afSJohn McCall     }
128b92ab1afSJohn McCall 
129b92ab1afSJohn McCall     switch (DestroyedType.getObjCLifetime()) {
130b92ab1afSJohn McCall     case Qualifiers::OCL_None:
131b92ab1afSJohn McCall     case Qualifiers::OCL_ExplicitNone:
132b92ab1afSJohn McCall     case Qualifiers::OCL_Autoreleasing:
133b92ab1afSJohn McCall       break;
134b92ab1afSJohn McCall 
135b92ab1afSJohn McCall     case Qualifiers::OCL_Strong:
136b92ab1afSJohn McCall       EmitARCRelease(Builder.CreateLoad(BaseValue,
137b92ab1afSJohn McCall                         DestroyedType.isVolatileQualified()),
138b92ab1afSJohn McCall                      ARCPreciseLifetime);
139b92ab1afSJohn McCall       break;
140b92ab1afSJohn McCall 
141b92ab1afSJohn McCall     case Qualifiers::OCL_Weak:
142b92ab1afSJohn McCall       EmitARCDestroyWeak(BaseValue);
143b92ab1afSJohn McCall       break;
144b92ab1afSJohn McCall     }
145b92ab1afSJohn McCall   } else {
146b92ab1afSJohn McCall     // C++ [expr.pseudo]p1:
147b92ab1afSJohn McCall     //   The result shall only be used as the operand for the function call
148b92ab1afSJohn McCall     //   operator (), and the result of such a call has type void. The only
149b92ab1afSJohn McCall     //   effect is the evaluation of the postfix-expression before the dot or
150b92ab1afSJohn McCall     //   arrow.
151b92ab1afSJohn McCall     EmitIgnoredExpr(E->getBase());
152b92ab1afSJohn McCall   }
153b92ab1afSJohn McCall 
154b92ab1afSJohn McCall   return RValue::get(nullptr);
1550c0b6d9aSDavid Majnemer }
1560c0b6d9aSDavid Majnemer 
1573b33c4ecSRafael Espindola static CXXRecordDecl *getCXXRecord(const Expr *E) {
1583b33c4ecSRafael Espindola   QualType T = E->getType();
1593b33c4ecSRafael Espindola   if (const PointerType *PTy = T->getAs<PointerType>())
1603b33c4ecSRafael Espindola     T = PTy->getPointeeType();
1613b33c4ecSRafael Espindola   const RecordType *Ty = T->castAs<RecordType>();
1623b33c4ecSRafael Espindola   return cast<CXXRecordDecl>(Ty->getDecl());
1633b33c4ecSRafael Espindola }
1643b33c4ecSRafael Espindola 
16564225794SFrancois Pichet // Note: This function also emit constructor calls to support a MSVC
16664225794SFrancois Pichet // extensions allowing explicit constructor function call.
16727da15baSAnders Carlsson RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
16827da15baSAnders Carlsson                                               ReturnValueSlot ReturnValue) {
1692d2e8707SJohn McCall   const Expr *callee = CE->getCallee()->IgnoreParens();
1702d2e8707SJohn McCall 
1712d2e8707SJohn McCall   if (isa<BinaryOperator>(callee))
17227da15baSAnders Carlsson     return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
17327da15baSAnders Carlsson 
1742d2e8707SJohn McCall   const MemberExpr *ME = cast<MemberExpr>(callee);
17527da15baSAnders Carlsson   const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
17627da15baSAnders Carlsson 
17727da15baSAnders Carlsson   if (MD->isStatic()) {
17827da15baSAnders Carlsson     // The method is static, emit it as we would a regular call.
179b92ab1afSJohn McCall     CGCallee callee = CGCallee::forDirect(CGM.GetAddrOfFunction(MD), MD);
180b92ab1afSJohn McCall     return EmitCall(getContext().getPointerType(MD->getType()), callee, CE,
18170b9c01bSAlexey Samsonov                     ReturnValue);
18227da15baSAnders Carlsson   }
18327da15baSAnders Carlsson 
184aad4af6dSNico Weber   bool HasQualifier = ME->hasQualifier();
185aad4af6dSNico Weber   NestedNameSpecifier *Qualifier = HasQualifier ? ME->getQualifier() : nullptr;
186aad4af6dSNico Weber   bool IsArrow = ME->isArrow();
187ecbe2e97SRafael Espindola   const Expr *Base = ME->getBase();
188aad4af6dSNico Weber 
189aad4af6dSNico Weber   return EmitCXXMemberOrOperatorMemberCallExpr(
190aad4af6dSNico Weber       CE, MD, ReturnValue, HasQualifier, Qualifier, IsArrow, Base);
191aad4af6dSNico Weber }
192aad4af6dSNico Weber 
193aad4af6dSNico Weber RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr(
194aad4af6dSNico Weber     const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue,
195aad4af6dSNico Weber     bool HasQualifier, NestedNameSpecifier *Qualifier, bool IsArrow,
196aad4af6dSNico Weber     const Expr *Base) {
197aad4af6dSNico Weber   assert(isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE));
198aad4af6dSNico Weber 
199aad4af6dSNico Weber   // Compute the object pointer.
200aad4af6dSNico Weber   bool CanUseVirtualCall = MD->isVirtual() && !HasQualifier;
201ecbe2e97SRafael Espindola 
2028a13c418SCraig Topper   const CXXMethodDecl *DevirtualizedMethod = nullptr;
20322461673SAkira Hatanaka   if (CanUseVirtualCall &&
20422461673SAkira Hatanaka       MD->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) {
2053b33c4ecSRafael Espindola     const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
2063b33c4ecSRafael Espindola     DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
2073b33c4ecSRafael Espindola     assert(DevirtualizedMethod);
2083b33c4ecSRafael Espindola     const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
2093b33c4ecSRafael Espindola     const Expr *Inner = Base->ignoreParenBaseCasts();
2105bd68794SAlexey Bataev     if (DevirtualizedMethod->getReturnType().getCanonicalType() !=
2115bd68794SAlexey Bataev         MD->getReturnType().getCanonicalType())
2125bd68794SAlexey Bataev       // If the return types are not the same, this might be a case where more
2135bd68794SAlexey Bataev       // code needs to run to compensate for it. For example, the derived
2145bd68794SAlexey Bataev       // method might return a type that inherits form from the return
2155bd68794SAlexey Bataev       // type of MD and has a prefix.
2165bd68794SAlexey Bataev       // For now we just avoid devirtualizing these covariant cases.
2175bd68794SAlexey Bataev       DevirtualizedMethod = nullptr;
2185bd68794SAlexey Bataev     else if (getCXXRecord(Inner) == DevirtualizedClass)
2193b33c4ecSRafael Espindola       // If the class of the Inner expression is where the dynamic method
2203b33c4ecSRafael Espindola       // is defined, build the this pointer from it.
2213b33c4ecSRafael Espindola       Base = Inner;
2223b33c4ecSRafael Espindola     else if (getCXXRecord(Base) != DevirtualizedClass) {
2233b33c4ecSRafael Espindola       // If the method is defined in a class that is not the best dynamic
2243b33c4ecSRafael Espindola       // one or the one of the full expression, we would have to build
2253b33c4ecSRafael Espindola       // a derived-to-base cast to compute the correct this pointer, but
2263b33c4ecSRafael Espindola       // we don't have support for that yet, so do a virtual call.
2278a13c418SCraig Topper       DevirtualizedMethod = nullptr;
2283b33c4ecSRafael Espindola     }
2293b33c4ecSRafael Espindola   }
230ecbe2e97SRafael Espindola 
231762672a7SRichard Smith   // C++17 demands that we evaluate the RHS of a (possibly-compound) assignment
232762672a7SRichard Smith   // operator before the LHS.
233762672a7SRichard Smith   CallArgList RtlArgStorage;
234762672a7SRichard Smith   CallArgList *RtlArgs = nullptr;
235762672a7SRichard Smith   if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
236762672a7SRichard Smith     if (OCE->isAssignmentOp()) {
237762672a7SRichard Smith       RtlArgs = &RtlArgStorage;
238762672a7SRichard Smith       EmitCallArgs(*RtlArgs, MD->getType()->castAs<FunctionProtoType>(),
239762672a7SRichard Smith                    drop_begin(CE->arguments(), 1), CE->getDirectCallee(),
240a560ccf2SRichard Smith                    /*ParamsToSkip*/0, EvaluationOrder::ForceRightToLeft);
241762672a7SRichard Smith     }
242762672a7SRichard Smith   }
243762672a7SRichard Smith 
2447f416cc4SJohn McCall   Address This = Address::invalid();
245aad4af6dSNico Weber   if (IsArrow)
2467f416cc4SJohn McCall     This = EmitPointerWithAlignment(Base);
247f93ac894SFariborz Jahanian   else
2483b33c4ecSRafael Espindola     This = EmitLValue(Base).getAddress();
249ecbe2e97SRafael Espindola 
25027da15baSAnders Carlsson 
251419bd094SRichard Smith   if (MD->isTrivial() || (MD->isDefaulted() && MD->getParent()->isUnion())) {
2528a13c418SCraig Topper     if (isa<CXXDestructorDecl>(MD)) return RValue::get(nullptr);
25364225794SFrancois Pichet     if (isa<CXXConstructorDecl>(MD) &&
25464225794SFrancois Pichet         cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
2558a13c418SCraig Topper       return RValue::get(nullptr);
2560d635f53SJohn McCall 
257aad4af6dSNico Weber     if (!MD->getParent()->mayInsertExtraPadding()) {
25822653bacSSebastian Redl       if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
25922653bacSSebastian Redl         // We don't like to generate the trivial copy/move assignment operator
26022653bacSSebastian Redl         // when it isn't necessary; just produce the proper effect here.
261762672a7SRichard Smith         LValue RHS = isa<CXXOperatorCallExpr>(CE)
262762672a7SRichard Smith                          ? MakeNaturalAlignAddrLValue(
263762672a7SRichard Smith                                (*RtlArgs)[0].RV.getScalarVal(),
264762672a7SRichard Smith                                (*(CE->arg_begin() + 1))->getType())
265762672a7SRichard Smith                          : EmitLValue(*CE->arg_begin());
266762672a7SRichard Smith         EmitAggregateAssign(This, RHS.getAddress(), CE->getType());
2677f416cc4SJohn McCall         return RValue::get(This.getPointer());
26827da15baSAnders Carlsson       }
26927da15baSAnders Carlsson 
27064225794SFrancois Pichet       if (isa<CXXConstructorDecl>(MD) &&
27122653bacSSebastian Redl           cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
27222653bacSSebastian Redl         // Trivial move and copy ctor are the same.
273525bf650SAlexey Samsonov         assert(CE->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
2747f416cc4SJohn McCall         Address RHS = EmitLValue(*CE->arg_begin()).getAddress();
275f48ee448SBenjamin Kramer         EmitAggregateCopy(This, RHS, (*CE->arg_begin())->getType());
2767f416cc4SJohn McCall         return RValue::get(This.getPointer());
27764225794SFrancois Pichet       }
27864225794SFrancois Pichet       llvm_unreachable("unknown trivial member function");
27964225794SFrancois Pichet     }
280aad4af6dSNico Weber   }
28164225794SFrancois Pichet 
2820d635f53SJohn McCall   // Compute the function type we're calling.
2833abfe958SNico Weber   const CXXMethodDecl *CalleeDecl =
2843abfe958SNico Weber       DevirtualizedMethod ? DevirtualizedMethod : MD;
2858a13c418SCraig Topper   const CGFunctionInfo *FInfo = nullptr;
2863abfe958SNico Weber   if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
2878d2a19b4SRafael Espindola     FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
2888d2a19b4SRafael Espindola         Dtor, StructorType::Complete);
2893abfe958SNico Weber   else if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(CalleeDecl))
2908d2a19b4SRafael Espindola     FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
2918d2a19b4SRafael Espindola         Ctor, StructorType::Complete);
29264225794SFrancois Pichet   else
293ade60977SEli Friedman     FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
2940d635f53SJohn McCall 
295e7de47efSReid Kleckner   llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
2960d635f53SJohn McCall 
297d98f5d78SIvan Krasin   // C++11 [class.mfct.non-static]p2:
298d98f5d78SIvan Krasin   //   If a non-static member function of a class X is called for an object that
299d98f5d78SIvan Krasin   //   is not of type X, or of a type derived from X, the behavior is undefined.
300d98f5d78SIvan Krasin   SourceLocation CallLoc;
301d98f5d78SIvan Krasin   ASTContext &C = getContext();
302d98f5d78SIvan Krasin   if (CE)
303d98f5d78SIvan Krasin     CallLoc = CE->getExprLoc();
304d98f5d78SIvan Krasin 
30534b1fd6aSVedant Kumar   SanitizerSet SkippedChecks;
306ffd7c887SVedant Kumar   if (const auto *CMCE = dyn_cast<CXXMemberCallExpr>(CE)) {
307ffd7c887SVedant Kumar     auto *IOA = CMCE->getImplicitObjectArgument();
308ffd7c887SVedant Kumar     bool IsImplicitObjectCXXThis = IsWrappedCXXThis(IOA);
309ffd7c887SVedant Kumar     if (IsImplicitObjectCXXThis)
310ffd7c887SVedant Kumar       SkippedChecks.set(SanitizerKind::Alignment, true);
311ffd7c887SVedant Kumar     if (IsImplicitObjectCXXThis || isa<DeclRefExpr>(IOA))
31234b1fd6aSVedant Kumar       SkippedChecks.set(SanitizerKind::Null, true);
313ffd7c887SVedant Kumar   }
31434b1fd6aSVedant Kumar   EmitTypeCheck(
31534b1fd6aSVedant Kumar       isa<CXXConstructorDecl>(CalleeDecl) ? CodeGenFunction::TCK_ConstructorCall
316d98f5d78SIvan Krasin                                           : CodeGenFunction::TCK_MemberCall,
31734b1fd6aSVedant Kumar       CallLoc, This.getPointer(), C.getRecordType(CalleeDecl->getParent()),
31834b1fd6aSVedant Kumar       /*Alignment=*/CharUnits::Zero(), SkippedChecks);
319d98f5d78SIvan Krasin 
320018f266bSVedant Kumar   // FIXME: Uses of 'MD' past this point need to be audited. We may need to use
321018f266bSVedant Kumar   // 'CalleeDecl' instead.
322018f266bSVedant Kumar 
32327da15baSAnders Carlsson   // C++ [class.virtual]p12:
32427da15baSAnders Carlsson   //   Explicit qualification with the scope operator (5.1) suppresses the
32527da15baSAnders Carlsson   //   virtual call mechanism.
32627da15baSAnders Carlsson   //
32727da15baSAnders Carlsson   // We also don't emit a virtual call if the base expression has a record type
32827da15baSAnders Carlsson   // because then we know what the type is.
3293b33c4ecSRafael Espindola   bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
3309dc6eef7SStephen Lin 
3310d635f53SJohn McCall   if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
33219cee187SStephen Lin     assert(CE->arg_begin() == CE->arg_end() &&
3339dc6eef7SStephen Lin            "Destructor shouldn't have explicit parameters");
3349dc6eef7SStephen Lin     assert(ReturnValue.isNull() && "Destructor shouldn't have return value");
3359dc6eef7SStephen Lin     if (UseVirtualCall) {
336aad4af6dSNico Weber       CGM.getCXXABI().EmitVirtualDestructorCall(
337aad4af6dSNico Weber           *this, Dtor, Dtor_Complete, This, cast<CXXMemberCallExpr>(CE));
33827da15baSAnders Carlsson     } else {
339b92ab1afSJohn McCall       CGCallee Callee;
340aad4af6dSNico Weber       if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
341aad4af6dSNico Weber         Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
3423b33c4ecSRafael Espindola       else if (!DevirtualizedMethod)
343b92ab1afSJohn McCall         Callee = CGCallee::forDirect(
344b92ab1afSJohn McCall             CGM.getAddrOfCXXStructor(Dtor, StructorType::Complete, FInfo, Ty),
345b92ab1afSJohn McCall                                      Dtor);
34649e860b2SRafael Espindola       else {
3473b33c4ecSRafael Espindola         const CXXDestructorDecl *DDtor =
3483b33c4ecSRafael Espindola           cast<CXXDestructorDecl>(DevirtualizedMethod);
349b92ab1afSJohn McCall         Callee = CGCallee::forDirect(
350b92ab1afSJohn McCall                   CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty),
351b92ab1afSJohn McCall                                      DDtor);
35249e860b2SRafael Espindola       }
353018f266bSVedant Kumar       EmitCXXMemberOrOperatorCall(
354018f266bSVedant Kumar           CalleeDecl, Callee, ReturnValue, This.getPointer(),
355018f266bSVedant Kumar           /*ImplicitParam=*/nullptr, QualType(), CE, nullptr);
35627da15baSAnders Carlsson     }
3578a13c418SCraig Topper     return RValue::get(nullptr);
3589dc6eef7SStephen Lin   }
3599dc6eef7SStephen Lin 
360b92ab1afSJohn McCall   CGCallee Callee;
3619dc6eef7SStephen Lin   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
362b92ab1afSJohn McCall     Callee = CGCallee::forDirect(
363b92ab1afSJohn McCall                   CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty),
364b92ab1afSJohn McCall                                  Ctor);
3650d635f53SJohn McCall   } else if (UseVirtualCall) {
3666708c4a1SPeter Collingbourne     Callee = CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, Ty,
3676708c4a1SPeter Collingbourne                                                        CE->getLocStart());
36827da15baSAnders Carlsson   } else {
3691a7488afSPeter Collingbourne     if (SanOpts.has(SanitizerKind::CFINVCall) &&
3701a7488afSPeter Collingbourne         MD->getParent()->isDynamicClass()) {
3716010880bSPeter Collingbourne       llvm::Value *VTable;
3726010880bSPeter Collingbourne       const CXXRecordDecl *RD;
3736010880bSPeter Collingbourne       std::tie(VTable, RD) =
3746010880bSPeter Collingbourne           CGM.getCXXABI().LoadVTablePtr(*this, This, MD->getParent());
3756010880bSPeter Collingbourne       EmitVTablePtrCheckForCall(RD, VTable, CFITCK_NVCall, CE->getLocStart());
3761a7488afSPeter Collingbourne     }
3771a7488afSPeter Collingbourne 
378aad4af6dSNico Weber     if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
379aad4af6dSNico Weber       Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
3803b33c4ecSRafael Espindola     else if (!DevirtualizedMethod)
381b92ab1afSJohn McCall       Callee = CGCallee::forDirect(CGM.GetAddrOfFunction(MD, Ty), MD);
38249e860b2SRafael Espindola     else {
383b92ab1afSJohn McCall       Callee = CGCallee::forDirect(
384b92ab1afSJohn McCall                                 CGM.GetAddrOfFunction(DevirtualizedMethod, Ty),
385b92ab1afSJohn McCall                                    DevirtualizedMethod);
38649e860b2SRafael Espindola     }
38727da15baSAnders Carlsson   }
38827da15baSAnders Carlsson 
389f1749427STimur Iskhodzhanov   if (MD->isVirtual()) {
390f1749427STimur Iskhodzhanov     This = CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
3914b60f30aSReid Kleckner         *this, CalleeDecl, This, UseVirtualCall);
392f1749427STimur Iskhodzhanov   }
39388fd439aSTimur Iskhodzhanov 
394018f266bSVedant Kumar   return EmitCXXMemberOrOperatorCall(
395018f266bSVedant Kumar       CalleeDecl, Callee, ReturnValue, This.getPointer(),
396018f266bSVedant Kumar       /*ImplicitParam=*/nullptr, QualType(), CE, RtlArgs);
39727da15baSAnders Carlsson }
39827da15baSAnders Carlsson 
39927da15baSAnders Carlsson RValue
40027da15baSAnders Carlsson CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
40127da15baSAnders Carlsson                                               ReturnValueSlot ReturnValue) {
40227da15baSAnders Carlsson   const BinaryOperator *BO =
40327da15baSAnders Carlsson       cast<BinaryOperator>(E->getCallee()->IgnoreParens());
40427da15baSAnders Carlsson   const Expr *BaseExpr = BO->getLHS();
40527da15baSAnders Carlsson   const Expr *MemFnExpr = BO->getRHS();
40627da15baSAnders Carlsson 
40727da15baSAnders Carlsson   const MemberPointerType *MPT =
4080009fcc3SJohn McCall     MemFnExpr->getType()->castAs<MemberPointerType>();
409475999dcSJohn McCall 
41027da15baSAnders Carlsson   const FunctionProtoType *FPT =
4110009fcc3SJohn McCall     MPT->getPointeeType()->castAs<FunctionProtoType>();
41227da15baSAnders Carlsson   const CXXRecordDecl *RD =
41327da15baSAnders Carlsson     cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
41427da15baSAnders Carlsson 
41527da15baSAnders Carlsson   // Emit the 'this' pointer.
4167f416cc4SJohn McCall   Address This = Address::invalid();
417e302792bSJohn McCall   if (BO->getOpcode() == BO_PtrMemI)
4187f416cc4SJohn McCall     This = EmitPointerWithAlignment(BaseExpr);
41927da15baSAnders Carlsson   else
42027da15baSAnders Carlsson     This = EmitLValue(BaseExpr).getAddress();
42127da15baSAnders Carlsson 
4227f416cc4SJohn McCall   EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This.getPointer(),
423e30752c9SRichard Smith                 QualType(MPT->getClass(), 0));
42469d0d262SRichard Smith 
425bde62d78SRichard Smith   // Get the member function pointer.
426bde62d78SRichard Smith   llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
427bde62d78SRichard Smith 
428475999dcSJohn McCall   // Ask the ABI to load the callee.  Note that This is modified.
4297f416cc4SJohn McCall   llvm::Value *ThisPtrForCall = nullptr;
430b92ab1afSJohn McCall   CGCallee Callee =
4317f416cc4SJohn McCall     CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This,
4327f416cc4SJohn McCall                                              ThisPtrForCall, MemFnPtr, MPT);
43327da15baSAnders Carlsson 
43427da15baSAnders Carlsson   CallArgList Args;
43527da15baSAnders Carlsson 
43627da15baSAnders Carlsson   QualType ThisType =
43727da15baSAnders Carlsson     getContext().getPointerType(getContext().getTagDeclType(RD));
43827da15baSAnders Carlsson 
43927da15baSAnders Carlsson   // Push the this ptr.
4407f416cc4SJohn McCall   Args.add(RValue::get(ThisPtrForCall), ThisType);
44127da15baSAnders Carlsson 
442419996ccSGeorge Burgess IV   RequiredArgs required =
443419996ccSGeorge Burgess IV       RequiredArgs::forPrototypePlus(FPT, 1, /*FD=*/nullptr);
4448dda7b27SJohn McCall 
44527da15baSAnders Carlsson   // And the rest of the call args
446419996ccSGeorge Burgess IV   EmitCallArgs(Args, FPT, E->arguments());
447d0a9e807SGeorge Burgess IV   return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required,
448d0a9e807SGeorge Burgess IV                                                       /*PrefixSize=*/0),
4495fa40c3bSNick Lewycky                   Callee, ReturnValue, Args);
45027da15baSAnders Carlsson }
45127da15baSAnders Carlsson 
45227da15baSAnders Carlsson RValue
45327da15baSAnders Carlsson CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
45427da15baSAnders Carlsson                                                const CXXMethodDecl *MD,
45527da15baSAnders Carlsson                                                ReturnValueSlot ReturnValue) {
45627da15baSAnders Carlsson   assert(MD->isInstance() &&
45727da15baSAnders Carlsson          "Trying to emit a member call expr on a static method!");
458aad4af6dSNico Weber   return EmitCXXMemberOrOperatorMemberCallExpr(
459aad4af6dSNico Weber       E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr,
460aad4af6dSNico Weber       /*IsArrow=*/false, E->getArg(0));
46127da15baSAnders Carlsson }
46227da15baSAnders Carlsson 
463fe883422SPeter Collingbourne RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
464fe883422SPeter Collingbourne                                                ReturnValueSlot ReturnValue) {
465fe883422SPeter Collingbourne   return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
466fe883422SPeter Collingbourne }
467fe883422SPeter Collingbourne 
468fde961dbSEli Friedman static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
4697f416cc4SJohn McCall                                             Address DestPtr,
470fde961dbSEli Friedman                                             const CXXRecordDecl *Base) {
471fde961dbSEli Friedman   if (Base->isEmpty())
472fde961dbSEli Friedman     return;
473fde961dbSEli Friedman 
4747f416cc4SJohn McCall   DestPtr = CGF.Builder.CreateElementBitCast(DestPtr, CGF.Int8Ty);
475fde961dbSEli Friedman 
476fde961dbSEli Friedman   const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
4778671c6e0SDavid Majnemer   CharUnits NVSize = Layout.getNonVirtualSize();
4788671c6e0SDavid Majnemer 
4798671c6e0SDavid Majnemer   // We cannot simply zero-initialize the entire base sub-object if vbptrs are
4808671c6e0SDavid Majnemer   // present, they are initialized by the most derived class before calling the
4818671c6e0SDavid Majnemer   // constructor.
4828671c6e0SDavid Majnemer   SmallVector<std::pair<CharUnits, CharUnits>, 1> Stores;
4838671c6e0SDavid Majnemer   Stores.emplace_back(CharUnits::Zero(), NVSize);
4848671c6e0SDavid Majnemer 
4858671c6e0SDavid Majnemer   // Each store is split by the existence of a vbptr.
4868671c6e0SDavid Majnemer   CharUnits VBPtrWidth = CGF.getPointerSize();
4878671c6e0SDavid Majnemer   std::vector<CharUnits> VBPtrOffsets =
4888671c6e0SDavid Majnemer       CGF.CGM.getCXXABI().getVBPtrOffsets(Base);
4898671c6e0SDavid Majnemer   for (CharUnits VBPtrOffset : VBPtrOffsets) {
4907f980d84SDavid Majnemer     // Stop before we hit any virtual base pointers located in virtual bases.
4917f980d84SDavid Majnemer     if (VBPtrOffset >= NVSize)
4927f980d84SDavid Majnemer       break;
4938671c6e0SDavid Majnemer     std::pair<CharUnits, CharUnits> LastStore = Stores.pop_back_val();
4948671c6e0SDavid Majnemer     CharUnits LastStoreOffset = LastStore.first;
4958671c6e0SDavid Majnemer     CharUnits LastStoreSize = LastStore.second;
4968671c6e0SDavid Majnemer 
4978671c6e0SDavid Majnemer     CharUnits SplitBeforeOffset = LastStoreOffset;
4988671c6e0SDavid Majnemer     CharUnits SplitBeforeSize = VBPtrOffset - SplitBeforeOffset;
4998671c6e0SDavid Majnemer     assert(!SplitBeforeSize.isNegative() && "negative store size!");
5008671c6e0SDavid Majnemer     if (!SplitBeforeSize.isZero())
5018671c6e0SDavid Majnemer       Stores.emplace_back(SplitBeforeOffset, SplitBeforeSize);
5028671c6e0SDavid Majnemer 
5038671c6e0SDavid Majnemer     CharUnits SplitAfterOffset = VBPtrOffset + VBPtrWidth;
5048671c6e0SDavid Majnemer     CharUnits SplitAfterSize = LastStoreSize - SplitAfterOffset;
5058671c6e0SDavid Majnemer     assert(!SplitAfterSize.isNegative() && "negative store size!");
5068671c6e0SDavid Majnemer     if (!SplitAfterSize.isZero())
5078671c6e0SDavid Majnemer       Stores.emplace_back(SplitAfterOffset, SplitAfterSize);
5088671c6e0SDavid Majnemer   }
509fde961dbSEli Friedman 
510fde961dbSEli Friedman   // If the type contains a pointer to data member we can't memset it to zero.
511fde961dbSEli Friedman   // Instead, create a null constant and copy it to the destination.
512fde961dbSEli Friedman   // TODO: there are other patterns besides zero that we can usefully memset,
513fde961dbSEli Friedman   // like -1, which happens to be the pattern used by member-pointers.
514fde961dbSEli Friedman   // TODO: isZeroInitializable can be over-conservative in the case where a
515fde961dbSEli Friedman   // virtual base contains a member pointer.
5168671c6e0SDavid Majnemer   llvm::Constant *NullConstantForBase = CGF.CGM.EmitNullConstantForBase(Base);
5178671c6e0SDavid Majnemer   if (!NullConstantForBase->isNullValue()) {
5188671c6e0SDavid Majnemer     llvm::GlobalVariable *NullVariable = new llvm::GlobalVariable(
5198671c6e0SDavid Majnemer         CGF.CGM.getModule(), NullConstantForBase->getType(),
5208671c6e0SDavid Majnemer         /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage,
5218671c6e0SDavid Majnemer         NullConstantForBase, Twine());
5227f416cc4SJohn McCall 
5237f416cc4SJohn McCall     CharUnits Align = std::max(Layout.getNonVirtualAlignment(),
5247f416cc4SJohn McCall                                DestPtr.getAlignment());
525fde961dbSEli Friedman     NullVariable->setAlignment(Align.getQuantity());
5267f416cc4SJohn McCall 
5277f416cc4SJohn McCall     Address SrcPtr = Address(CGF.EmitCastToVoidPtr(NullVariable), Align);
528fde961dbSEli Friedman 
529fde961dbSEli Friedman     // Get and call the appropriate llvm.memcpy overload.
5308671c6e0SDavid Majnemer     for (std::pair<CharUnits, CharUnits> Store : Stores) {
5318671c6e0SDavid Majnemer       CharUnits StoreOffset = Store.first;
5328671c6e0SDavid Majnemer       CharUnits StoreSize = Store.second;
5338671c6e0SDavid Majnemer       llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
5348671c6e0SDavid Majnemer       CGF.Builder.CreateMemCpy(
5358671c6e0SDavid Majnemer           CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
5368671c6e0SDavid Majnemer           CGF.Builder.CreateConstInBoundsByteGEP(SrcPtr, StoreOffset),
5378671c6e0SDavid Majnemer           StoreSizeVal);
538fde961dbSEli Friedman     }
539fde961dbSEli Friedman 
540fde961dbSEli Friedman   // Otherwise, just memset the whole thing to zero.  This is legal
541fde961dbSEli Friedman   // because in LLVM, all default initializers (other than the ones we just
542fde961dbSEli Friedman   // handled above) are guaranteed to have a bit pattern of all zeros.
5438671c6e0SDavid Majnemer   } else {
5448671c6e0SDavid Majnemer     for (std::pair<CharUnits, CharUnits> Store : Stores) {
5458671c6e0SDavid Majnemer       CharUnits StoreOffset = Store.first;
5468671c6e0SDavid Majnemer       CharUnits StoreSize = Store.second;
5478671c6e0SDavid Majnemer       llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
5488671c6e0SDavid Majnemer       CGF.Builder.CreateMemSet(
5498671c6e0SDavid Majnemer           CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
5508671c6e0SDavid Majnemer           CGF.Builder.getInt8(0), StoreSizeVal);
5518671c6e0SDavid Majnemer     }
5528671c6e0SDavid Majnemer   }
553fde961dbSEli Friedman }
554fde961dbSEli Friedman 
55527da15baSAnders Carlsson void
5567a626f63SJohn McCall CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
5577a626f63SJohn McCall                                       AggValueSlot Dest) {
5587a626f63SJohn McCall   assert(!Dest.isIgnored() && "Must have a destination!");
55927da15baSAnders Carlsson   const CXXConstructorDecl *CD = E->getConstructor();
560630c76efSDouglas Gregor 
561630c76efSDouglas Gregor   // If we require zero initialization before (or instead of) calling the
562630c76efSDouglas Gregor   // constructor, as can be the case with a non-user-provided default
56303535265SArgyrios Kyrtzidis   // constructor, emit the zero initialization now, unless destination is
56403535265SArgyrios Kyrtzidis   // already zeroed.
565fde961dbSEli Friedman   if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
566fde961dbSEli Friedman     switch (E->getConstructionKind()) {
567fde961dbSEli Friedman     case CXXConstructExpr::CK_Delegating:
568fde961dbSEli Friedman     case CXXConstructExpr::CK_Complete:
5697f416cc4SJohn McCall       EmitNullInitialization(Dest.getAddress(), E->getType());
570fde961dbSEli Friedman       break;
571fde961dbSEli Friedman     case CXXConstructExpr::CK_VirtualBase:
572fde961dbSEli Friedman     case CXXConstructExpr::CK_NonVirtualBase:
5737f416cc4SJohn McCall       EmitNullBaseClassInitialization(*this, Dest.getAddress(),
5747f416cc4SJohn McCall                                       CD->getParent());
575fde961dbSEli Friedman       break;
576fde961dbSEli Friedman     }
577fde961dbSEli Friedman   }
578630c76efSDouglas Gregor 
579630c76efSDouglas Gregor   // If this is a call to a trivial default constructor, do nothing.
580630c76efSDouglas Gregor   if (CD->isTrivial() && CD->isDefaultConstructor())
58127da15baSAnders Carlsson     return;
582630c76efSDouglas Gregor 
5838ea46b66SJohn McCall   // Elide the constructor if we're constructing from a temporary.
5848ea46b66SJohn McCall   // The temporary check is required because Sema sets this on NRVO
5858ea46b66SJohn McCall   // returns.
5869c6890a7SRichard Smith   if (getLangOpts().ElideConstructors && E->isElidable()) {
5878ea46b66SJohn McCall     assert(getContext().hasSameUnqualifiedType(E->getType(),
5888ea46b66SJohn McCall                                                E->getArg(0)->getType()));
5897a626f63SJohn McCall     if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
5907a626f63SJohn McCall       EmitAggExpr(E->getArg(0), Dest);
59127da15baSAnders Carlsson       return;
59227da15baSAnders Carlsson     }
593222cf0efSDouglas Gregor   }
594630c76efSDouglas Gregor 
595e7545b33SAlexey Bataev   if (const ArrayType *arrayType
596e7545b33SAlexey Bataev         = getContext().getAsArrayType(E->getType())) {
5977f416cc4SJohn McCall     EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddress(), E);
598f677a8e9SJohn McCall   } else {
599bceca20aSCameron Esfahani     CXXCtorType Type = Ctor_Complete;
600271c3681SAlexis Hunt     bool ForVirtualBase = false;
60161535005SDouglas Gregor     bool Delegating = false;
602271c3681SAlexis Hunt 
603271c3681SAlexis Hunt     switch (E->getConstructionKind()) {
604271c3681SAlexis Hunt      case CXXConstructExpr::CK_Delegating:
60561bc1737SAlexis Hunt       // We should be emitting a constructor; GlobalDecl will assert this
60661bc1737SAlexis Hunt       Type = CurGD.getCtorType();
60761535005SDouglas Gregor       Delegating = true;
608271c3681SAlexis Hunt       break;
60961bc1737SAlexis Hunt 
610271c3681SAlexis Hunt      case CXXConstructExpr::CK_Complete:
611271c3681SAlexis Hunt       Type = Ctor_Complete;
612271c3681SAlexis Hunt       break;
613271c3681SAlexis Hunt 
614271c3681SAlexis Hunt      case CXXConstructExpr::CK_VirtualBase:
615271c3681SAlexis Hunt       ForVirtualBase = true;
616*f3b3ccdaSAdrian Prantl       LLVM_FALLTHROUGH;
617271c3681SAlexis Hunt 
618271c3681SAlexis Hunt      case CXXConstructExpr::CK_NonVirtualBase:
619271c3681SAlexis Hunt       Type = Ctor_Base;
620271c3681SAlexis Hunt     }
621e11f9ce9SAnders Carlsson 
62227da15baSAnders Carlsson     // Call the constructor.
6237f416cc4SJohn McCall     EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating,
6247f416cc4SJohn McCall                            Dest.getAddress(), E);
62527da15baSAnders Carlsson   }
626e11f9ce9SAnders Carlsson }
62727da15baSAnders Carlsson 
6287f416cc4SJohn McCall void CodeGenFunction::EmitSynthesizedCXXCopyCtor(Address Dest, Address Src,
62950198098SFariborz Jahanian                                                  const Expr *Exp) {
6305d413781SJohn McCall   if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
631e988bdacSFariborz Jahanian     Exp = E->getSubExpr();
632e988bdacSFariborz Jahanian   assert(isa<CXXConstructExpr>(Exp) &&
633e988bdacSFariborz Jahanian          "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
634e988bdacSFariborz Jahanian   const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
635e988bdacSFariborz Jahanian   const CXXConstructorDecl *CD = E->getConstructor();
636e988bdacSFariborz Jahanian   RunCleanupsScope Scope(*this);
637e988bdacSFariborz Jahanian 
638e988bdacSFariborz Jahanian   // If we require zero initialization before (or instead of) calling the
639e988bdacSFariborz Jahanian   // constructor, as can be the case with a non-user-provided default
640e988bdacSFariborz Jahanian   // constructor, emit the zero initialization now.
641e988bdacSFariborz Jahanian   // FIXME. Do I still need this for a copy ctor synthesis?
642e988bdacSFariborz Jahanian   if (E->requiresZeroInitialization())
643e988bdacSFariborz Jahanian     EmitNullInitialization(Dest, E->getType());
644e988bdacSFariborz Jahanian 
64599da11cfSChandler Carruth   assert(!getContext().getAsConstantArrayType(E->getType())
64699da11cfSChandler Carruth          && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
647525bf650SAlexey Samsonov   EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E);
648e988bdacSFariborz Jahanian }
649e988bdacSFariborz Jahanian 
6508ed55a54SJohn McCall static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
6518ed55a54SJohn McCall                                         const CXXNewExpr *E) {
65221122cf6SAnders Carlsson   if (!E->isArray())
6533eb55cfeSKen Dyck     return CharUnits::Zero();
65421122cf6SAnders Carlsson 
6557ec4b434SJohn McCall   // No cookie is required if the operator new[] being used is the
6567ec4b434SJohn McCall   // reserved placement operator new[].
6577ec4b434SJohn McCall   if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
6583eb55cfeSKen Dyck     return CharUnits::Zero();
659399f499fSAnders Carlsson 
660284c48ffSJohn McCall   return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
66159486a2dSAnders Carlsson }
66259486a2dSAnders Carlsson 
663036f2f6bSJohn McCall static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
664036f2f6bSJohn McCall                                         const CXXNewExpr *e,
665f862eb6aSSebastian Redl                                         unsigned minElements,
666036f2f6bSJohn McCall                                         llvm::Value *&numElements,
667036f2f6bSJohn McCall                                         llvm::Value *&sizeWithoutCookie) {
668036f2f6bSJohn McCall   QualType type = e->getAllocatedType();
66959486a2dSAnders Carlsson 
670036f2f6bSJohn McCall   if (!e->isArray()) {
671036f2f6bSJohn McCall     CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
672036f2f6bSJohn McCall     sizeWithoutCookie
673036f2f6bSJohn McCall       = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
674036f2f6bSJohn McCall     return sizeWithoutCookie;
67505fc5be3SDouglas Gregor   }
67659486a2dSAnders Carlsson 
677036f2f6bSJohn McCall   // The width of size_t.
678036f2f6bSJohn McCall   unsigned sizeWidth = CGF.SizeTy->getBitWidth();
679036f2f6bSJohn McCall 
6808ed55a54SJohn McCall   // Figure out the cookie size.
681036f2f6bSJohn McCall   llvm::APInt cookieSize(sizeWidth,
682036f2f6bSJohn McCall                          CalculateCookiePadding(CGF, e).getQuantity());
6838ed55a54SJohn McCall 
68459486a2dSAnders Carlsson   // Emit the array size expression.
6857648fb46SArgyrios Kyrtzidis   // We multiply the size of all dimensions for NumElements.
6867648fb46SArgyrios Kyrtzidis   // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
687de0fe07eSJohn McCall   numElements =
688de0fe07eSJohn McCall     ConstantEmitter(CGF).tryEmitAbstract(e->getArraySize(), e->getType());
68907527621SNick Lewycky   if (!numElements)
690036f2f6bSJohn McCall     numElements = CGF.EmitScalarExpr(e->getArraySize());
691036f2f6bSJohn McCall   assert(isa<llvm::IntegerType>(numElements->getType()));
6928ed55a54SJohn McCall 
693036f2f6bSJohn McCall   // The number of elements can be have an arbitrary integer type;
694036f2f6bSJohn McCall   // essentially, we need to multiply it by a constant factor, add a
695036f2f6bSJohn McCall   // cookie size, and verify that the result is representable as a
696036f2f6bSJohn McCall   // size_t.  That's just a gloss, though, and it's wrong in one
697036f2f6bSJohn McCall   // important way: if the count is negative, it's an error even if
698036f2f6bSJohn McCall   // the cookie size would bring the total size >= 0.
6996ab2fa8fSDouglas Gregor   bool isSigned
7006ab2fa8fSDouglas Gregor     = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
7012192fe50SChris Lattner   llvm::IntegerType *numElementsType
702036f2f6bSJohn McCall     = cast<llvm::IntegerType>(numElements->getType());
703036f2f6bSJohn McCall   unsigned numElementsWidth = numElementsType->getBitWidth();
704036f2f6bSJohn McCall 
705036f2f6bSJohn McCall   // Compute the constant factor.
706036f2f6bSJohn McCall   llvm::APInt arraySizeMultiplier(sizeWidth, 1);
7077648fb46SArgyrios Kyrtzidis   while (const ConstantArrayType *CAT
708036f2f6bSJohn McCall              = CGF.getContext().getAsConstantArrayType(type)) {
709036f2f6bSJohn McCall     type = CAT->getElementType();
710036f2f6bSJohn McCall     arraySizeMultiplier *= CAT->getSize();
7117648fb46SArgyrios Kyrtzidis   }
71259486a2dSAnders Carlsson 
713036f2f6bSJohn McCall   CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
714036f2f6bSJohn McCall   llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
715036f2f6bSJohn McCall   typeSizeMultiplier *= arraySizeMultiplier;
716036f2f6bSJohn McCall 
717036f2f6bSJohn McCall   // This will be a size_t.
718036f2f6bSJohn McCall   llvm::Value *size;
71932ac583dSChris Lattner 
72032ac583dSChris Lattner   // If someone is doing 'new int[42]' there is no need to do a dynamic check.
72132ac583dSChris Lattner   // Don't bloat the -O0 code.
722036f2f6bSJohn McCall   if (llvm::ConstantInt *numElementsC =
723036f2f6bSJohn McCall         dyn_cast<llvm::ConstantInt>(numElements)) {
724036f2f6bSJohn McCall     const llvm::APInt &count = numElementsC->getValue();
72532ac583dSChris Lattner 
726036f2f6bSJohn McCall     bool hasAnyOverflow = false;
72732ac583dSChris Lattner 
728036f2f6bSJohn McCall     // If 'count' was a negative number, it's an overflow.
729036f2f6bSJohn McCall     if (isSigned && count.isNegative())
730036f2f6bSJohn McCall       hasAnyOverflow = true;
7318ed55a54SJohn McCall 
732036f2f6bSJohn McCall     // We want to do all this arithmetic in size_t.  If numElements is
733036f2f6bSJohn McCall     // wider than that, check whether it's already too big, and if so,
734036f2f6bSJohn McCall     // overflow.
735036f2f6bSJohn McCall     else if (numElementsWidth > sizeWidth &&
736036f2f6bSJohn McCall              numElementsWidth - sizeWidth > count.countLeadingZeros())
737036f2f6bSJohn McCall       hasAnyOverflow = true;
738036f2f6bSJohn McCall 
739036f2f6bSJohn McCall     // Okay, compute a count at the right width.
740036f2f6bSJohn McCall     llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
741036f2f6bSJohn McCall 
742f862eb6aSSebastian Redl     // If there is a brace-initializer, we cannot allocate fewer elements than
743f862eb6aSSebastian Redl     // there are initializers. If we do, that's treated like an overflow.
744f862eb6aSSebastian Redl     if (adjustedCount.ult(minElements))
745f862eb6aSSebastian Redl       hasAnyOverflow = true;
746f862eb6aSSebastian Redl 
747036f2f6bSJohn McCall     // Scale numElements by that.  This might overflow, but we don't
748036f2f6bSJohn McCall     // care because it only overflows if allocationSize does, too, and
749036f2f6bSJohn McCall     // if that overflows then we shouldn't use this.
750036f2f6bSJohn McCall     numElements = llvm::ConstantInt::get(CGF.SizeTy,
751036f2f6bSJohn McCall                                          adjustedCount * arraySizeMultiplier);
752036f2f6bSJohn McCall 
753036f2f6bSJohn McCall     // Compute the size before cookie, and track whether it overflowed.
754036f2f6bSJohn McCall     bool overflow;
755036f2f6bSJohn McCall     llvm::APInt allocationSize
756036f2f6bSJohn McCall       = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
757036f2f6bSJohn McCall     hasAnyOverflow |= overflow;
758036f2f6bSJohn McCall 
759036f2f6bSJohn McCall     // Add in the cookie, and check whether it's overflowed.
760036f2f6bSJohn McCall     if (cookieSize != 0) {
761036f2f6bSJohn McCall       // Save the current size without a cookie.  This shouldn't be
762036f2f6bSJohn McCall       // used if there was overflow.
763036f2f6bSJohn McCall       sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
764036f2f6bSJohn McCall 
765036f2f6bSJohn McCall       allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
766036f2f6bSJohn McCall       hasAnyOverflow |= overflow;
7678ed55a54SJohn McCall     }
7688ed55a54SJohn McCall 
769036f2f6bSJohn McCall     // On overflow, produce a -1 so operator new will fail.
770455f42c9SAaron Ballman     if (hasAnyOverflow) {
771455f42c9SAaron Ballman       size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
772455f42c9SAaron Ballman     } else {
773036f2f6bSJohn McCall       size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
774455f42c9SAaron Ballman     }
77532ac583dSChris Lattner 
776036f2f6bSJohn McCall   // Otherwise, we might need to use the overflow intrinsics.
7778ed55a54SJohn McCall   } else {
778f862eb6aSSebastian Redl     // There are up to five conditions we need to test for:
779036f2f6bSJohn McCall     // 1) if isSigned, we need to check whether numElements is negative;
780036f2f6bSJohn McCall     // 2) if numElementsWidth > sizeWidth, we need to check whether
781036f2f6bSJohn McCall     //   numElements is larger than something representable in size_t;
782f862eb6aSSebastian Redl     // 3) if minElements > 0, we need to check whether numElements is smaller
783f862eb6aSSebastian Redl     //    than that.
784f862eb6aSSebastian Redl     // 4) we need to compute
785036f2f6bSJohn McCall     //      sizeWithoutCookie := numElements * typeSizeMultiplier
786036f2f6bSJohn McCall     //    and check whether it overflows; and
787f862eb6aSSebastian Redl     // 5) if we need a cookie, we need to compute
788036f2f6bSJohn McCall     //      size := sizeWithoutCookie + cookieSize
789036f2f6bSJohn McCall     //    and check whether it overflows.
7908ed55a54SJohn McCall 
7918a13c418SCraig Topper     llvm::Value *hasOverflow = nullptr;
7928ed55a54SJohn McCall 
793036f2f6bSJohn McCall     // If numElementsWidth > sizeWidth, then one way or another, we're
794036f2f6bSJohn McCall     // going to have to do a comparison for (2), and this happens to
795036f2f6bSJohn McCall     // take care of (1), too.
796036f2f6bSJohn McCall     if (numElementsWidth > sizeWidth) {
797036f2f6bSJohn McCall       llvm::APInt threshold(numElementsWidth, 1);
798036f2f6bSJohn McCall       threshold <<= sizeWidth;
7998ed55a54SJohn McCall 
800036f2f6bSJohn McCall       llvm::Value *thresholdV
801036f2f6bSJohn McCall         = llvm::ConstantInt::get(numElementsType, threshold);
802036f2f6bSJohn McCall 
803036f2f6bSJohn McCall       hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
804036f2f6bSJohn McCall       numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
805036f2f6bSJohn McCall 
806036f2f6bSJohn McCall     // Otherwise, if we're signed, we want to sext up to size_t.
807036f2f6bSJohn McCall     } else if (isSigned) {
808036f2f6bSJohn McCall       if (numElementsWidth < sizeWidth)
809036f2f6bSJohn McCall         numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
810036f2f6bSJohn McCall 
811036f2f6bSJohn McCall       // If there's a non-1 type size multiplier, then we can do the
812036f2f6bSJohn McCall       // signedness check at the same time as we do the multiply
813036f2f6bSJohn McCall       // because a negative number times anything will cause an
814f862eb6aSSebastian Redl       // unsigned overflow.  Otherwise, we have to do it here. But at least
815f862eb6aSSebastian Redl       // in this case, we can subsume the >= minElements check.
816036f2f6bSJohn McCall       if (typeSizeMultiplier == 1)
817036f2f6bSJohn McCall         hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
818f862eb6aSSebastian Redl                               llvm::ConstantInt::get(CGF.SizeTy, minElements));
819036f2f6bSJohn McCall 
820036f2f6bSJohn McCall     // Otherwise, zext up to size_t if necessary.
821036f2f6bSJohn McCall     } else if (numElementsWidth < sizeWidth) {
822036f2f6bSJohn McCall       numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
823036f2f6bSJohn McCall     }
824036f2f6bSJohn McCall 
825036f2f6bSJohn McCall     assert(numElements->getType() == CGF.SizeTy);
826036f2f6bSJohn McCall 
827f862eb6aSSebastian Redl     if (minElements) {
828f862eb6aSSebastian Redl       // Don't allow allocation of fewer elements than we have initializers.
829f862eb6aSSebastian Redl       if (!hasOverflow) {
830f862eb6aSSebastian Redl         hasOverflow = CGF.Builder.CreateICmpULT(numElements,
831f862eb6aSSebastian Redl                               llvm::ConstantInt::get(CGF.SizeTy, minElements));
832f862eb6aSSebastian Redl       } else if (numElementsWidth > sizeWidth) {
833f862eb6aSSebastian Redl         // The other existing overflow subsumes this check.
834f862eb6aSSebastian Redl         // We do an unsigned comparison, since any signed value < -1 is
835f862eb6aSSebastian Redl         // taken care of either above or below.
836f862eb6aSSebastian Redl         hasOverflow = CGF.Builder.CreateOr(hasOverflow,
837f862eb6aSSebastian Redl                           CGF.Builder.CreateICmpULT(numElements,
838f862eb6aSSebastian Redl                               llvm::ConstantInt::get(CGF.SizeTy, minElements)));
839f862eb6aSSebastian Redl       }
840f862eb6aSSebastian Redl     }
841f862eb6aSSebastian Redl 
842036f2f6bSJohn McCall     size = numElements;
843036f2f6bSJohn McCall 
844036f2f6bSJohn McCall     // Multiply by the type size if necessary.  This multiplier
845036f2f6bSJohn McCall     // includes all the factors for nested arrays.
8468ed55a54SJohn McCall     //
847036f2f6bSJohn McCall     // This step also causes numElements to be scaled up by the
848036f2f6bSJohn McCall     // nested-array factor if necessary.  Overflow on this computation
849036f2f6bSJohn McCall     // can be ignored because the result shouldn't be used if
850036f2f6bSJohn McCall     // allocation fails.
851036f2f6bSJohn McCall     if (typeSizeMultiplier != 1) {
852036f2f6bSJohn McCall       llvm::Value *umul_with_overflow
8538d375cefSBenjamin Kramer         = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
8548ed55a54SJohn McCall 
855036f2f6bSJohn McCall       llvm::Value *tsmV =
856036f2f6bSJohn McCall         llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
857036f2f6bSJohn McCall       llvm::Value *result =
85843f9bb73SDavid Blaikie           CGF.Builder.CreateCall(umul_with_overflow, {size, tsmV});
8598ed55a54SJohn McCall 
860036f2f6bSJohn McCall       llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
861036f2f6bSJohn McCall       if (hasOverflow)
862036f2f6bSJohn McCall         hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
8638ed55a54SJohn McCall       else
864036f2f6bSJohn McCall         hasOverflow = overflowed;
86559486a2dSAnders Carlsson 
866036f2f6bSJohn McCall       size = CGF.Builder.CreateExtractValue(result, 0);
867036f2f6bSJohn McCall 
868036f2f6bSJohn McCall       // Also scale up numElements by the array size multiplier.
869036f2f6bSJohn McCall       if (arraySizeMultiplier != 1) {
870036f2f6bSJohn McCall         // If the base element type size is 1, then we can re-use the
871036f2f6bSJohn McCall         // multiply we just did.
872036f2f6bSJohn McCall         if (typeSize.isOne()) {
873036f2f6bSJohn McCall           assert(arraySizeMultiplier == typeSizeMultiplier);
874036f2f6bSJohn McCall           numElements = size;
875036f2f6bSJohn McCall 
876036f2f6bSJohn McCall         // Otherwise we need a separate multiply.
877036f2f6bSJohn McCall         } else {
878036f2f6bSJohn McCall           llvm::Value *asmV =
879036f2f6bSJohn McCall             llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
880036f2f6bSJohn McCall           numElements = CGF.Builder.CreateMul(numElements, asmV);
881036f2f6bSJohn McCall         }
882036f2f6bSJohn McCall       }
883036f2f6bSJohn McCall     } else {
884036f2f6bSJohn McCall       // numElements doesn't need to be scaled.
885036f2f6bSJohn McCall       assert(arraySizeMultiplier == 1);
886036f2f6bSJohn McCall     }
887036f2f6bSJohn McCall 
888036f2f6bSJohn McCall     // Add in the cookie size if necessary.
889036f2f6bSJohn McCall     if (cookieSize != 0) {
890036f2f6bSJohn McCall       sizeWithoutCookie = size;
891036f2f6bSJohn McCall 
892036f2f6bSJohn McCall       llvm::Value *uadd_with_overflow
8938d375cefSBenjamin Kramer         = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
894036f2f6bSJohn McCall 
895036f2f6bSJohn McCall       llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
896036f2f6bSJohn McCall       llvm::Value *result =
89743f9bb73SDavid Blaikie           CGF.Builder.CreateCall(uadd_with_overflow, {size, cookieSizeV});
898036f2f6bSJohn McCall 
899036f2f6bSJohn McCall       llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
900036f2f6bSJohn McCall       if (hasOverflow)
901036f2f6bSJohn McCall         hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
902036f2f6bSJohn McCall       else
903036f2f6bSJohn McCall         hasOverflow = overflowed;
904036f2f6bSJohn McCall 
905036f2f6bSJohn McCall       size = CGF.Builder.CreateExtractValue(result, 0);
906036f2f6bSJohn McCall     }
907036f2f6bSJohn McCall 
908036f2f6bSJohn McCall     // If we had any possibility of dynamic overflow, make a select to
909036f2f6bSJohn McCall     // overwrite 'size' with an all-ones value, which should cause
910036f2f6bSJohn McCall     // operator new to throw.
911036f2f6bSJohn McCall     if (hasOverflow)
912455f42c9SAaron Ballman       size = CGF.Builder.CreateSelect(hasOverflow,
913455f42c9SAaron Ballman                                  llvm::Constant::getAllOnesValue(CGF.SizeTy),
914036f2f6bSJohn McCall                                       size);
915036f2f6bSJohn McCall   }
916036f2f6bSJohn McCall 
917036f2f6bSJohn McCall   if (cookieSize == 0)
918036f2f6bSJohn McCall     sizeWithoutCookie = size;
919036f2f6bSJohn McCall   else
920036f2f6bSJohn McCall     assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
921036f2f6bSJohn McCall 
922036f2f6bSJohn McCall   return size;
92359486a2dSAnders Carlsson }
92459486a2dSAnders Carlsson 
925f862eb6aSSebastian Redl static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
9267f416cc4SJohn McCall                                     QualType AllocType, Address NewPtr) {
9271c96bc5dSRichard Smith   // FIXME: Refactor with EmitExprAsInit.
92847fb9508SJohn McCall   switch (CGF.getEvaluationKind(AllocType)) {
92947fb9508SJohn McCall   case TEK_Scalar:
930a2c1124fSDavid Blaikie     CGF.EmitScalarInit(Init, nullptr,
9317f416cc4SJohn McCall                        CGF.MakeAddrLValue(NewPtr, AllocType), false);
93247fb9508SJohn McCall     return;
93347fb9508SJohn McCall   case TEK_Complex:
9347f416cc4SJohn McCall     CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType),
93547fb9508SJohn McCall                                   /*isInit*/ true);
93647fb9508SJohn McCall     return;
93747fb9508SJohn McCall   case TEK_Aggregate: {
9387a626f63SJohn McCall     AggValueSlot Slot
9397f416cc4SJohn McCall       = AggValueSlot::forAddr(NewPtr, AllocType.getQualifiers(),
9408d6fc958SJohn McCall                               AggValueSlot::IsDestructed,
94146759f4fSJohn McCall                               AggValueSlot::DoesNotNeedGCBarriers,
942615ed1a3SChad Rosier                               AggValueSlot::IsNotAliased);
9437a626f63SJohn McCall     CGF.EmitAggExpr(Init, Slot);
94447fb9508SJohn McCall     return;
9457a626f63SJohn McCall   }
946d5202e09SFariborz Jahanian   }
94747fb9508SJohn McCall   llvm_unreachable("bad evaluation kind");
94847fb9508SJohn McCall }
949d5202e09SFariborz Jahanian 
950fb901c7aSDavid Blaikie void CodeGenFunction::EmitNewArrayInitializer(
951fb901c7aSDavid Blaikie     const CXXNewExpr *E, QualType ElementType, llvm::Type *ElementTy,
9527f416cc4SJohn McCall     Address BeginPtr, llvm::Value *NumElements,
95306a67e2cSRichard Smith     llvm::Value *AllocSizeWithoutCookie) {
95406a67e2cSRichard Smith   // If we have a type with trivial initialization and no initializer,
95506a67e2cSRichard Smith   // there's nothing to do.
9566047f07eSSebastian Redl   if (!E->hasInitializer())
95706a67e2cSRichard Smith     return;
958b66b08efSFariborz Jahanian 
9597f416cc4SJohn McCall   Address CurPtr = BeginPtr;
960d5202e09SFariborz Jahanian 
96106a67e2cSRichard Smith   unsigned InitListElements = 0;
962f862eb6aSSebastian Redl 
963f862eb6aSSebastian Redl   const Expr *Init = E->getInitializer();
9647f416cc4SJohn McCall   Address EndOfInit = Address::invalid();
96506a67e2cSRichard Smith   QualType::DestructionKind DtorKind = ElementType.isDestructedType();
96606a67e2cSRichard Smith   EHScopeStack::stable_iterator Cleanup;
96706a67e2cSRichard Smith   llvm::Instruction *CleanupDominator = nullptr;
9681c96bc5dSRichard Smith 
9697f416cc4SJohn McCall   CharUnits ElementSize = getContext().getTypeSizeInChars(ElementType);
9707f416cc4SJohn McCall   CharUnits ElementAlign =
9717f416cc4SJohn McCall     BeginPtr.getAlignment().alignmentOfArrayElement(ElementSize);
9727f416cc4SJohn McCall 
9730511d23aSRichard Smith   // Attempt to perform zero-initialization using memset.
9740511d23aSRichard Smith   auto TryMemsetInitialization = [&]() -> bool {
9750511d23aSRichard Smith     // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
9760511d23aSRichard Smith     // we can initialize with a memset to -1.
9770511d23aSRichard Smith     if (!CGM.getTypes().isZeroInitializable(ElementType))
9780511d23aSRichard Smith       return false;
9790511d23aSRichard Smith 
9800511d23aSRichard Smith     // Optimization: since zero initialization will just set the memory
9810511d23aSRichard Smith     // to all zeroes, generate a single memset to do it in one shot.
9820511d23aSRichard Smith 
9830511d23aSRichard Smith     // Subtract out the size of any elements we've already initialized.
9840511d23aSRichard Smith     auto *RemainingSize = AllocSizeWithoutCookie;
9850511d23aSRichard Smith     if (InitListElements) {
9860511d23aSRichard Smith       // We know this can't overflow; we check this when doing the allocation.
9870511d23aSRichard Smith       auto *InitializedSize = llvm::ConstantInt::get(
9880511d23aSRichard Smith           RemainingSize->getType(),
9890511d23aSRichard Smith           getContext().getTypeSizeInChars(ElementType).getQuantity() *
9900511d23aSRichard Smith               InitListElements);
9910511d23aSRichard Smith       RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
9920511d23aSRichard Smith     }
9930511d23aSRichard Smith 
9940511d23aSRichard Smith     // Create the memset.
9950511d23aSRichard Smith     Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize, false);
9960511d23aSRichard Smith     return true;
9970511d23aSRichard Smith   };
9980511d23aSRichard Smith 
999f862eb6aSSebastian Redl   // If the initializer is an initializer list, first do the explicit elements.
1000f862eb6aSSebastian Redl   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
10010511d23aSRichard Smith     // Initializing from a (braced) string literal is a special case; the init
10020511d23aSRichard Smith     // list element does not initialize a (single) array element.
10030511d23aSRichard Smith     if (ILE->isStringLiteralInit()) {
10040511d23aSRichard Smith       // Initialize the initial portion of length equal to that of the string
10050511d23aSRichard Smith       // literal. The allocation must be for at least this much; we emitted a
10060511d23aSRichard Smith       // check for that earlier.
10070511d23aSRichard Smith       AggValueSlot Slot =
10080511d23aSRichard Smith           AggValueSlot::forAddr(CurPtr, ElementType.getQualifiers(),
10090511d23aSRichard Smith                                 AggValueSlot::IsDestructed,
10100511d23aSRichard Smith                                 AggValueSlot::DoesNotNeedGCBarriers,
10110511d23aSRichard Smith                                 AggValueSlot::IsNotAliased);
10120511d23aSRichard Smith       EmitAggExpr(ILE->getInit(0), Slot);
10130511d23aSRichard Smith 
10140511d23aSRichard Smith       // Move past these elements.
10150511d23aSRichard Smith       InitListElements =
10160511d23aSRichard Smith           cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe())
10170511d23aSRichard Smith               ->getSize().getZExtValue();
10180511d23aSRichard Smith       CurPtr =
10190511d23aSRichard Smith           Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(),
10200511d23aSRichard Smith                                             Builder.getSize(InitListElements),
10210511d23aSRichard Smith                                             "string.init.end"),
10220511d23aSRichard Smith                   CurPtr.getAlignment().alignmentAtOffset(InitListElements *
10230511d23aSRichard Smith                                                           ElementSize));
10240511d23aSRichard Smith 
10250511d23aSRichard Smith       // Zero out the rest, if any remain.
10260511d23aSRichard Smith       llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
10270511d23aSRichard Smith       if (!ConstNum || !ConstNum->equalsInt(InitListElements)) {
10280511d23aSRichard Smith         bool OK = TryMemsetInitialization();
10290511d23aSRichard Smith         (void)OK;
10300511d23aSRichard Smith         assert(OK && "couldn't memset character type?");
10310511d23aSRichard Smith       }
10320511d23aSRichard Smith       return;
10330511d23aSRichard Smith     }
10340511d23aSRichard Smith 
103506a67e2cSRichard Smith     InitListElements = ILE->getNumInits();
1036f62290a1SChad Rosier 
10371c96bc5dSRichard Smith     // If this is a multi-dimensional array new, we will initialize multiple
10381c96bc5dSRichard Smith     // elements with each init list element.
10391c96bc5dSRichard Smith     QualType AllocType = E->getAllocatedType();
10401c96bc5dSRichard Smith     if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
10411c96bc5dSRichard Smith             AllocType->getAsArrayTypeUnsafe())) {
1042fb901c7aSDavid Blaikie       ElementTy = ConvertTypeForMem(AllocType);
10437f416cc4SJohn McCall       CurPtr = Builder.CreateElementBitCast(CurPtr, ElementTy);
104406a67e2cSRichard Smith       InitListElements *= getContext().getConstantArrayElementCount(CAT);
10451c96bc5dSRichard Smith     }
10461c96bc5dSRichard Smith 
104706a67e2cSRichard Smith     // Enter a partial-destruction Cleanup if necessary.
104806a67e2cSRichard Smith     if (needsEHCleanup(DtorKind)) {
104906a67e2cSRichard Smith       // In principle we could tell the Cleanup where we are more
1050f62290a1SChad Rosier       // directly, but the control flow can get so varied here that it
1051f62290a1SChad Rosier       // would actually be quite complex.  Therefore we go through an
1052f62290a1SChad Rosier       // alloca.
10537f416cc4SJohn McCall       EndOfInit = CreateTempAlloca(BeginPtr.getType(), getPointerAlign(),
10547f416cc4SJohn McCall                                    "array.init.end");
10557f416cc4SJohn McCall       CleanupDominator = Builder.CreateStore(BeginPtr.getPointer(), EndOfInit);
10567f416cc4SJohn McCall       pushIrregularPartialArrayCleanup(BeginPtr.getPointer(), EndOfInit,
10577f416cc4SJohn McCall                                        ElementType, ElementAlign,
105806a67e2cSRichard Smith                                        getDestroyer(DtorKind));
105906a67e2cSRichard Smith       Cleanup = EHStack.stable_begin();
1060f62290a1SChad Rosier     }
1061f62290a1SChad Rosier 
10627f416cc4SJohn McCall     CharUnits StartAlign = CurPtr.getAlignment();
1063f862eb6aSSebastian Redl     for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
1064f62290a1SChad Rosier       // Tell the cleanup that it needs to destroy up to this
1065f62290a1SChad Rosier       // element.  TODO: some of these stores can be trivially
1066f62290a1SChad Rosier       // observed to be unnecessary.
10677f416cc4SJohn McCall       if (EndOfInit.isValid()) {
10687f416cc4SJohn McCall         auto FinishedPtr =
10697f416cc4SJohn McCall           Builder.CreateBitCast(CurPtr.getPointer(), BeginPtr.getType());
10707f416cc4SJohn McCall         Builder.CreateStore(FinishedPtr, EndOfInit);
10717f416cc4SJohn McCall       }
107206a67e2cSRichard Smith       // FIXME: If the last initializer is an incomplete initializer list for
107306a67e2cSRichard Smith       // an array, and we have an array filler, we can fold together the two
107406a67e2cSRichard Smith       // initialization loops.
10751c96bc5dSRichard Smith       StoreAnyExprIntoOneUnit(*this, ILE->getInit(i),
107606a67e2cSRichard Smith                               ILE->getInit(i)->getType(), CurPtr);
10777f416cc4SJohn McCall       CurPtr = Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(),
10787f416cc4SJohn McCall                                                  Builder.getSize(1),
10797f416cc4SJohn McCall                                                  "array.exp.next"),
10807f416cc4SJohn McCall                        StartAlign.alignmentAtOffset((i + 1) * ElementSize));
1081f862eb6aSSebastian Redl     }
1082f862eb6aSSebastian Redl 
1083f862eb6aSSebastian Redl     // The remaining elements are filled with the array filler expression.
1084f862eb6aSSebastian Redl     Init = ILE->getArrayFiller();
10851c96bc5dSRichard Smith 
108606a67e2cSRichard Smith     // Extract the initializer for the individual array elements by pulling
108706a67e2cSRichard Smith     // out the array filler from all the nested initializer lists. This avoids
108806a67e2cSRichard Smith     // generating a nested loop for the initialization.
108906a67e2cSRichard Smith     while (Init && Init->getType()->isConstantArrayType()) {
109006a67e2cSRichard Smith       auto *SubILE = dyn_cast<InitListExpr>(Init);
109106a67e2cSRichard Smith       if (!SubILE)
109206a67e2cSRichard Smith         break;
109306a67e2cSRichard Smith       assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
109406a67e2cSRichard Smith       Init = SubILE->getArrayFiller();
1095f862eb6aSSebastian Redl     }
1096f862eb6aSSebastian Redl 
109706a67e2cSRichard Smith     // Switch back to initializing one base element at a time.
10987f416cc4SJohn McCall     CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr.getType());
1099f62290a1SChad Rosier   }
1100e6c980c4SChandler Carruth 
1101454a7cdfSRichard Smith   // If all elements have already been initialized, skip any further
1102454a7cdfSRichard Smith   // initialization.
1103454a7cdfSRichard Smith   llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
1104454a7cdfSRichard Smith   if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
1105454a7cdfSRichard Smith     // If there was a Cleanup, deactivate it.
1106454a7cdfSRichard Smith     if (CleanupDominator)
1107454a7cdfSRichard Smith       DeactivateCleanupBlock(Cleanup, CleanupDominator);
1108454a7cdfSRichard Smith     return;
1109454a7cdfSRichard Smith   }
1110454a7cdfSRichard Smith 
1111454a7cdfSRichard Smith   assert(Init && "have trailing elements to initialize but no initializer");
1112454a7cdfSRichard Smith 
111306a67e2cSRichard Smith   // If this is a constructor call, try to optimize it out, and failing that
111406a67e2cSRichard Smith   // emit a single loop to initialize all remaining elements.
1115454a7cdfSRichard Smith   if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
11166047f07eSSebastian Redl     CXXConstructorDecl *Ctor = CCE->getConstructor();
1117d153103cSDouglas Gregor     if (Ctor->isTrivial()) {
111805fc5be3SDouglas Gregor       // If new expression did not specify value-initialization, then there
111905fc5be3SDouglas Gregor       // is no initialization.
11206047f07eSSebastian Redl       if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
112105fc5be3SDouglas Gregor         return;
112205fc5be3SDouglas Gregor 
112306a67e2cSRichard Smith       if (TryMemsetInitialization())
11243a202f60SAnders Carlsson         return;
11253a202f60SAnders Carlsson     }
112605fc5be3SDouglas Gregor 
112706a67e2cSRichard Smith     // Store the new Cleanup position for irregular Cleanups.
112806a67e2cSRichard Smith     //
112906a67e2cSRichard Smith     // FIXME: Share this cleanup with the constructor call emission rather than
113006a67e2cSRichard Smith     // having it create a cleanup of its own.
11317f416cc4SJohn McCall     if (EndOfInit.isValid())
11327f416cc4SJohn McCall       Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
113306a67e2cSRichard Smith 
113406a67e2cSRichard Smith     // Emit a constructor call loop to initialize the remaining elements.
113506a67e2cSRichard Smith     if (InitListElements)
113606a67e2cSRichard Smith       NumElements = Builder.CreateSub(
113706a67e2cSRichard Smith           NumElements,
113806a67e2cSRichard Smith           llvm::ConstantInt::get(NumElements->getType(), InitListElements));
113970b9c01bSAlexey Samsonov     EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,
114048ddcf2cSEli Friedman                                CCE->requiresZeroInitialization());
114105fc5be3SDouglas Gregor     return;
11426047f07eSSebastian Redl   }
114306a67e2cSRichard Smith 
114406a67e2cSRichard Smith   // If this is value-initialization, we can usually use memset.
114506a67e2cSRichard Smith   ImplicitValueInitExpr IVIE(ElementType);
1146454a7cdfSRichard Smith   if (isa<ImplicitValueInitExpr>(Init)) {
114706a67e2cSRichard Smith     if (TryMemsetInitialization())
114806a67e2cSRichard Smith       return;
114906a67e2cSRichard Smith 
115006a67e2cSRichard Smith     // Switch to an ImplicitValueInitExpr for the element type. This handles
115106a67e2cSRichard Smith     // only one case: multidimensional array new of pointers to members. In
115206a67e2cSRichard Smith     // all other cases, we already have an initializer for the array element.
115306a67e2cSRichard Smith     Init = &IVIE;
115406a67e2cSRichard Smith   }
115506a67e2cSRichard Smith 
115606a67e2cSRichard Smith   // At this point we should have found an initializer for the individual
115706a67e2cSRichard Smith   // elements of the array.
115806a67e2cSRichard Smith   assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&
115906a67e2cSRichard Smith          "got wrong type of element to initialize");
116006a67e2cSRichard Smith 
1161454a7cdfSRichard Smith   // If we have an empty initializer list, we can usually use memset.
1162454a7cdfSRichard Smith   if (auto *ILE = dyn_cast<InitListExpr>(Init))
1163454a7cdfSRichard Smith     if (ILE->getNumInits() == 0 && TryMemsetInitialization())
1164d5202e09SFariborz Jahanian       return;
116559486a2dSAnders Carlsson 
1166cb77930dSYunzhong Gao   // If we have a struct whose every field is value-initialized, we can
1167cb77930dSYunzhong Gao   // usually use memset.
1168cb77930dSYunzhong Gao   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
1169cb77930dSYunzhong Gao     if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
1170cb77930dSYunzhong Gao       if (RType->getDecl()->isStruct()) {
1171872307e2SRichard Smith         unsigned NumElements = 0;
1172872307e2SRichard Smith         if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RType->getDecl()))
1173872307e2SRichard Smith           NumElements = CXXRD->getNumBases();
1174cb77930dSYunzhong Gao         for (auto *Field : RType->getDecl()->fields())
1175cb77930dSYunzhong Gao           if (!Field->isUnnamedBitfield())
1176872307e2SRichard Smith             ++NumElements;
1177872307e2SRichard Smith         // FIXME: Recurse into nested InitListExprs.
1178872307e2SRichard Smith         if (ILE->getNumInits() == NumElements)
1179cb77930dSYunzhong Gao           for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
1180cb77930dSYunzhong Gao             if (!isa<ImplicitValueInitExpr>(ILE->getInit(i)))
1181872307e2SRichard Smith               --NumElements;
1182872307e2SRichard Smith         if (ILE->getNumInits() == NumElements && TryMemsetInitialization())
1183cb77930dSYunzhong Gao           return;
1184cb77930dSYunzhong Gao       }
1185cb77930dSYunzhong Gao     }
1186cb77930dSYunzhong Gao   }
1187cb77930dSYunzhong Gao 
118806a67e2cSRichard Smith   // Create the loop blocks.
118906a67e2cSRichard Smith   llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
119006a67e2cSRichard Smith   llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
119106a67e2cSRichard Smith   llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
119259486a2dSAnders Carlsson 
119306a67e2cSRichard Smith   // Find the end of the array, hoisted out of the loop.
119406a67e2cSRichard Smith   llvm::Value *EndPtr =
11957f416cc4SJohn McCall     Builder.CreateInBoundsGEP(BeginPtr.getPointer(), NumElements, "array.end");
119606a67e2cSRichard Smith 
119706a67e2cSRichard Smith   // If the number of elements isn't constant, we have to now check if there is
119806a67e2cSRichard Smith   // anything left to initialize.
119906a67e2cSRichard Smith   if (!ConstNum) {
12007f416cc4SJohn McCall     llvm::Value *IsEmpty =
12017f416cc4SJohn McCall       Builder.CreateICmpEQ(CurPtr.getPointer(), EndPtr, "array.isempty");
120206a67e2cSRichard Smith     Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
120306a67e2cSRichard Smith   }
120406a67e2cSRichard Smith 
120506a67e2cSRichard Smith   // Enter the loop.
120606a67e2cSRichard Smith   EmitBlock(LoopBB);
120706a67e2cSRichard Smith 
120806a67e2cSRichard Smith   // Set up the current-element phi.
120906a67e2cSRichard Smith   llvm::PHINode *CurPtrPhi =
12107f416cc4SJohn McCall     Builder.CreatePHI(CurPtr.getType(), 2, "array.cur");
12117f416cc4SJohn McCall   CurPtrPhi->addIncoming(CurPtr.getPointer(), EntryBB);
12127f416cc4SJohn McCall 
12137f416cc4SJohn McCall   CurPtr = Address(CurPtrPhi, ElementAlign);
121406a67e2cSRichard Smith 
121506a67e2cSRichard Smith   // Store the new Cleanup position for irregular Cleanups.
12167f416cc4SJohn McCall   if (EndOfInit.isValid())
12177f416cc4SJohn McCall     Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
121806a67e2cSRichard Smith 
121906a67e2cSRichard Smith   // Enter a partial-destruction Cleanup if necessary.
122006a67e2cSRichard Smith   if (!CleanupDominator && needsEHCleanup(DtorKind)) {
12217f416cc4SJohn McCall     pushRegularPartialArrayCleanup(BeginPtr.getPointer(), CurPtr.getPointer(),
12227f416cc4SJohn McCall                                    ElementType, ElementAlign,
122306a67e2cSRichard Smith                                    getDestroyer(DtorKind));
122406a67e2cSRichard Smith     Cleanup = EHStack.stable_begin();
122506a67e2cSRichard Smith     CleanupDominator = Builder.CreateUnreachable();
122606a67e2cSRichard Smith   }
122706a67e2cSRichard Smith 
122806a67e2cSRichard Smith   // Emit the initializer into this element.
122906a67e2cSRichard Smith   StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr);
123006a67e2cSRichard Smith 
123106a67e2cSRichard Smith   // Leave the Cleanup if we entered one.
123206a67e2cSRichard Smith   if (CleanupDominator) {
123306a67e2cSRichard Smith     DeactivateCleanupBlock(Cleanup, CleanupDominator);
123406a67e2cSRichard Smith     CleanupDominator->eraseFromParent();
123506a67e2cSRichard Smith   }
123606a67e2cSRichard Smith 
123706a67e2cSRichard Smith   // Advance to the next element by adjusting the pointer type as necessary.
123806a67e2cSRichard Smith   llvm::Value *NextPtr =
12397f416cc4SJohn McCall     Builder.CreateConstInBoundsGEP1_32(ElementTy, CurPtr.getPointer(), 1,
12407f416cc4SJohn McCall                                        "array.next");
124106a67e2cSRichard Smith 
124206a67e2cSRichard Smith   // Check whether we've gotten to the end of the array and, if so,
124306a67e2cSRichard Smith   // exit the loop.
124406a67e2cSRichard Smith   llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
124506a67e2cSRichard Smith   Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
124606a67e2cSRichard Smith   CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
124706a67e2cSRichard Smith 
124806a67e2cSRichard Smith   EmitBlock(ContBB);
124906a67e2cSRichard Smith }
125006a67e2cSRichard Smith 
125106a67e2cSRichard Smith static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
1252fb901c7aSDavid Blaikie                                QualType ElementType, llvm::Type *ElementTy,
12537f416cc4SJohn McCall                                Address NewPtr, llvm::Value *NumElements,
125406a67e2cSRichard Smith                                llvm::Value *AllocSizeWithoutCookie) {
12559b479666SDavid Blaikie   ApplyDebugLocation DL(CGF, E);
125606a67e2cSRichard Smith   if (E->isArray())
1257fb901c7aSDavid Blaikie     CGF.EmitNewArrayInitializer(E, ElementType, ElementTy, NewPtr, NumElements,
125806a67e2cSRichard Smith                                 AllocSizeWithoutCookie);
125906a67e2cSRichard Smith   else if (const Expr *Init = E->getInitializer())
126066e4197fSDavid Blaikie     StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
126159486a2dSAnders Carlsson }
126259486a2dSAnders Carlsson 
12638d0dc31dSRichard Smith /// Emit a call to an operator new or operator delete function, as implicitly
12648d0dc31dSRichard Smith /// created by new-expressions and delete-expressions.
12658d0dc31dSRichard Smith static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
1266b92ab1afSJohn McCall                                 const FunctionDecl *CalleeDecl,
12678d0dc31dSRichard Smith                                 const FunctionProtoType *CalleeType,
12688d0dc31dSRichard Smith                                 const CallArgList &Args) {
12698d0dc31dSRichard Smith   llvm::Instruction *CallOrInvoke;
1270b92ab1afSJohn McCall   llvm::Constant *CalleePtr = CGF.CGM.GetAddrOfFunction(CalleeDecl);
1271b92ab1afSJohn McCall   CGCallee Callee = CGCallee::forDirect(CalleePtr, CalleeDecl);
12728d0dc31dSRichard Smith   RValue RV =
1273f770683fSPeter Collingbourne       CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(
1274f770683fSPeter Collingbourne                        Args, CalleeType, /*chainCall=*/false),
1275b92ab1afSJohn McCall                    Callee, ReturnValueSlot(), Args, &CallOrInvoke);
12768d0dc31dSRichard Smith 
12778d0dc31dSRichard Smith   /// C++1y [expr.new]p10:
12788d0dc31dSRichard Smith   ///   [In a new-expression,] an implementation is allowed to omit a call
12798d0dc31dSRichard Smith   ///   to a replaceable global allocation function.
12808d0dc31dSRichard Smith   ///
12818d0dc31dSRichard Smith   /// We model such elidable calls with the 'builtin' attribute.
1282b92ab1afSJohn McCall   llvm::Function *Fn = dyn_cast<llvm::Function>(CalleePtr);
1283b92ab1afSJohn McCall   if (CalleeDecl->isReplaceableGlobalAllocationFunction() &&
12846956d587SRafael Espindola       Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
12858d0dc31dSRichard Smith     // FIXME: Add addAttribute to CallSite.
12868d0dc31dSRichard Smith     if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(CallOrInvoke))
1287de86482cSReid Kleckner       CI->addAttribute(llvm::AttributeList::FunctionIndex,
12888d0dc31dSRichard Smith                        llvm::Attribute::Builtin);
12898d0dc31dSRichard Smith     else if (llvm::InvokeInst *II = dyn_cast<llvm::InvokeInst>(CallOrInvoke))
1290de86482cSReid Kleckner       II->addAttribute(llvm::AttributeList::FunctionIndex,
12918d0dc31dSRichard Smith                        llvm::Attribute::Builtin);
12928d0dc31dSRichard Smith     else
12938d0dc31dSRichard Smith       llvm_unreachable("unexpected kind of call instruction");
12948d0dc31dSRichard Smith   }
12958d0dc31dSRichard Smith 
12968d0dc31dSRichard Smith   return RV;
12978d0dc31dSRichard Smith }
12988d0dc31dSRichard Smith 
1299760520bcSRichard Smith RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
1300760520bcSRichard Smith                                                  const Expr *Arg,
1301760520bcSRichard Smith                                                  bool IsDelete) {
1302760520bcSRichard Smith   CallArgList Args;
1303760520bcSRichard Smith   const Stmt *ArgS = Arg;
1304f05779e2SDavid Blaikie   EmitCallArgs(Args, *Type->param_type_begin(), llvm::makeArrayRef(ArgS));
1305760520bcSRichard Smith   // Find the allocation or deallocation function that we're calling.
1306760520bcSRichard Smith   ASTContext &Ctx = getContext();
1307760520bcSRichard Smith   DeclarationName Name = Ctx.DeclarationNames
1308760520bcSRichard Smith       .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
1309760520bcSRichard Smith   for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
1310599bed75SRichard Smith     if (auto *FD = dyn_cast<FunctionDecl>(Decl))
1311599bed75SRichard Smith       if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
1312760520bcSRichard Smith         return EmitNewDeleteCall(*this, cast<FunctionDecl>(Decl), Type, Args);
1313760520bcSRichard Smith   llvm_unreachable("predeclared global operator new/delete is missing");
1314760520bcSRichard Smith }
1315760520bcSRichard Smith 
13165b34958bSRichard Smith namespace {
13175b34958bSRichard Smith /// The parameters to pass to a usual operator delete.
13185b34958bSRichard Smith struct UsualDeleteParams {
13195b34958bSRichard Smith   bool DestroyingDelete = false;
13205b34958bSRichard Smith   bool Size = false;
13215b34958bSRichard Smith   bool Alignment = false;
13225b34958bSRichard Smith };
13235b34958bSRichard Smith }
13245b34958bSRichard Smith 
13255b34958bSRichard Smith static UsualDeleteParams getUsualDeleteParams(const FunctionDecl *FD) {
13265b34958bSRichard Smith   UsualDeleteParams Params;
13275b34958bSRichard Smith 
13285b34958bSRichard Smith   const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
1329b2f0f057SRichard Smith   auto AI = FPT->param_type_begin(), AE = FPT->param_type_end();
1330e9abe648SDaniel Jasper 
1331b2f0f057SRichard Smith   // The first argument is always a void*.
1332b2f0f057SRichard Smith   ++AI;
1333b2f0f057SRichard Smith 
13345b34958bSRichard Smith   // The next parameter may be a std::destroying_delete_t.
13355b34958bSRichard Smith   if (FD->isDestroyingOperatorDelete()) {
13365b34958bSRichard Smith     Params.DestroyingDelete = true;
13375b34958bSRichard Smith     assert(AI != AE);
13385b34958bSRichard Smith     ++AI;
13395b34958bSRichard Smith   }
1340b2f0f057SRichard Smith 
13415b34958bSRichard Smith   // Figure out what other parameters we should be implicitly passing.
1342b2f0f057SRichard Smith   if (AI != AE && (*AI)->isIntegerType()) {
13435b34958bSRichard Smith     Params.Size = true;
1344b2f0f057SRichard Smith     ++AI;
1345b2f0f057SRichard Smith   }
1346b2f0f057SRichard Smith 
1347b2f0f057SRichard Smith   if (AI != AE && (*AI)->isAlignValT()) {
13485b34958bSRichard Smith     Params.Alignment = true;
1349b2f0f057SRichard Smith     ++AI;
1350b2f0f057SRichard Smith   }
1351b2f0f057SRichard Smith 
1352b2f0f057SRichard Smith   assert(AI == AE && "unexpected usual deallocation function parameter");
13535b34958bSRichard Smith   return Params;
1354b2f0f057SRichard Smith }
1355b2f0f057SRichard Smith 
1356b2f0f057SRichard Smith namespace {
1357b2f0f057SRichard Smith   /// A cleanup to call the given 'operator delete' function upon abnormal
1358b2f0f057SRichard Smith   /// exit from a new expression. Templated on a traits type that deals with
1359b2f0f057SRichard Smith   /// ensuring that the arguments dominate the cleanup if necessary.
1360b2f0f057SRichard Smith   template<typename Traits>
1361b2f0f057SRichard Smith   class CallDeleteDuringNew final : public EHScopeStack::Cleanup {
1362b2f0f057SRichard Smith     /// Type used to hold llvm::Value*s.
1363b2f0f057SRichard Smith     typedef typename Traits::ValueTy ValueTy;
1364b2f0f057SRichard Smith     /// Type used to hold RValues.
1365b2f0f057SRichard Smith     typedef typename Traits::RValueTy RValueTy;
1366b2f0f057SRichard Smith     struct PlacementArg {
1367b2f0f057SRichard Smith       RValueTy ArgValue;
1368b2f0f057SRichard Smith       QualType ArgType;
1369b2f0f057SRichard Smith     };
1370b2f0f057SRichard Smith 
1371b2f0f057SRichard Smith     unsigned NumPlacementArgs : 31;
1372b2f0f057SRichard Smith     unsigned PassAlignmentToPlacementDelete : 1;
1373b2f0f057SRichard Smith     const FunctionDecl *OperatorDelete;
1374b2f0f057SRichard Smith     ValueTy Ptr;
1375b2f0f057SRichard Smith     ValueTy AllocSize;
1376b2f0f057SRichard Smith     CharUnits AllocAlign;
1377b2f0f057SRichard Smith 
1378b2f0f057SRichard Smith     PlacementArg *getPlacementArgs() {
1379b2f0f057SRichard Smith       return reinterpret_cast<PlacementArg *>(this + 1);
1380b2f0f057SRichard Smith     }
1381e9abe648SDaniel Jasper 
1382e9abe648SDaniel Jasper   public:
1383e9abe648SDaniel Jasper     static size_t getExtraSize(size_t NumPlacementArgs) {
1384b2f0f057SRichard Smith       return NumPlacementArgs * sizeof(PlacementArg);
1385e9abe648SDaniel Jasper     }
1386e9abe648SDaniel Jasper 
1387e9abe648SDaniel Jasper     CallDeleteDuringNew(size_t NumPlacementArgs,
1388b2f0f057SRichard Smith                         const FunctionDecl *OperatorDelete, ValueTy Ptr,
1389b2f0f057SRichard Smith                         ValueTy AllocSize, bool PassAlignmentToPlacementDelete,
1390b2f0f057SRichard Smith                         CharUnits AllocAlign)
1391b2f0f057SRichard Smith       : NumPlacementArgs(NumPlacementArgs),
1392b2f0f057SRichard Smith         PassAlignmentToPlacementDelete(PassAlignmentToPlacementDelete),
1393b2f0f057SRichard Smith         OperatorDelete(OperatorDelete), Ptr(Ptr), AllocSize(AllocSize),
1394b2f0f057SRichard Smith         AllocAlign(AllocAlign) {}
1395e9abe648SDaniel Jasper 
1396b2f0f057SRichard Smith     void setPlacementArg(unsigned I, RValueTy Arg, QualType Type) {
1397e9abe648SDaniel Jasper       assert(I < NumPlacementArgs && "index out of range");
1398b2f0f057SRichard Smith       getPlacementArgs()[I] = {Arg, Type};
1399e9abe648SDaniel Jasper     }
1400e9abe648SDaniel Jasper 
1401e9abe648SDaniel Jasper     void Emit(CodeGenFunction &CGF, Flags flags) override {
1402b2f0f057SRichard Smith       const FunctionProtoType *FPT =
1403b2f0f057SRichard Smith           OperatorDelete->getType()->getAs<FunctionProtoType>();
1404e9abe648SDaniel Jasper       CallArgList DeleteArgs;
1405824c2f53SJohn McCall 
14065b34958bSRichard Smith       // The first argument is always a void* (or C* for a destroying operator
14075b34958bSRichard Smith       // delete for class type C).
1408b2f0f057SRichard Smith       DeleteArgs.add(Traits::get(CGF, Ptr), FPT->getParamType(0));
1409189e52fcSRichard Smith 
1410b2f0f057SRichard Smith       // Figure out what other parameters we should be implicitly passing.
14115b34958bSRichard Smith       UsualDeleteParams Params;
1412b2f0f057SRichard Smith       if (NumPlacementArgs) {
1413b2f0f057SRichard Smith         // A placement deallocation function is implicitly passed an alignment
1414b2f0f057SRichard Smith         // if the placement allocation function was, but is never passed a size.
14155b34958bSRichard Smith         Params.Alignment = PassAlignmentToPlacementDelete;
1416b2f0f057SRichard Smith       } else {
1417b2f0f057SRichard Smith         // For a non-placement new-expression, 'operator delete' can take a
1418b2f0f057SRichard Smith         // size and/or an alignment if it has the right parameters.
14195b34958bSRichard Smith         Params = getUsualDeleteParams(OperatorDelete);
1420189e52fcSRichard Smith       }
1421824c2f53SJohn McCall 
14225b34958bSRichard Smith       assert(!Params.DestroyingDelete &&
14235b34958bSRichard Smith              "should not call destroying delete in a new-expression");
14245b34958bSRichard Smith 
1425b2f0f057SRichard Smith       // The second argument can be a std::size_t (for non-placement delete).
14265b34958bSRichard Smith       if (Params.Size)
1427b2f0f057SRichard Smith         DeleteArgs.add(Traits::get(CGF, AllocSize),
1428b2f0f057SRichard Smith                        CGF.getContext().getSizeType());
1429824c2f53SJohn McCall 
1430b2f0f057SRichard Smith       // The next (second or third) argument can be a std::align_val_t, which
1431b2f0f057SRichard Smith       // is an enum whose underlying type is std::size_t.
1432b2f0f057SRichard Smith       // FIXME: Use the right type as the parameter type. Note that in a call
1433b2f0f057SRichard Smith       // to operator delete(size_t, ...), we may not have it available.
14345b34958bSRichard Smith       if (Params.Alignment)
1435b2f0f057SRichard Smith         DeleteArgs.add(RValue::get(llvm::ConstantInt::get(
1436b2f0f057SRichard Smith                            CGF.SizeTy, AllocAlign.getQuantity())),
1437b2f0f057SRichard Smith                        CGF.getContext().getSizeType());
14387f9c92a9SJohn McCall 
14397f9c92a9SJohn McCall       // Pass the rest of the arguments, which must match exactly.
14407f9c92a9SJohn McCall       for (unsigned I = 0; I != NumPlacementArgs; ++I) {
1441b2f0f057SRichard Smith         auto Arg = getPlacementArgs()[I];
1442b2f0f057SRichard Smith         DeleteArgs.add(Traits::get(CGF, Arg.ArgValue), Arg.ArgType);
14437f9c92a9SJohn McCall       }
14447f9c92a9SJohn McCall 
14457f9c92a9SJohn McCall       // Call 'operator delete'.
14468d0dc31dSRichard Smith       EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
14477f9c92a9SJohn McCall     }
14487f9c92a9SJohn McCall   };
1449ab9db510SAlexander Kornienko }
14507f9c92a9SJohn McCall 
14517f9c92a9SJohn McCall /// Enter a cleanup to call 'operator delete' if the initializer in a
14527f9c92a9SJohn McCall /// new-expression throws.
14537f9c92a9SJohn McCall static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
14547f9c92a9SJohn McCall                                   const CXXNewExpr *E,
14557f416cc4SJohn McCall                                   Address NewPtr,
14567f9c92a9SJohn McCall                                   llvm::Value *AllocSize,
1457b2f0f057SRichard Smith                                   CharUnits AllocAlign,
14587f9c92a9SJohn McCall                                   const CallArgList &NewArgs) {
1459b2f0f057SRichard Smith   unsigned NumNonPlacementArgs = E->passAlignment() ? 2 : 1;
1460b2f0f057SRichard Smith 
14617f9c92a9SJohn McCall   // If we're not inside a conditional branch, then the cleanup will
14627f9c92a9SJohn McCall   // dominate and we can do the easier (and more efficient) thing.
14637f9c92a9SJohn McCall   if (!CGF.isInConditionalBranch()) {
1464b2f0f057SRichard Smith     struct DirectCleanupTraits {
1465b2f0f057SRichard Smith       typedef llvm::Value *ValueTy;
1466b2f0f057SRichard Smith       typedef RValue RValueTy;
1467b2f0f057SRichard Smith       static RValue get(CodeGenFunction &, ValueTy V) { return RValue::get(V); }
1468b2f0f057SRichard Smith       static RValue get(CodeGenFunction &, RValueTy V) { return V; }
1469b2f0f057SRichard Smith     };
1470b2f0f057SRichard Smith 
1471b2f0f057SRichard Smith     typedef CallDeleteDuringNew<DirectCleanupTraits> DirectCleanup;
1472b2f0f057SRichard Smith 
1473b2f0f057SRichard Smith     DirectCleanup *Cleanup = CGF.EHStack
1474b2f0f057SRichard Smith       .pushCleanupWithExtra<DirectCleanup>(EHCleanup,
14757f9c92a9SJohn McCall                                            E->getNumPlacementArgs(),
14767f9c92a9SJohn McCall                                            E->getOperatorDelete(),
14777f416cc4SJohn McCall                                            NewPtr.getPointer(),
1478b2f0f057SRichard Smith                                            AllocSize,
1479b2f0f057SRichard Smith                                            E->passAlignment(),
1480b2f0f057SRichard Smith                                            AllocAlign);
1481b2f0f057SRichard Smith     for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
1482b2f0f057SRichard Smith       auto &Arg = NewArgs[I + NumNonPlacementArgs];
1483b2f0f057SRichard Smith       Cleanup->setPlacementArg(I, Arg.RV, Arg.Ty);
1484b2f0f057SRichard Smith     }
14857f9c92a9SJohn McCall 
14867f9c92a9SJohn McCall     return;
14877f9c92a9SJohn McCall   }
14887f9c92a9SJohn McCall 
14897f9c92a9SJohn McCall   // Otherwise, we need to save all this stuff.
1490cb5f77f0SJohn McCall   DominatingValue<RValue>::saved_type SavedNewPtr =
14917f416cc4SJohn McCall     DominatingValue<RValue>::save(CGF, RValue::get(NewPtr.getPointer()));
1492cb5f77f0SJohn McCall   DominatingValue<RValue>::saved_type SavedAllocSize =
1493cb5f77f0SJohn McCall     DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
14947f9c92a9SJohn McCall 
1495b2f0f057SRichard Smith   struct ConditionalCleanupTraits {
1496b2f0f057SRichard Smith     typedef DominatingValue<RValue>::saved_type ValueTy;
1497b2f0f057SRichard Smith     typedef DominatingValue<RValue>::saved_type RValueTy;
1498b2f0f057SRichard Smith     static RValue get(CodeGenFunction &CGF, ValueTy V) {
1499b2f0f057SRichard Smith       return V.restore(CGF);
1500b2f0f057SRichard Smith     }
1501b2f0f057SRichard Smith   };
1502b2f0f057SRichard Smith   typedef CallDeleteDuringNew<ConditionalCleanupTraits> ConditionalCleanup;
1503b2f0f057SRichard Smith 
1504b2f0f057SRichard Smith   ConditionalCleanup *Cleanup = CGF.EHStack
1505b2f0f057SRichard Smith     .pushCleanupWithExtra<ConditionalCleanup>(EHCleanup,
15067f9c92a9SJohn McCall                                               E->getNumPlacementArgs(),
15077f9c92a9SJohn McCall                                               E->getOperatorDelete(),
15087f9c92a9SJohn McCall                                               SavedNewPtr,
1509b2f0f057SRichard Smith                                               SavedAllocSize,
1510b2f0f057SRichard Smith                                               E->passAlignment(),
1511b2f0f057SRichard Smith                                               AllocAlign);
1512b2f0f057SRichard Smith   for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
1513b2f0f057SRichard Smith     auto &Arg = NewArgs[I + NumNonPlacementArgs];
1514b2f0f057SRichard Smith     Cleanup->setPlacementArg(I, DominatingValue<RValue>::save(CGF, Arg.RV),
1515b2f0f057SRichard Smith                              Arg.Ty);
1516b2f0f057SRichard Smith   }
15177f9c92a9SJohn McCall 
1518f4beacd0SJohn McCall   CGF.initFullExprCleanup();
1519824c2f53SJohn McCall }
1520824c2f53SJohn McCall 
152159486a2dSAnders Carlsson llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
152275f9498aSJohn McCall   // The element type being allocated.
152375f9498aSJohn McCall   QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
15248ed55a54SJohn McCall 
152575f9498aSJohn McCall   // 1. Build a call to the allocation function.
152675f9498aSJohn McCall   FunctionDecl *allocator = E->getOperatorNew();
152759486a2dSAnders Carlsson 
1528f862eb6aSSebastian Redl   // If there is a brace-initializer, cannot allocate fewer elements than inits.
1529f862eb6aSSebastian Redl   unsigned minElements = 0;
1530f862eb6aSSebastian Redl   if (E->isArray() && E->hasInitializer()) {
15310511d23aSRichard Smith     const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer());
15320511d23aSRichard Smith     if (ILE && ILE->isStringLiteralInit())
15330511d23aSRichard Smith       minElements =
15340511d23aSRichard Smith           cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe())
15350511d23aSRichard Smith               ->getSize().getZExtValue();
15360511d23aSRichard Smith     else if (ILE)
1537f862eb6aSSebastian Redl       minElements = ILE->getNumInits();
1538f862eb6aSSebastian Redl   }
1539f862eb6aSSebastian Redl 
15408a13c418SCraig Topper   llvm::Value *numElements = nullptr;
15418a13c418SCraig Topper   llvm::Value *allocSizeWithoutCookie = nullptr;
154275f9498aSJohn McCall   llvm::Value *allocSize =
1543f862eb6aSSebastian Redl     EmitCXXNewAllocSize(*this, E, minElements, numElements,
1544f862eb6aSSebastian Redl                         allocSizeWithoutCookie);
1545b2f0f057SRichard Smith   CharUnits allocAlign = getContext().getTypeAlignInChars(allocType);
154659486a2dSAnders Carlsson 
15477f416cc4SJohn McCall   // Emit the allocation call.  If the allocator is a global placement
15487f416cc4SJohn McCall   // operator, just "inline" it directly.
15497f416cc4SJohn McCall   Address allocation = Address::invalid();
15507f416cc4SJohn McCall   CallArgList allocatorArgs;
15517f416cc4SJohn McCall   if (allocator->isReservedGlobalPlacementOperator()) {
155253dcf94dSJohn McCall     assert(E->getNumPlacementArgs() == 1);
155353dcf94dSJohn McCall     const Expr *arg = *E->placement_arguments().begin();
155453dcf94dSJohn McCall 
15558f248234SKrzysztof Parzyszek     LValueBaseInfo BaseInfo;
15568f248234SKrzysztof Parzyszek     allocation = EmitPointerWithAlignment(arg, &BaseInfo);
15577f416cc4SJohn McCall 
15587f416cc4SJohn McCall     // The pointer expression will, in many cases, be an opaque void*.
15597f416cc4SJohn McCall     // In these cases, discard the computed alignment and use the
15607f416cc4SJohn McCall     // formal alignment of the allocated type.
15618f248234SKrzysztof Parzyszek     if (BaseInfo.getAlignmentSource() != AlignmentSource::Decl)
1562b2f0f057SRichard Smith       allocation = Address(allocation.getPointer(), allocAlign);
15637f416cc4SJohn McCall 
156453dcf94dSJohn McCall     // Set up allocatorArgs for the call to operator delete if it's not
156553dcf94dSJohn McCall     // the reserved global operator.
156653dcf94dSJohn McCall     if (E->getOperatorDelete() &&
156753dcf94dSJohn McCall         !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
156853dcf94dSJohn McCall       allocatorArgs.add(RValue::get(allocSize), getContext().getSizeType());
156953dcf94dSJohn McCall       allocatorArgs.add(RValue::get(allocation.getPointer()), arg->getType());
157053dcf94dSJohn McCall     }
157153dcf94dSJohn McCall 
15727f416cc4SJohn McCall   } else {
15737f416cc4SJohn McCall     const FunctionProtoType *allocatorType =
15747f416cc4SJohn McCall       allocator->getType()->castAs<FunctionProtoType>();
1575b2f0f057SRichard Smith     unsigned ParamsToSkip = 0;
15767f416cc4SJohn McCall 
15777f416cc4SJohn McCall     // The allocation size is the first argument.
15787f416cc4SJohn McCall     QualType sizeType = getContext().getSizeType();
157943dca6a8SEli Friedman     allocatorArgs.add(RValue::get(allocSize), sizeType);
1580b2f0f057SRichard Smith     ++ParamsToSkip;
158159486a2dSAnders Carlsson 
1582b2f0f057SRichard Smith     if (allocSize != allocSizeWithoutCookie) {
1583b2f0f057SRichard Smith       CharUnits cookieAlign = getSizeAlign(); // FIXME: Ask the ABI.
1584b2f0f057SRichard Smith       allocAlign = std::max(allocAlign, cookieAlign);
1585b2f0f057SRichard Smith     }
1586b2f0f057SRichard Smith 
1587b2f0f057SRichard Smith     // The allocation alignment may be passed as the second argument.
1588b2f0f057SRichard Smith     if (E->passAlignment()) {
1589b2f0f057SRichard Smith       QualType AlignValT = sizeType;
1590b2f0f057SRichard Smith       if (allocatorType->getNumParams() > 1) {
1591b2f0f057SRichard Smith         AlignValT = allocatorType->getParamType(1);
1592b2f0f057SRichard Smith         assert(getContext().hasSameUnqualifiedType(
1593b2f0f057SRichard Smith                    AlignValT->castAs<EnumType>()->getDecl()->getIntegerType(),
1594b2f0f057SRichard Smith                    sizeType) &&
1595b2f0f057SRichard Smith                "wrong type for alignment parameter");
1596b2f0f057SRichard Smith         ++ParamsToSkip;
1597b2f0f057SRichard Smith       } else {
1598b2f0f057SRichard Smith         // Corner case, passing alignment to 'operator new(size_t, ...)'.
1599b2f0f057SRichard Smith         assert(allocator->isVariadic() && "can't pass alignment to allocator");
1600b2f0f057SRichard Smith       }
1601b2f0f057SRichard Smith       allocatorArgs.add(
1602b2f0f057SRichard Smith           RValue::get(llvm::ConstantInt::get(SizeTy, allocAlign.getQuantity())),
1603b2f0f057SRichard Smith           AlignValT);
1604b2f0f057SRichard Smith     }
1605b2f0f057SRichard Smith 
1606b2f0f057SRichard Smith     // FIXME: Why do we not pass a CalleeDecl here?
1607f05779e2SDavid Blaikie     EmitCallArgs(allocatorArgs, allocatorType, E->placement_arguments(),
1608ed00ea08SVedant Kumar                  /*AC*/AbstractCallee(), /*ParamsToSkip*/ParamsToSkip);
160959486a2dSAnders Carlsson 
16107f416cc4SJohn McCall     RValue RV =
16117f416cc4SJohn McCall       EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
16127f416cc4SJohn McCall 
1613b2f0f057SRichard Smith     // If this was a call to a global replaceable allocation function that does
1614b2f0f057SRichard Smith     // not take an alignment argument, the allocator is known to produce
1615b2f0f057SRichard Smith     // storage that's suitably aligned for any object that fits, up to a known
1616b2f0f057SRichard Smith     // threshold. Otherwise assume it's suitably aligned for the allocated type.
1617b2f0f057SRichard Smith     CharUnits allocationAlign = allocAlign;
1618b2f0f057SRichard Smith     if (!E->passAlignment() &&
1619b2f0f057SRichard Smith         allocator->isReplaceableGlobalAllocationFunction()) {
1620b2f0f057SRichard Smith       unsigned AllocatorAlign = llvm::PowerOf2Floor(std::min<uint64_t>(
1621b2f0f057SRichard Smith           Target.getNewAlign(), getContext().getTypeSize(allocType)));
1622b2f0f057SRichard Smith       allocationAlign = std::max(
1623b2f0f057SRichard Smith           allocationAlign, getContext().toCharUnitsFromBits(AllocatorAlign));
16247f416cc4SJohn McCall     }
16257f416cc4SJohn McCall 
16267f416cc4SJohn McCall     allocation = Address(RV.getScalarVal(), allocationAlign);
16277ec4b434SJohn McCall   }
162859486a2dSAnders Carlsson 
162975f9498aSJohn McCall   // Emit a null check on the allocation result if the allocation
163075f9498aSJohn McCall   // function is allowed to return null (because it has a non-throwing
1631902a0238SRichard Smith   // exception spec or is the reserved placement new) and we have an
163275f9498aSJohn McCall   // interesting initializer.
1633902a0238SRichard Smith   bool nullCheck = E->shouldNullCheckAllocation(getContext()) &&
16346047f07eSSebastian Redl     (!allocType.isPODType(getContext()) || E->hasInitializer());
163559486a2dSAnders Carlsson 
16368a13c418SCraig Topper   llvm::BasicBlock *nullCheckBB = nullptr;
16378a13c418SCraig Topper   llvm::BasicBlock *contBB = nullptr;
163859486a2dSAnders Carlsson 
1639f7dcf320SJohn McCall   // The null-check means that the initializer is conditionally
1640f7dcf320SJohn McCall   // evaluated.
1641f7dcf320SJohn McCall   ConditionalEvaluation conditional(*this);
1642f7dcf320SJohn McCall 
164375f9498aSJohn McCall   if (nullCheck) {
1644f7dcf320SJohn McCall     conditional.begin(*this);
164575f9498aSJohn McCall 
164675f9498aSJohn McCall     nullCheckBB = Builder.GetInsertBlock();
164775f9498aSJohn McCall     llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
164875f9498aSJohn McCall     contBB = createBasicBlock("new.cont");
164975f9498aSJohn McCall 
16507f416cc4SJohn McCall     llvm::Value *isNull =
16517f416cc4SJohn McCall       Builder.CreateIsNull(allocation.getPointer(), "new.isnull");
165275f9498aSJohn McCall     Builder.CreateCondBr(isNull, contBB, notNullBB);
165375f9498aSJohn McCall     EmitBlock(notNullBB);
165459486a2dSAnders Carlsson   }
165559486a2dSAnders Carlsson 
1656824c2f53SJohn McCall   // If there's an operator delete, enter a cleanup to call it if an
1657824c2f53SJohn McCall   // exception is thrown.
165875f9498aSJohn McCall   EHScopeStack::stable_iterator operatorDeleteCleanup;
16598a13c418SCraig Topper   llvm::Instruction *cleanupDominator = nullptr;
16607ec4b434SJohn McCall   if (E->getOperatorDelete() &&
16617ec4b434SJohn McCall       !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
1662b2f0f057SRichard Smith     EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocAlign,
1663b2f0f057SRichard Smith                           allocatorArgs);
166475f9498aSJohn McCall     operatorDeleteCleanup = EHStack.stable_begin();
1665f4beacd0SJohn McCall     cleanupDominator = Builder.CreateUnreachable();
1666824c2f53SJohn McCall   }
1667824c2f53SJohn McCall 
1668cf9b1f65SEli Friedman   assert((allocSize == allocSizeWithoutCookie) ==
1669cf9b1f65SEli Friedman          CalculateCookiePadding(*this, E).isZero());
1670cf9b1f65SEli Friedman   if (allocSize != allocSizeWithoutCookie) {
1671cf9b1f65SEli Friedman     assert(E->isArray());
1672cf9b1f65SEli Friedman     allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1673cf9b1f65SEli Friedman                                                        numElements,
1674cf9b1f65SEli Friedman                                                        E, allocType);
1675cf9b1f65SEli Friedman   }
1676cf9b1f65SEli Friedman 
1677fb901c7aSDavid Blaikie   llvm::Type *elementTy = ConvertTypeForMem(allocType);
16787f416cc4SJohn McCall   Address result = Builder.CreateElementBitCast(allocation, elementTy);
1679824c2f53SJohn McCall 
1680338c9d0aSPiotr Padlewski   // Passing pointer through invariant.group.barrier to avoid propagation of
1681338c9d0aSPiotr Padlewski   // vptrs information which may be included in previous type.
168231fd99cfSPiotr Padlewski   // To not break LTO with different optimizations levels, we do it regardless
168331fd99cfSPiotr Padlewski   // of optimization level.
1684338c9d0aSPiotr Padlewski   if (CGM.getCodeGenOpts().StrictVTablePointers &&
1685338c9d0aSPiotr Padlewski       allocator->isReservedGlobalPlacementOperator())
1686338c9d0aSPiotr Padlewski     result = Address(Builder.CreateInvariantGroupBarrier(result.getPointer()),
1687338c9d0aSPiotr Padlewski                      result.getAlignment());
1688338c9d0aSPiotr Padlewski 
1689fb901c7aSDavid Blaikie   EmitNewInitializer(*this, E, allocType, elementTy, result, numElements,
169099210dc9SJohn McCall                      allocSizeWithoutCookie);
16918ed55a54SJohn McCall   if (E->isArray()) {
16928ed55a54SJohn McCall     // NewPtr is a pointer to the base element type.  If we're
16938ed55a54SJohn McCall     // allocating an array of arrays, we'll need to cast back to the
16948ed55a54SJohn McCall     // array pointer type.
16952192fe50SChris Lattner     llvm::Type *resultType = ConvertTypeForMem(E->getType());
16967f416cc4SJohn McCall     if (result.getType() != resultType)
169775f9498aSJohn McCall       result = Builder.CreateBitCast(result, resultType);
169847b4629bSFariborz Jahanian   }
169959486a2dSAnders Carlsson 
1700824c2f53SJohn McCall   // Deactivate the 'operator delete' cleanup if we finished
1701824c2f53SJohn McCall   // initialization.
1702f4beacd0SJohn McCall   if (operatorDeleteCleanup.isValid()) {
1703f4beacd0SJohn McCall     DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1704f4beacd0SJohn McCall     cleanupDominator->eraseFromParent();
1705f4beacd0SJohn McCall   }
1706824c2f53SJohn McCall 
17077f416cc4SJohn McCall   llvm::Value *resultPtr = result.getPointer();
170875f9498aSJohn McCall   if (nullCheck) {
1709f7dcf320SJohn McCall     conditional.end(*this);
1710f7dcf320SJohn McCall 
171175f9498aSJohn McCall     llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
171275f9498aSJohn McCall     EmitBlock(contBB);
171359486a2dSAnders Carlsson 
17147f416cc4SJohn McCall     llvm::PHINode *PHI = Builder.CreatePHI(resultPtr->getType(), 2);
17157f416cc4SJohn McCall     PHI->addIncoming(resultPtr, notNullBB);
17167f416cc4SJohn McCall     PHI->addIncoming(llvm::Constant::getNullValue(resultPtr->getType()),
171775f9498aSJohn McCall                      nullCheckBB);
171859486a2dSAnders Carlsson 
17197f416cc4SJohn McCall     resultPtr = PHI;
172059486a2dSAnders Carlsson   }
172159486a2dSAnders Carlsson 
17227f416cc4SJohn McCall   return resultPtr;
172359486a2dSAnders Carlsson }
172459486a2dSAnders Carlsson 
172559486a2dSAnders Carlsson void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1726b2f0f057SRichard Smith                                      llvm::Value *Ptr, QualType DeleteTy,
1727b2f0f057SRichard Smith                                      llvm::Value *NumElements,
1728b2f0f057SRichard Smith                                      CharUnits CookieSize) {
1729b2f0f057SRichard Smith   assert((!NumElements && CookieSize.isZero()) ||
1730b2f0f057SRichard Smith          DeleteFD->getOverloadedOperator() == OO_Array_Delete);
17318ed55a54SJohn McCall 
173259486a2dSAnders Carlsson   const FunctionProtoType *DeleteFTy =
173359486a2dSAnders Carlsson     DeleteFD->getType()->getAs<FunctionProtoType>();
173459486a2dSAnders Carlsson 
173559486a2dSAnders Carlsson   CallArgList DeleteArgs;
173659486a2dSAnders Carlsson 
17375b34958bSRichard Smith   auto Params = getUsualDeleteParams(DeleteFD);
1738b2f0f057SRichard Smith   auto ParamTypeIt = DeleteFTy->param_type_begin();
1739b2f0f057SRichard Smith 
1740b2f0f057SRichard Smith   // Pass the pointer itself.
1741b2f0f057SRichard Smith   QualType ArgTy = *ParamTypeIt++;
174259486a2dSAnders Carlsson   llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
174343dca6a8SEli Friedman   DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
174459486a2dSAnders Carlsson 
17455b34958bSRichard Smith   // Pass the std::destroying_delete tag if present.
17465b34958bSRichard Smith   if (Params.DestroyingDelete) {
17475b34958bSRichard Smith     QualType DDTag = *ParamTypeIt++;
17485b34958bSRichard Smith     // Just pass an 'undef'. We expect the tag type to be an empty struct.
17495b34958bSRichard Smith     auto *V = llvm::UndefValue::get(getTypes().ConvertType(DDTag));
17505b34958bSRichard Smith     DeleteArgs.add(RValue::get(V), DDTag);
17515b34958bSRichard Smith   }
17525b34958bSRichard Smith 
1753b2f0f057SRichard Smith   // Pass the size if the delete function has a size_t parameter.
17545b34958bSRichard Smith   if (Params.Size) {
1755b2f0f057SRichard Smith     QualType SizeType = *ParamTypeIt++;
1756b2f0f057SRichard Smith     CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1757b2f0f057SRichard Smith     llvm::Value *Size = llvm::ConstantInt::get(ConvertType(SizeType),
1758b2f0f057SRichard Smith                                                DeleteTypeSize.getQuantity());
1759b2f0f057SRichard Smith 
1760b2f0f057SRichard Smith     // For array new, multiply by the number of elements.
1761b2f0f057SRichard Smith     if (NumElements)
1762b2f0f057SRichard Smith       Size = Builder.CreateMul(Size, NumElements);
1763b2f0f057SRichard Smith 
1764b2f0f057SRichard Smith     // If there is a cookie, add the cookie size.
1765b2f0f057SRichard Smith     if (!CookieSize.isZero())
1766b2f0f057SRichard Smith       Size = Builder.CreateAdd(
1767b2f0f057SRichard Smith           Size, llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity()));
1768b2f0f057SRichard Smith 
1769b2f0f057SRichard Smith     DeleteArgs.add(RValue::get(Size), SizeType);
1770b2f0f057SRichard Smith   }
1771b2f0f057SRichard Smith 
1772b2f0f057SRichard Smith   // Pass the alignment if the delete function has an align_val_t parameter.
17735b34958bSRichard Smith   if (Params.Alignment) {
1774b2f0f057SRichard Smith     QualType AlignValType = *ParamTypeIt++;
1775b2f0f057SRichard Smith     CharUnits DeleteTypeAlign = getContext().toCharUnitsFromBits(
1776b2f0f057SRichard Smith         getContext().getTypeAlignIfKnown(DeleteTy));
1777b2f0f057SRichard Smith     llvm::Value *Align = llvm::ConstantInt::get(ConvertType(AlignValType),
1778b2f0f057SRichard Smith                                                 DeleteTypeAlign.getQuantity());
1779b2f0f057SRichard Smith     DeleteArgs.add(RValue::get(Align), AlignValType);
1780b2f0f057SRichard Smith   }
1781b2f0f057SRichard Smith 
1782b2f0f057SRichard Smith   assert(ParamTypeIt == DeleteFTy->param_type_end() &&
1783b2f0f057SRichard Smith          "unknown parameter to usual delete function");
178459486a2dSAnders Carlsson 
178559486a2dSAnders Carlsson   // Emit the call to delete.
17868d0dc31dSRichard Smith   EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
178759486a2dSAnders Carlsson }
178859486a2dSAnders Carlsson 
17898ed55a54SJohn McCall namespace {
17908ed55a54SJohn McCall   /// Calls the given 'operator delete' on a single object.
17917e70d680SDavid Blaikie   struct CallObjectDelete final : EHScopeStack::Cleanup {
17928ed55a54SJohn McCall     llvm::Value *Ptr;
17938ed55a54SJohn McCall     const FunctionDecl *OperatorDelete;
17948ed55a54SJohn McCall     QualType ElementType;
17958ed55a54SJohn McCall 
17968ed55a54SJohn McCall     CallObjectDelete(llvm::Value *Ptr,
17978ed55a54SJohn McCall                      const FunctionDecl *OperatorDelete,
17988ed55a54SJohn McCall                      QualType ElementType)
17998ed55a54SJohn McCall       : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
18008ed55a54SJohn McCall 
18014f12f10dSCraig Topper     void Emit(CodeGenFunction &CGF, Flags flags) override {
18028ed55a54SJohn McCall       CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
18038ed55a54SJohn McCall     }
18048ed55a54SJohn McCall   };
1805ab9db510SAlexander Kornienko }
18068ed55a54SJohn McCall 
18070c0b6d9aSDavid Majnemer void
18080c0b6d9aSDavid Majnemer CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
18090c0b6d9aSDavid Majnemer                                              llvm::Value *CompletePtr,
18100c0b6d9aSDavid Majnemer                                              QualType ElementType) {
18110c0b6d9aSDavid Majnemer   EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr,
18120c0b6d9aSDavid Majnemer                                         OperatorDelete, ElementType);
18130c0b6d9aSDavid Majnemer }
18140c0b6d9aSDavid Majnemer 
18155b34958bSRichard Smith /// Emit the code for deleting a single object with a destroying operator
18165b34958bSRichard Smith /// delete. If the element type has a non-virtual destructor, Ptr has already
18175b34958bSRichard Smith /// been converted to the type of the parameter of 'operator delete'. Otherwise
18185b34958bSRichard Smith /// Ptr points to an object of the static type.
18195b34958bSRichard Smith static void EmitDestroyingObjectDelete(CodeGenFunction &CGF,
18205b34958bSRichard Smith                                        const CXXDeleteExpr *DE, Address Ptr,
18215b34958bSRichard Smith                                        QualType ElementType) {
18225b34958bSRichard Smith   auto *Dtor = ElementType->getAsCXXRecordDecl()->getDestructor();
18235b34958bSRichard Smith   if (Dtor && Dtor->isVirtual())
18245b34958bSRichard Smith     CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
18255b34958bSRichard Smith                                                 Dtor);
18265b34958bSRichard Smith   else
18275b34958bSRichard Smith     CGF.EmitDeleteCall(DE->getOperatorDelete(), Ptr.getPointer(), ElementType);
18285b34958bSRichard Smith }
18295b34958bSRichard Smith 
18308ed55a54SJohn McCall /// Emit the code for deleting a single object.
18318ed55a54SJohn McCall static void EmitObjectDelete(CodeGenFunction &CGF,
18320868137aSDavid Majnemer                              const CXXDeleteExpr *DE,
18337f416cc4SJohn McCall                              Address Ptr,
18340868137aSDavid Majnemer                              QualType ElementType) {
1835d98f5d78SIvan Krasin   // C++11 [expr.delete]p3:
1836d98f5d78SIvan Krasin   //   If the static type of the object to be deleted is different from its
1837d98f5d78SIvan Krasin   //   dynamic type, the static type shall be a base class of the dynamic type
1838d98f5d78SIvan Krasin   //   of the object to be deleted and the static type shall have a virtual
1839d98f5d78SIvan Krasin   //   destructor or the behavior is undefined.
1840d98f5d78SIvan Krasin   CGF.EmitTypeCheck(CodeGenFunction::TCK_MemberCall,
1841d98f5d78SIvan Krasin                     DE->getExprLoc(), Ptr.getPointer(),
1842d98f5d78SIvan Krasin                     ElementType);
1843d98f5d78SIvan Krasin 
18445b34958bSRichard Smith   const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
18455b34958bSRichard Smith   assert(!OperatorDelete->isDestroyingOperatorDelete());
18465b34958bSRichard Smith 
18478ed55a54SJohn McCall   // Find the destructor for the type, if applicable.  If the
18488ed55a54SJohn McCall   // destructor is virtual, we'll just emit the vcall and return.
18498a13c418SCraig Topper   const CXXDestructorDecl *Dtor = nullptr;
18508ed55a54SJohn McCall   if (const RecordType *RT = ElementType->getAs<RecordType>()) {
18518ed55a54SJohn McCall     CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1852b23533dbSEli Friedman     if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
18538ed55a54SJohn McCall       Dtor = RD->getDestructor();
18548ed55a54SJohn McCall 
18558ed55a54SJohn McCall       if (Dtor->isVirtual()) {
18560868137aSDavid Majnemer         CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
18570868137aSDavid Majnemer                                                     Dtor);
18588ed55a54SJohn McCall         return;
18598ed55a54SJohn McCall       }
18608ed55a54SJohn McCall     }
18618ed55a54SJohn McCall   }
18628ed55a54SJohn McCall 
18638ed55a54SJohn McCall   // Make sure that we call delete even if the dtor throws.
1864e4df6c8dSJohn McCall   // This doesn't have to a conditional cleanup because we're going
1865e4df6c8dSJohn McCall   // to pop it off in a second.
18668ed55a54SJohn McCall   CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
18677f416cc4SJohn McCall                                             Ptr.getPointer(),
18687f416cc4SJohn McCall                                             OperatorDelete, ElementType);
18698ed55a54SJohn McCall 
18708ed55a54SJohn McCall   if (Dtor)
18718ed55a54SJohn McCall     CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
187261535005SDouglas Gregor                               /*ForVirtualBase=*/false,
187361535005SDouglas Gregor                               /*Delegating=*/false,
187461535005SDouglas Gregor                               Ptr);
1875460ce58fSJohn McCall   else if (auto Lifetime = ElementType.getObjCLifetime()) {
1876460ce58fSJohn McCall     switch (Lifetime) {
187731168b07SJohn McCall     case Qualifiers::OCL_None:
187831168b07SJohn McCall     case Qualifiers::OCL_ExplicitNone:
187931168b07SJohn McCall     case Qualifiers::OCL_Autoreleasing:
188031168b07SJohn McCall       break;
188131168b07SJohn McCall 
18827f416cc4SJohn McCall     case Qualifiers::OCL_Strong:
18837f416cc4SJohn McCall       CGF.EmitARCDestroyStrong(Ptr, ARCPreciseLifetime);
188431168b07SJohn McCall       break;
188531168b07SJohn McCall 
188631168b07SJohn McCall     case Qualifiers::OCL_Weak:
188731168b07SJohn McCall       CGF.EmitARCDestroyWeak(Ptr);
188831168b07SJohn McCall       break;
188931168b07SJohn McCall     }
189031168b07SJohn McCall   }
18918ed55a54SJohn McCall 
18928ed55a54SJohn McCall   CGF.PopCleanupBlock();
18938ed55a54SJohn McCall }
18948ed55a54SJohn McCall 
18958ed55a54SJohn McCall namespace {
18968ed55a54SJohn McCall   /// Calls the given 'operator delete' on an array of objects.
18977e70d680SDavid Blaikie   struct CallArrayDelete final : EHScopeStack::Cleanup {
18988ed55a54SJohn McCall     llvm::Value *Ptr;
18998ed55a54SJohn McCall     const FunctionDecl *OperatorDelete;
19008ed55a54SJohn McCall     llvm::Value *NumElements;
19018ed55a54SJohn McCall     QualType ElementType;
19028ed55a54SJohn McCall     CharUnits CookieSize;
19038ed55a54SJohn McCall 
19048ed55a54SJohn McCall     CallArrayDelete(llvm::Value *Ptr,
19058ed55a54SJohn McCall                     const FunctionDecl *OperatorDelete,
19068ed55a54SJohn McCall                     llvm::Value *NumElements,
19078ed55a54SJohn McCall                     QualType ElementType,
19088ed55a54SJohn McCall                     CharUnits CookieSize)
19098ed55a54SJohn McCall       : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
19108ed55a54SJohn McCall         ElementType(ElementType), CookieSize(CookieSize) {}
19118ed55a54SJohn McCall 
19124f12f10dSCraig Topper     void Emit(CodeGenFunction &CGF, Flags flags) override {
1913b2f0f057SRichard Smith       CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType, NumElements,
1914b2f0f057SRichard Smith                          CookieSize);
19158ed55a54SJohn McCall     }
19168ed55a54SJohn McCall   };
1917ab9db510SAlexander Kornienko }
19188ed55a54SJohn McCall 
19198ed55a54SJohn McCall /// Emit the code for deleting an array of objects.
19208ed55a54SJohn McCall static void EmitArrayDelete(CodeGenFunction &CGF,
1921284c48ffSJohn McCall                             const CXXDeleteExpr *E,
19227f416cc4SJohn McCall                             Address deletedPtr,
1923ca2c56f2SJohn McCall                             QualType elementType) {
19248a13c418SCraig Topper   llvm::Value *numElements = nullptr;
19258a13c418SCraig Topper   llvm::Value *allocatedPtr = nullptr;
1926ca2c56f2SJohn McCall   CharUnits cookieSize;
1927ca2c56f2SJohn McCall   CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1928ca2c56f2SJohn McCall                                       numElements, allocatedPtr, cookieSize);
19298ed55a54SJohn McCall 
1930ca2c56f2SJohn McCall   assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
19318ed55a54SJohn McCall 
19328ed55a54SJohn McCall   // Make sure that we call delete even if one of the dtors throws.
1933ca2c56f2SJohn McCall   const FunctionDecl *operatorDelete = E->getOperatorDelete();
19348ed55a54SJohn McCall   CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
1935ca2c56f2SJohn McCall                                            allocatedPtr, operatorDelete,
1936ca2c56f2SJohn McCall                                            numElements, elementType,
1937ca2c56f2SJohn McCall                                            cookieSize);
19388ed55a54SJohn McCall 
1939ca2c56f2SJohn McCall   // Destroy the elements.
1940ca2c56f2SJohn McCall   if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1941ca2c56f2SJohn McCall     assert(numElements && "no element count for a type with a destructor!");
194231168b07SJohn McCall 
19437f416cc4SJohn McCall     CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
19447f416cc4SJohn McCall     CharUnits elementAlign =
19457f416cc4SJohn McCall       deletedPtr.getAlignment().alignmentOfArrayElement(elementSize);
19467f416cc4SJohn McCall 
19477f416cc4SJohn McCall     llvm::Value *arrayBegin = deletedPtr.getPointer();
1948ca2c56f2SJohn McCall     llvm::Value *arrayEnd =
19497f416cc4SJohn McCall       CGF.Builder.CreateInBoundsGEP(arrayBegin, numElements, "delete.end");
195097eab0a2SJohn McCall 
195197eab0a2SJohn McCall     // Note that it is legal to allocate a zero-length array, and we
195297eab0a2SJohn McCall     // can never fold the check away because the length should always
195397eab0a2SJohn McCall     // come from a cookie.
19547f416cc4SJohn McCall     CGF.emitArrayDestroy(arrayBegin, arrayEnd, elementType, elementAlign,
1955ca2c56f2SJohn McCall                          CGF.getDestroyer(dtorKind),
195697eab0a2SJohn McCall                          /*checkZeroLength*/ true,
1957ca2c56f2SJohn McCall                          CGF.needsEHCleanup(dtorKind));
19588ed55a54SJohn McCall   }
19598ed55a54SJohn McCall 
1960ca2c56f2SJohn McCall   // Pop the cleanup block.
19618ed55a54SJohn McCall   CGF.PopCleanupBlock();
19628ed55a54SJohn McCall }
19638ed55a54SJohn McCall 
196459486a2dSAnders Carlsson void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
196559486a2dSAnders Carlsson   const Expr *Arg = E->getArgument();
19667f416cc4SJohn McCall   Address Ptr = EmitPointerWithAlignment(Arg);
196759486a2dSAnders Carlsson 
196859486a2dSAnders Carlsson   // Null check the pointer.
196959486a2dSAnders Carlsson   llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
197059486a2dSAnders Carlsson   llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
197159486a2dSAnders Carlsson 
19727f416cc4SJohn McCall   llvm::Value *IsNull = Builder.CreateIsNull(Ptr.getPointer(), "isnull");
197359486a2dSAnders Carlsson 
197459486a2dSAnders Carlsson   Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
197559486a2dSAnders Carlsson   EmitBlock(DeleteNotNull);
197659486a2dSAnders Carlsson 
19775b34958bSRichard Smith   QualType DeleteTy = E->getDestroyedType();
19785b34958bSRichard Smith 
19795b34958bSRichard Smith   // A destroying operator delete overrides the entire operation of the
19805b34958bSRichard Smith   // delete expression.
19815b34958bSRichard Smith   if (E->getOperatorDelete()->isDestroyingOperatorDelete()) {
19825b34958bSRichard Smith     EmitDestroyingObjectDelete(*this, E, Ptr, DeleteTy);
19835b34958bSRichard Smith     EmitBlock(DeleteEnd);
19845b34958bSRichard Smith     return;
19855b34958bSRichard Smith   }
19865b34958bSRichard Smith 
19878ed55a54SJohn McCall   // We might be deleting a pointer to array.  If so, GEP down to the
19888ed55a54SJohn McCall   // first non-array element.
19898ed55a54SJohn McCall   // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
19908ed55a54SJohn McCall   if (DeleteTy->isConstantArrayType()) {
19918ed55a54SJohn McCall     llvm::Value *Zero = Builder.getInt32(0);
19920e62c1ccSChris Lattner     SmallVector<llvm::Value*,8> GEP;
199359486a2dSAnders Carlsson 
19948ed55a54SJohn McCall     GEP.push_back(Zero); // point at the outermost array
19958ed55a54SJohn McCall 
19968ed55a54SJohn McCall     // For each layer of array type we're pointing at:
19978ed55a54SJohn McCall     while (const ConstantArrayType *Arr
19988ed55a54SJohn McCall              = getContext().getAsConstantArrayType(DeleteTy)) {
19998ed55a54SJohn McCall       // 1. Unpeel the array type.
20008ed55a54SJohn McCall       DeleteTy = Arr->getElementType();
20018ed55a54SJohn McCall 
20028ed55a54SJohn McCall       // 2. GEP to the first element of the array.
20038ed55a54SJohn McCall       GEP.push_back(Zero);
20048ed55a54SJohn McCall     }
20058ed55a54SJohn McCall 
20067f416cc4SJohn McCall     Ptr = Address(Builder.CreateInBoundsGEP(Ptr.getPointer(), GEP, "del.first"),
20077f416cc4SJohn McCall                   Ptr.getAlignment());
20088ed55a54SJohn McCall   }
20098ed55a54SJohn McCall 
20107f416cc4SJohn McCall   assert(ConvertTypeForMem(DeleteTy) == Ptr.getElementType());
20118ed55a54SJohn McCall 
20127270ef57SReid Kleckner   if (E->isArrayForm()) {
20137270ef57SReid Kleckner     EmitArrayDelete(*this, E, Ptr, DeleteTy);
20147270ef57SReid Kleckner   } else {
20157270ef57SReid Kleckner     EmitObjectDelete(*this, E, Ptr, DeleteTy);
20167270ef57SReid Kleckner   }
201759486a2dSAnders Carlsson 
201859486a2dSAnders Carlsson   EmitBlock(DeleteEnd);
201959486a2dSAnders Carlsson }
202059486a2dSAnders Carlsson 
20211c3d95ebSDavid Majnemer static bool isGLValueFromPointerDeref(const Expr *E) {
20221c3d95ebSDavid Majnemer   E = E->IgnoreParens();
20231c3d95ebSDavid Majnemer 
20241c3d95ebSDavid Majnemer   if (const auto *CE = dyn_cast<CastExpr>(E)) {
20251c3d95ebSDavid Majnemer     if (!CE->getSubExpr()->isGLValue())
20261c3d95ebSDavid Majnemer       return false;
20271c3d95ebSDavid Majnemer     return isGLValueFromPointerDeref(CE->getSubExpr());
20281c3d95ebSDavid Majnemer   }
20291c3d95ebSDavid Majnemer 
20301c3d95ebSDavid Majnemer   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
20311c3d95ebSDavid Majnemer     return isGLValueFromPointerDeref(OVE->getSourceExpr());
20321c3d95ebSDavid Majnemer 
20331c3d95ebSDavid Majnemer   if (const auto *BO = dyn_cast<BinaryOperator>(E))
20341c3d95ebSDavid Majnemer     if (BO->getOpcode() == BO_Comma)
20351c3d95ebSDavid Majnemer       return isGLValueFromPointerDeref(BO->getRHS());
20361c3d95ebSDavid Majnemer 
20371c3d95ebSDavid Majnemer   if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E))
20381c3d95ebSDavid Majnemer     return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
20391c3d95ebSDavid Majnemer            isGLValueFromPointerDeref(ACO->getFalseExpr());
20401c3d95ebSDavid Majnemer 
20411c3d95ebSDavid Majnemer   // C++11 [expr.sub]p1:
20421c3d95ebSDavid Majnemer   //   The expression E1[E2] is identical (by definition) to *((E1)+(E2))
20431c3d95ebSDavid Majnemer   if (isa<ArraySubscriptExpr>(E))
20441c3d95ebSDavid Majnemer     return true;
20451c3d95ebSDavid Majnemer 
20461c3d95ebSDavid Majnemer   if (const auto *UO = dyn_cast<UnaryOperator>(E))
20471c3d95ebSDavid Majnemer     if (UO->getOpcode() == UO_Deref)
20481c3d95ebSDavid Majnemer       return true;
20491c3d95ebSDavid Majnemer 
20501c3d95ebSDavid Majnemer   return false;
20511c3d95ebSDavid Majnemer }
20521c3d95ebSDavid Majnemer 
2053747e301eSWarren Hunt static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
20542192fe50SChris Lattner                                          llvm::Type *StdTypeInfoPtrTy) {
2055940f02d2SAnders Carlsson   // Get the vtable pointer.
20567f416cc4SJohn McCall   Address ThisPtr = CGF.EmitLValue(E).getAddress();
2057940f02d2SAnders Carlsson 
2058940f02d2SAnders Carlsson   // C++ [expr.typeid]p2:
2059940f02d2SAnders Carlsson   //   If the glvalue expression is obtained by applying the unary * operator to
2060940f02d2SAnders Carlsson   //   a pointer and the pointer is a null pointer value, the typeid expression
2061940f02d2SAnders Carlsson   //   throws the std::bad_typeid exception.
20621c3d95ebSDavid Majnemer   //
20631c3d95ebSDavid Majnemer   // However, this paragraph's intent is not clear.  We choose a very generous
20641c3d95ebSDavid Majnemer   // interpretation which implores us to consider comma operators, conditional
20651c3d95ebSDavid Majnemer   // operators, parentheses and other such constructs.
20661162d25cSDavid Majnemer   QualType SrcRecordTy = E->getType();
20671c3d95ebSDavid Majnemer   if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(
20681c3d95ebSDavid Majnemer           isGLValueFromPointerDeref(E), SrcRecordTy)) {
2069940f02d2SAnders Carlsson     llvm::BasicBlock *BadTypeidBlock =
2070940f02d2SAnders Carlsson         CGF.createBasicBlock("typeid.bad_typeid");
20711162d25cSDavid Majnemer     llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
2072940f02d2SAnders Carlsson 
20737f416cc4SJohn McCall     llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr.getPointer());
2074940f02d2SAnders Carlsson     CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
2075940f02d2SAnders Carlsson 
2076940f02d2SAnders Carlsson     CGF.EmitBlock(BadTypeidBlock);
20771162d25cSDavid Majnemer     CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
2078940f02d2SAnders Carlsson     CGF.EmitBlock(EndBlock);
2079940f02d2SAnders Carlsson   }
2080940f02d2SAnders Carlsson 
20811162d25cSDavid Majnemer   return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
20821162d25cSDavid Majnemer                                         StdTypeInfoPtrTy);
2083940f02d2SAnders Carlsson }
2084940f02d2SAnders Carlsson 
208559486a2dSAnders Carlsson llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
20862192fe50SChris Lattner   llvm::Type *StdTypeInfoPtrTy =
2087940f02d2SAnders Carlsson     ConvertType(E->getType())->getPointerTo();
2088fd7dfeb7SAnders Carlsson 
20893f4336cbSAnders Carlsson   if (E->isTypeOperand()) {
20903f4336cbSAnders Carlsson     llvm::Constant *TypeInfo =
2091143c55eaSDavid Majnemer         CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
2092940f02d2SAnders Carlsson     return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
20933f4336cbSAnders Carlsson   }
2094fd7dfeb7SAnders Carlsson 
2095940f02d2SAnders Carlsson   // C++ [expr.typeid]p2:
2096940f02d2SAnders Carlsson   //   When typeid is applied to a glvalue expression whose type is a
2097940f02d2SAnders Carlsson   //   polymorphic class type, the result refers to a std::type_info object
2098940f02d2SAnders Carlsson   //   representing the type of the most derived object (that is, the dynamic
2099940f02d2SAnders Carlsson   //   type) to which the glvalue refers.
2100ef8bf436SRichard Smith   if (E->isPotentiallyEvaluated())
2101940f02d2SAnders Carlsson     return EmitTypeidFromVTable(*this, E->getExprOperand(),
2102940f02d2SAnders Carlsson                                 StdTypeInfoPtrTy);
2103940f02d2SAnders Carlsson 
2104940f02d2SAnders Carlsson   QualType OperandTy = E->getExprOperand()->getType();
2105940f02d2SAnders Carlsson   return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
2106940f02d2SAnders Carlsson                                StdTypeInfoPtrTy);
210759486a2dSAnders Carlsson }
210859486a2dSAnders Carlsson 
2109c1c9971cSAnders Carlsson static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
2110c1c9971cSAnders Carlsson                                           QualType DestTy) {
21112192fe50SChris Lattner   llvm::Type *DestLTy = CGF.ConvertType(DestTy);
2112c1c9971cSAnders Carlsson   if (DestTy->isPointerType())
2113c1c9971cSAnders Carlsson     return llvm::Constant::getNullValue(DestLTy);
2114c1c9971cSAnders Carlsson 
2115c1c9971cSAnders Carlsson   /// C++ [expr.dynamic.cast]p9:
2116c1c9971cSAnders Carlsson   ///   A failed cast to reference type throws std::bad_cast
21171162d25cSDavid Majnemer   if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
21181162d25cSDavid Majnemer     return nullptr;
2119c1c9971cSAnders Carlsson 
2120c1c9971cSAnders Carlsson   CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
2121c1c9971cSAnders Carlsson   return llvm::UndefValue::get(DestLTy);
2122c1c9971cSAnders Carlsson }
2123c1c9971cSAnders Carlsson 
21247f416cc4SJohn McCall llvm::Value *CodeGenFunction::EmitDynamicCast(Address ThisAddr,
212559486a2dSAnders Carlsson                                               const CXXDynamicCastExpr *DCE) {
21262bf9b4c0SAlexey Bataev   CGM.EmitExplicitCastExprType(DCE, this);
21273f4336cbSAnders Carlsson   QualType DestTy = DCE->getTypeAsWritten();
21283f4336cbSAnders Carlsson 
2129c1c9971cSAnders Carlsson   if (DCE->isAlwaysNull())
21301162d25cSDavid Majnemer     if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy))
21311162d25cSDavid Majnemer       return T;
2132c1c9971cSAnders Carlsson 
2133c1c9971cSAnders Carlsson   QualType SrcTy = DCE->getSubExpr()->getType();
2134c1c9971cSAnders Carlsson 
21351162d25cSDavid Majnemer   // C++ [expr.dynamic.cast]p7:
21361162d25cSDavid Majnemer   //   If T is "pointer to cv void," then the result is a pointer to the most
21371162d25cSDavid Majnemer   //   derived object pointed to by v.
21381162d25cSDavid Majnemer   const PointerType *DestPTy = DestTy->getAs<PointerType>();
21391162d25cSDavid Majnemer 
21401162d25cSDavid Majnemer   bool isDynamicCastToVoid;
21411162d25cSDavid Majnemer   QualType SrcRecordTy;
21421162d25cSDavid Majnemer   QualType DestRecordTy;
21431162d25cSDavid Majnemer   if (DestPTy) {
21441162d25cSDavid Majnemer     isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType();
21451162d25cSDavid Majnemer     SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
21461162d25cSDavid Majnemer     DestRecordTy = DestPTy->getPointeeType();
21471162d25cSDavid Majnemer   } else {
21481162d25cSDavid Majnemer     isDynamicCastToVoid = false;
21491162d25cSDavid Majnemer     SrcRecordTy = SrcTy;
21501162d25cSDavid Majnemer     DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
21511162d25cSDavid Majnemer   }
21521162d25cSDavid Majnemer 
21531162d25cSDavid Majnemer   assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
21541162d25cSDavid Majnemer 
2155882d790fSAnders Carlsson   // C++ [expr.dynamic.cast]p4:
2156882d790fSAnders Carlsson   //   If the value of v is a null pointer value in the pointer case, the result
2157882d790fSAnders Carlsson   //   is the null pointer value of type T.
21581162d25cSDavid Majnemer   bool ShouldNullCheckSrcValue =
21591162d25cSDavid Majnemer       CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(),
21601162d25cSDavid Majnemer                                                          SrcRecordTy);
216159486a2dSAnders Carlsson 
21628a13c418SCraig Topper   llvm::BasicBlock *CastNull = nullptr;
21638a13c418SCraig Topper   llvm::BasicBlock *CastNotNull = nullptr;
2164882d790fSAnders Carlsson   llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
2165fa8b4955SDouglas Gregor 
2166882d790fSAnders Carlsson   if (ShouldNullCheckSrcValue) {
2167882d790fSAnders Carlsson     CastNull = createBasicBlock("dynamic_cast.null");
2168882d790fSAnders Carlsson     CastNotNull = createBasicBlock("dynamic_cast.notnull");
2169882d790fSAnders Carlsson 
21707f416cc4SJohn McCall     llvm::Value *IsNull = Builder.CreateIsNull(ThisAddr.getPointer());
2171882d790fSAnders Carlsson     Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
2172882d790fSAnders Carlsson     EmitBlock(CastNotNull);
217359486a2dSAnders Carlsson   }
217459486a2dSAnders Carlsson 
21757f416cc4SJohn McCall   llvm::Value *Value;
21761162d25cSDavid Majnemer   if (isDynamicCastToVoid) {
21777f416cc4SJohn McCall     Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, ThisAddr, SrcRecordTy,
21781162d25cSDavid Majnemer                                                   DestTy);
21791162d25cSDavid Majnemer   } else {
21801162d25cSDavid Majnemer     assert(DestRecordTy->isRecordType() &&
21811162d25cSDavid Majnemer            "destination type must be a record type!");
21827f416cc4SJohn McCall     Value = CGM.getCXXABI().EmitDynamicCastCall(*this, ThisAddr, SrcRecordTy,
21831162d25cSDavid Majnemer                                                 DestTy, DestRecordTy, CastEnd);
218467528eaaSDavid Majnemer     CastNotNull = Builder.GetInsertBlock();
21851162d25cSDavid Majnemer   }
21863f4336cbSAnders Carlsson 
2187882d790fSAnders Carlsson   if (ShouldNullCheckSrcValue) {
2188882d790fSAnders Carlsson     EmitBranch(CastEnd);
218959486a2dSAnders Carlsson 
2190882d790fSAnders Carlsson     EmitBlock(CastNull);
2191882d790fSAnders Carlsson     EmitBranch(CastEnd);
219259486a2dSAnders Carlsson   }
219359486a2dSAnders Carlsson 
2194882d790fSAnders Carlsson   EmitBlock(CastEnd);
219559486a2dSAnders Carlsson 
2196882d790fSAnders Carlsson   if (ShouldNullCheckSrcValue) {
2197882d790fSAnders Carlsson     llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
2198882d790fSAnders Carlsson     PHI->addIncoming(Value, CastNotNull);
2199882d790fSAnders Carlsson     PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
220059486a2dSAnders Carlsson 
2201882d790fSAnders Carlsson     Value = PHI;
220259486a2dSAnders Carlsson   }
220359486a2dSAnders Carlsson 
2204882d790fSAnders Carlsson   return Value;
220559486a2dSAnders Carlsson }
2206c370a7eeSEli Friedman 
2207c370a7eeSEli Friedman void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
22088631f3e8SEli Friedman   RunCleanupsScope Scope(*this);
22097f416cc4SJohn McCall   LValue SlotLV = MakeAddrLValue(Slot.getAddress(), E->getType());
22108631f3e8SEli Friedman 
2211c370a7eeSEli Friedman   CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
221253c7616eSJames Y Knight   for (LambdaExpr::const_capture_init_iterator i = E->capture_init_begin(),
2213c370a7eeSEli Friedman                                                e = E->capture_init_end();
2214c370a7eeSEli Friedman        i != e; ++i, ++CurField) {
2215c370a7eeSEli Friedman     // Emit initialization
221640ed2973SDavid Blaikie     LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
221739c81e28SAlexey Bataev     if (CurField->hasCapturedVLAType()) {
221839c81e28SAlexey Bataev       auto VAT = CurField->getCapturedVLAType();
221939c81e28SAlexey Bataev       EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
222039c81e28SAlexey Bataev     } else {
222130e304e2SRichard Smith       EmitInitializerForField(*CurField, LV, *i);
2222c370a7eeSEli Friedman     }
2223c370a7eeSEli Friedman   }
222439c81e28SAlexey Bataev }
2225