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 "clang/Frontend/CodeGenOptions.h"
15 #include "CodeGenFunction.h"
16 #include "CGCXXABI.h"
17 #include "CGObjCRuntime.h"
18 #include "CGDebugInfo.h"
19 #include "llvm/Intrinsics.h"
20 #include "llvm/Support/CallSite.h"
21 
22 using namespace clang;
23 using namespace CodeGen;
24 
25 RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
26                                           llvm::Value *Callee,
27                                           ReturnValueSlot ReturnValue,
28                                           llvm::Value *This,
29                                           llvm::Value *VTT,
30                                           CallExpr::const_arg_iterator ArgBeg,
31                                           CallExpr::const_arg_iterator ArgEnd) {
32   assert(MD->isInstance() &&
33          "Trying to emit a member call expr on a static method!");
34 
35   const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
36 
37   CallArgList Args;
38 
39   // Push the this ptr.
40   Args.add(RValue::get(This), MD->getThisType(getContext()));
41 
42   // If there is a VTT parameter, emit it.
43   if (VTT) {
44     QualType T = getContext().getPointerType(getContext().VoidPtrTy);
45     Args.add(RValue::get(VTT), T);
46   }
47 
48   // And the rest of the call args
49   EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
50 
51   QualType ResultType = FPT->getResultType();
52   return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args,
53                                                  FPT->getExtInfo()),
54                   Callee, ReturnValue, Args, MD);
55 }
56 
57 static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) {
58   const Expr *E = Base;
59 
60   while (true) {
61     E = E->IgnoreParens();
62     if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
63       if (CE->getCastKind() == CK_DerivedToBase ||
64           CE->getCastKind() == CK_UncheckedDerivedToBase ||
65           CE->getCastKind() == CK_NoOp) {
66         E = CE->getSubExpr();
67         continue;
68       }
69     }
70 
71     break;
72   }
73 
74   QualType DerivedType = E->getType();
75   if (const PointerType *PTy = DerivedType->getAs<PointerType>())
76     DerivedType = PTy->getPointeeType();
77 
78   return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl());
79 }
80 
81 // FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
82 // quite what we want.
83 static const Expr *skipNoOpCastsAndParens(const Expr *E) {
84   while (true) {
85     if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
86       E = PE->getSubExpr();
87       continue;
88     }
89 
90     if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
91       if (CE->getCastKind() == CK_NoOp) {
92         E = CE->getSubExpr();
93         continue;
94       }
95     }
96     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
97       if (UO->getOpcode() == UO_Extension) {
98         E = UO->getSubExpr();
99         continue;
100       }
101     }
102     return E;
103   }
104 }
105 
106 /// canDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
107 /// expr can be devirtualized.
108 static bool canDevirtualizeMemberFunctionCalls(ASTContext &Context,
109                                                const Expr *Base,
110                                                const CXXMethodDecl *MD) {
111 
112   // When building with -fapple-kext, all calls must go through the vtable since
113   // the kernel linker can do runtime patching of vtables.
114   if (Context.getLangOptions().AppleKext)
115     return false;
116 
117   // If the most derived class is marked final, we know that no subclass can
118   // override this member function and so we can devirtualize it. For example:
119   //
120   // struct A { virtual void f(); }
121   // struct B final : A { };
122   //
123   // void f(B *b) {
124   //   b->f();
125   // }
126   //
127   const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base);
128   if (MostDerivedClassDecl->hasAttr<FinalAttr>())
129     return true;
130 
131   // If the member function is marked 'final', we know that it can't be
132   // overridden and can therefore devirtualize it.
133   if (MD->hasAttr<FinalAttr>())
134     return true;
135 
136   // Similarly, if the class itself is marked 'final' it can't be overridden
137   // and we can therefore devirtualize the member function call.
138   if (MD->getParent()->hasAttr<FinalAttr>())
139     return true;
140 
141   Base = skipNoOpCastsAndParens(Base);
142   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
143     if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
144       // This is a record decl. We know the type and can devirtualize it.
145       return VD->getType()->isRecordType();
146     }
147 
148     return false;
149   }
150 
151   // We can always devirtualize calls on temporary object expressions.
152   if (isa<CXXConstructExpr>(Base))
153     return true;
154 
155   // And calls on bound temporaries.
156   if (isa<CXXBindTemporaryExpr>(Base))
157     return true;
158 
159   // Check if this is a call expr that returns a record type.
160   if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
161     return CE->getCallReturnType()->isRecordType();
162 
163   // We can't devirtualize the call.
164   return false;
165 }
166 
167 // Note: This function also emit constructor calls to support a MSVC
168 // extensions allowing explicit constructor function call.
169 RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
170                                               ReturnValueSlot ReturnValue) {
171   const Expr *callee = CE->getCallee()->IgnoreParens();
172 
173   if (isa<BinaryOperator>(callee))
174     return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
175 
176   const MemberExpr *ME = cast<MemberExpr>(callee);
177   const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
178 
179   CGDebugInfo *DI = getDebugInfo();
180   if (DI && CGM.getCodeGenOpts().LimitDebugInfo
181       && !isa<CallExpr>(ME->getBase())) {
182     QualType PQTy = ME->getBase()->IgnoreParenImpCasts()->getType();
183     if (const PointerType * PTy = dyn_cast<PointerType>(PQTy)) {
184       DI->getOrCreateRecordType(PTy->getPointeeType(),
185                                 MD->getParent()->getLocation());
186     }
187   }
188 
189   if (MD->isStatic()) {
190     // The method is static, emit it as we would a regular call.
191     llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
192     return EmitCall(getContext().getPointerType(MD->getType()), Callee,
193                     ReturnValue, CE->arg_begin(), CE->arg_end());
194   }
195 
196   // Compute the object pointer.
197   llvm::Value *This;
198   if (ME->isArrow())
199     This = EmitScalarExpr(ME->getBase());
200   else
201     This = EmitLValue(ME->getBase()).getAddress();
202 
203   if (MD->isTrivial()) {
204     if (isa<CXXDestructorDecl>(MD)) return RValue::get(0);
205     if (isa<CXXConstructorDecl>(MD) &&
206         cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
207       return RValue::get(0);
208 
209     if (MD->isCopyAssignmentOperator()) {
210       // We don't like to generate the trivial copy assignment operator when
211       // it isn't necessary; just produce the proper effect here.
212       llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
213       EmitAggregateCopy(This, RHS, CE->getType());
214       return RValue::get(This);
215     }
216 
217     if (isa<CXXConstructorDecl>(MD) &&
218         cast<CXXConstructorDecl>(MD)->isCopyConstructor()) {
219       llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
220       EmitSynthesizedCXXCopyCtorCall(cast<CXXConstructorDecl>(MD), This, RHS,
221                                      CE->arg_begin(), CE->arg_end());
222       return RValue::get(This);
223     }
224     llvm_unreachable("unknown trivial member function");
225   }
226 
227   // Compute the function type we're calling.
228   const CGFunctionInfo *FInfo = 0;
229   if (isa<CXXDestructorDecl>(MD))
230     FInfo = &CGM.getTypes().getFunctionInfo(cast<CXXDestructorDecl>(MD),
231                                            Dtor_Complete);
232   else if (isa<CXXConstructorDecl>(MD))
233     FInfo = &CGM.getTypes().getFunctionInfo(cast<CXXConstructorDecl>(MD),
234                                             Ctor_Complete);
235   else
236     FInfo = &CGM.getTypes().getFunctionInfo(MD);
237 
238   const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
239   const llvm::Type *Ty
240     = CGM.getTypes().GetFunctionType(*FInfo, FPT->isVariadic());
241 
242   // C++ [class.virtual]p12:
243   //   Explicit qualification with the scope operator (5.1) suppresses the
244   //   virtual call mechanism.
245   //
246   // We also don't emit a virtual call if the base expression has a record type
247   // because then we know what the type is.
248   bool UseVirtualCall;
249   UseVirtualCall = MD->isVirtual() && !ME->hasQualifier()
250                    && !canDevirtualizeMemberFunctionCalls(getContext(),
251                                                           ME->getBase(), MD);
252   llvm::Value *Callee;
253   if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
254     if (UseVirtualCall) {
255       Callee = BuildVirtualCall(Dtor, Dtor_Complete, This, Ty);
256     } else {
257       if (getContext().getLangOptions().AppleKext &&
258           MD->isVirtual() &&
259           ME->hasQualifier())
260         Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
261       else
262         Callee = CGM.GetAddrOfFunction(GlobalDecl(Dtor, Dtor_Complete), Ty);
263     }
264   } else if (const CXXConstructorDecl *Ctor =
265                dyn_cast<CXXConstructorDecl>(MD)) {
266     Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
267   } else if (UseVirtualCall) {
268       Callee = BuildVirtualCall(MD, This, Ty);
269   } else {
270     if (getContext().getLangOptions().AppleKext &&
271         MD->isVirtual() &&
272         ME->hasQualifier())
273       Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
274     else
275       Callee = CGM.GetAddrOfFunction(MD, Ty);
276   }
277 
278   return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
279                            CE->arg_begin(), CE->arg_end());
280 }
281 
282 RValue
283 CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
284                                               ReturnValueSlot ReturnValue) {
285   const BinaryOperator *BO =
286       cast<BinaryOperator>(E->getCallee()->IgnoreParens());
287   const Expr *BaseExpr = BO->getLHS();
288   const Expr *MemFnExpr = BO->getRHS();
289 
290   const MemberPointerType *MPT =
291     MemFnExpr->getType()->castAs<MemberPointerType>();
292 
293   const FunctionProtoType *FPT =
294     MPT->getPointeeType()->castAs<FunctionProtoType>();
295   const CXXRecordDecl *RD =
296     cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
297 
298   // Get the member function pointer.
299   llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
300 
301   // Emit the 'this' pointer.
302   llvm::Value *This;
303 
304   if (BO->getOpcode() == BO_PtrMemI)
305     This = EmitScalarExpr(BaseExpr);
306   else
307     This = EmitLValue(BaseExpr).getAddress();
308 
309   // Ask the ABI to load the callee.  Note that This is modified.
310   llvm::Value *Callee =
311     CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, 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   // And the rest of the call args
322   EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
323   return EmitCall(CGM.getTypes().getFunctionInfo(Args, FPT), Callee,
324                   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   LValue LV = EmitLValue(E->getArg(0));
334   llvm::Value *This = LV.getAddress();
335 
336   if (MD->isCopyAssignmentOperator()) {
337     const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(MD->getDeclContext());
338     if (ClassDecl->hasTrivialCopyAssignment()) {
339       assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
340              "EmitCXXOperatorMemberCallExpr - user declared copy assignment");
341       llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
342       QualType Ty = E->getType();
343       EmitAggregateCopy(This, Src, Ty);
344       return RValue::get(This);
345     }
346   }
347 
348   const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
349   const llvm::Type *Ty =
350     CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
351                                    FPT->isVariadic());
352   llvm::Value *Callee;
353   if (MD->isVirtual() &&
354       !canDevirtualizeMemberFunctionCalls(getContext(),
355                                            E->getArg(0), MD))
356     Callee = BuildVirtualCall(MD, This, Ty);
357   else
358     Callee = CGM.GetAddrOfFunction(MD, Ty);
359 
360   return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
361                            E->arg_begin() + 1, E->arg_end());
362 }
363 
364 void
365 CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
366                                       AggValueSlot Dest) {
367   assert(!Dest.isIgnored() && "Must have a destination!");
368   const CXXConstructorDecl *CD = E->getConstructor();
369 
370   // If we require zero initialization before (or instead of) calling the
371   // constructor, as can be the case with a non-user-provided default
372   // constructor, emit the zero initialization now, unless destination is
373   // already zeroed.
374   if (E->requiresZeroInitialization() && !Dest.isZeroed())
375     EmitNullInitialization(Dest.getAddr(), E->getType());
376 
377   // If this is a call to a trivial default constructor, do nothing.
378   if (CD->isTrivial() && CD->isDefaultConstructor())
379     return;
380 
381   // Elide the constructor if we're constructing from a temporary.
382   // The temporary check is required because Sema sets this on NRVO
383   // returns.
384   if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
385     assert(getContext().hasSameUnqualifiedType(E->getType(),
386                                                E->getArg(0)->getType()));
387     if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
388       EmitAggExpr(E->getArg(0), Dest);
389       return;
390     }
391   }
392 
393   const ConstantArrayType *Array
394     = getContext().getAsConstantArrayType(E->getType());
395   if (Array) {
396     QualType BaseElementTy = getContext().getBaseElementType(Array);
397     const llvm::Type *BasePtr = ConvertType(BaseElementTy);
398     BasePtr = llvm::PointerType::getUnqual(BasePtr);
399     llvm::Value *BaseAddrPtr =
400       Builder.CreateBitCast(Dest.getAddr(), BasePtr);
401 
402     EmitCXXAggrConstructorCall(CD, Array, BaseAddrPtr,
403                                E->arg_begin(), E->arg_end());
404   }
405   else {
406     CXXCtorType Type;
407     CXXConstructExpr::ConstructionKind K = E->getConstructionKind();
408     if (K == CXXConstructExpr::CK_Delegating) {
409       // We should be emitting a constructor; GlobalDecl will assert this
410       Type = CurGD.getCtorType();
411     } else {
412       Type = (E->getConstructionKind() == CXXConstructExpr::CK_Complete)
413              ? Ctor_Complete : Ctor_Base;
414     }
415 
416     bool ForVirtualBase =
417       E->getConstructionKind() == CXXConstructExpr::CK_VirtualBase;
418 
419     // Call the constructor.
420     EmitCXXConstructorCall(CD, Type, ForVirtualBase, Dest.getAddr(),
421                            E->arg_begin(), E->arg_end());
422   }
423 }
424 
425 void
426 CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
427                                             llvm::Value *Src,
428                                             const Expr *Exp) {
429   if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
430     Exp = E->getSubExpr();
431   assert(isa<CXXConstructExpr>(Exp) &&
432          "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
433   const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
434   const CXXConstructorDecl *CD = E->getConstructor();
435   RunCleanupsScope Scope(*this);
436 
437   // If we require zero initialization before (or instead of) calling the
438   // constructor, as can be the case with a non-user-provided default
439   // constructor, emit the zero initialization now.
440   // FIXME. Do I still need this for a copy ctor synthesis?
441   if (E->requiresZeroInitialization())
442     EmitNullInitialization(Dest, E->getType());
443 
444   assert(!getContext().getAsConstantArrayType(E->getType())
445          && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
446   EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src,
447                                  E->arg_begin(), E->arg_end());
448 }
449 
450 /// Check whether the given operator new[] is the global placement
451 /// operator new[].
452 static bool IsPlacementOperatorNewArray(ASTContext &Ctx,
453                                         const FunctionDecl *Fn) {
454   // Must be in global scope.  Note that allocation functions can't be
455   // declared in namespaces.
456   if (!Fn->getDeclContext()->getRedeclContext()->isFileContext())
457     return false;
458 
459   // Signature must be void *operator new[](size_t, void*).
460   // The size_t is common to all operator new[]s.
461   if (Fn->getNumParams() != 2)
462     return false;
463 
464   CanQualType ParamType = Ctx.getCanonicalType(Fn->getParamDecl(1)->getType());
465   return (ParamType == Ctx.VoidPtrTy);
466 }
467 
468 static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
469                                         const CXXNewExpr *E) {
470   if (!E->isArray())
471     return CharUnits::Zero();
472 
473   // No cookie is required if the new operator being used is
474   // ::operator new[](size_t, void*).
475   const FunctionDecl *OperatorNew = E->getOperatorNew();
476   if (IsPlacementOperatorNewArray(CGF.getContext(), OperatorNew))
477     return CharUnits::Zero();
478 
479   return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
480 }
481 
482 static llvm::Value *EmitCXXNewAllocSize(ASTContext &Context,
483                                         CodeGenFunction &CGF,
484                                         const CXXNewExpr *E,
485                                         llvm::Value *&NumElements,
486                                         llvm::Value *&SizeWithoutCookie) {
487   QualType ElemType = E->getAllocatedType();
488 
489   const llvm::IntegerType *SizeTy =
490     cast<llvm::IntegerType>(CGF.ConvertType(CGF.getContext().getSizeType()));
491 
492   CharUnits TypeSize = CGF.getContext().getTypeSizeInChars(ElemType);
493 
494   if (!E->isArray()) {
495     SizeWithoutCookie = llvm::ConstantInt::get(SizeTy, TypeSize.getQuantity());
496     return SizeWithoutCookie;
497   }
498 
499   // Figure out the cookie size.
500   CharUnits CookieSize = CalculateCookiePadding(CGF, E);
501 
502   // Emit the array size expression.
503   // We multiply the size of all dimensions for NumElements.
504   // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
505   NumElements = CGF.EmitScalarExpr(E->getArraySize());
506   assert(NumElements->getType() == SizeTy && "element count not a size_t");
507 
508   uint64_t ArraySizeMultiplier = 1;
509   while (const ConstantArrayType *CAT
510              = CGF.getContext().getAsConstantArrayType(ElemType)) {
511     ElemType = CAT->getElementType();
512     ArraySizeMultiplier *= CAT->getSize().getZExtValue();
513   }
514 
515   llvm::Value *Size;
516 
517   // If someone is doing 'new int[42]' there is no need to do a dynamic check.
518   // Don't bloat the -O0 code.
519   if (llvm::ConstantInt *NumElementsC =
520         dyn_cast<llvm::ConstantInt>(NumElements)) {
521     llvm::APInt NEC = NumElementsC->getValue();
522     unsigned SizeWidth = NEC.getBitWidth();
523 
524     // Determine if there is an overflow here by doing an extended multiply.
525     NEC = NEC.zext(SizeWidth*2);
526     llvm::APInt SC(SizeWidth*2, TypeSize.getQuantity());
527     SC *= NEC;
528 
529     if (!CookieSize.isZero()) {
530       // Save the current size without a cookie.  We don't care if an
531       // overflow's already happened because SizeWithoutCookie isn't
532       // used if the allocator returns null or throws, as it should
533       // always do on an overflow.
534       llvm::APInt SWC = SC.trunc(SizeWidth);
535       SizeWithoutCookie = llvm::ConstantInt::get(SizeTy, SWC);
536 
537       // Add the cookie size.
538       SC += llvm::APInt(SizeWidth*2, CookieSize.getQuantity());
539     }
540 
541     if (SC.countLeadingZeros() >= SizeWidth) {
542       SC = SC.trunc(SizeWidth);
543       Size = llvm::ConstantInt::get(SizeTy, SC);
544     } else {
545       // On overflow, produce a -1 so operator new throws.
546       Size = llvm::Constant::getAllOnesValue(SizeTy);
547     }
548 
549     // Scale NumElements while we're at it.
550     uint64_t N = NEC.getZExtValue() * ArraySizeMultiplier;
551     NumElements = llvm::ConstantInt::get(SizeTy, N);
552 
553   // Otherwise, we don't need to do an overflow-checked multiplication if
554   // we're multiplying by one.
555   } else if (TypeSize.isOne()) {
556     assert(ArraySizeMultiplier == 1);
557 
558     Size = NumElements;
559 
560     // If we need a cookie, add its size in with an overflow check.
561     // This is maybe a little paranoid.
562     if (!CookieSize.isZero()) {
563       SizeWithoutCookie = Size;
564 
565       llvm::Value *CookieSizeV
566         = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
567 
568       const llvm::Type *Types[] = { SizeTy };
569       llvm::Value *UAddF
570         = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, Types, 1);
571       llvm::Value *AddRes
572         = CGF.Builder.CreateCall2(UAddF, Size, CookieSizeV);
573 
574       Size = CGF.Builder.CreateExtractValue(AddRes, 0);
575       llvm::Value *DidOverflow = CGF.Builder.CreateExtractValue(AddRes, 1);
576       Size = CGF.Builder.CreateSelect(DidOverflow,
577                                       llvm::ConstantInt::get(SizeTy, -1),
578                                       Size);
579     }
580 
581   // Otherwise use the int.umul.with.overflow intrinsic.
582   } else {
583     llvm::Value *OutermostElementSize
584       = llvm::ConstantInt::get(SizeTy, TypeSize.getQuantity());
585 
586     llvm::Value *NumOutermostElements = NumElements;
587 
588     // Scale NumElements by the array size multiplier.  This might
589     // overflow, but only if the multiplication below also overflows,
590     // in which case this multiplication isn't used.
591     if (ArraySizeMultiplier != 1)
592       NumElements = CGF.Builder.CreateMul(NumElements,
593                          llvm::ConstantInt::get(SizeTy, ArraySizeMultiplier));
594 
595     // The requested size of the outermost array is non-constant.
596     // Multiply that by the static size of the elements of that array;
597     // on unsigned overflow, set the size to -1 to trigger an
598     // exception from the allocation routine.  This is sufficient to
599     // prevent buffer overruns from the allocator returning a
600     // seemingly valid pointer to insufficient space.  This idea comes
601     // originally from MSVC, and GCC has an open bug requesting
602     // similar behavior:
603     //   http://gcc.gnu.org/bugzilla/show_bug.cgi?id=19351
604     //
605     // This will not be sufficient for C++0x, which requires a
606     // specific exception class (std::bad_array_new_length).
607     // That will require ABI support that has not yet been specified.
608     const llvm::Type *Types[] = { SizeTy };
609     llvm::Value *UMulF
610       = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, Types, 1);
611     llvm::Value *MulRes = CGF.Builder.CreateCall2(UMulF, NumOutermostElements,
612                                                   OutermostElementSize);
613 
614     // The overflow bit.
615     llvm::Value *DidOverflow = CGF.Builder.CreateExtractValue(MulRes, 1);
616 
617     // The result of the multiplication.
618     Size = CGF.Builder.CreateExtractValue(MulRes, 0);
619 
620     // If we have a cookie, we need to add that size in, too.
621     if (!CookieSize.isZero()) {
622       SizeWithoutCookie = Size;
623 
624       llvm::Value *CookieSizeV
625         = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
626       llvm::Value *UAddF
627         = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, Types, 1);
628       llvm::Value *AddRes
629         = CGF.Builder.CreateCall2(UAddF, SizeWithoutCookie, CookieSizeV);
630 
631       Size = CGF.Builder.CreateExtractValue(AddRes, 0);
632 
633       llvm::Value *AddDidOverflow = CGF.Builder.CreateExtractValue(AddRes, 1);
634       DidOverflow = CGF.Builder.CreateOr(DidOverflow, AddDidOverflow);
635     }
636 
637     Size = CGF.Builder.CreateSelect(DidOverflow,
638                                     llvm::ConstantInt::get(SizeTy, -1),
639                                     Size);
640   }
641 
642   if (CookieSize.isZero())
643     SizeWithoutCookie = Size;
644   else
645     assert(SizeWithoutCookie && "didn't set SizeWithoutCookie?");
646 
647   return Size;
648 }
649 
650 static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const CXXNewExpr *E,
651                                     llvm::Value *NewPtr) {
652 
653   assert(E->getNumConstructorArgs() == 1 &&
654          "Can only have one argument to initializer of POD type.");
655 
656   const Expr *Init = E->getConstructorArg(0);
657   QualType AllocType = E->getAllocatedType();
658 
659   unsigned Alignment =
660     CGF.getContext().getTypeAlignInChars(AllocType).getQuantity();
661   if (!CGF.hasAggregateLLVMType(AllocType))
662     CGF.EmitStoreOfScalar(CGF.EmitScalarExpr(Init), NewPtr,
663                           AllocType.isVolatileQualified(), Alignment,
664                           AllocType);
665   else if (AllocType->isAnyComplexType())
666     CGF.EmitComplexExprIntoAddr(Init, NewPtr,
667                                 AllocType.isVolatileQualified());
668   else {
669     AggValueSlot Slot
670       = AggValueSlot::forAddr(NewPtr, AllocType.isVolatileQualified(), true);
671     CGF.EmitAggExpr(Init, Slot);
672   }
673 }
674 
675 void
676 CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
677                                          llvm::Value *NewPtr,
678                                          llvm::Value *NumElements) {
679   // We have a POD type.
680   if (E->getNumConstructorArgs() == 0)
681     return;
682 
683   const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
684 
685   // Create a temporary for the loop index and initialize it with 0.
686   llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
687   llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
688   Builder.CreateStore(Zero, IndexPtr);
689 
690   // Start the loop with a block that tests the condition.
691   llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
692   llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
693 
694   EmitBlock(CondBlock);
695 
696   llvm::BasicBlock *ForBody = createBasicBlock("for.body");
697 
698   // Generate: if (loop-index < number-of-elements fall to the loop body,
699   // otherwise, go to the block after the for-loop.
700   llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
701   llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
702   // If the condition is true, execute the body.
703   Builder.CreateCondBr(IsLess, ForBody, AfterFor);
704 
705   EmitBlock(ForBody);
706 
707   llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
708   // Inside the loop body, emit the constructor call on the array element.
709   Counter = Builder.CreateLoad(IndexPtr);
710   llvm::Value *Address = Builder.CreateInBoundsGEP(NewPtr, Counter,
711                                                    "arrayidx");
712   StoreAnyExprIntoOneUnit(*this, E, Address);
713 
714   EmitBlock(ContinueBlock);
715 
716   // Emit the increment of the loop counter.
717   llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
718   Counter = Builder.CreateLoad(IndexPtr);
719   NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
720   Builder.CreateStore(NextVal, IndexPtr);
721 
722   // Finally, branch back up to the condition for the next iteration.
723   EmitBranch(CondBlock);
724 
725   // Emit the fall-through block.
726   EmitBlock(AfterFor, true);
727 }
728 
729 static void EmitZeroMemSet(CodeGenFunction &CGF, QualType T,
730                            llvm::Value *NewPtr, llvm::Value *Size) {
731   CGF.EmitCastToVoidPtr(NewPtr);
732   CharUnits Alignment = CGF.getContext().getTypeAlignInChars(T);
733   CGF.Builder.CreateMemSet(NewPtr, CGF.Builder.getInt8(0), Size,
734                            Alignment.getQuantity(), false);
735 }
736 
737 static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
738                                llvm::Value *NewPtr,
739                                llvm::Value *NumElements,
740                                llvm::Value *AllocSizeWithoutCookie) {
741   if (E->isArray()) {
742     if (CXXConstructorDecl *Ctor = E->getConstructor()) {
743       bool RequiresZeroInitialization = false;
744       if (Ctor->getParent()->hasTrivialConstructor()) {
745         // If new expression did not specify value-initialization, then there
746         // is no initialization.
747         if (!E->hasInitializer() || Ctor->getParent()->isEmpty())
748           return;
749 
750         if (CGF.CGM.getTypes().isZeroInitializable(E->getAllocatedType())) {
751           // Optimization: since zero initialization will just set the memory
752           // to all zeroes, generate a single memset to do it in one shot.
753           EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
754                          AllocSizeWithoutCookie);
755           return;
756         }
757 
758         RequiresZeroInitialization = true;
759       }
760 
761       CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr,
762                                      E->constructor_arg_begin(),
763                                      E->constructor_arg_end(),
764                                      RequiresZeroInitialization);
765       return;
766     } else if (E->getNumConstructorArgs() == 1 &&
767                isa<ImplicitValueInitExpr>(E->getConstructorArg(0))) {
768       // Optimization: since zero initialization will just set the memory
769       // to all zeroes, generate a single memset to do it in one shot.
770       EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
771                      AllocSizeWithoutCookie);
772       return;
773     } else {
774       CGF.EmitNewArrayInitializer(E, NewPtr, NumElements);
775       return;
776     }
777   }
778 
779   if (CXXConstructorDecl *Ctor = E->getConstructor()) {
780     // Per C++ [expr.new]p15, if we have an initializer, then we're performing
781     // direct initialization. C++ [dcl.init]p5 requires that we
782     // zero-initialize storage if there are no user-declared constructors.
783     if (E->hasInitializer() &&
784         !Ctor->getParent()->hasUserDeclaredConstructor() &&
785         !Ctor->getParent()->isEmpty())
786       CGF.EmitNullInitialization(NewPtr, E->getAllocatedType());
787 
788     CGF.EmitCXXConstructorCall(Ctor, Ctor_Complete, /*ForVirtualBase=*/false,
789                                NewPtr, E->constructor_arg_begin(),
790                                E->constructor_arg_end());
791 
792     return;
793   }
794   // We have a POD type.
795   if (E->getNumConstructorArgs() == 0)
796     return;
797 
798   StoreAnyExprIntoOneUnit(CGF, E, NewPtr);
799 }
800 
801 namespace {
802   /// A cleanup to call the given 'operator delete' function upon
803   /// abnormal exit from a new expression.
804   class CallDeleteDuringNew : public EHScopeStack::Cleanup {
805     size_t NumPlacementArgs;
806     const FunctionDecl *OperatorDelete;
807     llvm::Value *Ptr;
808     llvm::Value *AllocSize;
809 
810     RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
811 
812   public:
813     static size_t getExtraSize(size_t NumPlacementArgs) {
814       return NumPlacementArgs * sizeof(RValue);
815     }
816 
817     CallDeleteDuringNew(size_t NumPlacementArgs,
818                         const FunctionDecl *OperatorDelete,
819                         llvm::Value *Ptr,
820                         llvm::Value *AllocSize)
821       : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
822         Ptr(Ptr), AllocSize(AllocSize) {}
823 
824     void setPlacementArg(unsigned I, RValue Arg) {
825       assert(I < NumPlacementArgs && "index out of range");
826       getPlacementArgs()[I] = Arg;
827     }
828 
829     void Emit(CodeGenFunction &CGF, bool IsForEH) {
830       const FunctionProtoType *FPT
831         = OperatorDelete->getType()->getAs<FunctionProtoType>();
832       assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
833              (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
834 
835       CallArgList DeleteArgs;
836 
837       // The first argument is always a void*.
838       FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
839       DeleteArgs.add(RValue::get(Ptr), *AI++);
840 
841       // A member 'operator delete' can take an extra 'size_t' argument.
842       if (FPT->getNumArgs() == NumPlacementArgs + 2)
843         DeleteArgs.add(RValue::get(AllocSize), *AI++);
844 
845       // Pass the rest of the arguments, which must match exactly.
846       for (unsigned I = 0; I != NumPlacementArgs; ++I)
847         DeleteArgs.add(getPlacementArgs()[I], *AI++);
848 
849       // Call 'operator delete'.
850       CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
851                    CGF.CGM.GetAddrOfFunction(OperatorDelete),
852                    ReturnValueSlot(), DeleteArgs, OperatorDelete);
853     }
854   };
855 
856   /// A cleanup to call the given 'operator delete' function upon
857   /// abnormal exit from a new expression when the new expression is
858   /// conditional.
859   class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
860     size_t NumPlacementArgs;
861     const FunctionDecl *OperatorDelete;
862     DominatingValue<RValue>::saved_type Ptr;
863     DominatingValue<RValue>::saved_type AllocSize;
864 
865     DominatingValue<RValue>::saved_type *getPlacementArgs() {
866       return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
867     }
868 
869   public:
870     static size_t getExtraSize(size_t NumPlacementArgs) {
871       return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
872     }
873 
874     CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
875                                    const FunctionDecl *OperatorDelete,
876                                    DominatingValue<RValue>::saved_type Ptr,
877                               DominatingValue<RValue>::saved_type AllocSize)
878       : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
879         Ptr(Ptr), AllocSize(AllocSize) {}
880 
881     void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
882       assert(I < NumPlacementArgs && "index out of range");
883       getPlacementArgs()[I] = Arg;
884     }
885 
886     void Emit(CodeGenFunction &CGF, bool IsForEH) {
887       const FunctionProtoType *FPT
888         = OperatorDelete->getType()->getAs<FunctionProtoType>();
889       assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
890              (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
891 
892       CallArgList DeleteArgs;
893 
894       // The first argument is always a void*.
895       FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
896       DeleteArgs.add(Ptr.restore(CGF), *AI++);
897 
898       // A member 'operator delete' can take an extra 'size_t' argument.
899       if (FPT->getNumArgs() == NumPlacementArgs + 2) {
900         RValue RV = AllocSize.restore(CGF);
901         DeleteArgs.add(RV, *AI++);
902       }
903 
904       // Pass the rest of the arguments, which must match exactly.
905       for (unsigned I = 0; I != NumPlacementArgs; ++I) {
906         RValue RV = getPlacementArgs()[I].restore(CGF);
907         DeleteArgs.add(RV, *AI++);
908       }
909 
910       // Call 'operator delete'.
911       CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
912                    CGF.CGM.GetAddrOfFunction(OperatorDelete),
913                    ReturnValueSlot(), DeleteArgs, OperatorDelete);
914     }
915   };
916 }
917 
918 /// Enter a cleanup to call 'operator delete' if the initializer in a
919 /// new-expression throws.
920 static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
921                                   const CXXNewExpr *E,
922                                   llvm::Value *NewPtr,
923                                   llvm::Value *AllocSize,
924                                   const CallArgList &NewArgs) {
925   // If we're not inside a conditional branch, then the cleanup will
926   // dominate and we can do the easier (and more efficient) thing.
927   if (!CGF.isInConditionalBranch()) {
928     CallDeleteDuringNew *Cleanup = CGF.EHStack
929       .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
930                                                  E->getNumPlacementArgs(),
931                                                  E->getOperatorDelete(),
932                                                  NewPtr, AllocSize);
933     for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
934       Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
935 
936     return;
937   }
938 
939   // Otherwise, we need to save all this stuff.
940   DominatingValue<RValue>::saved_type SavedNewPtr =
941     DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
942   DominatingValue<RValue>::saved_type SavedAllocSize =
943     DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
944 
945   CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
946     .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(InactiveEHCleanup,
947                                                  E->getNumPlacementArgs(),
948                                                  E->getOperatorDelete(),
949                                                  SavedNewPtr,
950                                                  SavedAllocSize);
951   for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
952     Cleanup->setPlacementArg(I,
953                      DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
954 
955   CGF.ActivateCleanupBlock(CGF.EHStack.stable_begin());
956 }
957 
958 llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
959   // The element type being allocated.
960   QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
961 
962   // 1. Build a call to the allocation function.
963   FunctionDecl *allocator = E->getOperatorNew();
964   const FunctionProtoType *allocatorType =
965     allocator->getType()->castAs<FunctionProtoType>();
966 
967   CallArgList allocatorArgs;
968 
969   // The allocation size is the first argument.
970   QualType sizeType = getContext().getSizeType();
971 
972   llvm::Value *numElements = 0;
973   llvm::Value *allocSizeWithoutCookie = 0;
974   llvm::Value *allocSize =
975     EmitCXXNewAllocSize(getContext(), *this, E, numElements,
976                         allocSizeWithoutCookie);
977 
978   allocatorArgs.add(RValue::get(allocSize), sizeType);
979 
980   // Emit the rest of the arguments.
981   // FIXME: Ideally, this should just use EmitCallArgs.
982   CXXNewExpr::const_arg_iterator placementArg = E->placement_arg_begin();
983 
984   // First, use the types from the function type.
985   // We start at 1 here because the first argument (the allocation size)
986   // has already been emitted.
987   for (unsigned i = 1, e = allocatorType->getNumArgs(); i != e;
988        ++i, ++placementArg) {
989     QualType argType = allocatorType->getArgType(i);
990 
991     assert(getContext().hasSameUnqualifiedType(argType.getNonReferenceType(),
992                                                placementArg->getType()) &&
993            "type mismatch in call argument!");
994 
995     EmitCallArg(allocatorArgs, *placementArg, argType);
996   }
997 
998   // Either we've emitted all the call args, or we have a call to a
999   // variadic function.
1000   assert((placementArg == E->placement_arg_end() ||
1001           allocatorType->isVariadic()) &&
1002          "Extra arguments to non-variadic function!");
1003 
1004   // If we still have any arguments, emit them using the type of the argument.
1005   for (CXXNewExpr::const_arg_iterator placementArgsEnd = E->placement_arg_end();
1006        placementArg != placementArgsEnd; ++placementArg) {
1007     EmitCallArg(allocatorArgs, *placementArg, placementArg->getType());
1008   }
1009 
1010   // Emit the allocation call.
1011   RValue RV =
1012     EmitCall(CGM.getTypes().getFunctionInfo(allocatorArgs, allocatorType),
1013              CGM.GetAddrOfFunction(allocator), ReturnValueSlot(),
1014              allocatorArgs, allocator);
1015 
1016   // Emit a null check on the allocation result if the allocation
1017   // function is allowed to return null (because it has a non-throwing
1018   // exception spec; for this part, we inline
1019   // CXXNewExpr::shouldNullCheckAllocation()) and we have an
1020   // interesting initializer.
1021   bool nullCheck = allocatorType->isNothrow(getContext()) &&
1022     !(allocType->isPODType() && !E->hasInitializer());
1023 
1024   llvm::BasicBlock *nullCheckBB = 0;
1025   llvm::BasicBlock *contBB = 0;
1026 
1027   llvm::Value *allocation = RV.getScalarVal();
1028   unsigned AS =
1029     cast<llvm::PointerType>(allocation->getType())->getAddressSpace();
1030 
1031   // The null-check means that the initializer is conditionally
1032   // evaluated.
1033   ConditionalEvaluation conditional(*this);
1034 
1035   if (nullCheck) {
1036     conditional.begin(*this);
1037 
1038     nullCheckBB = Builder.GetInsertBlock();
1039     llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1040     contBB = createBasicBlock("new.cont");
1041 
1042     llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1043     Builder.CreateCondBr(isNull, contBB, notNullBB);
1044     EmitBlock(notNullBB);
1045   }
1046 
1047   assert((allocSize == allocSizeWithoutCookie) ==
1048          CalculateCookiePadding(*this, E).isZero());
1049   if (allocSize != allocSizeWithoutCookie) {
1050     assert(E->isArray());
1051     allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1052                                                        numElements,
1053                                                        E, allocType);
1054   }
1055 
1056   // If there's an operator delete, enter a cleanup to call it if an
1057   // exception is thrown.
1058   EHScopeStack::stable_iterator operatorDeleteCleanup;
1059   if (E->getOperatorDelete()) {
1060     EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1061     operatorDeleteCleanup = EHStack.stable_begin();
1062   }
1063 
1064   const llvm::Type *elementPtrTy
1065     = ConvertTypeForMem(allocType)->getPointerTo(AS);
1066   llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
1067 
1068   if (E->isArray()) {
1069     EmitNewInitializer(*this, E, result, numElements, allocSizeWithoutCookie);
1070 
1071     // NewPtr is a pointer to the base element type.  If we're
1072     // allocating an array of arrays, we'll need to cast back to the
1073     // array pointer type.
1074     const llvm::Type *resultType = ConvertTypeForMem(E->getType());
1075     if (result->getType() != resultType)
1076       result = Builder.CreateBitCast(result, resultType);
1077   } else {
1078     EmitNewInitializer(*this, E, result, numElements, allocSizeWithoutCookie);
1079   }
1080 
1081   // Deactivate the 'operator delete' cleanup if we finished
1082   // initialization.
1083   if (operatorDeleteCleanup.isValid())
1084     DeactivateCleanupBlock(operatorDeleteCleanup);
1085 
1086   if (nullCheck) {
1087     conditional.end(*this);
1088 
1089     llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1090     EmitBlock(contBB);
1091 
1092     llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
1093     PHI->addIncoming(result, notNullBB);
1094     PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1095                      nullCheckBB);
1096 
1097     result = PHI;
1098   }
1099 
1100   return result;
1101 }
1102 
1103 void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1104                                      llvm::Value *Ptr,
1105                                      QualType DeleteTy) {
1106   assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1107 
1108   const FunctionProtoType *DeleteFTy =
1109     DeleteFD->getType()->getAs<FunctionProtoType>();
1110 
1111   CallArgList DeleteArgs;
1112 
1113   // Check if we need to pass the size to the delete operator.
1114   llvm::Value *Size = 0;
1115   QualType SizeTy;
1116   if (DeleteFTy->getNumArgs() == 2) {
1117     SizeTy = DeleteFTy->getArgType(1);
1118     CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1119     Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1120                                   DeleteTypeSize.getQuantity());
1121   }
1122 
1123   QualType ArgTy = DeleteFTy->getArgType(0);
1124   llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
1125   DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
1126 
1127   if (Size)
1128     DeleteArgs.add(RValue::get(Size), SizeTy);
1129 
1130   // Emit the call to delete.
1131   EmitCall(CGM.getTypes().getFunctionInfo(DeleteArgs, DeleteFTy),
1132            CGM.GetAddrOfFunction(DeleteFD), ReturnValueSlot(),
1133            DeleteArgs, DeleteFD);
1134 }
1135 
1136 namespace {
1137   /// Calls the given 'operator delete' on a single object.
1138   struct CallObjectDelete : EHScopeStack::Cleanup {
1139     llvm::Value *Ptr;
1140     const FunctionDecl *OperatorDelete;
1141     QualType ElementType;
1142 
1143     CallObjectDelete(llvm::Value *Ptr,
1144                      const FunctionDecl *OperatorDelete,
1145                      QualType ElementType)
1146       : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1147 
1148     void Emit(CodeGenFunction &CGF, bool IsForEH) {
1149       CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1150     }
1151   };
1152 }
1153 
1154 /// Emit the code for deleting a single object.
1155 static void EmitObjectDelete(CodeGenFunction &CGF,
1156                              const FunctionDecl *OperatorDelete,
1157                              llvm::Value *Ptr,
1158                              QualType ElementType) {
1159   // Find the destructor for the type, if applicable.  If the
1160   // destructor is virtual, we'll just emit the vcall and return.
1161   const CXXDestructorDecl *Dtor = 0;
1162   if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1163     CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1164     if (!RD->hasTrivialDestructor()) {
1165       Dtor = RD->getDestructor();
1166 
1167       if (Dtor->isVirtual()) {
1168         const llvm::Type *Ty =
1169           CGF.getTypes().GetFunctionType(CGF.getTypes().getFunctionInfo(Dtor,
1170                                                                Dtor_Complete),
1171                                          /*isVariadic=*/false);
1172 
1173         llvm::Value *Callee
1174           = CGF.BuildVirtualCall(Dtor, Dtor_Deleting, Ptr, Ty);
1175         CGF.EmitCXXMemberCall(Dtor, Callee, ReturnValueSlot(), Ptr, /*VTT=*/0,
1176                               0, 0);
1177 
1178         // The dtor took care of deleting the object.
1179         return;
1180       }
1181     }
1182   }
1183 
1184   // Make sure that we call delete even if the dtor throws.
1185   // This doesn't have to a conditional cleanup because we're going
1186   // to pop it off in a second.
1187   CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1188                                             Ptr, OperatorDelete, ElementType);
1189 
1190   if (Dtor)
1191     CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1192                               /*ForVirtualBase=*/false, Ptr);
1193 
1194   CGF.PopCleanupBlock();
1195 }
1196 
1197 namespace {
1198   /// Calls the given 'operator delete' on an array of objects.
1199   struct CallArrayDelete : EHScopeStack::Cleanup {
1200     llvm::Value *Ptr;
1201     const FunctionDecl *OperatorDelete;
1202     llvm::Value *NumElements;
1203     QualType ElementType;
1204     CharUnits CookieSize;
1205 
1206     CallArrayDelete(llvm::Value *Ptr,
1207                     const FunctionDecl *OperatorDelete,
1208                     llvm::Value *NumElements,
1209                     QualType ElementType,
1210                     CharUnits CookieSize)
1211       : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1212         ElementType(ElementType), CookieSize(CookieSize) {}
1213 
1214     void Emit(CodeGenFunction &CGF, bool IsForEH) {
1215       const FunctionProtoType *DeleteFTy =
1216         OperatorDelete->getType()->getAs<FunctionProtoType>();
1217       assert(DeleteFTy->getNumArgs() == 1 || DeleteFTy->getNumArgs() == 2);
1218 
1219       CallArgList Args;
1220 
1221       // Pass the pointer as the first argument.
1222       QualType VoidPtrTy = DeleteFTy->getArgType(0);
1223       llvm::Value *DeletePtr
1224         = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
1225       Args.add(RValue::get(DeletePtr), VoidPtrTy);
1226 
1227       // Pass the original requested size as the second argument.
1228       if (DeleteFTy->getNumArgs() == 2) {
1229         QualType size_t = DeleteFTy->getArgType(1);
1230         const llvm::IntegerType *SizeTy
1231           = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1232 
1233         CharUnits ElementTypeSize =
1234           CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1235 
1236         // The size of an element, multiplied by the number of elements.
1237         llvm::Value *Size
1238           = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1239         Size = CGF.Builder.CreateMul(Size, NumElements);
1240 
1241         // Plus the size of the cookie if applicable.
1242         if (!CookieSize.isZero()) {
1243           llvm::Value *CookieSizeV
1244             = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1245           Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1246         }
1247 
1248         Args.add(RValue::get(Size), size_t);
1249       }
1250 
1251       // Emit the call to delete.
1252       CGF.EmitCall(CGF.getTypes().getFunctionInfo(Args, DeleteFTy),
1253                    CGF.CGM.GetAddrOfFunction(OperatorDelete),
1254                    ReturnValueSlot(), Args, OperatorDelete);
1255     }
1256   };
1257 }
1258 
1259 /// Emit the code for deleting an array of objects.
1260 static void EmitArrayDelete(CodeGenFunction &CGF,
1261                             const CXXDeleteExpr *E,
1262                             llvm::Value *Ptr,
1263                             QualType ElementType) {
1264   llvm::Value *NumElements = 0;
1265   llvm::Value *AllocatedPtr = 0;
1266   CharUnits CookieSize;
1267   CGF.CGM.getCXXABI().ReadArrayCookie(CGF, Ptr, E, ElementType,
1268                                       NumElements, AllocatedPtr, CookieSize);
1269 
1270   assert(AllocatedPtr && "ReadArrayCookie didn't set AllocatedPtr");
1271 
1272   // Make sure that we call delete even if one of the dtors throws.
1273   const FunctionDecl *OperatorDelete = E->getOperatorDelete();
1274   CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
1275                                            AllocatedPtr, OperatorDelete,
1276                                            NumElements, ElementType,
1277                                            CookieSize);
1278 
1279   if (const CXXRecordDecl *RD = ElementType->getAsCXXRecordDecl()) {
1280     if (!RD->hasTrivialDestructor()) {
1281       assert(NumElements && "ReadArrayCookie didn't find element count"
1282                             " for a class with destructor");
1283       CGF.EmitCXXAggrDestructorCall(RD->getDestructor(), NumElements, Ptr);
1284     }
1285   }
1286 
1287   CGF.PopCleanupBlock();
1288 }
1289 
1290 void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
1291 
1292   // Get at the argument before we performed the implicit conversion
1293   // to void*.
1294   const Expr *Arg = E->getArgument();
1295   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
1296     if (ICE->getCastKind() != CK_UserDefinedConversion &&
1297         ICE->getType()->isVoidPointerType())
1298       Arg = ICE->getSubExpr();
1299     else
1300       break;
1301   }
1302 
1303   llvm::Value *Ptr = EmitScalarExpr(Arg);
1304 
1305   // Null check the pointer.
1306   llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1307   llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1308 
1309   llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
1310 
1311   Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1312   EmitBlock(DeleteNotNull);
1313 
1314   // We might be deleting a pointer to array.  If so, GEP down to the
1315   // first non-array element.
1316   // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1317   QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1318   if (DeleteTy->isConstantArrayType()) {
1319     llvm::Value *Zero = Builder.getInt32(0);
1320     llvm::SmallVector<llvm::Value*,8> GEP;
1321 
1322     GEP.push_back(Zero); // point at the outermost array
1323 
1324     // For each layer of array type we're pointing at:
1325     while (const ConstantArrayType *Arr
1326              = getContext().getAsConstantArrayType(DeleteTy)) {
1327       // 1. Unpeel the array type.
1328       DeleteTy = Arr->getElementType();
1329 
1330       // 2. GEP to the first element of the array.
1331       GEP.push_back(Zero);
1332     }
1333 
1334     Ptr = Builder.CreateInBoundsGEP(Ptr, GEP.begin(), GEP.end(), "del.first");
1335   }
1336 
1337   assert(ConvertTypeForMem(DeleteTy) ==
1338          cast<llvm::PointerType>(Ptr->getType())->getElementType());
1339 
1340   if (E->isArrayForm()) {
1341     EmitArrayDelete(*this, E, Ptr, DeleteTy);
1342   } else {
1343     EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy);
1344   }
1345 
1346   EmitBlock(DeleteEnd);
1347 }
1348 
1349 static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1350   // void __cxa_bad_typeid();
1351 
1352   const llvm::Type *VoidTy = llvm::Type::getVoidTy(CGF.getLLVMContext());
1353   const llvm::FunctionType *FTy =
1354   llvm::FunctionType::get(VoidTy, false);
1355 
1356   return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1357 }
1358 
1359 static void EmitBadTypeidCall(CodeGenFunction &CGF) {
1360   llvm::Value *Fn = getBadTypeidFn(CGF);
1361   CGF.EmitCallOrInvoke(Fn, 0, 0).setDoesNotReturn();
1362   CGF.Builder.CreateUnreachable();
1363 }
1364 
1365 static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF,
1366                                          const Expr *E,
1367                                          const llvm::Type *StdTypeInfoPtrTy) {
1368   // Get the vtable pointer.
1369   llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
1370 
1371   // C++ [expr.typeid]p2:
1372   //   If the glvalue expression is obtained by applying the unary * operator to
1373   //   a pointer and the pointer is a null pointer value, the typeid expression
1374   //   throws the std::bad_typeid exception.
1375   if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
1376     if (UO->getOpcode() == UO_Deref) {
1377       llvm::BasicBlock *BadTypeidBlock =
1378         CGF.createBasicBlock("typeid.bad_typeid");
1379       llvm::BasicBlock *EndBlock =
1380         CGF.createBasicBlock("typeid.end");
1381 
1382       llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
1383       CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
1384 
1385       CGF.EmitBlock(BadTypeidBlock);
1386       EmitBadTypeidCall(CGF);
1387       CGF.EmitBlock(EndBlock);
1388     }
1389   }
1390 
1391   llvm::Value *Value = CGF.GetVTablePtr(ThisPtr,
1392                                         StdTypeInfoPtrTy->getPointerTo());
1393 
1394   // Load the type info.
1395   Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
1396   return CGF.Builder.CreateLoad(Value);
1397 }
1398 
1399 llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
1400   const llvm::Type *StdTypeInfoPtrTy =
1401     ConvertType(E->getType())->getPointerTo();
1402 
1403   if (E->isTypeOperand()) {
1404     llvm::Constant *TypeInfo =
1405       CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand());
1406     return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
1407   }
1408 
1409   // C++ [expr.typeid]p2:
1410   //   When typeid is applied to a glvalue expression whose type is a
1411   //   polymorphic class type, the result refers to a std::type_info object
1412   //   representing the type of the most derived object (that is, the dynamic
1413   //   type) to which the glvalue refers.
1414   if (E->getExprOperand()->isGLValue()) {
1415     if (const RecordType *RT =
1416           E->getExprOperand()->getType()->getAs<RecordType>()) {
1417       const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1418       if (RD->isPolymorphic())
1419         return EmitTypeidFromVTable(*this, E->getExprOperand(),
1420                                     StdTypeInfoPtrTy);
1421     }
1422   }
1423 
1424   QualType OperandTy = E->getExprOperand()->getType();
1425   return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1426                                StdTypeInfoPtrTy);
1427 }
1428 
1429 static llvm::Constant *getDynamicCastFn(CodeGenFunction &CGF) {
1430   // void *__dynamic_cast(const void *sub,
1431   //                      const abi::__class_type_info *src,
1432   //                      const abi::__class_type_info *dst,
1433   //                      std::ptrdiff_t src2dst_offset);
1434 
1435   const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
1436   const llvm::Type *PtrDiffTy =
1437     CGF.ConvertType(CGF.getContext().getPointerDiffType());
1438 
1439   const llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
1440 
1441   const llvm::FunctionType *FTy =
1442     llvm::FunctionType::get(Int8PtrTy, Args, false);
1443 
1444   return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast");
1445 }
1446 
1447 static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1448   // void __cxa_bad_cast();
1449 
1450   const llvm::Type *VoidTy = llvm::Type::getVoidTy(CGF.getLLVMContext());
1451   const llvm::FunctionType *FTy =
1452     llvm::FunctionType::get(VoidTy, false);
1453 
1454   return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1455 }
1456 
1457 static void EmitBadCastCall(CodeGenFunction &CGF) {
1458   llvm::Value *Fn = getBadCastFn(CGF);
1459   CGF.EmitCallOrInvoke(Fn, 0, 0).setDoesNotReturn();
1460   CGF.Builder.CreateUnreachable();
1461 }
1462 
1463 static llvm::Value *
1464 EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
1465                     QualType SrcTy, QualType DestTy,
1466                     llvm::BasicBlock *CastEnd) {
1467   const llvm::Type *PtrDiffLTy =
1468     CGF.ConvertType(CGF.getContext().getPointerDiffType());
1469   const llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1470 
1471   if (const PointerType *PTy = DestTy->getAs<PointerType>()) {
1472     if (PTy->getPointeeType()->isVoidType()) {
1473       // C++ [expr.dynamic.cast]p7:
1474       //   If T is "pointer to cv void," then the result is a pointer to the
1475       //   most derived object pointed to by v.
1476 
1477       // Get the vtable pointer.
1478       llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1479 
1480       // Get the offset-to-top from the vtable.
1481       llvm::Value *OffsetToTop =
1482         CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1483       OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1484 
1485       // Finally, add the offset to the pointer.
1486       Value = CGF.EmitCastToVoidPtr(Value);
1487       Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1488 
1489       return CGF.Builder.CreateBitCast(Value, DestLTy);
1490     }
1491   }
1492 
1493   QualType SrcRecordTy;
1494   QualType DestRecordTy;
1495 
1496   if (const PointerType *DestPTy = DestTy->getAs<PointerType>()) {
1497     SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
1498     DestRecordTy = DestPTy->getPointeeType();
1499   } else {
1500     SrcRecordTy = SrcTy;
1501     DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
1502   }
1503 
1504   assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
1505   assert(DestRecordTy->isRecordType() && "dest type must be a record type!");
1506 
1507   llvm::Value *SrcRTTI =
1508     CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1509   llvm::Value *DestRTTI =
1510     CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1511 
1512   // FIXME: Actually compute a hint here.
1513   llvm::Value *OffsetHint = llvm::ConstantInt::get(PtrDiffLTy, -1ULL);
1514 
1515   // Emit the call to __dynamic_cast.
1516   Value = CGF.EmitCastToVoidPtr(Value);
1517   Value = CGF.Builder.CreateCall4(getDynamicCastFn(CGF), Value,
1518                                   SrcRTTI, DestRTTI, OffsetHint);
1519   Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1520 
1521   /// C++ [expr.dynamic.cast]p9:
1522   ///   A failed cast to reference type throws std::bad_cast
1523   if (DestTy->isReferenceType()) {
1524     llvm::BasicBlock *BadCastBlock =
1525       CGF.createBasicBlock("dynamic_cast.bad_cast");
1526 
1527     llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1528     CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1529 
1530     CGF.EmitBlock(BadCastBlock);
1531     EmitBadCastCall(CGF);
1532   }
1533 
1534   return Value;
1535 }
1536 
1537 static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1538                                           QualType DestTy) {
1539   const llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1540   if (DestTy->isPointerType())
1541     return llvm::Constant::getNullValue(DestLTy);
1542 
1543   /// C++ [expr.dynamic.cast]p9:
1544   ///   A failed cast to reference type throws std::bad_cast
1545   EmitBadCastCall(CGF);
1546 
1547   CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1548   return llvm::UndefValue::get(DestLTy);
1549 }
1550 
1551 llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
1552                                               const CXXDynamicCastExpr *DCE) {
1553   QualType DestTy = DCE->getTypeAsWritten();
1554 
1555   if (DCE->isAlwaysNull())
1556     return EmitDynamicCastToNull(*this, DestTy);
1557 
1558   QualType SrcTy = DCE->getSubExpr()->getType();
1559 
1560   // C++ [expr.dynamic.cast]p4:
1561   //   If the value of v is a null pointer value in the pointer case, the result
1562   //   is the null pointer value of type T.
1563   bool ShouldNullCheckSrcValue = SrcTy->isPointerType();
1564 
1565   llvm::BasicBlock *CastNull = 0;
1566   llvm::BasicBlock *CastNotNull = 0;
1567   llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
1568 
1569   if (ShouldNullCheckSrcValue) {
1570     CastNull = createBasicBlock("dynamic_cast.null");
1571     CastNotNull = createBasicBlock("dynamic_cast.notnull");
1572 
1573     llvm::Value *IsNull = Builder.CreateIsNull(Value);
1574     Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1575     EmitBlock(CastNotNull);
1576   }
1577 
1578   Value = EmitDynamicCastCall(*this, Value, SrcTy, DestTy, CastEnd);
1579 
1580   if (ShouldNullCheckSrcValue) {
1581     EmitBranch(CastEnd);
1582 
1583     EmitBlock(CastNull);
1584     EmitBranch(CastEnd);
1585   }
1586 
1587   EmitBlock(CastEnd);
1588 
1589   if (ShouldNullCheckSrcValue) {
1590     llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1591     PHI->addIncoming(Value, CastNotNull);
1592     PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
1593 
1594     Value = PHI;
1595   }
1596 
1597   return Value;
1598 }
1599