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