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