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