]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/CodeGen/CGExprCXX.cpp
Merge clang trunk r321017 to contrib/llvm/tools/clang.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / CodeGen / CGExprCXX.cpp
1 //===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This contains code dealing with code generation of C++ expressions
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "CodeGenFunction.h"
15 #include "CGCUDARuntime.h"
16 #include "CGCXXABI.h"
17 #include "CGDebugInfo.h"
18 #include "CGObjCRuntime.h"
19 #include "ConstantEmitter.h"
20 #include "clang/CodeGen/CGFunctionInfo.h"
21 #include "clang/Frontend/CodeGenOptions.h"
22 #include "llvm/IR/CallSite.h"
23 #include "llvm/IR/Intrinsics.h"
24
25 using namespace clang;
26 using namespace CodeGen;
27
28 namespace {
29 struct MemberCallInfo {
30   RequiredArgs ReqArgs;
31   // Number of prefix arguments for the call. Ignores the `this` pointer.
32   unsigned PrefixSize;
33 };
34 }
35
36 static MemberCallInfo
37 commonEmitCXXMemberOrOperatorCall(CodeGenFunction &CGF, const CXXMethodDecl *MD,
38                                   llvm::Value *This, llvm::Value *ImplicitParam,
39                                   QualType ImplicitParamTy, const CallExpr *CE,
40                                   CallArgList &Args, CallArgList *RtlArgs) {
41   assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) ||
42          isa<CXXOperatorCallExpr>(CE));
43   assert(MD->isInstance() &&
44          "Trying to emit a member or operator call expr on a static method!");
45   ASTContext &C = CGF.getContext();
46
47   // Push the this ptr.
48   const CXXRecordDecl *RD =
49       CGF.CGM.getCXXABI().getThisArgumentTypeForMethod(MD);
50   Args.add(RValue::get(This),
51            RD ? C.getPointerType(C.getTypeDeclType(RD)) : C.VoidPtrTy);
52
53   // If there is an implicit parameter (e.g. VTT), emit it.
54   if (ImplicitParam) {
55     Args.add(RValue::get(ImplicitParam), ImplicitParamTy);
56   }
57
58   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
59   RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size(), MD);
60   unsigned PrefixSize = Args.size() - 1;
61
62   // And the rest of the call args.
63   if (RtlArgs) {
64     // Special case: if the caller emitted the arguments right-to-left already
65     // (prior to emitting the *this argument), we're done. This happens for
66     // assignment operators.
67     Args.addFrom(*RtlArgs);
68   } else if (CE) {
69     // Special case: skip first argument of CXXOperatorCall (it is "this").
70     unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0;
71     CGF.EmitCallArgs(Args, FPT, drop_begin(CE->arguments(), ArgsToSkip),
72                      CE->getDirectCallee());
73   } else {
74     assert(
75         FPT->getNumParams() == 0 &&
76         "No CallExpr specified for function with non-zero number of arguments");
77   }
78   return {required, PrefixSize};
79 }
80
81 RValue CodeGenFunction::EmitCXXMemberOrOperatorCall(
82     const CXXMethodDecl *MD, const CGCallee &Callee,
83     ReturnValueSlot ReturnValue,
84     llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,
85     const CallExpr *CE, CallArgList *RtlArgs) {
86   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
87   CallArgList Args;
88   MemberCallInfo CallInfo = commonEmitCXXMemberOrOperatorCall(
89       *this, MD, This, ImplicitParam, ImplicitParamTy, CE, Args, RtlArgs);
90   auto &FnInfo = CGM.getTypes().arrangeCXXMethodCall(
91       Args, FPT, CallInfo.ReqArgs, CallInfo.PrefixSize);
92   return EmitCall(FnInfo, Callee, ReturnValue, Args);
93 }
94
95 RValue CodeGenFunction::EmitCXXDestructorCall(
96     const CXXDestructorDecl *DD, const CGCallee &Callee, llvm::Value *This,
97     llvm::Value *ImplicitParam, QualType ImplicitParamTy, const CallExpr *CE,
98     StructorType Type) {
99   CallArgList Args;
100   commonEmitCXXMemberOrOperatorCall(*this, DD, This, ImplicitParam,
101                                     ImplicitParamTy, CE, Args, nullptr);
102   return EmitCall(CGM.getTypes().arrangeCXXStructorDeclaration(DD, Type),
103                   Callee, ReturnValueSlot(), Args);
104 }
105
106 RValue CodeGenFunction::EmitCXXPseudoDestructorExpr(
107                                             const CXXPseudoDestructorExpr *E) {
108   QualType DestroyedType = E->getDestroyedType();
109   if (DestroyedType.hasStrongOrWeakObjCLifetime()) {
110     // Automatic Reference Counting:
111     //   If the pseudo-expression names a retainable object with weak or
112     //   strong lifetime, the object shall be released.
113     Expr *BaseExpr = E->getBase();
114     Address BaseValue = Address::invalid();
115     Qualifiers BaseQuals;
116
117     // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
118     if (E->isArrow()) {
119       BaseValue = EmitPointerWithAlignment(BaseExpr);
120       const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>();
121       BaseQuals = PTy->getPointeeType().getQualifiers();
122     } else {
123       LValue BaseLV = EmitLValue(BaseExpr);
124       BaseValue = BaseLV.getAddress();
125       QualType BaseTy = BaseExpr->getType();
126       BaseQuals = BaseTy.getQualifiers();
127     }
128
129     switch (DestroyedType.getObjCLifetime()) {
130     case Qualifiers::OCL_None:
131     case Qualifiers::OCL_ExplicitNone:
132     case Qualifiers::OCL_Autoreleasing:
133       break;
134
135     case Qualifiers::OCL_Strong:
136       EmitARCRelease(Builder.CreateLoad(BaseValue,
137                         DestroyedType.isVolatileQualified()),
138                      ARCPreciseLifetime);
139       break;
140
141     case Qualifiers::OCL_Weak:
142       EmitARCDestroyWeak(BaseValue);
143       break;
144     }
145   } else {
146     // C++ [expr.pseudo]p1:
147     //   The result shall only be used as the operand for the function call
148     //   operator (), and the result of such a call has type void. The only
149     //   effect is the evaluation of the postfix-expression before the dot or
150     //   arrow.
151     EmitIgnoredExpr(E->getBase());
152   }
153
154   return RValue::get(nullptr);
155 }
156
157 static CXXRecordDecl *getCXXRecord(const Expr *E) {
158   QualType T = E->getType();
159   if (const PointerType *PTy = T->getAs<PointerType>())
160     T = PTy->getPointeeType();
161   const RecordType *Ty = T->castAs<RecordType>();
162   return cast<CXXRecordDecl>(Ty->getDecl());
163 }
164
165 // Note: This function also emit constructor calls to support a MSVC
166 // extensions allowing explicit constructor function call.
167 RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
168                                               ReturnValueSlot ReturnValue) {
169   const Expr *callee = CE->getCallee()->IgnoreParens();
170
171   if (isa<BinaryOperator>(callee))
172     return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
173
174   const MemberExpr *ME = cast<MemberExpr>(callee);
175   const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
176
177   if (MD->isStatic()) {
178     // The method is static, emit it as we would a regular call.
179     CGCallee callee = CGCallee::forDirect(CGM.GetAddrOfFunction(MD), MD);
180     return EmitCall(getContext().getPointerType(MD->getType()), callee, CE,
181                     ReturnValue);
182   }
183
184   bool HasQualifier = ME->hasQualifier();
185   NestedNameSpecifier *Qualifier = HasQualifier ? ME->getQualifier() : nullptr;
186   bool IsArrow = ME->isArrow();
187   const Expr *Base = ME->getBase();
188
189   return EmitCXXMemberOrOperatorMemberCallExpr(
190       CE, MD, ReturnValue, HasQualifier, Qualifier, IsArrow, Base);
191 }
192
193 RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr(
194     const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue,
195     bool HasQualifier, NestedNameSpecifier *Qualifier, bool IsArrow,
196     const Expr *Base) {
197   assert(isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE));
198
199   // Compute the object pointer.
200   bool CanUseVirtualCall = MD->isVirtual() && !HasQualifier;
201
202   const CXXMethodDecl *DevirtualizedMethod = nullptr;
203   if (CanUseVirtualCall &&
204       MD->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) {
205     const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
206     DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
207     assert(DevirtualizedMethod);
208     const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
209     const Expr *Inner = Base->ignoreParenBaseCasts();
210     if (DevirtualizedMethod->getReturnType().getCanonicalType() !=
211         MD->getReturnType().getCanonicalType())
212       // If the return types are not the same, this might be a case where more
213       // code needs to run to compensate for it. For example, the derived
214       // method might return a type that inherits form from the return
215       // type of MD and has a prefix.
216       // For now we just avoid devirtualizing these covariant cases.
217       DevirtualizedMethod = nullptr;
218     else if (getCXXRecord(Inner) == DevirtualizedClass)
219       // If the class of the Inner expression is where the dynamic method
220       // is defined, build the this pointer from it.
221       Base = Inner;
222     else if (getCXXRecord(Base) != DevirtualizedClass) {
223       // If the method is defined in a class that is not the best dynamic
224       // one or the one of the full expression, we would have to build
225       // a derived-to-base cast to compute the correct this pointer, but
226       // we don't have support for that yet, so do a virtual call.
227       DevirtualizedMethod = nullptr;
228     }
229   }
230
231   // C++17 demands that we evaluate the RHS of a (possibly-compound) assignment
232   // operator before the LHS.
233   CallArgList RtlArgStorage;
234   CallArgList *RtlArgs = nullptr;
235   if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
236     if (OCE->isAssignmentOp()) {
237       RtlArgs = &RtlArgStorage;
238       EmitCallArgs(*RtlArgs, MD->getType()->castAs<FunctionProtoType>(),
239                    drop_begin(CE->arguments(), 1), CE->getDirectCallee(),
240                    /*ParamsToSkip*/0, EvaluationOrder::ForceRightToLeft);
241     }
242   }
243
244   Address This = Address::invalid();
245   if (IsArrow)
246     This = EmitPointerWithAlignment(Base);
247   else
248     This = EmitLValue(Base).getAddress();
249
250
251   if (MD->isTrivial() || (MD->isDefaulted() && MD->getParent()->isUnion())) {
252     if (isa<CXXDestructorDecl>(MD)) return RValue::get(nullptr);
253     if (isa<CXXConstructorDecl>(MD) && 
254         cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
255       return RValue::get(nullptr);
256
257     if (!MD->getParent()->mayInsertExtraPadding()) {
258       if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
259         // We don't like to generate the trivial copy/move assignment operator
260         // when it isn't necessary; just produce the proper effect here.
261         LValue RHS = isa<CXXOperatorCallExpr>(CE)
262                          ? MakeNaturalAlignAddrLValue(
263                                (*RtlArgs)[0].RV.getScalarVal(),
264                                (*(CE->arg_begin() + 1))->getType())
265                          : EmitLValue(*CE->arg_begin());
266         EmitAggregateAssign(This, RHS.getAddress(), CE->getType());
267         return RValue::get(This.getPointer());
268       }
269
270       if (isa<CXXConstructorDecl>(MD) &&
271           cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
272         // Trivial move and copy ctor are the same.
273         assert(CE->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
274         Address RHS = EmitLValue(*CE->arg_begin()).getAddress();
275         EmitAggregateCopy(This, RHS, (*CE->arg_begin())->getType());
276         return RValue::get(This.getPointer());
277       }
278       llvm_unreachable("unknown trivial member function");
279     }
280   }
281
282   // Compute the function type we're calling.
283   const CXXMethodDecl *CalleeDecl =
284       DevirtualizedMethod ? DevirtualizedMethod : MD;
285   const CGFunctionInfo *FInfo = nullptr;
286   if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
287     FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
288         Dtor, StructorType::Complete);
289   else if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(CalleeDecl))
290     FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
291         Ctor, StructorType::Complete);
292   else
293     FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
294
295   llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
296
297   // C++11 [class.mfct.non-static]p2:
298   //   If a non-static member function of a class X is called for an object that
299   //   is not of type X, or of a type derived from X, the behavior is undefined.
300   SourceLocation CallLoc;
301   ASTContext &C = getContext();
302   if (CE)
303     CallLoc = CE->getExprLoc();
304
305   SanitizerSet SkippedChecks;
306   if (const auto *CMCE = dyn_cast<CXXMemberCallExpr>(CE)) {
307     auto *IOA = CMCE->getImplicitObjectArgument();
308     bool IsImplicitObjectCXXThis = IsWrappedCXXThis(IOA);
309     if (IsImplicitObjectCXXThis)
310       SkippedChecks.set(SanitizerKind::Alignment, true);
311     if (IsImplicitObjectCXXThis || isa<DeclRefExpr>(IOA))
312       SkippedChecks.set(SanitizerKind::Null, true);
313   }
314   EmitTypeCheck(
315       isa<CXXConstructorDecl>(CalleeDecl) ? CodeGenFunction::TCK_ConstructorCall
316                                           : CodeGenFunction::TCK_MemberCall,
317       CallLoc, This.getPointer(), C.getRecordType(CalleeDecl->getParent()),
318       /*Alignment=*/CharUnits::Zero(), SkippedChecks);
319
320   // FIXME: Uses of 'MD' past this point need to be audited. We may need to use
321   // 'CalleeDecl' instead.
322
323   // C++ [class.virtual]p12:
324   //   Explicit qualification with the scope operator (5.1) suppresses the
325   //   virtual call mechanism.
326   //
327   // We also don't emit a virtual call if the base expression has a record type
328   // because then we know what the type is.
329   bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
330   
331   if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
332     assert(CE->arg_begin() == CE->arg_end() &&
333            "Destructor shouldn't have explicit parameters");
334     assert(ReturnValue.isNull() && "Destructor shouldn't have return value");
335     if (UseVirtualCall) {
336       CGM.getCXXABI().EmitVirtualDestructorCall(
337           *this, Dtor, Dtor_Complete, This, cast<CXXMemberCallExpr>(CE));
338     } else {
339       CGCallee Callee;
340       if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
341         Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
342       else if (!DevirtualizedMethod)
343         Callee = CGCallee::forDirect(
344             CGM.getAddrOfCXXStructor(Dtor, StructorType::Complete, FInfo, Ty),
345                                      Dtor);
346       else {
347         const CXXDestructorDecl *DDtor =
348           cast<CXXDestructorDecl>(DevirtualizedMethod);
349         Callee = CGCallee::forDirect(
350                   CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty),
351                                      DDtor);
352       }
353       EmitCXXMemberOrOperatorCall(
354           CalleeDecl, Callee, ReturnValue, This.getPointer(),
355           /*ImplicitParam=*/nullptr, QualType(), CE, nullptr);
356     }
357     return RValue::get(nullptr);
358   }
359   
360   CGCallee Callee;
361   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
362     Callee = CGCallee::forDirect(
363                   CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty),
364                                  Ctor);
365   } else if (UseVirtualCall) {
366     Callee = CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, Ty,
367                                                        CE->getLocStart());
368   } else {
369     if (SanOpts.has(SanitizerKind::CFINVCall) &&
370         MD->getParent()->isDynamicClass()) {
371       llvm::Value *VTable;
372       const CXXRecordDecl *RD;
373       std::tie(VTable, RD) =
374           CGM.getCXXABI().LoadVTablePtr(*this, This, MD->getParent());
375       EmitVTablePtrCheckForCall(RD, VTable, CFITCK_NVCall, CE->getLocStart());
376     }
377
378     if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
379       Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
380     else if (!DevirtualizedMethod)
381       Callee = CGCallee::forDirect(CGM.GetAddrOfFunction(MD, Ty), MD);
382     else {
383       Callee = CGCallee::forDirect(
384                                 CGM.GetAddrOfFunction(DevirtualizedMethod, Ty),
385                                    DevirtualizedMethod);
386     }
387   }
388
389   if (MD->isVirtual()) {
390     This = CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
391         *this, CalleeDecl, This, UseVirtualCall);
392   }
393
394   return EmitCXXMemberOrOperatorCall(
395       CalleeDecl, Callee, ReturnValue, This.getPointer(),
396       /*ImplicitParam=*/nullptr, QualType(), CE, RtlArgs);
397 }
398
399 RValue
400 CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
401                                               ReturnValueSlot ReturnValue) {
402   const BinaryOperator *BO =
403       cast<BinaryOperator>(E->getCallee()->IgnoreParens());
404   const Expr *BaseExpr = BO->getLHS();
405   const Expr *MemFnExpr = BO->getRHS();
406   
407   const MemberPointerType *MPT = 
408     MemFnExpr->getType()->castAs<MemberPointerType>();
409
410   const FunctionProtoType *FPT = 
411     MPT->getPointeeType()->castAs<FunctionProtoType>();
412   const CXXRecordDecl *RD = 
413     cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
414
415   // Emit the 'this' pointer.
416   Address This = Address::invalid();
417   if (BO->getOpcode() == BO_PtrMemI)
418     This = EmitPointerWithAlignment(BaseExpr);
419   else 
420     This = EmitLValue(BaseExpr).getAddress();
421
422   EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This.getPointer(),
423                 QualType(MPT->getClass(), 0));
424
425   // Get the member function pointer.
426   llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
427
428   // Ask the ABI to load the callee.  Note that This is modified.
429   llvm::Value *ThisPtrForCall = nullptr;
430   CGCallee Callee =
431     CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This,
432                                              ThisPtrForCall, MemFnPtr, MPT);
433   
434   CallArgList Args;
435
436   QualType ThisType = 
437     getContext().getPointerType(getContext().getTagDeclType(RD));
438
439   // Push the this ptr.
440   Args.add(RValue::get(ThisPtrForCall), ThisType);
441
442   RequiredArgs required =
443       RequiredArgs::forPrototypePlus(FPT, 1, /*FD=*/nullptr);
444
445   // And the rest of the call args
446   EmitCallArgs(Args, FPT, E->arguments());
447   return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required,
448                                                       /*PrefixSize=*/0),
449                   Callee, ReturnValue, Args);
450 }
451
452 RValue
453 CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
454                                                const CXXMethodDecl *MD,
455                                                ReturnValueSlot ReturnValue) {
456   assert(MD->isInstance() &&
457          "Trying to emit a member call expr on a static method!");
458   return EmitCXXMemberOrOperatorMemberCallExpr(
459       E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr,
460       /*IsArrow=*/false, E->getArg(0));
461 }
462
463 RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
464                                                ReturnValueSlot ReturnValue) {
465   return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
466 }
467
468 static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
469                                             Address DestPtr,
470                                             const CXXRecordDecl *Base) {
471   if (Base->isEmpty())
472     return;
473
474   DestPtr = CGF.Builder.CreateElementBitCast(DestPtr, CGF.Int8Ty);
475
476   const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
477   CharUnits NVSize = Layout.getNonVirtualSize();
478
479   // We cannot simply zero-initialize the entire base sub-object if vbptrs are
480   // present, they are initialized by the most derived class before calling the
481   // constructor.
482   SmallVector<std::pair<CharUnits, CharUnits>, 1> Stores;
483   Stores.emplace_back(CharUnits::Zero(), NVSize);
484
485   // Each store is split by the existence of a vbptr.
486   CharUnits VBPtrWidth = CGF.getPointerSize();
487   std::vector<CharUnits> VBPtrOffsets =
488       CGF.CGM.getCXXABI().getVBPtrOffsets(Base);
489   for (CharUnits VBPtrOffset : VBPtrOffsets) {
490     // Stop before we hit any virtual base pointers located in virtual bases.
491     if (VBPtrOffset >= NVSize)
492       break;
493     std::pair<CharUnits, CharUnits> LastStore = Stores.pop_back_val();
494     CharUnits LastStoreOffset = LastStore.first;
495     CharUnits LastStoreSize = LastStore.second;
496
497     CharUnits SplitBeforeOffset = LastStoreOffset;
498     CharUnits SplitBeforeSize = VBPtrOffset - SplitBeforeOffset;
499     assert(!SplitBeforeSize.isNegative() && "negative store size!");
500     if (!SplitBeforeSize.isZero())
501       Stores.emplace_back(SplitBeforeOffset, SplitBeforeSize);
502
503     CharUnits SplitAfterOffset = VBPtrOffset + VBPtrWidth;
504     CharUnits SplitAfterSize = LastStoreSize - SplitAfterOffset;
505     assert(!SplitAfterSize.isNegative() && "negative store size!");
506     if (!SplitAfterSize.isZero())
507       Stores.emplace_back(SplitAfterOffset, SplitAfterSize);
508   }
509
510   // If the type contains a pointer to data member we can't memset it to zero.
511   // Instead, create a null constant and copy it to the destination.
512   // TODO: there are other patterns besides zero that we can usefully memset,
513   // like -1, which happens to be the pattern used by member-pointers.
514   // TODO: isZeroInitializable can be over-conservative in the case where a
515   // virtual base contains a member pointer.
516   llvm::Constant *NullConstantForBase = CGF.CGM.EmitNullConstantForBase(Base);
517   if (!NullConstantForBase->isNullValue()) {
518     llvm::GlobalVariable *NullVariable = new llvm::GlobalVariable(
519         CGF.CGM.getModule(), NullConstantForBase->getType(),
520         /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage,
521         NullConstantForBase, Twine());
522
523     CharUnits Align = std::max(Layout.getNonVirtualAlignment(),
524                                DestPtr.getAlignment());
525     NullVariable->setAlignment(Align.getQuantity());
526
527     Address SrcPtr = Address(CGF.EmitCastToVoidPtr(NullVariable), Align);
528
529     // Get and call the appropriate llvm.memcpy overload.
530     for (std::pair<CharUnits, CharUnits> Store : Stores) {
531       CharUnits StoreOffset = Store.first;
532       CharUnits StoreSize = Store.second;
533       llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
534       CGF.Builder.CreateMemCpy(
535           CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
536           CGF.Builder.CreateConstInBoundsByteGEP(SrcPtr, StoreOffset),
537           StoreSizeVal);
538     }
539
540   // Otherwise, just memset the whole thing to zero.  This is legal
541   // because in LLVM, all default initializers (other than the ones we just
542   // handled above) are guaranteed to have a bit pattern of all zeros.
543   } else {
544     for (std::pair<CharUnits, CharUnits> Store : Stores) {
545       CharUnits StoreOffset = Store.first;
546       CharUnits StoreSize = Store.second;
547       llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
548       CGF.Builder.CreateMemSet(
549           CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
550           CGF.Builder.getInt8(0), StoreSizeVal);
551     }
552   }
553 }
554
555 void
556 CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
557                                       AggValueSlot Dest) {
558   assert(!Dest.isIgnored() && "Must have a destination!");
559   const CXXConstructorDecl *CD = E->getConstructor();
560   
561   // If we require zero initialization before (or instead of) calling the
562   // constructor, as can be the case with a non-user-provided default
563   // constructor, emit the zero initialization now, unless destination is
564   // already zeroed.
565   if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
566     switch (E->getConstructionKind()) {
567     case CXXConstructExpr::CK_Delegating:
568     case CXXConstructExpr::CK_Complete:
569       EmitNullInitialization(Dest.getAddress(), E->getType());
570       break;
571     case CXXConstructExpr::CK_VirtualBase:
572     case CXXConstructExpr::CK_NonVirtualBase:
573       EmitNullBaseClassInitialization(*this, Dest.getAddress(),
574                                       CD->getParent());
575       break;
576     }
577   }
578   
579   // If this is a call to a trivial default constructor, do nothing.
580   if (CD->isTrivial() && CD->isDefaultConstructor())
581     return;
582   
583   // Elide the constructor if we're constructing from a temporary.
584   // The temporary check is required because Sema sets this on NRVO
585   // returns.
586   if (getLangOpts().ElideConstructors && E->isElidable()) {
587     assert(getContext().hasSameUnqualifiedType(E->getType(),
588                                                E->getArg(0)->getType()));
589     if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
590       EmitAggExpr(E->getArg(0), Dest);
591       return;
592     }
593   }
594   
595   if (const ArrayType *arrayType
596         = getContext().getAsArrayType(E->getType())) {
597     EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddress(), E);
598   } else {
599     CXXCtorType Type = Ctor_Complete;
600     bool ForVirtualBase = false;
601     bool Delegating = false;
602     
603     switch (E->getConstructionKind()) {
604      case CXXConstructExpr::CK_Delegating:
605       // We should be emitting a constructor; GlobalDecl will assert this
606       Type = CurGD.getCtorType();
607       Delegating = true;
608       break;
609
610      case CXXConstructExpr::CK_Complete:
611       Type = Ctor_Complete;
612       break;
613
614      case CXXConstructExpr::CK_VirtualBase:
615       ForVirtualBase = true;
616       // fall-through
617
618      case CXXConstructExpr::CK_NonVirtualBase:
619       Type = Ctor_Base;
620     }
621     
622     // Call the constructor.
623     EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating,
624                            Dest.getAddress(), E);
625   }
626 }
627
628 void CodeGenFunction::EmitSynthesizedCXXCopyCtor(Address Dest, Address Src,
629                                                  const Expr *Exp) {
630   if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
631     Exp = E->getSubExpr();
632   assert(isa<CXXConstructExpr>(Exp) && 
633          "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
634   const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
635   const CXXConstructorDecl *CD = E->getConstructor();
636   RunCleanupsScope Scope(*this);
637   
638   // If we require zero initialization before (or instead of) calling the
639   // constructor, as can be the case with a non-user-provided default
640   // constructor, emit the zero initialization now.
641   // FIXME. Do I still need this for a copy ctor synthesis?
642   if (E->requiresZeroInitialization())
643     EmitNullInitialization(Dest, E->getType());
644   
645   assert(!getContext().getAsConstantArrayType(E->getType())
646          && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
647   EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E);
648 }
649
650 static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
651                                         const CXXNewExpr *E) {
652   if (!E->isArray())
653     return CharUnits::Zero();
654
655   // No cookie is required if the operator new[] being used is the
656   // reserved placement operator new[].
657   if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
658     return CharUnits::Zero();
659
660   return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
661 }
662
663 static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
664                                         const CXXNewExpr *e,
665                                         unsigned minElements,
666                                         llvm::Value *&numElements,
667                                         llvm::Value *&sizeWithoutCookie) {
668   QualType type = e->getAllocatedType();
669
670   if (!e->isArray()) {
671     CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
672     sizeWithoutCookie
673       = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
674     return sizeWithoutCookie;
675   }
676
677   // The width of size_t.
678   unsigned sizeWidth = CGF.SizeTy->getBitWidth();
679
680   // Figure out the cookie size.
681   llvm::APInt cookieSize(sizeWidth,
682                          CalculateCookiePadding(CGF, e).getQuantity());
683
684   // Emit the array size expression.
685   // We multiply the size of all dimensions for NumElements.
686   // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
687   numElements =
688     ConstantEmitter(CGF).tryEmitAbstract(e->getArraySize(), e->getType());
689   if (!numElements)
690     numElements = CGF.EmitScalarExpr(e->getArraySize());
691   assert(isa<llvm::IntegerType>(numElements->getType()));
692
693   // The number of elements can be have an arbitrary integer type;
694   // essentially, we need to multiply it by a constant factor, add a
695   // cookie size, and verify that the result is representable as a
696   // size_t.  That's just a gloss, though, and it's wrong in one
697   // important way: if the count is negative, it's an error even if
698   // the cookie size would bring the total size >= 0.
699   bool isSigned 
700     = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
701   llvm::IntegerType *numElementsType
702     = cast<llvm::IntegerType>(numElements->getType());
703   unsigned numElementsWidth = numElementsType->getBitWidth();
704
705   // Compute the constant factor.
706   llvm::APInt arraySizeMultiplier(sizeWidth, 1);
707   while (const ConstantArrayType *CAT
708              = CGF.getContext().getAsConstantArrayType(type)) {
709     type = CAT->getElementType();
710     arraySizeMultiplier *= CAT->getSize();
711   }
712
713   CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
714   llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
715   typeSizeMultiplier *= arraySizeMultiplier;
716
717   // This will be a size_t.
718   llvm::Value *size;
719   
720   // If someone is doing 'new int[42]' there is no need to do a dynamic check.
721   // Don't bloat the -O0 code.
722   if (llvm::ConstantInt *numElementsC =
723         dyn_cast<llvm::ConstantInt>(numElements)) {
724     const llvm::APInt &count = numElementsC->getValue();
725
726     bool hasAnyOverflow = false;
727
728     // If 'count' was a negative number, it's an overflow.
729     if (isSigned && count.isNegative())
730       hasAnyOverflow = true;
731
732     // We want to do all this arithmetic in size_t.  If numElements is
733     // wider than that, check whether it's already too big, and if so,
734     // overflow.
735     else if (numElementsWidth > sizeWidth &&
736              numElementsWidth - sizeWidth > count.countLeadingZeros())
737       hasAnyOverflow = true;
738
739     // Okay, compute a count at the right width.
740     llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
741
742     // If there is a brace-initializer, we cannot allocate fewer elements than
743     // there are initializers. If we do, that's treated like an overflow.
744     if (adjustedCount.ult(minElements))
745       hasAnyOverflow = true;
746
747     // Scale numElements by that.  This might overflow, but we don't
748     // care because it only overflows if allocationSize does, too, and
749     // if that overflows then we shouldn't use this.
750     numElements = llvm::ConstantInt::get(CGF.SizeTy,
751                                          adjustedCount * arraySizeMultiplier);
752
753     // Compute the size before cookie, and track whether it overflowed.
754     bool overflow;
755     llvm::APInt allocationSize
756       = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
757     hasAnyOverflow |= overflow;
758
759     // Add in the cookie, and check whether it's overflowed.
760     if (cookieSize != 0) {
761       // Save the current size without a cookie.  This shouldn't be
762       // used if there was overflow.
763       sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
764
765       allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
766       hasAnyOverflow |= overflow;
767     }
768
769     // On overflow, produce a -1 so operator new will fail.
770     if (hasAnyOverflow) {
771       size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
772     } else {
773       size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
774     }
775
776   // Otherwise, we might need to use the overflow intrinsics.
777   } else {
778     // There are up to five conditions we need to test for:
779     // 1) if isSigned, we need to check whether numElements is negative;
780     // 2) if numElementsWidth > sizeWidth, we need to check whether
781     //   numElements is larger than something representable in size_t;
782     // 3) if minElements > 0, we need to check whether numElements is smaller
783     //    than that.
784     // 4) we need to compute
785     //      sizeWithoutCookie := numElements * typeSizeMultiplier
786     //    and check whether it overflows; and
787     // 5) if we need a cookie, we need to compute
788     //      size := sizeWithoutCookie + cookieSize
789     //    and check whether it overflows.
790
791     llvm::Value *hasOverflow = nullptr;
792
793     // If numElementsWidth > sizeWidth, then one way or another, we're
794     // going to have to do a comparison for (2), and this happens to
795     // take care of (1), too.
796     if (numElementsWidth > sizeWidth) {
797       llvm::APInt threshold(numElementsWidth, 1);
798       threshold <<= sizeWidth;
799
800       llvm::Value *thresholdV
801         = llvm::ConstantInt::get(numElementsType, threshold);
802
803       hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
804       numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
805
806     // Otherwise, if we're signed, we want to sext up to size_t.
807     } else if (isSigned) {
808       if (numElementsWidth < sizeWidth)
809         numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
810       
811       // If there's a non-1 type size multiplier, then we can do the
812       // signedness check at the same time as we do the multiply
813       // because a negative number times anything will cause an
814       // unsigned overflow.  Otherwise, we have to do it here. But at least
815       // in this case, we can subsume the >= minElements check.
816       if (typeSizeMultiplier == 1)
817         hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
818                               llvm::ConstantInt::get(CGF.SizeTy, minElements));
819
820     // Otherwise, zext up to size_t if necessary.
821     } else if (numElementsWidth < sizeWidth) {
822       numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
823     }
824
825     assert(numElements->getType() == CGF.SizeTy);
826
827     if (minElements) {
828       // Don't allow allocation of fewer elements than we have initializers.
829       if (!hasOverflow) {
830         hasOverflow = CGF.Builder.CreateICmpULT(numElements,
831                               llvm::ConstantInt::get(CGF.SizeTy, minElements));
832       } else if (numElementsWidth > sizeWidth) {
833         // The other existing overflow subsumes this check.
834         // We do an unsigned comparison, since any signed value < -1 is
835         // taken care of either above or below.
836         hasOverflow = CGF.Builder.CreateOr(hasOverflow,
837                           CGF.Builder.CreateICmpULT(numElements,
838                               llvm::ConstantInt::get(CGF.SizeTy, minElements)));
839       }
840     }
841
842     size = numElements;
843
844     // Multiply by the type size if necessary.  This multiplier
845     // includes all the factors for nested arrays.
846     //
847     // This step also causes numElements to be scaled up by the
848     // nested-array factor if necessary.  Overflow on this computation
849     // can be ignored because the result shouldn't be used if
850     // allocation fails.
851     if (typeSizeMultiplier != 1) {
852       llvm::Value *umul_with_overflow
853         = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
854
855       llvm::Value *tsmV =
856         llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
857       llvm::Value *result =
858           CGF.Builder.CreateCall(umul_with_overflow, {size, tsmV});
859
860       llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
861       if (hasOverflow)
862         hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
863       else
864         hasOverflow = overflowed;
865
866       size = CGF.Builder.CreateExtractValue(result, 0);
867
868       // Also scale up numElements by the array size multiplier.
869       if (arraySizeMultiplier != 1) {
870         // If the base element type size is 1, then we can re-use the
871         // multiply we just did.
872         if (typeSize.isOne()) {
873           assert(arraySizeMultiplier == typeSizeMultiplier);
874           numElements = size;
875
876         // Otherwise we need a separate multiply.
877         } else {
878           llvm::Value *asmV =
879             llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
880           numElements = CGF.Builder.CreateMul(numElements, asmV);
881         }
882       }
883     } else {
884       // numElements doesn't need to be scaled.
885       assert(arraySizeMultiplier == 1);
886     }
887     
888     // Add in the cookie size if necessary.
889     if (cookieSize != 0) {
890       sizeWithoutCookie = size;
891
892       llvm::Value *uadd_with_overflow
893         = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
894
895       llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
896       llvm::Value *result =
897           CGF.Builder.CreateCall(uadd_with_overflow, {size, cookieSizeV});
898
899       llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
900       if (hasOverflow)
901         hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
902       else
903         hasOverflow = overflowed;
904
905       size = CGF.Builder.CreateExtractValue(result, 0);
906     }
907
908     // If we had any possibility of dynamic overflow, make a select to
909     // overwrite 'size' with an all-ones value, which should cause
910     // operator new to throw.
911     if (hasOverflow)
912       size = CGF.Builder.CreateSelect(hasOverflow,
913                                  llvm::Constant::getAllOnesValue(CGF.SizeTy),
914                                       size);
915   }
916
917   if (cookieSize == 0)
918     sizeWithoutCookie = size;
919   else
920     assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
921
922   return size;
923 }
924
925 static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
926                                     QualType AllocType, Address NewPtr) {
927   // FIXME: Refactor with EmitExprAsInit.
928   switch (CGF.getEvaluationKind(AllocType)) {
929   case TEK_Scalar:
930     CGF.EmitScalarInit(Init, nullptr,
931                        CGF.MakeAddrLValue(NewPtr, AllocType), false);
932     return;
933   case TEK_Complex:
934     CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType),
935                                   /*isInit*/ true);
936     return;
937   case TEK_Aggregate: {
938     AggValueSlot Slot
939       = AggValueSlot::forAddr(NewPtr, AllocType.getQualifiers(),
940                               AggValueSlot::IsDestructed,
941                               AggValueSlot::DoesNotNeedGCBarriers,
942                               AggValueSlot::IsNotAliased);
943     CGF.EmitAggExpr(Init, Slot);
944     return;
945   }
946   }
947   llvm_unreachable("bad evaluation kind");
948 }
949
950 void CodeGenFunction::EmitNewArrayInitializer(
951     const CXXNewExpr *E, QualType ElementType, llvm::Type *ElementTy,
952     Address BeginPtr, llvm::Value *NumElements,
953     llvm::Value *AllocSizeWithoutCookie) {
954   // If we have a type with trivial initialization and no initializer,
955   // there's nothing to do.
956   if (!E->hasInitializer())
957     return;
958
959   Address CurPtr = BeginPtr;
960
961   unsigned InitListElements = 0;
962
963   const Expr *Init = E->getInitializer();
964   Address EndOfInit = Address::invalid();
965   QualType::DestructionKind DtorKind = ElementType.isDestructedType();
966   EHScopeStack::stable_iterator Cleanup;
967   llvm::Instruction *CleanupDominator = nullptr;
968
969   CharUnits ElementSize = getContext().getTypeSizeInChars(ElementType);
970   CharUnits ElementAlign =
971     BeginPtr.getAlignment().alignmentOfArrayElement(ElementSize);
972
973   // Attempt to perform zero-initialization using memset.
974   auto TryMemsetInitialization = [&]() -> bool {
975     // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
976     // we can initialize with a memset to -1.
977     if (!CGM.getTypes().isZeroInitializable(ElementType))
978       return false;
979
980     // Optimization: since zero initialization will just set the memory
981     // to all zeroes, generate a single memset to do it in one shot.
982
983     // Subtract out the size of any elements we've already initialized.
984     auto *RemainingSize = AllocSizeWithoutCookie;
985     if (InitListElements) {
986       // We know this can't overflow; we check this when doing the allocation.
987       auto *InitializedSize = llvm::ConstantInt::get(
988           RemainingSize->getType(),
989           getContext().getTypeSizeInChars(ElementType).getQuantity() *
990               InitListElements);
991       RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
992     }
993
994     // Create the memset.
995     Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize, false);
996     return true;
997   };
998
999   // If the initializer is an initializer list, first do the explicit elements.
1000   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
1001     // Initializing from a (braced) string literal is a special case; the init
1002     // list element does not initialize a (single) array element.
1003     if (ILE->isStringLiteralInit()) {
1004       // Initialize the initial portion of length equal to that of the string
1005       // literal. The allocation must be for at least this much; we emitted a
1006       // check for that earlier.
1007       AggValueSlot Slot =
1008           AggValueSlot::forAddr(CurPtr, ElementType.getQualifiers(),
1009                                 AggValueSlot::IsDestructed,
1010                                 AggValueSlot::DoesNotNeedGCBarriers,
1011                                 AggValueSlot::IsNotAliased);
1012       EmitAggExpr(ILE->getInit(0), Slot);
1013
1014       // Move past these elements.
1015       InitListElements =
1016           cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe())
1017               ->getSize().getZExtValue();
1018       CurPtr =
1019           Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(),
1020                                             Builder.getSize(InitListElements),
1021                                             "string.init.end"),
1022                   CurPtr.getAlignment().alignmentAtOffset(InitListElements *
1023                                                           ElementSize));
1024
1025       // Zero out the rest, if any remain.
1026       llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
1027       if (!ConstNum || !ConstNum->equalsInt(InitListElements)) {
1028         bool OK = TryMemsetInitialization();
1029         (void)OK;
1030         assert(OK && "couldn't memset character type?");
1031       }
1032       return;
1033     }
1034
1035     InitListElements = ILE->getNumInits();
1036
1037     // If this is a multi-dimensional array new, we will initialize multiple
1038     // elements with each init list element.
1039     QualType AllocType = E->getAllocatedType();
1040     if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
1041             AllocType->getAsArrayTypeUnsafe())) {
1042       ElementTy = ConvertTypeForMem(AllocType);
1043       CurPtr = Builder.CreateElementBitCast(CurPtr, ElementTy);
1044       InitListElements *= getContext().getConstantArrayElementCount(CAT);
1045     }
1046
1047     // Enter a partial-destruction Cleanup if necessary.
1048     if (needsEHCleanup(DtorKind)) {
1049       // In principle we could tell the Cleanup where we are more
1050       // directly, but the control flow can get so varied here that it
1051       // would actually be quite complex.  Therefore we go through an
1052       // alloca.
1053       EndOfInit = CreateTempAlloca(BeginPtr.getType(), getPointerAlign(),
1054                                    "array.init.end");
1055       CleanupDominator = Builder.CreateStore(BeginPtr.getPointer(), EndOfInit);
1056       pushIrregularPartialArrayCleanup(BeginPtr.getPointer(), EndOfInit,
1057                                        ElementType, ElementAlign,
1058                                        getDestroyer(DtorKind));
1059       Cleanup = EHStack.stable_begin();
1060     }
1061
1062     CharUnits StartAlign = CurPtr.getAlignment();
1063     for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
1064       // Tell the cleanup that it needs to destroy up to this
1065       // element.  TODO: some of these stores can be trivially
1066       // observed to be unnecessary.
1067       if (EndOfInit.isValid()) {
1068         auto FinishedPtr =
1069           Builder.CreateBitCast(CurPtr.getPointer(), BeginPtr.getType());
1070         Builder.CreateStore(FinishedPtr, EndOfInit);
1071       }
1072       // FIXME: If the last initializer is an incomplete initializer list for
1073       // an array, and we have an array filler, we can fold together the two
1074       // initialization loops.
1075       StoreAnyExprIntoOneUnit(*this, ILE->getInit(i),
1076                               ILE->getInit(i)->getType(), CurPtr);
1077       CurPtr = Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(),
1078                                                  Builder.getSize(1),
1079                                                  "array.exp.next"),
1080                        StartAlign.alignmentAtOffset((i + 1) * ElementSize));
1081     }
1082
1083     // The remaining elements are filled with the array filler expression.
1084     Init = ILE->getArrayFiller();
1085
1086     // Extract the initializer for the individual array elements by pulling
1087     // out the array filler from all the nested initializer lists. This avoids
1088     // generating a nested loop for the initialization.
1089     while (Init && Init->getType()->isConstantArrayType()) {
1090       auto *SubILE = dyn_cast<InitListExpr>(Init);
1091       if (!SubILE)
1092         break;
1093       assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
1094       Init = SubILE->getArrayFiller();
1095     }
1096
1097     // Switch back to initializing one base element at a time.
1098     CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr.getType());
1099   }
1100
1101   // If all elements have already been initialized, skip any further
1102   // initialization.
1103   llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
1104   if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
1105     // If there was a Cleanup, deactivate it.
1106     if (CleanupDominator)
1107       DeactivateCleanupBlock(Cleanup, CleanupDominator);
1108     return;
1109   }
1110
1111   assert(Init && "have trailing elements to initialize but no initializer");
1112
1113   // If this is a constructor call, try to optimize it out, and failing that
1114   // emit a single loop to initialize all remaining elements.
1115   if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
1116     CXXConstructorDecl *Ctor = CCE->getConstructor();
1117     if (Ctor->isTrivial()) {
1118       // If new expression did not specify value-initialization, then there
1119       // is no initialization.
1120       if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
1121         return;
1122
1123       if (TryMemsetInitialization())
1124         return;
1125     }
1126
1127     // Store the new Cleanup position for irregular Cleanups.
1128     //
1129     // FIXME: Share this cleanup with the constructor call emission rather than
1130     // having it create a cleanup of its own.
1131     if (EndOfInit.isValid())
1132       Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
1133
1134     // Emit a constructor call loop to initialize the remaining elements.
1135     if (InitListElements)
1136       NumElements = Builder.CreateSub(
1137           NumElements,
1138           llvm::ConstantInt::get(NumElements->getType(), InitListElements));
1139     EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,
1140                                CCE->requiresZeroInitialization());
1141     return;
1142   }
1143
1144   // If this is value-initialization, we can usually use memset.
1145   ImplicitValueInitExpr IVIE(ElementType);
1146   if (isa<ImplicitValueInitExpr>(Init)) {
1147     if (TryMemsetInitialization())
1148       return;
1149
1150     // Switch to an ImplicitValueInitExpr for the element type. This handles
1151     // only one case: multidimensional array new of pointers to members. In
1152     // all other cases, we already have an initializer for the array element.
1153     Init = &IVIE;
1154   }
1155
1156   // At this point we should have found an initializer for the individual
1157   // elements of the array.
1158   assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&
1159          "got wrong type of element to initialize");
1160
1161   // If we have an empty initializer list, we can usually use memset.
1162   if (auto *ILE = dyn_cast<InitListExpr>(Init))
1163     if (ILE->getNumInits() == 0 && TryMemsetInitialization())
1164       return;
1165
1166   // If we have a struct whose every field is value-initialized, we can
1167   // usually use memset.
1168   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
1169     if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
1170       if (RType->getDecl()->isStruct()) {
1171         unsigned NumElements = 0;
1172         if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RType->getDecl()))
1173           NumElements = CXXRD->getNumBases();
1174         for (auto *Field : RType->getDecl()->fields())
1175           if (!Field->isUnnamedBitfield())
1176             ++NumElements;
1177         // FIXME: Recurse into nested InitListExprs.
1178         if (ILE->getNumInits() == NumElements)
1179           for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
1180             if (!isa<ImplicitValueInitExpr>(ILE->getInit(i)))
1181               --NumElements;
1182         if (ILE->getNumInits() == NumElements && TryMemsetInitialization())
1183           return;
1184       }
1185     }
1186   }
1187
1188   // Create the loop blocks.
1189   llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
1190   llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
1191   llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
1192
1193   // Find the end of the array, hoisted out of the loop.
1194   llvm::Value *EndPtr =
1195     Builder.CreateInBoundsGEP(BeginPtr.getPointer(), NumElements, "array.end");
1196
1197   // If the number of elements isn't constant, we have to now check if there is
1198   // anything left to initialize.
1199   if (!ConstNum) {
1200     llvm::Value *IsEmpty =
1201       Builder.CreateICmpEQ(CurPtr.getPointer(), EndPtr, "array.isempty");
1202     Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
1203   }
1204
1205   // Enter the loop.
1206   EmitBlock(LoopBB);
1207
1208   // Set up the current-element phi.
1209   llvm::PHINode *CurPtrPhi =
1210     Builder.CreatePHI(CurPtr.getType(), 2, "array.cur");
1211   CurPtrPhi->addIncoming(CurPtr.getPointer(), EntryBB);
1212
1213   CurPtr = Address(CurPtrPhi, ElementAlign);
1214
1215   // Store the new Cleanup position for irregular Cleanups.
1216   if (EndOfInit.isValid()) 
1217     Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
1218
1219   // Enter a partial-destruction Cleanup if necessary.
1220   if (!CleanupDominator && needsEHCleanup(DtorKind)) {
1221     pushRegularPartialArrayCleanup(BeginPtr.getPointer(), CurPtr.getPointer(),
1222                                    ElementType, ElementAlign,
1223                                    getDestroyer(DtorKind));
1224     Cleanup = EHStack.stable_begin();
1225     CleanupDominator = Builder.CreateUnreachable();
1226   }
1227
1228   // Emit the initializer into this element.
1229   StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr);
1230
1231   // Leave the Cleanup if we entered one.
1232   if (CleanupDominator) {
1233     DeactivateCleanupBlock(Cleanup, CleanupDominator);
1234     CleanupDominator->eraseFromParent();
1235   }
1236
1237   // Advance to the next element by adjusting the pointer type as necessary.
1238   llvm::Value *NextPtr =
1239     Builder.CreateConstInBoundsGEP1_32(ElementTy, CurPtr.getPointer(), 1,
1240                                        "array.next");
1241
1242   // Check whether we've gotten to the end of the array and, if so,
1243   // exit the loop.
1244   llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
1245   Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
1246   CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
1247
1248   EmitBlock(ContBB);
1249 }
1250
1251 static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
1252                                QualType ElementType, llvm::Type *ElementTy,
1253                                Address NewPtr, llvm::Value *NumElements,
1254                                llvm::Value *AllocSizeWithoutCookie) {
1255   ApplyDebugLocation DL(CGF, E);
1256   if (E->isArray())
1257     CGF.EmitNewArrayInitializer(E, ElementType, ElementTy, NewPtr, NumElements,
1258                                 AllocSizeWithoutCookie);
1259   else if (const Expr *Init = E->getInitializer())
1260     StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
1261 }
1262
1263 /// Emit a call to an operator new or operator delete function, as implicitly
1264 /// created by new-expressions and delete-expressions.
1265 static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
1266                                 const FunctionDecl *CalleeDecl,
1267                                 const FunctionProtoType *CalleeType,
1268                                 const CallArgList &Args) {
1269   llvm::Instruction *CallOrInvoke;
1270   llvm::Constant *CalleePtr = CGF.CGM.GetAddrOfFunction(CalleeDecl);
1271   CGCallee Callee = CGCallee::forDirect(CalleePtr, CalleeDecl);
1272   RValue RV =
1273       CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(
1274                        Args, CalleeType, /*chainCall=*/false),
1275                    Callee, ReturnValueSlot(), Args, &CallOrInvoke);
1276
1277   /// C++1y [expr.new]p10:
1278   ///   [In a new-expression,] an implementation is allowed to omit a call
1279   ///   to a replaceable global allocation function.
1280   ///
1281   /// We model such elidable calls with the 'builtin' attribute.
1282   llvm::Function *Fn = dyn_cast<llvm::Function>(CalleePtr);
1283   if (CalleeDecl->isReplaceableGlobalAllocationFunction() &&
1284       Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
1285     // FIXME: Add addAttribute to CallSite.
1286     if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(CallOrInvoke))
1287       CI->addAttribute(llvm::AttributeList::FunctionIndex,
1288                        llvm::Attribute::Builtin);
1289     else if (llvm::InvokeInst *II = dyn_cast<llvm::InvokeInst>(CallOrInvoke))
1290       II->addAttribute(llvm::AttributeList::FunctionIndex,
1291                        llvm::Attribute::Builtin);
1292     else
1293       llvm_unreachable("unexpected kind of call instruction");
1294   }
1295
1296   return RV;
1297 }
1298
1299 RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
1300                                                  const Expr *Arg,
1301                                                  bool IsDelete) {
1302   CallArgList Args;
1303   const Stmt *ArgS = Arg;
1304   EmitCallArgs(Args, *Type->param_type_begin(), llvm::makeArrayRef(ArgS));
1305   // Find the allocation or deallocation function that we're calling.
1306   ASTContext &Ctx = getContext();
1307   DeclarationName Name = Ctx.DeclarationNames
1308       .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
1309   for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
1310     if (auto *FD = dyn_cast<FunctionDecl>(Decl))
1311       if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
1312         return EmitNewDeleteCall(*this, cast<FunctionDecl>(Decl), Type, Args);
1313   llvm_unreachable("predeclared global operator new/delete is missing");
1314 }
1315
1316 namespace {
1317 /// The parameters to pass to a usual operator delete.
1318 struct UsualDeleteParams {
1319   bool DestroyingDelete = false;
1320   bool Size = false;
1321   bool Alignment = false;
1322 };
1323 }
1324
1325 static UsualDeleteParams getUsualDeleteParams(const FunctionDecl *FD) {
1326   UsualDeleteParams Params;
1327
1328   const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
1329   auto AI = FPT->param_type_begin(), AE = FPT->param_type_end();
1330
1331   // The first argument is always a void*.
1332   ++AI;
1333
1334   // The next parameter may be a std::destroying_delete_t.
1335   if (FD->isDestroyingOperatorDelete()) {
1336     Params.DestroyingDelete = true;
1337     assert(AI != AE);
1338     ++AI;
1339   }
1340
1341   // Figure out what other parameters we should be implicitly passing.
1342   if (AI != AE && (*AI)->isIntegerType()) {
1343     Params.Size = true;
1344     ++AI;
1345   }
1346
1347   if (AI != AE && (*AI)->isAlignValT()) {
1348     Params.Alignment = true;
1349     ++AI;
1350   }
1351
1352   assert(AI == AE && "unexpected usual deallocation function parameter");
1353   return Params;
1354 }
1355
1356 namespace {
1357   /// A cleanup to call the given 'operator delete' function upon abnormal
1358   /// exit from a new expression. Templated on a traits type that deals with
1359   /// ensuring that the arguments dominate the cleanup if necessary.
1360   template<typename Traits>
1361   class CallDeleteDuringNew final : public EHScopeStack::Cleanup {
1362     /// Type used to hold llvm::Value*s.
1363     typedef typename Traits::ValueTy ValueTy;
1364     /// Type used to hold RValues.
1365     typedef typename Traits::RValueTy RValueTy;
1366     struct PlacementArg {
1367       RValueTy ArgValue;
1368       QualType ArgType;
1369     };
1370
1371     unsigned NumPlacementArgs : 31;
1372     unsigned PassAlignmentToPlacementDelete : 1;
1373     const FunctionDecl *OperatorDelete;
1374     ValueTy Ptr;
1375     ValueTy AllocSize;
1376     CharUnits AllocAlign;
1377
1378     PlacementArg *getPlacementArgs() {
1379       return reinterpret_cast<PlacementArg *>(this + 1);
1380     }
1381
1382   public:
1383     static size_t getExtraSize(size_t NumPlacementArgs) {
1384       return NumPlacementArgs * sizeof(PlacementArg);
1385     }
1386
1387     CallDeleteDuringNew(size_t NumPlacementArgs,
1388                         const FunctionDecl *OperatorDelete, ValueTy Ptr,
1389                         ValueTy AllocSize, bool PassAlignmentToPlacementDelete,
1390                         CharUnits AllocAlign)
1391       : NumPlacementArgs(NumPlacementArgs),
1392         PassAlignmentToPlacementDelete(PassAlignmentToPlacementDelete),
1393         OperatorDelete(OperatorDelete), Ptr(Ptr), AllocSize(AllocSize),
1394         AllocAlign(AllocAlign) {}
1395
1396     void setPlacementArg(unsigned I, RValueTy Arg, QualType Type) {
1397       assert(I < NumPlacementArgs && "index out of range");
1398       getPlacementArgs()[I] = {Arg, Type};
1399     }
1400
1401     void Emit(CodeGenFunction &CGF, Flags flags) override {
1402       const FunctionProtoType *FPT =
1403           OperatorDelete->getType()->getAs<FunctionProtoType>();
1404       CallArgList DeleteArgs;
1405
1406       // The first argument is always a void* (or C* for a destroying operator
1407       // delete for class type C).
1408       DeleteArgs.add(Traits::get(CGF, Ptr), FPT->getParamType(0));
1409
1410       // Figure out what other parameters we should be implicitly passing.
1411       UsualDeleteParams Params;
1412       if (NumPlacementArgs) {
1413         // A placement deallocation function is implicitly passed an alignment
1414         // if the placement allocation function was, but is never passed a size.
1415         Params.Alignment = PassAlignmentToPlacementDelete;
1416       } else {
1417         // For a non-placement new-expression, 'operator delete' can take a
1418         // size and/or an alignment if it has the right parameters.
1419         Params = getUsualDeleteParams(OperatorDelete);
1420       }
1421
1422       assert(!Params.DestroyingDelete &&
1423              "should not call destroying delete in a new-expression");
1424
1425       // The second argument can be a std::size_t (for non-placement delete).
1426       if (Params.Size)
1427         DeleteArgs.add(Traits::get(CGF, AllocSize),
1428                        CGF.getContext().getSizeType());
1429
1430       // The next (second or third) argument can be a std::align_val_t, which
1431       // is an enum whose underlying type is std::size_t.
1432       // FIXME: Use the right type as the parameter type. Note that in a call
1433       // to operator delete(size_t, ...), we may not have it available.
1434       if (Params.Alignment)
1435         DeleteArgs.add(RValue::get(llvm::ConstantInt::get(
1436                            CGF.SizeTy, AllocAlign.getQuantity())),
1437                        CGF.getContext().getSizeType());
1438
1439       // Pass the rest of the arguments, which must match exactly.
1440       for (unsigned I = 0; I != NumPlacementArgs; ++I) {
1441         auto Arg = getPlacementArgs()[I];
1442         DeleteArgs.add(Traits::get(CGF, Arg.ArgValue), Arg.ArgType);
1443       }
1444
1445       // Call 'operator delete'.
1446       EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
1447     }
1448   };
1449 }
1450
1451 /// Enter a cleanup to call 'operator delete' if the initializer in a
1452 /// new-expression throws.
1453 static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1454                                   const CXXNewExpr *E,
1455                                   Address NewPtr,
1456                                   llvm::Value *AllocSize,
1457                                   CharUnits AllocAlign,
1458                                   const CallArgList &NewArgs) {
1459   unsigned NumNonPlacementArgs = E->passAlignment() ? 2 : 1;
1460
1461   // If we're not inside a conditional branch, then the cleanup will
1462   // dominate and we can do the easier (and more efficient) thing.
1463   if (!CGF.isInConditionalBranch()) {
1464     struct DirectCleanupTraits {
1465       typedef llvm::Value *ValueTy;
1466       typedef RValue RValueTy;
1467       static RValue get(CodeGenFunction &, ValueTy V) { return RValue::get(V); }
1468       static RValue get(CodeGenFunction &, RValueTy V) { return V; }
1469     };
1470
1471     typedef CallDeleteDuringNew<DirectCleanupTraits> DirectCleanup;
1472
1473     DirectCleanup *Cleanup = CGF.EHStack
1474       .pushCleanupWithExtra<DirectCleanup>(EHCleanup,
1475                                            E->getNumPlacementArgs(),
1476                                            E->getOperatorDelete(),
1477                                            NewPtr.getPointer(),
1478                                            AllocSize,
1479                                            E->passAlignment(),
1480                                            AllocAlign);
1481     for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
1482       auto &Arg = NewArgs[I + NumNonPlacementArgs];
1483       Cleanup->setPlacementArg(I, Arg.RV, Arg.Ty);
1484     }
1485
1486     return;
1487   }
1488
1489   // Otherwise, we need to save all this stuff.
1490   DominatingValue<RValue>::saved_type SavedNewPtr =
1491     DominatingValue<RValue>::save(CGF, RValue::get(NewPtr.getPointer()));
1492   DominatingValue<RValue>::saved_type SavedAllocSize =
1493     DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
1494
1495   struct ConditionalCleanupTraits {
1496     typedef DominatingValue<RValue>::saved_type ValueTy;
1497     typedef DominatingValue<RValue>::saved_type RValueTy;
1498     static RValue get(CodeGenFunction &CGF, ValueTy V) {
1499       return V.restore(CGF);
1500     }
1501   };
1502   typedef CallDeleteDuringNew<ConditionalCleanupTraits> ConditionalCleanup;
1503
1504   ConditionalCleanup *Cleanup = CGF.EHStack
1505     .pushCleanupWithExtra<ConditionalCleanup>(EHCleanup,
1506                                               E->getNumPlacementArgs(),
1507                                               E->getOperatorDelete(),
1508                                               SavedNewPtr,
1509                                               SavedAllocSize,
1510                                               E->passAlignment(),
1511                                               AllocAlign);
1512   for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
1513     auto &Arg = NewArgs[I + NumNonPlacementArgs];
1514     Cleanup->setPlacementArg(I, DominatingValue<RValue>::save(CGF, Arg.RV),
1515                              Arg.Ty);
1516   }
1517
1518   CGF.initFullExprCleanup();
1519 }
1520
1521 llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
1522   // The element type being allocated.
1523   QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
1524
1525   // 1. Build a call to the allocation function.
1526   FunctionDecl *allocator = E->getOperatorNew();
1527
1528   // If there is a brace-initializer, cannot allocate fewer elements than inits.
1529   unsigned minElements = 0;
1530   if (E->isArray() && E->hasInitializer()) {
1531     const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer());
1532     if (ILE && ILE->isStringLiteralInit())
1533       minElements =
1534           cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe())
1535               ->getSize().getZExtValue();
1536     else if (ILE)
1537       minElements = ILE->getNumInits();
1538   }
1539
1540   llvm::Value *numElements = nullptr;
1541   llvm::Value *allocSizeWithoutCookie = nullptr;
1542   llvm::Value *allocSize =
1543     EmitCXXNewAllocSize(*this, E, minElements, numElements,
1544                         allocSizeWithoutCookie);
1545   CharUnits allocAlign = getContext().getTypeAlignInChars(allocType);
1546
1547   // Emit the allocation call.  If the allocator is a global placement
1548   // operator, just "inline" it directly.
1549   Address allocation = Address::invalid();
1550   CallArgList allocatorArgs;
1551   if (allocator->isReservedGlobalPlacementOperator()) {
1552     assert(E->getNumPlacementArgs() == 1);
1553     const Expr *arg = *E->placement_arguments().begin();
1554
1555     LValueBaseInfo BaseInfo;
1556     allocation = EmitPointerWithAlignment(arg, &BaseInfo);
1557
1558     // The pointer expression will, in many cases, be an opaque void*.
1559     // In these cases, discard the computed alignment and use the
1560     // formal alignment of the allocated type.
1561     if (BaseInfo.getAlignmentSource() != AlignmentSource::Decl)
1562       allocation = Address(allocation.getPointer(), allocAlign);
1563
1564     // Set up allocatorArgs for the call to operator delete if it's not
1565     // the reserved global operator.
1566     if (E->getOperatorDelete() &&
1567         !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
1568       allocatorArgs.add(RValue::get(allocSize), getContext().getSizeType());
1569       allocatorArgs.add(RValue::get(allocation.getPointer()), arg->getType());
1570     }
1571
1572   } else {
1573     const FunctionProtoType *allocatorType =
1574       allocator->getType()->castAs<FunctionProtoType>();
1575     unsigned ParamsToSkip = 0;
1576
1577     // The allocation size is the first argument.
1578     QualType sizeType = getContext().getSizeType();
1579     allocatorArgs.add(RValue::get(allocSize), sizeType);
1580     ++ParamsToSkip;
1581
1582     if (allocSize != allocSizeWithoutCookie) {
1583       CharUnits cookieAlign = getSizeAlign(); // FIXME: Ask the ABI.
1584       allocAlign = std::max(allocAlign, cookieAlign);
1585     }
1586
1587     // The allocation alignment may be passed as the second argument.
1588     if (E->passAlignment()) {
1589       QualType AlignValT = sizeType;
1590       if (allocatorType->getNumParams() > 1) {
1591         AlignValT = allocatorType->getParamType(1);
1592         assert(getContext().hasSameUnqualifiedType(
1593                    AlignValT->castAs<EnumType>()->getDecl()->getIntegerType(),
1594                    sizeType) &&
1595                "wrong type for alignment parameter");
1596         ++ParamsToSkip;
1597       } else {
1598         // Corner case, passing alignment to 'operator new(size_t, ...)'.
1599         assert(allocator->isVariadic() && "can't pass alignment to allocator");
1600       }
1601       allocatorArgs.add(
1602           RValue::get(llvm::ConstantInt::get(SizeTy, allocAlign.getQuantity())),
1603           AlignValT);
1604     }
1605
1606     // FIXME: Why do we not pass a CalleeDecl here?
1607     EmitCallArgs(allocatorArgs, allocatorType, E->placement_arguments(),
1608                  /*AC*/AbstractCallee(), /*ParamsToSkip*/ParamsToSkip);
1609
1610     RValue RV =
1611       EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
1612
1613     // If this was a call to a global replaceable allocation function that does
1614     // not take an alignment argument, the allocator is known to produce
1615     // storage that's suitably aligned for any object that fits, up to a known
1616     // threshold. Otherwise assume it's suitably aligned for the allocated type.
1617     CharUnits allocationAlign = allocAlign;
1618     if (!E->passAlignment() &&
1619         allocator->isReplaceableGlobalAllocationFunction()) {
1620       unsigned AllocatorAlign = llvm::PowerOf2Floor(std::min<uint64_t>(
1621           Target.getNewAlign(), getContext().getTypeSize(allocType)));
1622       allocationAlign = std::max(
1623           allocationAlign, getContext().toCharUnitsFromBits(AllocatorAlign));
1624     }
1625
1626     allocation = Address(RV.getScalarVal(), allocationAlign);
1627   }
1628
1629   // Emit a null check on the allocation result if the allocation
1630   // function is allowed to return null (because it has a non-throwing
1631   // exception spec or is the reserved placement new) and we have an
1632   // interesting initializer.
1633   bool nullCheck = E->shouldNullCheckAllocation(getContext()) &&
1634     (!allocType.isPODType(getContext()) || E->hasInitializer());
1635
1636   llvm::BasicBlock *nullCheckBB = nullptr;
1637   llvm::BasicBlock *contBB = nullptr;
1638
1639   // The null-check means that the initializer is conditionally
1640   // evaluated.
1641   ConditionalEvaluation conditional(*this);
1642
1643   if (nullCheck) {
1644     conditional.begin(*this);
1645
1646     nullCheckBB = Builder.GetInsertBlock();
1647     llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1648     contBB = createBasicBlock("new.cont");
1649
1650     llvm::Value *isNull =
1651       Builder.CreateIsNull(allocation.getPointer(), "new.isnull");
1652     Builder.CreateCondBr(isNull, contBB, notNullBB);
1653     EmitBlock(notNullBB);
1654   }
1655
1656   // If there's an operator delete, enter a cleanup to call it if an
1657   // exception is thrown.
1658   EHScopeStack::stable_iterator operatorDeleteCleanup;
1659   llvm::Instruction *cleanupDominator = nullptr;
1660   if (E->getOperatorDelete() &&
1661       !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
1662     EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocAlign,
1663                           allocatorArgs);
1664     operatorDeleteCleanup = EHStack.stable_begin();
1665     cleanupDominator = Builder.CreateUnreachable();
1666   }
1667
1668   assert((allocSize == allocSizeWithoutCookie) ==
1669          CalculateCookiePadding(*this, E).isZero());
1670   if (allocSize != allocSizeWithoutCookie) {
1671     assert(E->isArray());
1672     allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1673                                                        numElements,
1674                                                        E, allocType);
1675   }
1676
1677   llvm::Type *elementTy = ConvertTypeForMem(allocType);
1678   Address result = Builder.CreateElementBitCast(allocation, elementTy);
1679
1680   // Passing pointer through invariant.group.barrier to avoid propagation of
1681   // vptrs information which may be included in previous type.
1682   // To not break LTO with different optimizations levels, we do it regardless
1683   // of optimization level.
1684   if (CGM.getCodeGenOpts().StrictVTablePointers &&
1685       allocator->isReservedGlobalPlacementOperator())
1686     result = Address(Builder.CreateInvariantGroupBarrier(result.getPointer()),
1687                      result.getAlignment());
1688
1689   EmitNewInitializer(*this, E, allocType, elementTy, result, numElements,
1690                      allocSizeWithoutCookie);
1691   if (E->isArray()) {
1692     // NewPtr is a pointer to the base element type.  If we're
1693     // allocating an array of arrays, we'll need to cast back to the
1694     // array pointer type.
1695     llvm::Type *resultType = ConvertTypeForMem(E->getType());
1696     if (result.getType() != resultType)
1697       result = Builder.CreateBitCast(result, resultType);
1698   }
1699
1700   // Deactivate the 'operator delete' cleanup if we finished
1701   // initialization.
1702   if (operatorDeleteCleanup.isValid()) {
1703     DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1704     cleanupDominator->eraseFromParent();
1705   }
1706
1707   llvm::Value *resultPtr = result.getPointer();
1708   if (nullCheck) {
1709     conditional.end(*this);
1710
1711     llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1712     EmitBlock(contBB);
1713
1714     llvm::PHINode *PHI = Builder.CreatePHI(resultPtr->getType(), 2);
1715     PHI->addIncoming(resultPtr, notNullBB);
1716     PHI->addIncoming(llvm::Constant::getNullValue(resultPtr->getType()),
1717                      nullCheckBB);
1718
1719     resultPtr = PHI;
1720   }
1721   
1722   return resultPtr;
1723 }
1724
1725 void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1726                                      llvm::Value *Ptr, QualType DeleteTy,
1727                                      llvm::Value *NumElements,
1728                                      CharUnits CookieSize) {
1729   assert((!NumElements && CookieSize.isZero()) ||
1730          DeleteFD->getOverloadedOperator() == OO_Array_Delete);
1731
1732   const FunctionProtoType *DeleteFTy =
1733     DeleteFD->getType()->getAs<FunctionProtoType>();
1734
1735   CallArgList DeleteArgs;
1736
1737   auto Params = getUsualDeleteParams(DeleteFD);
1738   auto ParamTypeIt = DeleteFTy->param_type_begin();
1739
1740   // Pass the pointer itself.
1741   QualType ArgTy = *ParamTypeIt++;
1742   llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
1743   DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
1744
1745   // Pass the std::destroying_delete tag if present.
1746   if (Params.DestroyingDelete) {
1747     QualType DDTag = *ParamTypeIt++;
1748     // Just pass an 'undef'. We expect the tag type to be an empty struct.
1749     auto *V = llvm::UndefValue::get(getTypes().ConvertType(DDTag));
1750     DeleteArgs.add(RValue::get(V), DDTag);
1751   }
1752
1753   // Pass the size if the delete function has a size_t parameter.
1754   if (Params.Size) {
1755     QualType SizeType = *ParamTypeIt++;
1756     CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1757     llvm::Value *Size = llvm::ConstantInt::get(ConvertType(SizeType),
1758                                                DeleteTypeSize.getQuantity());
1759
1760     // For array new, multiply by the number of elements.
1761     if (NumElements)
1762       Size = Builder.CreateMul(Size, NumElements);
1763
1764     // If there is a cookie, add the cookie size.
1765     if (!CookieSize.isZero())
1766       Size = Builder.CreateAdd(
1767           Size, llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity()));
1768
1769     DeleteArgs.add(RValue::get(Size), SizeType);
1770   }
1771
1772   // Pass the alignment if the delete function has an align_val_t parameter.
1773   if (Params.Alignment) {
1774     QualType AlignValType = *ParamTypeIt++;
1775     CharUnits DeleteTypeAlign = getContext().toCharUnitsFromBits(
1776         getContext().getTypeAlignIfKnown(DeleteTy));
1777     llvm::Value *Align = llvm::ConstantInt::get(ConvertType(AlignValType),
1778                                                 DeleteTypeAlign.getQuantity());
1779     DeleteArgs.add(RValue::get(Align), AlignValType);
1780   }
1781
1782   assert(ParamTypeIt == DeleteFTy->param_type_end() &&
1783          "unknown parameter to usual delete function");
1784
1785   // Emit the call to delete.
1786   EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
1787 }
1788
1789 namespace {
1790   /// Calls the given 'operator delete' on a single object.
1791   struct CallObjectDelete final : EHScopeStack::Cleanup {
1792     llvm::Value *Ptr;
1793     const FunctionDecl *OperatorDelete;
1794     QualType ElementType;
1795
1796     CallObjectDelete(llvm::Value *Ptr,
1797                      const FunctionDecl *OperatorDelete,
1798                      QualType ElementType)
1799       : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1800
1801     void Emit(CodeGenFunction &CGF, Flags flags) override {
1802       CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1803     }
1804   };
1805 }
1806
1807 void
1808 CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
1809                                              llvm::Value *CompletePtr,
1810                                              QualType ElementType) {
1811   EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr,
1812                                         OperatorDelete, ElementType);
1813 }
1814
1815 /// Emit the code for deleting a single object with a destroying operator
1816 /// delete. If the element type has a non-virtual destructor, Ptr has already
1817 /// been converted to the type of the parameter of 'operator delete'. Otherwise
1818 /// Ptr points to an object of the static type.
1819 static void EmitDestroyingObjectDelete(CodeGenFunction &CGF,
1820                                        const CXXDeleteExpr *DE, Address Ptr,
1821                                        QualType ElementType) {
1822   auto *Dtor = ElementType->getAsCXXRecordDecl()->getDestructor();
1823   if (Dtor && Dtor->isVirtual())
1824     CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
1825                                                 Dtor);
1826   else
1827     CGF.EmitDeleteCall(DE->getOperatorDelete(), Ptr.getPointer(), ElementType);
1828 }
1829
1830 /// Emit the code for deleting a single object.
1831 static void EmitObjectDelete(CodeGenFunction &CGF,
1832                              const CXXDeleteExpr *DE,
1833                              Address Ptr,
1834                              QualType ElementType) {
1835   // C++11 [expr.delete]p3:
1836   //   If the static type of the object to be deleted is different from its
1837   //   dynamic type, the static type shall be a base class of the dynamic type
1838   //   of the object to be deleted and the static type shall have a virtual
1839   //   destructor or the behavior is undefined.
1840   CGF.EmitTypeCheck(CodeGenFunction::TCK_MemberCall,
1841                     DE->getExprLoc(), Ptr.getPointer(),
1842                     ElementType);
1843
1844   const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
1845   assert(!OperatorDelete->isDestroyingOperatorDelete());
1846
1847   // Find the destructor for the type, if applicable.  If the
1848   // destructor is virtual, we'll just emit the vcall and return.
1849   const CXXDestructorDecl *Dtor = nullptr;
1850   if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1851     CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1852     if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
1853       Dtor = RD->getDestructor();
1854
1855       if (Dtor->isVirtual()) {
1856         CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
1857                                                     Dtor);
1858         return;
1859       }
1860     }
1861   }
1862
1863   // Make sure that we call delete even if the dtor throws.
1864   // This doesn't have to a conditional cleanup because we're going
1865   // to pop it off in a second.
1866   CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1867                                             Ptr.getPointer(),
1868                                             OperatorDelete, ElementType);
1869
1870   if (Dtor)
1871     CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1872                               /*ForVirtualBase=*/false,
1873                               /*Delegating=*/false,
1874                               Ptr);
1875   else if (auto Lifetime = ElementType.getObjCLifetime()) {
1876     switch (Lifetime) {
1877     case Qualifiers::OCL_None:
1878     case Qualifiers::OCL_ExplicitNone:
1879     case Qualifiers::OCL_Autoreleasing:
1880       break;
1881
1882     case Qualifiers::OCL_Strong:
1883       CGF.EmitARCDestroyStrong(Ptr, ARCPreciseLifetime);
1884       break;
1885         
1886     case Qualifiers::OCL_Weak:
1887       CGF.EmitARCDestroyWeak(Ptr);
1888       break;
1889     }
1890   }
1891            
1892   CGF.PopCleanupBlock();
1893 }
1894
1895 namespace {
1896   /// Calls the given 'operator delete' on an array of objects.
1897   struct CallArrayDelete final : EHScopeStack::Cleanup {
1898     llvm::Value *Ptr;
1899     const FunctionDecl *OperatorDelete;
1900     llvm::Value *NumElements;
1901     QualType ElementType;
1902     CharUnits CookieSize;
1903
1904     CallArrayDelete(llvm::Value *Ptr,
1905                     const FunctionDecl *OperatorDelete,
1906                     llvm::Value *NumElements,
1907                     QualType ElementType,
1908                     CharUnits CookieSize)
1909       : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1910         ElementType(ElementType), CookieSize(CookieSize) {}
1911
1912     void Emit(CodeGenFunction &CGF, Flags flags) override {
1913       CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType, NumElements,
1914                          CookieSize);
1915     }
1916   };
1917 }
1918
1919 /// Emit the code for deleting an array of objects.
1920 static void EmitArrayDelete(CodeGenFunction &CGF,
1921                             const CXXDeleteExpr *E,
1922                             Address deletedPtr,
1923                             QualType elementType) {
1924   llvm::Value *numElements = nullptr;
1925   llvm::Value *allocatedPtr = nullptr;
1926   CharUnits cookieSize;
1927   CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1928                                       numElements, allocatedPtr, cookieSize);
1929
1930   assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
1931
1932   // Make sure that we call delete even if one of the dtors throws.
1933   const FunctionDecl *operatorDelete = E->getOperatorDelete();
1934   CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
1935                                            allocatedPtr, operatorDelete,
1936                                            numElements, elementType,
1937                                            cookieSize);
1938
1939   // Destroy the elements.
1940   if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1941     assert(numElements && "no element count for a type with a destructor!");
1942
1943     CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
1944     CharUnits elementAlign =
1945       deletedPtr.getAlignment().alignmentOfArrayElement(elementSize);
1946
1947     llvm::Value *arrayBegin = deletedPtr.getPointer();
1948     llvm::Value *arrayEnd =
1949       CGF.Builder.CreateInBoundsGEP(arrayBegin, numElements, "delete.end");
1950
1951     // Note that it is legal to allocate a zero-length array, and we
1952     // can never fold the check away because the length should always
1953     // come from a cookie.
1954     CGF.emitArrayDestroy(arrayBegin, arrayEnd, elementType, elementAlign,
1955                          CGF.getDestroyer(dtorKind),
1956                          /*checkZeroLength*/ true,
1957                          CGF.needsEHCleanup(dtorKind));
1958   }
1959
1960   // Pop the cleanup block.
1961   CGF.PopCleanupBlock();
1962 }
1963
1964 void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
1965   const Expr *Arg = E->getArgument();
1966   Address Ptr = EmitPointerWithAlignment(Arg);
1967
1968   // Null check the pointer.
1969   llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1970   llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1971
1972   llvm::Value *IsNull = Builder.CreateIsNull(Ptr.getPointer(), "isnull");
1973
1974   Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1975   EmitBlock(DeleteNotNull);
1976
1977   QualType DeleteTy = E->getDestroyedType();
1978
1979   // A destroying operator delete overrides the entire operation of the
1980   // delete expression.
1981   if (E->getOperatorDelete()->isDestroyingOperatorDelete()) {
1982     EmitDestroyingObjectDelete(*this, E, Ptr, DeleteTy);
1983     EmitBlock(DeleteEnd);
1984     return;
1985   }
1986
1987   // We might be deleting a pointer to array.  If so, GEP down to the
1988   // first non-array element.
1989   // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1990   if (DeleteTy->isConstantArrayType()) {
1991     llvm::Value *Zero = Builder.getInt32(0);
1992     SmallVector<llvm::Value*,8> GEP;
1993
1994     GEP.push_back(Zero); // point at the outermost array
1995
1996     // For each layer of array type we're pointing at:
1997     while (const ConstantArrayType *Arr
1998              = getContext().getAsConstantArrayType(DeleteTy)) {
1999       // 1. Unpeel the array type.
2000       DeleteTy = Arr->getElementType();
2001
2002       // 2. GEP to the first element of the array.
2003       GEP.push_back(Zero);
2004     }
2005
2006     Ptr = Address(Builder.CreateInBoundsGEP(Ptr.getPointer(), GEP, "del.first"),
2007                   Ptr.getAlignment());
2008   }
2009
2010   assert(ConvertTypeForMem(DeleteTy) == Ptr.getElementType());
2011
2012   if (E->isArrayForm()) {
2013     EmitArrayDelete(*this, E, Ptr, DeleteTy);
2014   } else {
2015     EmitObjectDelete(*this, E, Ptr, DeleteTy);
2016   }
2017
2018   EmitBlock(DeleteEnd);
2019 }
2020
2021 static bool isGLValueFromPointerDeref(const Expr *E) {
2022   E = E->IgnoreParens();
2023
2024   if (const auto *CE = dyn_cast<CastExpr>(E)) {
2025     if (!CE->getSubExpr()->isGLValue())
2026       return false;
2027     return isGLValueFromPointerDeref(CE->getSubExpr());
2028   }
2029
2030   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
2031     return isGLValueFromPointerDeref(OVE->getSourceExpr());
2032
2033   if (const auto *BO = dyn_cast<BinaryOperator>(E))
2034     if (BO->getOpcode() == BO_Comma)
2035       return isGLValueFromPointerDeref(BO->getRHS());
2036
2037   if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E))
2038     return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
2039            isGLValueFromPointerDeref(ACO->getFalseExpr());
2040
2041   // C++11 [expr.sub]p1:
2042   //   The expression E1[E2] is identical (by definition) to *((E1)+(E2))
2043   if (isa<ArraySubscriptExpr>(E))
2044     return true;
2045
2046   if (const auto *UO = dyn_cast<UnaryOperator>(E))
2047     if (UO->getOpcode() == UO_Deref)
2048       return true;
2049
2050   return false;
2051 }
2052
2053 static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
2054                                          llvm::Type *StdTypeInfoPtrTy) {
2055   // Get the vtable pointer.
2056   Address ThisPtr = CGF.EmitLValue(E).getAddress();
2057
2058   // C++ [expr.typeid]p2:
2059   //   If the glvalue expression is obtained by applying the unary * operator to
2060   //   a pointer and the pointer is a null pointer value, the typeid expression
2061   //   throws the std::bad_typeid exception.
2062   //
2063   // However, this paragraph's intent is not clear.  We choose a very generous
2064   // interpretation which implores us to consider comma operators, conditional
2065   // operators, parentheses and other such constructs.
2066   QualType SrcRecordTy = E->getType();
2067   if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(
2068           isGLValueFromPointerDeref(E), SrcRecordTy)) {
2069     llvm::BasicBlock *BadTypeidBlock =
2070         CGF.createBasicBlock("typeid.bad_typeid");
2071     llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
2072
2073     llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr.getPointer());
2074     CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
2075
2076     CGF.EmitBlock(BadTypeidBlock);
2077     CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
2078     CGF.EmitBlock(EndBlock);
2079   }
2080
2081   return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
2082                                         StdTypeInfoPtrTy);
2083 }
2084
2085 llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
2086   llvm::Type *StdTypeInfoPtrTy = 
2087     ConvertType(E->getType())->getPointerTo();
2088   
2089   if (E->isTypeOperand()) {
2090     llvm::Constant *TypeInfo =
2091         CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
2092     return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
2093   }
2094
2095   // C++ [expr.typeid]p2:
2096   //   When typeid is applied to a glvalue expression whose type is a
2097   //   polymorphic class type, the result refers to a std::type_info object
2098   //   representing the type of the most derived object (that is, the dynamic
2099   //   type) to which the glvalue refers.
2100   if (E->isPotentiallyEvaluated())
2101     return EmitTypeidFromVTable(*this, E->getExprOperand(), 
2102                                 StdTypeInfoPtrTy);
2103
2104   QualType OperandTy = E->getExprOperand()->getType();
2105   return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
2106                                StdTypeInfoPtrTy);
2107 }
2108
2109 static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
2110                                           QualType DestTy) {
2111   llvm::Type *DestLTy = CGF.ConvertType(DestTy);
2112   if (DestTy->isPointerType())
2113     return llvm::Constant::getNullValue(DestLTy);
2114
2115   /// C++ [expr.dynamic.cast]p9:
2116   ///   A failed cast to reference type throws std::bad_cast
2117   if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
2118     return nullptr;
2119
2120   CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
2121   return llvm::UndefValue::get(DestLTy);
2122 }
2123
2124 llvm::Value *CodeGenFunction::EmitDynamicCast(Address ThisAddr,
2125                                               const CXXDynamicCastExpr *DCE) {
2126   CGM.EmitExplicitCastExprType(DCE, this);
2127   QualType DestTy = DCE->getTypeAsWritten();
2128
2129   if (DCE->isAlwaysNull())
2130     if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy))
2131       return T;
2132
2133   QualType SrcTy = DCE->getSubExpr()->getType();
2134
2135   // C++ [expr.dynamic.cast]p7:
2136   //   If T is "pointer to cv void," then the result is a pointer to the most
2137   //   derived object pointed to by v.
2138   const PointerType *DestPTy = DestTy->getAs<PointerType>();
2139
2140   bool isDynamicCastToVoid;
2141   QualType SrcRecordTy;
2142   QualType DestRecordTy;
2143   if (DestPTy) {
2144     isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType();
2145     SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
2146     DestRecordTy = DestPTy->getPointeeType();
2147   } else {
2148     isDynamicCastToVoid = false;
2149     SrcRecordTy = SrcTy;
2150     DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
2151   }
2152
2153   assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
2154
2155   // C++ [expr.dynamic.cast]p4: 
2156   //   If the value of v is a null pointer value in the pointer case, the result
2157   //   is the null pointer value of type T.
2158   bool ShouldNullCheckSrcValue =
2159       CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(),
2160                                                          SrcRecordTy);
2161
2162   llvm::BasicBlock *CastNull = nullptr;
2163   llvm::BasicBlock *CastNotNull = nullptr;
2164   llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
2165   
2166   if (ShouldNullCheckSrcValue) {
2167     CastNull = createBasicBlock("dynamic_cast.null");
2168     CastNotNull = createBasicBlock("dynamic_cast.notnull");
2169
2170     llvm::Value *IsNull = Builder.CreateIsNull(ThisAddr.getPointer());
2171     Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
2172     EmitBlock(CastNotNull);
2173   }
2174
2175   llvm::Value *Value;
2176   if (isDynamicCastToVoid) {
2177     Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, ThisAddr, SrcRecordTy,
2178                                                   DestTy);
2179   } else {
2180     assert(DestRecordTy->isRecordType() &&
2181            "destination type must be a record type!");
2182     Value = CGM.getCXXABI().EmitDynamicCastCall(*this, ThisAddr, SrcRecordTy,
2183                                                 DestTy, DestRecordTy, CastEnd);
2184     CastNotNull = Builder.GetInsertBlock();
2185   }
2186
2187   if (ShouldNullCheckSrcValue) {
2188     EmitBranch(CastEnd);
2189
2190     EmitBlock(CastNull);
2191     EmitBranch(CastEnd);
2192   }
2193
2194   EmitBlock(CastEnd);
2195
2196   if (ShouldNullCheckSrcValue) {
2197     llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
2198     PHI->addIncoming(Value, CastNotNull);
2199     PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
2200
2201     Value = PHI;
2202   }
2203
2204   return Value;
2205 }
2206
2207 void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
2208   RunCleanupsScope Scope(*this);
2209   LValue SlotLV = MakeAddrLValue(Slot.getAddress(), E->getType());
2210
2211   CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
2212   for (LambdaExpr::const_capture_init_iterator i = E->capture_init_begin(),
2213                                                e = E->capture_init_end();
2214        i != e; ++i, ++CurField) {
2215     // Emit initialization
2216     LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
2217     if (CurField->hasCapturedVLAType()) {
2218       auto VAT = CurField->getCapturedVLAType();
2219       EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
2220     } else {
2221       EmitInitializerForField(*CurField, LV, *i);
2222     }
2223   }
2224 }