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