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