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().arrangeFunctionCall(FPT->getResultType(), Args,
54                                                      FPT->getExtInfo(),
55                                                      required),
56                   Callee, ReturnValue, Args, MD);
57 }
58 
59 // FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
60 // quite what we want.
61 static const Expr *skipNoOpCastsAndParens(const Expr *E) {
62   while (true) {
63     if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
64       E = PE->getSubExpr();
65       continue;
66     }
67 
68     if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
69       if (CE->getCastKind() == CK_NoOp) {
70         E = CE->getSubExpr();
71         continue;
72       }
73     }
74     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
75       if (UO->getOpcode() == UO_Extension) {
76         E = UO->getSubExpr();
77         continue;
78       }
79     }
80     return E;
81   }
82 }
83 
84 /// canDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
85 /// expr can be devirtualized.
86 static bool canDevirtualizeMemberFunctionCalls(ASTContext &Context,
87                                                const Expr *Base,
88                                                const CXXMethodDecl *MD) {
89 
90   // When building with -fapple-kext, all calls must go through the vtable since
91   // the kernel linker can do runtime patching of vtables.
92   if (Context.getLangOpts().AppleKext)
93     return false;
94 
95   // If the most derived class is marked final, we know that no subclass can
96   // override this member function and so we can devirtualize it. For example:
97   //
98   // struct A { virtual void f(); }
99   // struct B final : A { };
100   //
101   // void f(B *b) {
102   //   b->f();
103   // }
104   //
105   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
106   if (MostDerivedClassDecl->hasAttr<FinalAttr>())
107     return true;
108 
109   // If the member function is marked 'final', we know that it can't be
110   // overridden and can therefore devirtualize it.
111   if (MD->hasAttr<FinalAttr>())
112     return true;
113 
114   // Similarly, if the class itself is marked 'final' it can't be overridden
115   // and we can therefore devirtualize the member function call.
116   if (MD->getParent()->hasAttr<FinalAttr>())
117     return true;
118 
119   Base = skipNoOpCastsAndParens(Base);
120   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
121     if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
122       // This is a record decl. We know the type and can devirtualize it.
123       return VD->getType()->isRecordType();
124     }
125 
126     return false;
127   }
128 
129   // We can always devirtualize calls on temporary object expressions.
130   if (isa<CXXConstructExpr>(Base))
131     return true;
132 
133   // And calls on bound temporaries.
134   if (isa<CXXBindTemporaryExpr>(Base))
135     return true;
136 
137   // Check if this is a call expr that returns a record type.
138   if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
139     return CE->getCallReturnType()->isRecordType();
140 
141   // We can't devirtualize the call.
142   return false;
143 }
144 
145 static CXXRecordDecl *getCXXRecord(const Expr *E) {
146   QualType T = E->getType();
147   if (const PointerType *PTy = T->getAs<PointerType>())
148     T = PTy->getPointeeType();
149   const RecordType *Ty = T->castAs<RecordType>();
150   return cast<CXXRecordDecl>(Ty->getDecl());
151 }
152 
153 // Note: This function also emit constructor calls to support a MSVC
154 // extensions allowing explicit constructor function call.
155 RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
156                                               ReturnValueSlot ReturnValue) {
157   const Expr *callee = CE->getCallee()->IgnoreParens();
158 
159   if (isa<BinaryOperator>(callee))
160     return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
161 
162   const MemberExpr *ME = cast<MemberExpr>(callee);
163   const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
164 
165   CGDebugInfo *DI = getDebugInfo();
166   if (DI && CGM.getCodeGenOpts().DebugInfo == CodeGenOptions::LimitedDebugInfo
167       && !isa<CallExpr>(ME->getBase())) {
168     QualType PQTy = ME->getBase()->IgnoreParenImpCasts()->getType();
169     if (const PointerType * PTy = dyn_cast<PointerType>(PQTy)) {
170       DI->getOrCreateRecordType(PTy->getPointeeType(),
171                                 MD->getParent()->getLocation());
172     }
173   }
174 
175   if (MD->isStatic()) {
176     // The method is static, emit it as we would a regular call.
177     llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
178     return EmitCall(getContext().getPointerType(MD->getType()), Callee,
179                     ReturnValue, CE->arg_begin(), CE->arg_end());
180   }
181 
182   // Compute the object pointer.
183   const Expr *Base = ME->getBase();
184   bool CanUseVirtualCall = MD->isVirtual() && !ME->hasQualifier();
185 
186   const CXXMethodDecl *DevirtualizedMethod = NULL;
187   if (CanUseVirtualCall &&
188       canDevirtualizeMemberFunctionCalls(getContext(), Base, MD)) {
189     const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
190     DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
191     assert(DevirtualizedMethod);
192     const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
193     const Expr *Inner = Base->ignoreParenBaseCasts();
194     if (getCXXRecord(Inner) == DevirtualizedClass)
195       // If the class of the Inner expression is where the dynamic method
196       // is defined, build the this pointer from it.
197       Base = Inner;
198     else if (getCXXRecord(Base) != DevirtualizedClass) {
199       // If the method is defined in a class that is not the best dynamic
200       // one or the one of the full expression, we would have to build
201       // a derived-to-base cast to compute the correct this pointer, but
202       // we don't have support for that yet, so do a virtual call.
203       DevirtualizedMethod = NULL;
204     }
205     // If the return types are not the same, this might be a case where more
206     // code needs to run to compensate for it. For example, the derived
207     // method might return a type that inherits form from the return
208     // type of MD and has a prefix.
209     // For now we just avoid devirtualizing these covariant cases.
210     if (DevirtualizedMethod &&
211         DevirtualizedMethod->getResultType().getCanonicalType() !=
212         MD->getResultType().getCanonicalType())
213       DevirtualizedMethod = NULL;
214   }
215 
216   llvm::Value *This;
217   if (ME->isArrow())
218     This = EmitScalarExpr(Base);
219   else
220     This = EmitLValue(Base).getAddress();
221 
222 
223   if (MD->isTrivial()) {
224     if (isa<CXXDestructorDecl>(MD)) return RValue::get(0);
225     if (isa<CXXConstructorDecl>(MD) &&
226         cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
227       return RValue::get(0);
228 
229     if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
230       // We don't like to generate the trivial copy/move assignment operator
231       // when it isn't necessary; just produce the proper effect here.
232       llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
233       EmitAggregateCopy(This, RHS, CE->getType());
234       return RValue::get(This);
235     }
236 
237     if (isa<CXXConstructorDecl>(MD) &&
238         cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
239       // Trivial move and copy ctor are the same.
240       llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
241       EmitSynthesizedCXXCopyCtorCall(cast<CXXConstructorDecl>(MD), This, RHS,
242                                      CE->arg_begin(), CE->arg_end());
243       return RValue::get(This);
244     }
245     llvm_unreachable("unknown trivial member function");
246   }
247 
248   // Compute the function type we're calling.
249   const CGFunctionInfo *FInfo = 0;
250   if (isa<CXXDestructorDecl>(MD))
251     FInfo = &CGM.getTypes().arrangeCXXDestructor(cast<CXXDestructorDecl>(MD),
252                                                  Dtor_Complete);
253   else if (isa<CXXConstructorDecl>(MD))
254     FInfo = &CGM.getTypes().arrangeCXXConstructorDeclaration(
255                                                  cast<CXXConstructorDecl>(MD),
256                                                  Ctor_Complete);
257   else
258     FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(MD);
259 
260   llvm::Type *Ty = CGM.getTypes().GetFunctionType(*FInfo);
261 
262   // C++ [class.virtual]p12:
263   //   Explicit qualification with the scope operator (5.1) suppresses the
264   //   virtual call mechanism.
265   //
266   // We also don't emit a virtual call if the base expression has a record type
267   // because then we know what the type is.
268   bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
269 
270   llvm::Value *Callee;
271   if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
272     if (UseVirtualCall) {
273       Callee = BuildVirtualCall(Dtor, Dtor_Complete, This, Ty);
274     } else {
275       if (getContext().getLangOpts().AppleKext &&
276           MD->isVirtual() &&
277           ME->hasQualifier())
278         Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
279       else if (!DevirtualizedMethod)
280         Callee = CGM.GetAddrOfFunction(GlobalDecl(Dtor, Dtor_Complete), Ty);
281       else {
282         const CXXDestructorDecl *DDtor =
283           cast<CXXDestructorDecl>(DevirtualizedMethod);
284         Callee = CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty);
285       }
286     }
287   } else if (const CXXConstructorDecl *Ctor =
288                dyn_cast<CXXConstructorDecl>(MD)) {
289     Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
290   } else if (UseVirtualCall) {
291       Callee = BuildVirtualCall(MD, This, Ty);
292   } else {
293     if (getContext().getLangOpts().AppleKext &&
294         MD->isVirtual() &&
295         ME->hasQualifier())
296       Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
297     else if (!DevirtualizedMethod)
298       Callee = CGM.GetAddrOfFunction(MD, Ty);
299     else {
300       Callee = CGM.GetAddrOfFunction(DevirtualizedMethod, Ty);
301     }
302   }
303 
304   return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
305                            CE->arg_begin(), CE->arg_end());
306 }
307 
308 RValue
309 CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
310                                               ReturnValueSlot ReturnValue) {
311   const BinaryOperator *BO =
312       cast<BinaryOperator>(E->getCallee()->IgnoreParens());
313   const Expr *BaseExpr = BO->getLHS();
314   const Expr *MemFnExpr = BO->getRHS();
315 
316   const MemberPointerType *MPT =
317     MemFnExpr->getType()->castAs<MemberPointerType>();
318 
319   const FunctionProtoType *FPT =
320     MPT->getPointeeType()->castAs<FunctionProtoType>();
321   const CXXRecordDecl *RD =
322     cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
323 
324   // Get the member function pointer.
325   llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
326 
327   // Emit the 'this' pointer.
328   llvm::Value *This;
329 
330   if (BO->getOpcode() == BO_PtrMemI)
331     This = EmitScalarExpr(BaseExpr);
332   else
333     This = EmitLValue(BaseExpr).getAddress();
334 
335   // Ask the ABI to load the callee.  Note that This is modified.
336   llvm::Value *Callee =
337     CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, This, MemFnPtr, MPT);
338 
339   CallArgList Args;
340 
341   QualType ThisType =
342     getContext().getPointerType(getContext().getTagDeclType(RD));
343 
344   // Push the this ptr.
345   Args.add(RValue::get(This), ThisType);
346 
347   // And the rest of the call args
348   EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
349   return EmitCall(CGM.getTypes().arrangeFunctionCall(Args, FPT), 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().arrangeFunctionCall(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().arrangeFunctionCall(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().arrangeFunctionCall(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().arrangeFunctionCall(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().arrangeFunctionCall(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 
1537   // Get at the argument before we performed the implicit conversion
1538   // to void*.
1539   const Expr *Arg = E->getArgument();
1540   while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
1541     if (ICE->getCastKind() != CK_UserDefinedConversion &&
1542         ICE->getType()->isVoidPointerType())
1543       Arg = ICE->getSubExpr();
1544     else
1545       break;
1546   }
1547 
1548   llvm::Value *Ptr = EmitScalarExpr(Arg);
1549 
1550   // Null check the pointer.
1551   llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1552   llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1553 
1554   llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
1555 
1556   Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1557   EmitBlock(DeleteNotNull);
1558 
1559   // We might be deleting a pointer to array.  If so, GEP down to the
1560   // first non-array element.
1561   // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1562   QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1563   if (DeleteTy->isConstantArrayType()) {
1564     llvm::Value *Zero = Builder.getInt32(0);
1565     SmallVector<llvm::Value*,8> GEP;
1566 
1567     GEP.push_back(Zero); // point at the outermost array
1568 
1569     // For each layer of array type we're pointing at:
1570     while (const ConstantArrayType *Arr
1571              = getContext().getAsConstantArrayType(DeleteTy)) {
1572       // 1. Unpeel the array type.
1573       DeleteTy = Arr->getElementType();
1574 
1575       // 2. GEP to the first element of the array.
1576       GEP.push_back(Zero);
1577     }
1578 
1579     Ptr = Builder.CreateInBoundsGEP(Ptr, GEP, "del.first");
1580   }
1581 
1582   assert(ConvertTypeForMem(DeleteTy) ==
1583          cast<llvm::PointerType>(Ptr->getType())->getElementType());
1584 
1585   if (E->isArrayForm()) {
1586     EmitArrayDelete(*this, E, Ptr, DeleteTy);
1587   } else {
1588     EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy,
1589                      E->isGlobalDelete());
1590   }
1591 
1592   EmitBlock(DeleteEnd);
1593 }
1594 
1595 static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1596   // void __cxa_bad_typeid();
1597   llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1598 
1599   return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1600 }
1601 
1602 static void EmitBadTypeidCall(CodeGenFunction &CGF) {
1603   llvm::Value *Fn = getBadTypeidFn(CGF);
1604   CGF.EmitCallOrInvoke(Fn).setDoesNotReturn();
1605   CGF.Builder.CreateUnreachable();
1606 }
1607 
1608 static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF,
1609                                          const Expr *E,
1610                                          llvm::Type *StdTypeInfoPtrTy) {
1611   // Get the vtable pointer.
1612   llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
1613 
1614   // C++ [expr.typeid]p2:
1615   //   If the glvalue expression is obtained by applying the unary * operator to
1616   //   a pointer and the pointer is a null pointer value, the typeid expression
1617   //   throws the std::bad_typeid exception.
1618   if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
1619     if (UO->getOpcode() == UO_Deref) {
1620       llvm::BasicBlock *BadTypeidBlock =
1621         CGF.createBasicBlock("typeid.bad_typeid");
1622       llvm::BasicBlock *EndBlock =
1623         CGF.createBasicBlock("typeid.end");
1624 
1625       llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
1626       CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
1627 
1628       CGF.EmitBlock(BadTypeidBlock);
1629       EmitBadTypeidCall(CGF);
1630       CGF.EmitBlock(EndBlock);
1631     }
1632   }
1633 
1634   llvm::Value *Value = CGF.GetVTablePtr(ThisPtr,
1635                                         StdTypeInfoPtrTy->getPointerTo());
1636 
1637   // Load the type info.
1638   Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
1639   return CGF.Builder.CreateLoad(Value);
1640 }
1641 
1642 llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
1643   llvm::Type *StdTypeInfoPtrTy =
1644     ConvertType(E->getType())->getPointerTo();
1645 
1646   if (E->isTypeOperand()) {
1647     llvm::Constant *TypeInfo =
1648       CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand());
1649     return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
1650   }
1651 
1652   // C++ [expr.typeid]p2:
1653   //   When typeid is applied to a glvalue expression whose type is a
1654   //   polymorphic class type, the result refers to a std::type_info object
1655   //   representing the type of the most derived object (that is, the dynamic
1656   //   type) to which the glvalue refers.
1657   if (E->getExprOperand()->isGLValue()) {
1658     if (const RecordType *RT =
1659           E->getExprOperand()->getType()->getAs<RecordType>()) {
1660       const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1661       if (RD->isPolymorphic())
1662         return EmitTypeidFromVTable(*this, E->getExprOperand(),
1663                                     StdTypeInfoPtrTy);
1664     }
1665   }
1666 
1667   QualType OperandTy = E->getExprOperand()->getType();
1668   return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1669                                StdTypeInfoPtrTy);
1670 }
1671 
1672 static llvm::Constant *getDynamicCastFn(CodeGenFunction &CGF) {
1673   // void *__dynamic_cast(const void *sub,
1674   //                      const abi::__class_type_info *src,
1675   //                      const abi::__class_type_info *dst,
1676   //                      std::ptrdiff_t src2dst_offset);
1677 
1678   llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
1679   llvm::Type *PtrDiffTy =
1680     CGF.ConvertType(CGF.getContext().getPointerDiffType());
1681 
1682   llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
1683 
1684   llvm::FunctionType *FTy =
1685     llvm::FunctionType::get(Int8PtrTy, Args, false);
1686 
1687   return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast");
1688 }
1689 
1690 static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1691   // void __cxa_bad_cast();
1692   llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
1693   return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1694 }
1695 
1696 static void EmitBadCastCall(CodeGenFunction &CGF) {
1697   llvm::Value *Fn = getBadCastFn(CGF);
1698   CGF.EmitCallOrInvoke(Fn).setDoesNotReturn();
1699   CGF.Builder.CreateUnreachable();
1700 }
1701 
1702 static llvm::Value *
1703 EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
1704                     QualType SrcTy, QualType DestTy,
1705                     llvm::BasicBlock *CastEnd) {
1706   llvm::Type *PtrDiffLTy =
1707     CGF.ConvertType(CGF.getContext().getPointerDiffType());
1708   llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1709 
1710   if (const PointerType *PTy = DestTy->getAs<PointerType>()) {
1711     if (PTy->getPointeeType()->isVoidType()) {
1712       // C++ [expr.dynamic.cast]p7:
1713       //   If T is "pointer to cv void," then the result is a pointer to the
1714       //   most derived object pointed to by v.
1715 
1716       // Get the vtable pointer.
1717       llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1718 
1719       // Get the offset-to-top from the vtable.
1720       llvm::Value *OffsetToTop =
1721         CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1722       OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1723 
1724       // Finally, add the offset to the pointer.
1725       Value = CGF.EmitCastToVoidPtr(Value);
1726       Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1727 
1728       return CGF.Builder.CreateBitCast(Value, DestLTy);
1729     }
1730   }
1731 
1732   QualType SrcRecordTy;
1733   QualType DestRecordTy;
1734 
1735   if (const PointerType *DestPTy = DestTy->getAs<PointerType>()) {
1736     SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
1737     DestRecordTy = DestPTy->getPointeeType();
1738   } else {
1739     SrcRecordTy = SrcTy;
1740     DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
1741   }
1742 
1743   assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
1744   assert(DestRecordTy->isRecordType() && "dest type must be a record type!");
1745 
1746   llvm::Value *SrcRTTI =
1747     CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1748   llvm::Value *DestRTTI =
1749     CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1750 
1751   // FIXME: Actually compute a hint here.
1752   llvm::Value *OffsetHint = llvm::ConstantInt::get(PtrDiffLTy, -1ULL);
1753 
1754   // Emit the call to __dynamic_cast.
1755   Value = CGF.EmitCastToVoidPtr(Value);
1756   Value = CGF.Builder.CreateCall4(getDynamicCastFn(CGF), Value,
1757                                   SrcRTTI, DestRTTI, OffsetHint);
1758   Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1759 
1760   /// C++ [expr.dynamic.cast]p9:
1761   ///   A failed cast to reference type throws std::bad_cast
1762   if (DestTy->isReferenceType()) {
1763     llvm::BasicBlock *BadCastBlock =
1764       CGF.createBasicBlock("dynamic_cast.bad_cast");
1765 
1766     llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1767     CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1768 
1769     CGF.EmitBlock(BadCastBlock);
1770     EmitBadCastCall(CGF);
1771   }
1772 
1773   return Value;
1774 }
1775 
1776 static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1777                                           QualType DestTy) {
1778   llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1779   if (DestTy->isPointerType())
1780     return llvm::Constant::getNullValue(DestLTy);
1781 
1782   /// C++ [expr.dynamic.cast]p9:
1783   ///   A failed cast to reference type throws std::bad_cast
1784   EmitBadCastCall(CGF);
1785 
1786   CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1787   return llvm::UndefValue::get(DestLTy);
1788 }
1789 
1790 llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
1791                                               const CXXDynamicCastExpr *DCE) {
1792   QualType DestTy = DCE->getTypeAsWritten();
1793 
1794   if (DCE->isAlwaysNull())
1795     return EmitDynamicCastToNull(*this, DestTy);
1796 
1797   QualType SrcTy = DCE->getSubExpr()->getType();
1798 
1799   // C++ [expr.dynamic.cast]p4:
1800   //   If the value of v is a null pointer value in the pointer case, the result
1801   //   is the null pointer value of type T.
1802   bool ShouldNullCheckSrcValue = SrcTy->isPointerType();
1803 
1804   llvm::BasicBlock *CastNull = 0;
1805   llvm::BasicBlock *CastNotNull = 0;
1806   llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
1807 
1808   if (ShouldNullCheckSrcValue) {
1809     CastNull = createBasicBlock("dynamic_cast.null");
1810     CastNotNull = createBasicBlock("dynamic_cast.notnull");
1811 
1812     llvm::Value *IsNull = Builder.CreateIsNull(Value);
1813     Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1814     EmitBlock(CastNotNull);
1815   }
1816 
1817   Value = EmitDynamicCastCall(*this, Value, SrcTy, DestTy, CastEnd);
1818 
1819   if (ShouldNullCheckSrcValue) {
1820     EmitBranch(CastEnd);
1821 
1822     EmitBlock(CastNull);
1823     EmitBranch(CastEnd);
1824   }
1825 
1826   EmitBlock(CastEnd);
1827 
1828   if (ShouldNullCheckSrcValue) {
1829     llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1830     PHI->addIncoming(Value, CastNotNull);
1831     PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
1832 
1833     Value = PHI;
1834   }
1835 
1836   return Value;
1837 }
1838 
1839 void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
1840   RunCleanupsScope Scope(*this);
1841   LValue SlotLV = MakeAddrLValue(Slot.getAddr(), E->getType(),
1842                                  Slot.getAlignment());
1843 
1844   CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
1845   for (LambdaExpr::capture_init_iterator i = E->capture_init_begin(),
1846                                          e = E->capture_init_end();
1847        i != e; ++i, ++CurField) {
1848     // Emit initialization
1849 
1850     LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
1851     ArrayRef<VarDecl *> ArrayIndexes;
1852     if (CurField->getType()->isArrayType())
1853       ArrayIndexes = E->getCaptureInitIndexVars(i);
1854     EmitInitializerForField(*CurField, LV, *i, ArrayIndexes);
1855   }
1856 }
1857