1 //===--- CGClass.cpp - Emit LLVM Code for C++ classes ---------------------===//
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 C++ code generation of classes
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CGBlocks.h"
15 #include "CGDebugInfo.h"
16 #include "CGRecordLayout.h"
17 #include "CodeGenFunction.h"
18 #include "CGCXXABI.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/EvaluatedExprVisitor.h"
21 #include "clang/AST/RecordLayout.h"
22 #include "clang/AST/StmtCXX.h"
23 #include "clang/Basic/TargetBuiltins.h"
24 #include "clang/Frontend/CodeGenOptions.h"
25 
26 using namespace clang;
27 using namespace CodeGen;
28 
29 static CharUnits
30 ComputeNonVirtualBaseClassOffset(ASTContext &Context,
31                                  const CXXRecordDecl *DerivedClass,
32                                  CastExpr::path_const_iterator Start,
33                                  CastExpr::path_const_iterator End) {
34   CharUnits Offset = CharUnits::Zero();
35 
36   const CXXRecordDecl *RD = DerivedClass;
37 
38   for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
39     const CXXBaseSpecifier *Base = *I;
40     assert(!Base->isVirtual() && "Should not see virtual bases here!");
41 
42     // Get the layout.
43     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
44 
45     const CXXRecordDecl *BaseDecl =
46       cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
47 
48     // Add the offset.
49     Offset += Layout.getBaseClassOffset(BaseDecl);
50 
51     RD = BaseDecl;
52   }
53 
54   return Offset;
55 }
56 
57 llvm::Constant *
58 CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
59                                    CastExpr::path_const_iterator PathBegin,
60                                    CastExpr::path_const_iterator PathEnd) {
61   assert(PathBegin != PathEnd && "Base path should not be empty!");
62 
63   CharUnits Offset =
64     ComputeNonVirtualBaseClassOffset(getContext(), ClassDecl,
65                                      PathBegin, PathEnd);
66   if (Offset.isZero())
67     return 0;
68 
69   llvm::Type *PtrDiffTy =
70   Types.ConvertType(getContext().getPointerDiffType());
71 
72   return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
73 }
74 
75 /// Gets the address of a direct base class within a complete object.
76 /// This should only be used for (1) non-virtual bases or (2) virtual bases
77 /// when the type is known to be complete (e.g. in complete destructors).
78 ///
79 /// The object pointed to by 'This' is assumed to be non-null.
80 llvm::Value *
81 CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(llvm::Value *This,
82                                                    const CXXRecordDecl *Derived,
83                                                    const CXXRecordDecl *Base,
84                                                    bool BaseIsVirtual) {
85   // 'this' must be a pointer (in some address space) to Derived.
86   assert(This->getType()->isPointerTy() &&
87          cast<llvm::PointerType>(This->getType())->getElementType()
88            == ConvertType(Derived));
89 
90   // Compute the offset of the virtual base.
91   CharUnits Offset;
92   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
93   if (BaseIsVirtual)
94     Offset = Layout.getVBaseClassOffset(Base);
95   else
96     Offset = Layout.getBaseClassOffset(Base);
97 
98   // Shift and cast down to the base type.
99   // TODO: for complete types, this should be possible with a GEP.
100   llvm::Value *V = This;
101   if (Offset.isPositive()) {
102     V = Builder.CreateBitCast(V, Int8PtrTy);
103     V = Builder.CreateConstInBoundsGEP1_64(V, Offset.getQuantity());
104   }
105   V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo());
106 
107   return V;
108 }
109 
110 static llvm::Value *
111 ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, llvm::Value *ptr,
112                                 CharUnits nonVirtualOffset,
113                                 llvm::Value *virtualOffset) {
114   // Assert that we have something to do.
115   assert(!nonVirtualOffset.isZero() || virtualOffset != 0);
116 
117   // Compute the offset from the static and dynamic components.
118   llvm::Value *baseOffset;
119   if (!nonVirtualOffset.isZero()) {
120     baseOffset = llvm::ConstantInt::get(CGF.PtrDiffTy,
121                                         nonVirtualOffset.getQuantity());
122     if (virtualOffset) {
123       baseOffset = CGF.Builder.CreateAdd(virtualOffset, baseOffset);
124     }
125   } else {
126     baseOffset = virtualOffset;
127   }
128 
129   // Apply the base offset.
130   ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
131   ptr = CGF.Builder.CreateInBoundsGEP(ptr, baseOffset, "add.ptr");
132   return ptr;
133 }
134 
135 llvm::Value *
136 CodeGenFunction::GetAddressOfBaseClass(llvm::Value *Value,
137                                        const CXXRecordDecl *Derived,
138                                        CastExpr::path_const_iterator PathBegin,
139                                        CastExpr::path_const_iterator PathEnd,
140                                        bool NullCheckValue) {
141   assert(PathBegin != PathEnd && "Base path should not be empty!");
142 
143   CastExpr::path_const_iterator Start = PathBegin;
144   const CXXRecordDecl *VBase = 0;
145 
146   // Sema has done some convenient canonicalization here: if the
147   // access path involved any virtual steps, the conversion path will
148   // *start* with a step down to the correct virtual base subobject,
149   // and hence will not require any further steps.
150   if ((*Start)->isVirtual()) {
151     VBase =
152       cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
153     ++Start;
154   }
155 
156   // Compute the static offset of the ultimate destination within its
157   // allocating subobject (the virtual base, if there is one, or else
158   // the "complete" object that we see).
159   CharUnits NonVirtualOffset =
160     ComputeNonVirtualBaseClassOffset(getContext(), VBase ? VBase : Derived,
161                                      Start, PathEnd);
162 
163   // If there's a virtual step, we can sometimes "devirtualize" it.
164   // For now, that's limited to when the derived type is final.
165   // TODO: "devirtualize" this for accesses to known-complete objects.
166   if (VBase && Derived->hasAttr<FinalAttr>()) {
167     const ASTRecordLayout &layout = getContext().getASTRecordLayout(Derived);
168     CharUnits vBaseOffset = layout.getVBaseClassOffset(VBase);
169     NonVirtualOffset += vBaseOffset;
170     VBase = 0; // we no longer have a virtual step
171   }
172 
173   // Get the base pointer type.
174   llvm::Type *BasePtrTy =
175     ConvertType((PathEnd[-1])->getType())->getPointerTo();
176 
177   // If the static offset is zero and we don't have a virtual step,
178   // just do a bitcast; null checks are unnecessary.
179   if (NonVirtualOffset.isZero() && !VBase) {
180     return Builder.CreateBitCast(Value, BasePtrTy);
181   }
182 
183   llvm::BasicBlock *origBB = 0;
184   llvm::BasicBlock *endBB = 0;
185 
186   // Skip over the offset (and the vtable load) if we're supposed to
187   // null-check the pointer.
188   if (NullCheckValue) {
189     origBB = Builder.GetInsertBlock();
190     llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull");
191     endBB = createBasicBlock("cast.end");
192 
193     llvm::Value *isNull = Builder.CreateIsNull(Value);
194     Builder.CreateCondBr(isNull, endBB, notNullBB);
195     EmitBlock(notNullBB);
196   }
197 
198   // Compute the virtual offset.
199   llvm::Value *VirtualOffset = 0;
200   if (VBase) {
201     VirtualOffset =
202       CGM.getCXXABI().GetVirtualBaseClassOffset(*this, Value, Derived, VBase);
203   }
204 
205   // Apply both offsets.
206   Value = ApplyNonVirtualAndVirtualOffset(*this, Value,
207                                           NonVirtualOffset,
208                                           VirtualOffset);
209 
210   // Cast to the destination type.
211   Value = Builder.CreateBitCast(Value, BasePtrTy);
212 
213   // Build a phi if we needed a null check.
214   if (NullCheckValue) {
215     llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
216     Builder.CreateBr(endBB);
217     EmitBlock(endBB);
218 
219     llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result");
220     PHI->addIncoming(Value, notNullBB);
221     PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB);
222     Value = PHI;
223   }
224 
225   return Value;
226 }
227 
228 llvm::Value *
229 CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
230                                           const CXXRecordDecl *Derived,
231                                         CastExpr::path_const_iterator PathBegin,
232                                           CastExpr::path_const_iterator PathEnd,
233                                           bool NullCheckValue) {
234   assert(PathBegin != PathEnd && "Base path should not be empty!");
235 
236   QualType DerivedTy =
237     getContext().getCanonicalType(getContext().getTagDeclType(Derived));
238   llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
239 
240   llvm::Value *NonVirtualOffset =
241     CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
242 
243   if (!NonVirtualOffset) {
244     // No offset, we can just cast back.
245     return Builder.CreateBitCast(Value, DerivedPtrTy);
246   }
247 
248   llvm::BasicBlock *CastNull = 0;
249   llvm::BasicBlock *CastNotNull = 0;
250   llvm::BasicBlock *CastEnd = 0;
251 
252   if (NullCheckValue) {
253     CastNull = createBasicBlock("cast.null");
254     CastNotNull = createBasicBlock("cast.notnull");
255     CastEnd = createBasicBlock("cast.end");
256 
257     llvm::Value *IsNull = Builder.CreateIsNull(Value);
258     Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
259     EmitBlock(CastNotNull);
260   }
261 
262   // Apply the offset.
263   Value = Builder.CreateBitCast(Value, Int8PtrTy);
264   Value = Builder.CreateGEP(Value, Builder.CreateNeg(NonVirtualOffset),
265                             "sub.ptr");
266 
267   // Just cast.
268   Value = Builder.CreateBitCast(Value, DerivedPtrTy);
269 
270   if (NullCheckValue) {
271     Builder.CreateBr(CastEnd);
272     EmitBlock(CastNull);
273     Builder.CreateBr(CastEnd);
274     EmitBlock(CastEnd);
275 
276     llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
277     PHI->addIncoming(Value, CastNotNull);
278     PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
279                      CastNull);
280     Value = PHI;
281   }
282 
283   return Value;
284 }
285 
286 llvm::Value *CodeGenFunction::GetVTTParameter(GlobalDecl GD,
287                                               bool ForVirtualBase,
288                                               bool Delegating) {
289   if (!CGM.getCXXABI().NeedsVTTParameter(GD)) {
290     // This constructor/destructor does not need a VTT parameter.
291     return 0;
292   }
293 
294   const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurCodeDecl)->getParent();
295   const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
296 
297   llvm::Value *VTT;
298 
299   uint64_t SubVTTIndex;
300 
301   if (Delegating) {
302     // If this is a delegating constructor call, just load the VTT.
303     return LoadCXXVTT();
304   } else if (RD == Base) {
305     // If the record matches the base, this is the complete ctor/dtor
306     // variant calling the base variant in a class with virtual bases.
307     assert(!CGM.getCXXABI().NeedsVTTParameter(CurGD) &&
308            "doing no-op VTT offset in base dtor/ctor?");
309     assert(!ForVirtualBase && "Can't have same class as virtual base!");
310     SubVTTIndex = 0;
311   } else {
312     const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
313     CharUnits BaseOffset = ForVirtualBase ?
314       Layout.getVBaseClassOffset(Base) :
315       Layout.getBaseClassOffset(Base);
316 
317     SubVTTIndex =
318       CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
319     assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
320   }
321 
322   if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
323     // A VTT parameter was passed to the constructor, use it.
324     VTT = LoadCXXVTT();
325     VTT = Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
326   } else {
327     // We're the complete constructor, so get the VTT by name.
328     VTT = CGM.getVTables().GetAddrOfVTT(RD);
329     VTT = Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
330   }
331 
332   return VTT;
333 }
334 
335 namespace {
336   /// Call the destructor for a direct base class.
337   struct CallBaseDtor : EHScopeStack::Cleanup {
338     const CXXRecordDecl *BaseClass;
339     bool BaseIsVirtual;
340     CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
341       : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
342 
343     void Emit(CodeGenFunction &CGF, Flags flags) {
344       const CXXRecordDecl *DerivedClass =
345         cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
346 
347       const CXXDestructorDecl *D = BaseClass->getDestructor();
348       llvm::Value *Addr =
349         CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(),
350                                                   DerivedClass, BaseClass,
351                                                   BaseIsVirtual);
352       CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual,
353                                 /*Delegating=*/false, Addr);
354     }
355   };
356 
357   /// A visitor which checks whether an initializer uses 'this' in a
358   /// way which requires the vtable to be properly set.
359   struct DynamicThisUseChecker : EvaluatedExprVisitor<DynamicThisUseChecker> {
360     typedef EvaluatedExprVisitor<DynamicThisUseChecker> super;
361 
362     bool UsesThis;
363 
364     DynamicThisUseChecker(ASTContext &C) : super(C), UsesThis(false) {}
365 
366     // Black-list all explicit and implicit references to 'this'.
367     //
368     // Do we need to worry about external references to 'this' derived
369     // from arbitrary code?  If so, then anything which runs arbitrary
370     // external code might potentially access the vtable.
371     void VisitCXXThisExpr(CXXThisExpr *E) { UsesThis = true; }
372   };
373 }
374 
375 static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
376   DynamicThisUseChecker Checker(C);
377   Checker.Visit(const_cast<Expr*>(Init));
378   return Checker.UsesThis;
379 }
380 
381 static void EmitBaseInitializer(CodeGenFunction &CGF,
382                                 const CXXRecordDecl *ClassDecl,
383                                 CXXCtorInitializer *BaseInit,
384                                 CXXCtorType CtorType) {
385   assert(BaseInit->isBaseInitializer() &&
386          "Must have base initializer!");
387 
388   llvm::Value *ThisPtr = CGF.LoadCXXThis();
389 
390   const Type *BaseType = BaseInit->getBaseClass();
391   CXXRecordDecl *BaseClassDecl =
392     cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
393 
394   bool isBaseVirtual = BaseInit->isBaseVirtual();
395 
396   // The base constructor doesn't construct virtual bases.
397   if (CtorType == Ctor_Base && isBaseVirtual)
398     return;
399 
400   // If the initializer for the base (other than the constructor
401   // itself) accesses 'this' in any way, we need to initialize the
402   // vtables.
403   if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
404     CGF.InitializeVTablePointers(ClassDecl);
405 
406   // We can pretend to be a complete class because it only matters for
407   // virtual bases, and we only do virtual bases for complete ctors.
408   llvm::Value *V =
409     CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
410                                               BaseClassDecl,
411                                               isBaseVirtual);
412   CharUnits Alignment = CGF.getContext().getTypeAlignInChars(BaseType);
413   AggValueSlot AggSlot =
414     AggValueSlot::forAddr(V, Alignment, Qualifiers(),
415                           AggValueSlot::IsDestructed,
416                           AggValueSlot::DoesNotNeedGCBarriers,
417                           AggValueSlot::IsNotAliased);
418 
419   CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
420 
421   if (CGF.CGM.getLangOpts().Exceptions &&
422       !BaseClassDecl->hasTrivialDestructor())
423     CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
424                                           isBaseVirtual);
425 }
426 
427 static void EmitAggMemberInitializer(CodeGenFunction &CGF,
428                                      LValue LHS,
429                                      Expr *Init,
430                                      llvm::Value *ArrayIndexVar,
431                                      QualType T,
432                                      ArrayRef<VarDecl *> ArrayIndexes,
433                                      unsigned Index) {
434   if (Index == ArrayIndexes.size()) {
435     LValue LV = LHS;
436 
437     if (ArrayIndexVar) {
438       // If we have an array index variable, load it and use it as an offset.
439       // Then, increment the value.
440       llvm::Value *Dest = LHS.getAddress();
441       llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
442       Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
443       llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
444       Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
445       CGF.Builder.CreateStore(Next, ArrayIndexVar);
446 
447       // Update the LValue.
448       LV.setAddress(Dest);
449       CharUnits Align = CGF.getContext().getTypeAlignInChars(T);
450       LV.setAlignment(std::min(Align, LV.getAlignment()));
451     }
452 
453     switch (CGF.getEvaluationKind(T)) {
454     case TEK_Scalar:
455       CGF.EmitScalarInit(Init, /*decl*/ 0, LV, false);
456       break;
457     case TEK_Complex:
458       CGF.EmitComplexExprIntoLValue(Init, LV, /*isInit*/ true);
459       break;
460     case TEK_Aggregate: {
461       AggValueSlot Slot =
462         AggValueSlot::forLValue(LV,
463                                 AggValueSlot::IsDestructed,
464                                 AggValueSlot::DoesNotNeedGCBarriers,
465                                 AggValueSlot::IsNotAliased);
466 
467       CGF.EmitAggExpr(Init, Slot);
468       break;
469     }
470     }
471 
472     return;
473   }
474 
475   const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
476   assert(Array && "Array initialization without the array type?");
477   llvm::Value *IndexVar
478     = CGF.GetAddrOfLocalVar(ArrayIndexes[Index]);
479   assert(IndexVar && "Array index variable not loaded");
480 
481   // Initialize this index variable to zero.
482   llvm::Value* Zero
483     = llvm::Constant::getNullValue(
484                               CGF.ConvertType(CGF.getContext().getSizeType()));
485   CGF.Builder.CreateStore(Zero, IndexVar);
486 
487   // Start the loop with a block that tests the condition.
488   llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
489   llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
490 
491   CGF.EmitBlock(CondBlock);
492 
493   llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
494   // Generate: if (loop-index < number-of-elements) fall to the loop body,
495   // otherwise, go to the block after the for-loop.
496   uint64_t NumElements = Array->getSize().getZExtValue();
497   llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
498   llvm::Value *NumElementsPtr =
499     llvm::ConstantInt::get(Counter->getType(), NumElements);
500   llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
501                                                   "isless");
502 
503   // If the condition is true, execute the body.
504   CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
505 
506   CGF.EmitBlock(ForBody);
507   llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
508 
509   // Inside the loop body recurse to emit the inner loop or, eventually, the
510   // constructor call.
511   EmitAggMemberInitializer(CGF, LHS, Init, ArrayIndexVar,
512                            Array->getElementType(), ArrayIndexes, Index + 1);
513 
514   CGF.EmitBlock(ContinueBlock);
515 
516   // Emit the increment of the loop counter.
517   llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
518   Counter = CGF.Builder.CreateLoad(IndexVar);
519   NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
520   CGF.Builder.CreateStore(NextVal, IndexVar);
521 
522   // Finally, branch back up to the condition for the next iteration.
523   CGF.EmitBranch(CondBlock);
524 
525   // Emit the fall-through block.
526   CGF.EmitBlock(AfterFor, true);
527 }
528 
529 static void EmitMemberInitializer(CodeGenFunction &CGF,
530                                   const CXXRecordDecl *ClassDecl,
531                                   CXXCtorInitializer *MemberInit,
532                                   const CXXConstructorDecl *Constructor,
533                                   FunctionArgList &Args) {
534   assert(MemberInit->isAnyMemberInitializer() &&
535          "Must have member initializer!");
536   assert(MemberInit->getInit() && "Must have initializer!");
537 
538   // non-static data member initializers.
539   FieldDecl *Field = MemberInit->getAnyMember();
540   QualType FieldType = Field->getType();
541 
542   llvm::Value *ThisPtr = CGF.LoadCXXThis();
543   QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
544   LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
545 
546   if (MemberInit->isIndirectMemberInitializer()) {
547     // If we are initializing an anonymous union field, drill down to
548     // the field.
549     IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
550     IndirectFieldDecl::chain_iterator I = IndirectField->chain_begin(),
551       IEnd = IndirectField->chain_end();
552     for ( ; I != IEnd; ++I)
553       LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(*I));
554     FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
555   } else {
556     LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
557   }
558 
559   // Special case: if we are in a copy or move constructor, and we are copying
560   // an array of PODs or classes with trivial copy constructors, ignore the
561   // AST and perform the copy we know is equivalent.
562   // FIXME: This is hacky at best... if we had a bit more explicit information
563   // in the AST, we could generalize it more easily.
564   const ConstantArrayType *Array
565     = CGF.getContext().getAsConstantArrayType(FieldType);
566   if (Array && Constructor->isDefaulted() &&
567       Constructor->isCopyOrMoveConstructor()) {
568     QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
569     CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
570     if (BaseElementTy.isPODType(CGF.getContext()) ||
571         (CE && CE->getConstructor()->isTrivial())) {
572       // Find the source pointer. We know it's the last argument because
573       // we know we're in an implicit copy constructor.
574       unsigned SrcArgIndex = Args.size() - 1;
575       llvm::Value *SrcPtr
576         = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
577       LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
578       LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
579 
580       // Copy the aggregate.
581       CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
582                             LHS.isVolatileQualified());
583       return;
584     }
585   }
586 
587   ArrayRef<VarDecl *> ArrayIndexes;
588   if (MemberInit->getNumArrayIndices())
589     ArrayIndexes = MemberInit->getArrayIndexes();
590   CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit(), ArrayIndexes);
591 }
592 
593 void CodeGenFunction::EmitInitializerForField(FieldDecl *Field,
594                                               LValue LHS, Expr *Init,
595                                              ArrayRef<VarDecl *> ArrayIndexes) {
596   QualType FieldType = Field->getType();
597   switch (getEvaluationKind(FieldType)) {
598   case TEK_Scalar:
599     if (LHS.isSimple()) {
600       EmitExprAsInit(Init, Field, LHS, false);
601     } else {
602       RValue RHS = RValue::get(EmitScalarExpr(Init));
603       EmitStoreThroughLValue(RHS, LHS);
604     }
605     break;
606   case TEK_Complex:
607     EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true);
608     break;
609   case TEK_Aggregate: {
610     llvm::Value *ArrayIndexVar = 0;
611     if (ArrayIndexes.size()) {
612       llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
613 
614       // The LHS is a pointer to the first object we'll be constructing, as
615       // a flat array.
616       QualType BaseElementTy = getContext().getBaseElementType(FieldType);
617       llvm::Type *BasePtr = ConvertType(BaseElementTy);
618       BasePtr = llvm::PointerType::getUnqual(BasePtr);
619       llvm::Value *BaseAddrPtr = Builder.CreateBitCast(LHS.getAddress(),
620                                                        BasePtr);
621       LHS = MakeAddrLValue(BaseAddrPtr, BaseElementTy);
622 
623       // Create an array index that will be used to walk over all of the
624       // objects we're constructing.
625       ArrayIndexVar = CreateTempAlloca(SizeTy, "object.index");
626       llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
627       Builder.CreateStore(Zero, ArrayIndexVar);
628 
629 
630       // Emit the block variables for the array indices, if any.
631       for (unsigned I = 0, N = ArrayIndexes.size(); I != N; ++I)
632         EmitAutoVarDecl(*ArrayIndexes[I]);
633     }
634 
635     EmitAggMemberInitializer(*this, LHS, Init, ArrayIndexVar, FieldType,
636                              ArrayIndexes, 0);
637   }
638   }
639 
640   // Ensure that we destroy this object if an exception is thrown
641   // later in the constructor.
642   QualType::DestructionKind dtorKind = FieldType.isDestructedType();
643   if (needsEHCleanup(dtorKind))
644     pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
645 }
646 
647 /// Checks whether the given constructor is a valid subject for the
648 /// complete-to-base constructor delegation optimization, i.e.
649 /// emitting the complete constructor as a simple call to the base
650 /// constructor.
651 static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
652 
653   // Currently we disable the optimization for classes with virtual
654   // bases because (1) the addresses of parameter variables need to be
655   // consistent across all initializers but (2) the delegate function
656   // call necessarily creates a second copy of the parameter variable.
657   //
658   // The limiting example (purely theoretical AFAIK):
659   //   struct A { A(int &c) { c++; } };
660   //   struct B : virtual A {
661   //     B(int count) : A(count) { printf("%d\n", count); }
662   //   };
663   // ...although even this example could in principle be emitted as a
664   // delegation since the address of the parameter doesn't escape.
665   if (Ctor->getParent()->getNumVBases()) {
666     // TODO: white-list trivial vbase initializers.  This case wouldn't
667     // be subject to the restrictions below.
668 
669     // TODO: white-list cases where:
670     //  - there are no non-reference parameters to the constructor
671     //  - the initializers don't access any non-reference parameters
672     //  - the initializers don't take the address of non-reference
673     //    parameters
674     //  - etc.
675     // If we ever add any of the above cases, remember that:
676     //  - function-try-blocks will always blacklist this optimization
677     //  - we need to perform the constructor prologue and cleanup in
678     //    EmitConstructorBody.
679 
680     return false;
681   }
682 
683   // We also disable the optimization for variadic functions because
684   // it's impossible to "re-pass" varargs.
685   if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
686     return false;
687 
688   // FIXME: Decide if we can do a delegation of a delegating constructor.
689   if (Ctor->isDelegatingConstructor())
690     return false;
691 
692   return true;
693 }
694 
695 /// EmitConstructorBody - Emits the body of the current constructor.
696 void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
697   const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
698   CXXCtorType CtorType = CurGD.getCtorType();
699 
700   // Before we go any further, try the complete->base constructor
701   // delegation optimization.
702   if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
703       CGM.getTarget().getCXXABI().hasConstructorVariants()) {
704     if (CGDebugInfo *DI = getDebugInfo())
705       DI->EmitLocation(Builder, Ctor->getLocEnd());
706     EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args);
707     return;
708   }
709 
710   Stmt *Body = Ctor->getBody();
711 
712   // Enter the function-try-block before the constructor prologue if
713   // applicable.
714   bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
715   if (IsTryBody)
716     EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
717 
718   RunCleanupsScope RunCleanups(*this);
719 
720   // TODO: in restricted cases, we can emit the vbase initializers of
721   // a complete ctor and then delegate to the base ctor.
722 
723   // Emit the constructor prologue, i.e. the base and member
724   // initializers.
725   EmitCtorPrologue(Ctor, CtorType, Args);
726 
727   // Emit the body of the statement.
728   if (IsTryBody)
729     EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
730   else if (Body)
731     EmitStmt(Body);
732 
733   // Emit any cleanup blocks associated with the member or base
734   // initializers, which includes (along the exceptional path) the
735   // destructors for those members and bases that were fully
736   // constructed.
737   RunCleanups.ForceCleanup();
738 
739   if (IsTryBody)
740     ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
741 }
742 
743 namespace {
744   /// RAII object to indicate that codegen is copying the value representation
745   /// instead of the object representation. Useful when copying a struct or
746   /// class which has uninitialized members and we're only performing
747   /// lvalue-to-rvalue conversion on the object but not its members.
748   class CopyingValueRepresentation {
749   public:
750     explicit CopyingValueRepresentation(CodeGenFunction &CGF)
751         : CGF(CGF), SO(*CGF.SanOpts), OldSanOpts(CGF.SanOpts) {
752       SO.Bool = false;
753       SO.Enum = false;
754       CGF.SanOpts = &SO;
755     }
756     ~CopyingValueRepresentation() {
757       CGF.SanOpts = OldSanOpts;
758     }
759   private:
760     CodeGenFunction &CGF;
761     SanitizerOptions SO;
762     const SanitizerOptions *OldSanOpts;
763   };
764 }
765 
766 namespace {
767   class FieldMemcpyizer {
768   public:
769     FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
770                     const VarDecl *SrcRec)
771       : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
772         RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
773         FirstField(0), LastField(0), FirstFieldOffset(0), LastFieldOffset(0),
774         LastAddedFieldIndex(0) { }
775 
776     static bool isMemcpyableField(FieldDecl *F) {
777       Qualifiers Qual = F->getType().getQualifiers();
778       if (Qual.hasVolatile() || Qual.hasObjCLifetime())
779         return false;
780       return true;
781     }
782 
783     void addMemcpyableField(FieldDecl *F) {
784       if (FirstField == 0)
785         addInitialField(F);
786       else
787         addNextField(F);
788     }
789 
790     CharUnits getMemcpySize() const {
791       unsigned LastFieldSize =
792         LastField->isBitField() ?
793           LastField->getBitWidthValue(CGF.getContext()) :
794           CGF.getContext().getTypeSize(LastField->getType());
795       uint64_t MemcpySizeBits =
796         LastFieldOffset + LastFieldSize - FirstFieldOffset +
797         CGF.getContext().getCharWidth() - 1;
798       CharUnits MemcpySize =
799         CGF.getContext().toCharUnitsFromBits(MemcpySizeBits);
800       return MemcpySize;
801     }
802 
803     void emitMemcpy() {
804       // Give the subclass a chance to bail out if it feels the memcpy isn't
805       // worth it (e.g. Hasn't aggregated enough data).
806       if (FirstField == 0) {
807         return;
808       }
809 
810       CharUnits Alignment;
811 
812       if (FirstField->isBitField()) {
813         const CGRecordLayout &RL =
814           CGF.getTypes().getCGRecordLayout(FirstField->getParent());
815         const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
816         Alignment = CharUnits::fromQuantity(BFInfo.StorageAlignment);
817       } else {
818         Alignment = CGF.getContext().getDeclAlign(FirstField);
819       }
820 
821       assert((CGF.getContext().toCharUnitsFromBits(FirstFieldOffset) %
822               Alignment) == 0 && "Bad field alignment.");
823 
824       CharUnits MemcpySize = getMemcpySize();
825       QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
826       llvm::Value *ThisPtr = CGF.LoadCXXThis();
827       LValue DestLV = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
828       LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
829       llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
830       LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
831       LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
832 
833       emitMemcpyIR(Dest.isBitField() ? Dest.getBitFieldAddr() : Dest.getAddress(),
834                    Src.isBitField() ? Src.getBitFieldAddr() : Src.getAddress(),
835                    MemcpySize, Alignment);
836       reset();
837     }
838 
839     void reset() {
840       FirstField = 0;
841     }
842 
843   protected:
844     CodeGenFunction &CGF;
845     const CXXRecordDecl *ClassDecl;
846 
847   private:
848 
849     void emitMemcpyIR(llvm::Value *DestPtr, llvm::Value *SrcPtr,
850                       CharUnits Size, CharUnits Alignment) {
851       llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
852       llvm::Type *DBP =
853         llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace());
854       DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP);
855 
856       llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
857       llvm::Type *SBP =
858         llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace());
859       SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP);
860 
861       CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity(),
862                                Alignment.getQuantity());
863     }
864 
865     void addInitialField(FieldDecl *F) {
866         FirstField = F;
867         LastField = F;
868         FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
869         LastFieldOffset = FirstFieldOffset;
870         LastAddedFieldIndex = F->getFieldIndex();
871         return;
872       }
873 
874     void addNextField(FieldDecl *F) {
875       // For the most part, the following invariant will hold:
876       //   F->getFieldIndex() == LastAddedFieldIndex + 1
877       // The one exception is that Sema won't add a copy-initializer for an
878       // unnamed bitfield, which will show up here as a gap in the sequence.
879       assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
880              "Cannot aggregate fields out of order.");
881       LastAddedFieldIndex = F->getFieldIndex();
882 
883       // The 'first' and 'last' fields are chosen by offset, rather than field
884       // index. This allows the code to support bitfields, as well as regular
885       // fields.
886       uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
887       if (FOffset < FirstFieldOffset) {
888         FirstField = F;
889         FirstFieldOffset = FOffset;
890       } else if (FOffset > LastFieldOffset) {
891         LastField = F;
892         LastFieldOffset = FOffset;
893       }
894     }
895 
896     const VarDecl *SrcRec;
897     const ASTRecordLayout &RecLayout;
898     FieldDecl *FirstField;
899     FieldDecl *LastField;
900     uint64_t FirstFieldOffset, LastFieldOffset;
901     unsigned LastAddedFieldIndex;
902   };
903 
904   class ConstructorMemcpyizer : public FieldMemcpyizer {
905   private:
906 
907     /// Get source argument for copy constructor. Returns null if not a copy
908     /// constructor.
909     static const VarDecl* getTrivialCopySource(const CXXConstructorDecl *CD,
910                                                FunctionArgList &Args) {
911       if (CD->isCopyOrMoveConstructor() && CD->isDefaulted())
912         return Args[Args.size() - 1];
913       return 0;
914     }
915 
916     // Returns true if a CXXCtorInitializer represents a member initialization
917     // that can be rolled into a memcpy.
918     bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
919       if (!MemcpyableCtor)
920         return false;
921       FieldDecl *Field = MemberInit->getMember();
922       assert(Field != 0 && "No field for member init.");
923       QualType FieldType = Field->getType();
924       CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
925 
926       // Bail out on non-POD, not-trivially-constructable members.
927       if (!(CE && CE->getConstructor()->isTrivial()) &&
928           !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
929             FieldType->isReferenceType()))
930         return false;
931 
932       // Bail out on volatile fields.
933       if (!isMemcpyableField(Field))
934         return false;
935 
936       // Otherwise we're good.
937       return true;
938     }
939 
940   public:
941     ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
942                           FunctionArgList &Args)
943       : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CD, Args)),
944         ConstructorDecl(CD),
945         MemcpyableCtor(CD->isDefaulted() &&
946                        CD->isCopyOrMoveConstructor() &&
947                        CGF.getLangOpts().getGC() == LangOptions::NonGC),
948         Args(Args) { }
949 
950     void addMemberInitializer(CXXCtorInitializer *MemberInit) {
951       if (isMemberInitMemcpyable(MemberInit)) {
952         AggregatedInits.push_back(MemberInit);
953         addMemcpyableField(MemberInit->getMember());
954       } else {
955         emitAggregatedInits();
956         EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
957                               ConstructorDecl, Args);
958       }
959     }
960 
961     void emitAggregatedInits() {
962       if (AggregatedInits.size() <= 1) {
963         // This memcpy is too small to be worthwhile. Fall back on default
964         // codegen.
965         if (!AggregatedInits.empty()) {
966           CopyingValueRepresentation CVR(CGF);
967           EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
968                                 AggregatedInits[0], ConstructorDecl, Args);
969         }
970         reset();
971         return;
972       }
973 
974       pushEHDestructors();
975       emitMemcpy();
976       AggregatedInits.clear();
977     }
978 
979     void pushEHDestructors() {
980       llvm::Value *ThisPtr = CGF.LoadCXXThis();
981       QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
982       LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
983 
984       for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
985         QualType FieldType = AggregatedInits[i]->getMember()->getType();
986         QualType::DestructionKind dtorKind = FieldType.isDestructedType();
987         if (CGF.needsEHCleanup(dtorKind))
988           CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
989       }
990     }
991 
992     void finish() {
993       emitAggregatedInits();
994     }
995 
996   private:
997     const CXXConstructorDecl *ConstructorDecl;
998     bool MemcpyableCtor;
999     FunctionArgList &Args;
1000     SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
1001   };
1002 
1003   class AssignmentMemcpyizer : public FieldMemcpyizer {
1004   private:
1005 
1006     // Returns the memcpyable field copied by the given statement, if one
1007     // exists. Otherwise returns null.
1008     FieldDecl *getMemcpyableField(Stmt *S) {
1009       if (!AssignmentsMemcpyable)
1010         return 0;
1011       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
1012         // Recognise trivial assignments.
1013         if (BO->getOpcode() != BO_Assign)
1014           return 0;
1015         MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
1016         if (!ME)
1017           return 0;
1018         FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1019         if (!Field || !isMemcpyableField(Field))
1020           return 0;
1021         Stmt *RHS = BO->getRHS();
1022         if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
1023           RHS = EC->getSubExpr();
1024         if (!RHS)
1025           return 0;
1026         MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS);
1027         if (dyn_cast<FieldDecl>(ME2->getMemberDecl()) != Field)
1028           return 0;
1029         return Field;
1030       } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
1031         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
1032         if (!(MD && (MD->isCopyAssignmentOperator() ||
1033                        MD->isMoveAssignmentOperator()) &&
1034               MD->isTrivial()))
1035           return 0;
1036         MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
1037         if (!IOA)
1038           return 0;
1039         FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
1040         if (!Field || !isMemcpyableField(Field))
1041           return 0;
1042         MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
1043         if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
1044           return 0;
1045         return Field;
1046       } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1047         FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1048         if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
1049           return 0;
1050         Expr *DstPtr = CE->getArg(0);
1051         if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
1052           DstPtr = DC->getSubExpr();
1053         UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
1054         if (!DUO || DUO->getOpcode() != UO_AddrOf)
1055           return 0;
1056         MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
1057         if (!ME)
1058           return 0;
1059         FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1060         if (!Field || !isMemcpyableField(Field))
1061           return 0;
1062         Expr *SrcPtr = CE->getArg(1);
1063         if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
1064           SrcPtr = SC->getSubExpr();
1065         UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
1066         if (!SUO || SUO->getOpcode() != UO_AddrOf)
1067           return 0;
1068         MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
1069         if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
1070           return 0;
1071         return Field;
1072       }
1073 
1074       return 0;
1075     }
1076 
1077     bool AssignmentsMemcpyable;
1078     SmallVector<Stmt*, 16> AggregatedStmts;
1079 
1080   public:
1081 
1082     AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
1083                          FunctionArgList &Args)
1084       : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
1085         AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
1086       assert(Args.size() == 2);
1087     }
1088 
1089     void emitAssignment(Stmt *S) {
1090       FieldDecl *F = getMemcpyableField(S);
1091       if (F) {
1092         addMemcpyableField(F);
1093         AggregatedStmts.push_back(S);
1094       } else {
1095         emitAggregatedStmts();
1096         CGF.EmitStmt(S);
1097       }
1098     }
1099 
1100     void emitAggregatedStmts() {
1101       if (AggregatedStmts.size() <= 1) {
1102         if (!AggregatedStmts.empty()) {
1103           CopyingValueRepresentation CVR(CGF);
1104           CGF.EmitStmt(AggregatedStmts[0]);
1105         }
1106         reset();
1107       }
1108 
1109       emitMemcpy();
1110       AggregatedStmts.clear();
1111     }
1112 
1113     void finish() {
1114       emitAggregatedStmts();
1115     }
1116   };
1117 
1118 }
1119 
1120 /// EmitCtorPrologue - This routine generates necessary code to initialize
1121 /// base classes and non-static data members belonging to this constructor.
1122 void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
1123                                        CXXCtorType CtorType,
1124                                        FunctionArgList &Args) {
1125   if (CD->isDelegatingConstructor())
1126     return EmitDelegatingCXXConstructorCall(CD, Args);
1127 
1128   const CXXRecordDecl *ClassDecl = CD->getParent();
1129 
1130   CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1131                                           E = CD->init_end();
1132 
1133   llvm::BasicBlock *BaseCtorContinueBB = 0;
1134   if (ClassDecl->getNumVBases() &&
1135       !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
1136     // The ABIs that don't have constructor variants need to put a branch
1137     // before the virtual base initialization code.
1138     BaseCtorContinueBB =
1139       CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl);
1140     assert(BaseCtorContinueBB);
1141   }
1142 
1143   // Virtual base initializers first.
1144   for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
1145     EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
1146   }
1147 
1148   if (BaseCtorContinueBB) {
1149     // Complete object handler should continue to the remaining initializers.
1150     Builder.CreateBr(BaseCtorContinueBB);
1151     EmitBlock(BaseCtorContinueBB);
1152   }
1153 
1154   // Then, non-virtual base initializers.
1155   for (; B != E && (*B)->isBaseInitializer(); B++) {
1156     assert(!(*B)->isBaseVirtual());
1157     EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
1158   }
1159 
1160   InitializeVTablePointers(ClassDecl);
1161 
1162   // And finally, initialize class members.
1163   FieldConstructionScope FCS(*this, CXXThisValue);
1164   ConstructorMemcpyizer CM(*this, CD, Args);
1165   for (; B != E; B++) {
1166     CXXCtorInitializer *Member = (*B);
1167     assert(!Member->isBaseInitializer());
1168     assert(Member->isAnyMemberInitializer() &&
1169            "Delegating initializer on non-delegating constructor");
1170     CM.addMemberInitializer(Member);
1171   }
1172   CM.finish();
1173 }
1174 
1175 static bool
1176 FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
1177 
1178 static bool
1179 HasTrivialDestructorBody(ASTContext &Context,
1180                          const CXXRecordDecl *BaseClassDecl,
1181                          const CXXRecordDecl *MostDerivedClassDecl)
1182 {
1183   // If the destructor is trivial we don't have to check anything else.
1184   if (BaseClassDecl->hasTrivialDestructor())
1185     return true;
1186 
1187   if (!BaseClassDecl->getDestructor()->hasTrivialBody())
1188     return false;
1189 
1190   // Check fields.
1191   for (CXXRecordDecl::field_iterator I = BaseClassDecl->field_begin(),
1192        E = BaseClassDecl->field_end(); I != E; ++I) {
1193     const FieldDecl *Field = *I;
1194 
1195     if (!FieldHasTrivialDestructorBody(Context, Field))
1196       return false;
1197   }
1198 
1199   // Check non-virtual bases.
1200   for (CXXRecordDecl::base_class_const_iterator I =
1201        BaseClassDecl->bases_begin(), E = BaseClassDecl->bases_end();
1202        I != E; ++I) {
1203     if (I->isVirtual())
1204       continue;
1205 
1206     const CXXRecordDecl *NonVirtualBase =
1207       cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
1208     if (!HasTrivialDestructorBody(Context, NonVirtualBase,
1209                                   MostDerivedClassDecl))
1210       return false;
1211   }
1212 
1213   if (BaseClassDecl == MostDerivedClassDecl) {
1214     // Check virtual bases.
1215     for (CXXRecordDecl::base_class_const_iterator I =
1216          BaseClassDecl->vbases_begin(), E = BaseClassDecl->vbases_end();
1217          I != E; ++I) {
1218       const CXXRecordDecl *VirtualBase =
1219         cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
1220       if (!HasTrivialDestructorBody(Context, VirtualBase,
1221                                     MostDerivedClassDecl))
1222         return false;
1223     }
1224   }
1225 
1226   return true;
1227 }
1228 
1229 static bool
1230 FieldHasTrivialDestructorBody(ASTContext &Context,
1231                               const FieldDecl *Field)
1232 {
1233   QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
1234 
1235   const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
1236   if (!RT)
1237     return true;
1238 
1239   CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1240   return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
1241 }
1242 
1243 /// CanSkipVTablePointerInitialization - Check whether we need to initialize
1244 /// any vtable pointers before calling this destructor.
1245 static bool CanSkipVTablePointerInitialization(ASTContext &Context,
1246                                                const CXXDestructorDecl *Dtor) {
1247   if (!Dtor->hasTrivialBody())
1248     return false;
1249 
1250   // Check the fields.
1251   const CXXRecordDecl *ClassDecl = Dtor->getParent();
1252   for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1253        E = ClassDecl->field_end(); I != E; ++I) {
1254     const FieldDecl *Field = *I;
1255 
1256     if (!FieldHasTrivialDestructorBody(Context, Field))
1257       return false;
1258   }
1259 
1260   return true;
1261 }
1262 
1263 /// EmitDestructorBody - Emits the body of the current destructor.
1264 void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
1265   const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1266   CXXDtorType DtorType = CurGD.getDtorType();
1267 
1268   // The call to operator delete in a deleting destructor happens
1269   // outside of the function-try-block, which means it's always
1270   // possible to delegate the destructor body to the complete
1271   // destructor.  Do so.
1272   if (DtorType == Dtor_Deleting) {
1273     EnterDtorCleanups(Dtor, Dtor_Deleting);
1274     EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
1275                           /*Delegating=*/false, LoadCXXThis());
1276     PopCleanupBlock();
1277     return;
1278   }
1279 
1280   Stmt *Body = Dtor->getBody();
1281 
1282   // If the body is a function-try-block, enter the try before
1283   // anything else.
1284   bool isTryBody = (Body && isa<CXXTryStmt>(Body));
1285   if (isTryBody)
1286     EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
1287 
1288   // Enter the epilogue cleanups.
1289   RunCleanupsScope DtorEpilogue(*this);
1290 
1291   // If this is the complete variant, just invoke the base variant;
1292   // the epilogue will destruct the virtual bases.  But we can't do
1293   // this optimization if the body is a function-try-block, because
1294   // we'd introduce *two* handler blocks.  In the Microsoft ABI, we
1295   // always delegate because we might not have a definition in this TU.
1296   switch (DtorType) {
1297   case Dtor_Deleting: llvm_unreachable("already handled deleting case");
1298 
1299   case Dtor_Complete:
1300     assert((Body || getTarget().getCXXABI().isMicrosoft()) &&
1301            "can't emit a dtor without a body for non-Microsoft ABIs");
1302 
1303     // Enter the cleanup scopes for virtual bases.
1304     EnterDtorCleanups(Dtor, Dtor_Complete);
1305 
1306     if (!isTryBody) {
1307       EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
1308                             /*Delegating=*/false, LoadCXXThis());
1309       break;
1310     }
1311     // Fallthrough: act like we're in the base variant.
1312 
1313   case Dtor_Base:
1314     assert(Body);
1315 
1316     // Enter the cleanup scopes for fields and non-virtual bases.
1317     EnterDtorCleanups(Dtor, Dtor_Base);
1318 
1319     // Initialize the vtable pointers before entering the body.
1320     if (!CanSkipVTablePointerInitialization(getContext(), Dtor))
1321         InitializeVTablePointers(Dtor->getParent());
1322 
1323     if (isTryBody)
1324       EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1325     else if (Body)
1326       EmitStmt(Body);
1327     else {
1328       assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1329       // nothing to do besides what's in the epilogue
1330     }
1331     // -fapple-kext must inline any call to this dtor into
1332     // the caller's body.
1333     if (getLangOpts().AppleKext)
1334       CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
1335     break;
1336   }
1337 
1338   // Jump out through the epilogue cleanups.
1339   DtorEpilogue.ForceCleanup();
1340 
1341   // Exit the try if applicable.
1342   if (isTryBody)
1343     ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
1344 }
1345 
1346 void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
1347   const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
1348   const Stmt *RootS = AssignOp->getBody();
1349   assert(isa<CompoundStmt>(RootS) &&
1350          "Body of an implicit assignment operator should be compound stmt.");
1351   const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
1352 
1353   LexicalScope Scope(*this, RootCS->getSourceRange());
1354 
1355   AssignmentMemcpyizer AM(*this, AssignOp, Args);
1356   for (CompoundStmt::const_body_iterator I = RootCS->body_begin(),
1357                                          E = RootCS->body_end();
1358        I != E; ++I) {
1359     AM.emitAssignment(*I);
1360   }
1361   AM.finish();
1362 }
1363 
1364 namespace {
1365   /// Call the operator delete associated with the current destructor.
1366   struct CallDtorDelete : EHScopeStack::Cleanup {
1367     CallDtorDelete() {}
1368 
1369     void Emit(CodeGenFunction &CGF, Flags flags) {
1370       const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1371       const CXXRecordDecl *ClassDecl = Dtor->getParent();
1372       CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1373                          CGF.getContext().getTagDeclType(ClassDecl));
1374     }
1375   };
1376 
1377   struct CallDtorDeleteConditional : EHScopeStack::Cleanup {
1378     llvm::Value *ShouldDeleteCondition;
1379   public:
1380     CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
1381       : ShouldDeleteCondition(ShouldDeleteCondition) {
1382       assert(ShouldDeleteCondition != NULL);
1383     }
1384 
1385     void Emit(CodeGenFunction &CGF, Flags flags) {
1386       llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
1387       llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
1388       llvm::Value *ShouldCallDelete
1389         = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
1390       CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
1391 
1392       CGF.EmitBlock(callDeleteBB);
1393       const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1394       const CXXRecordDecl *ClassDecl = Dtor->getParent();
1395       CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1396                          CGF.getContext().getTagDeclType(ClassDecl));
1397       CGF.Builder.CreateBr(continueBB);
1398 
1399       CGF.EmitBlock(continueBB);
1400     }
1401   };
1402 
1403   class DestroyField  : public EHScopeStack::Cleanup {
1404     const FieldDecl *field;
1405     CodeGenFunction::Destroyer *destroyer;
1406     bool useEHCleanupForArray;
1407 
1408   public:
1409     DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1410                  bool useEHCleanupForArray)
1411       : field(field), destroyer(destroyer),
1412         useEHCleanupForArray(useEHCleanupForArray) {}
1413 
1414     void Emit(CodeGenFunction &CGF, Flags flags) {
1415       // Find the address of the field.
1416       llvm::Value *thisValue = CGF.LoadCXXThis();
1417       QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
1418       LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
1419       LValue LV = CGF.EmitLValueForField(ThisLV, field);
1420       assert(LV.isSimple());
1421 
1422       CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
1423                       flags.isForNormalCleanup() && useEHCleanupForArray);
1424     }
1425   };
1426 }
1427 
1428 /// EmitDtorEpilogue - Emit all code that comes at the end of class's
1429 /// destructor. This is to call destructors on members and base classes
1430 /// in reverse order of their construction.
1431 void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1432                                         CXXDtorType DtorType) {
1433   assert(!DD->isTrivial() &&
1434          "Should not emit dtor epilogue for trivial dtor!");
1435 
1436   // The deleting-destructor phase just needs to call the appropriate
1437   // operator delete that Sema picked up.
1438   if (DtorType == Dtor_Deleting) {
1439     assert(DD->getOperatorDelete() &&
1440            "operator delete missing - EmitDtorEpilogue");
1441     if (CXXStructorImplicitParamValue) {
1442       // If there is an implicit param to the deleting dtor, it's a boolean
1443       // telling whether we should call delete at the end of the dtor.
1444       EHStack.pushCleanup<CallDtorDeleteConditional>(
1445           NormalAndEHCleanup, CXXStructorImplicitParamValue);
1446     } else {
1447       EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1448     }
1449     return;
1450   }
1451 
1452   const CXXRecordDecl *ClassDecl = DD->getParent();
1453 
1454   // Unions have no bases and do not call field destructors.
1455   if (ClassDecl->isUnion())
1456     return;
1457 
1458   // The complete-destructor phase just destructs all the virtual bases.
1459   if (DtorType == Dtor_Complete) {
1460 
1461     // We push them in the forward order so that they'll be popped in
1462     // the reverse order.
1463     for (CXXRecordDecl::base_class_const_iterator I =
1464            ClassDecl->vbases_begin(), E = ClassDecl->vbases_end();
1465               I != E; ++I) {
1466       const CXXBaseSpecifier &Base = *I;
1467       CXXRecordDecl *BaseClassDecl
1468         = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1469 
1470       // Ignore trivial destructors.
1471       if (BaseClassDecl->hasTrivialDestructor())
1472         continue;
1473 
1474       EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1475                                         BaseClassDecl,
1476                                         /*BaseIsVirtual*/ true);
1477     }
1478 
1479     return;
1480   }
1481 
1482   assert(DtorType == Dtor_Base);
1483 
1484   // Destroy non-virtual bases.
1485   for (CXXRecordDecl::base_class_const_iterator I =
1486         ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
1487     const CXXBaseSpecifier &Base = *I;
1488 
1489     // Ignore virtual bases.
1490     if (Base.isVirtual())
1491       continue;
1492 
1493     CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
1494 
1495     // Ignore trivial destructors.
1496     if (BaseClassDecl->hasTrivialDestructor())
1497       continue;
1498 
1499     EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1500                                       BaseClassDecl,
1501                                       /*BaseIsVirtual*/ false);
1502   }
1503 
1504   // Destroy direct fields.
1505   SmallVector<const FieldDecl *, 16> FieldDecls;
1506   for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1507        E = ClassDecl->field_end(); I != E; ++I) {
1508     const FieldDecl *field = *I;
1509     QualType type = field->getType();
1510     QualType::DestructionKind dtorKind = type.isDestructedType();
1511     if (!dtorKind) continue;
1512 
1513     // Anonymous union members do not have their destructors called.
1514     const RecordType *RT = type->getAsUnionType();
1515     if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1516 
1517     CleanupKind cleanupKind = getCleanupKind(dtorKind);
1518     EHStack.pushCleanup<DestroyField>(cleanupKind, field,
1519                                       getDestroyer(dtorKind),
1520                                       cleanupKind & EHCleanup);
1521   }
1522 }
1523 
1524 /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1525 /// constructor for each of several members of an array.
1526 ///
1527 /// \param ctor the constructor to call for each element
1528 /// \param arrayType the type of the array to initialize
1529 /// \param arrayBegin an arrayType*
1530 /// \param zeroInitialize true if each element should be
1531 ///   zero-initialized before it is constructed
1532 void
1533 CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1534                                             const ConstantArrayType *arrayType,
1535                                             llvm::Value *arrayBegin,
1536                                           CallExpr::const_arg_iterator argBegin,
1537                                             CallExpr::const_arg_iterator argEnd,
1538                                             bool zeroInitialize) {
1539   QualType elementType;
1540   llvm::Value *numElements =
1541     emitArrayLength(arrayType, elementType, arrayBegin);
1542 
1543   EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin,
1544                              argBegin, argEnd, zeroInitialize);
1545 }
1546 
1547 /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1548 /// constructor for each of several members of an array.
1549 ///
1550 /// \param ctor the constructor to call for each element
1551 /// \param numElements the number of elements in the array;
1552 ///   may be zero
1553 /// \param arrayBegin a T*, where T is the type constructed by ctor
1554 /// \param zeroInitialize true if each element should be
1555 ///   zero-initialized before it is constructed
1556 void
1557 CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1558                                             llvm::Value *numElements,
1559                                             llvm::Value *arrayBegin,
1560                                          CallExpr::const_arg_iterator argBegin,
1561                                            CallExpr::const_arg_iterator argEnd,
1562                                             bool zeroInitialize) {
1563 
1564   // It's legal for numElements to be zero.  This can happen both
1565   // dynamically, because x can be zero in 'new A[x]', and statically,
1566   // because of GCC extensions that permit zero-length arrays.  There
1567   // are probably legitimate places where we could assume that this
1568   // doesn't happen, but it's not clear that it's worth it.
1569   llvm::BranchInst *zeroCheckBranch = 0;
1570 
1571   // Optimize for a constant count.
1572   llvm::ConstantInt *constantCount
1573     = dyn_cast<llvm::ConstantInt>(numElements);
1574   if (constantCount) {
1575     // Just skip out if the constant count is zero.
1576     if (constantCount->isZero()) return;
1577 
1578   // Otherwise, emit the check.
1579   } else {
1580     llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1581     llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1582     zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1583     EmitBlock(loopBB);
1584   }
1585 
1586   // Find the end of the array.
1587   llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1588                                                     "arrayctor.end");
1589 
1590   // Enter the loop, setting up a phi for the current location to initialize.
1591   llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1592   llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1593   EmitBlock(loopBB);
1594   llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1595                                          "arrayctor.cur");
1596   cur->addIncoming(arrayBegin, entryBB);
1597 
1598   // Inside the loop body, emit the constructor call on the array element.
1599 
1600   QualType type = getContext().getTypeDeclType(ctor->getParent());
1601 
1602   // Zero initialize the storage, if requested.
1603   if (zeroInitialize)
1604     EmitNullInitialization(cur, type);
1605 
1606   // C++ [class.temporary]p4:
1607   // There are two contexts in which temporaries are destroyed at a different
1608   // point than the end of the full-expression. The first context is when a
1609   // default constructor is called to initialize an element of an array.
1610   // If the constructor has one or more default arguments, the destruction of
1611   // every temporary created in a default argument expression is sequenced
1612   // before the construction of the next array element, if any.
1613 
1614   {
1615     RunCleanupsScope Scope(*this);
1616 
1617     // Evaluate the constructor and its arguments in a regular
1618     // partial-destroy cleanup.
1619     if (getLangOpts().Exceptions &&
1620         !ctor->getParent()->hasTrivialDestructor()) {
1621       Destroyer *destroyer = destroyCXXObject;
1622       pushRegularPartialArrayCleanup(arrayBegin, cur, type, *destroyer);
1623     }
1624 
1625     EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/ false,
1626                            /*Delegating=*/false, cur, argBegin, argEnd);
1627   }
1628 
1629   // Go to the next element.
1630   llvm::Value *next =
1631     Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1632                               "arrayctor.next");
1633   cur->addIncoming(next, Builder.GetInsertBlock());
1634 
1635   // Check whether that's the end of the loop.
1636   llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1637   llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1638   Builder.CreateCondBr(done, contBB, loopBB);
1639 
1640   // Patch the earlier check to skip over the loop.
1641   if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1642 
1643   EmitBlock(contBB);
1644 }
1645 
1646 void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
1647                                        llvm::Value *addr,
1648                                        QualType type) {
1649   const RecordType *rtype = type->castAs<RecordType>();
1650   const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
1651   const CXXDestructorDecl *dtor = record->getDestructor();
1652   assert(!dtor->isTrivial());
1653   CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
1654                             /*Delegating=*/false, addr);
1655 }
1656 
1657 void
1658 CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
1659                                         CXXCtorType Type, bool ForVirtualBase,
1660                                         bool Delegating,
1661                                         llvm::Value *This,
1662                                         CallExpr::const_arg_iterator ArgBeg,
1663                                         CallExpr::const_arg_iterator ArgEnd) {
1664   // If this is a trivial constructor, just emit what's needed.
1665   if (D->isTrivial()) {
1666     if (ArgBeg == ArgEnd) {
1667       // Trivial default constructor, no codegen required.
1668       assert(D->isDefaultConstructor() &&
1669              "trivial 0-arg ctor not a default ctor");
1670       return;
1671     }
1672 
1673     assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
1674     assert(D->isCopyOrMoveConstructor() &&
1675            "trivial 1-arg ctor not a copy/move ctor");
1676 
1677     const Expr *E = (*ArgBeg);
1678     QualType Ty = E->getType();
1679     llvm::Value *Src = EmitLValue(E).getAddress();
1680     EmitAggregateCopy(This, Src, Ty);
1681     return;
1682   }
1683 
1684   // Non-trivial constructors are handled in an ABI-specific manner.
1685   CGM.getCXXABI().EmitConstructorCall(*this, D, Type, ForVirtualBase,
1686                                       Delegating, This, ArgBeg, ArgEnd);
1687 }
1688 
1689 void
1690 CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1691                                         llvm::Value *This, llvm::Value *Src,
1692                                         CallExpr::const_arg_iterator ArgBeg,
1693                                         CallExpr::const_arg_iterator ArgEnd) {
1694   if (D->isTrivial()) {
1695     assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
1696     assert(D->isCopyOrMoveConstructor() &&
1697            "trivial 1-arg ctor not a copy/move ctor");
1698     EmitAggregateCopy(This, Src, (*ArgBeg)->getType());
1699     return;
1700   }
1701   llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, clang::Ctor_Complete);
1702   assert(D->isInstance() &&
1703          "Trying to emit a member call expr on a static method!");
1704 
1705   const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
1706 
1707   CallArgList Args;
1708 
1709   // Push the this ptr.
1710   Args.add(RValue::get(This), D->getThisType(getContext()));
1711 
1712 
1713   // Push the src ptr.
1714   QualType QT = *(FPT->arg_type_begin());
1715   llvm::Type *t = CGM.getTypes().ConvertType(QT);
1716   Src = Builder.CreateBitCast(Src, t);
1717   Args.add(RValue::get(Src), QT);
1718 
1719   // Skip over first argument (Src).
1720   ++ArgBeg;
1721   CallExpr::const_arg_iterator Arg = ArgBeg;
1722   for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin()+1,
1723        E = FPT->arg_type_end(); I != E; ++I, ++Arg) {
1724     assert(Arg != ArgEnd && "Running over edge of argument list!");
1725     EmitCallArg(Args, *Arg, *I);
1726   }
1727   // Either we've emitted all the call args, or we have a call to a
1728   // variadic function.
1729   assert((Arg == ArgEnd || FPT->isVariadic()) &&
1730          "Extra arguments in non-variadic function!");
1731   // If we still have any arguments, emit them using the type of the argument.
1732   for (; Arg != ArgEnd; ++Arg) {
1733     QualType ArgType = Arg->getType();
1734     EmitCallArg(Args, *Arg, ArgType);
1735   }
1736 
1737   EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, RequiredArgs::All),
1738            Callee, ReturnValueSlot(), Args, D);
1739 }
1740 
1741 void
1742 CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1743                                                 CXXCtorType CtorType,
1744                                                 const FunctionArgList &Args) {
1745   CallArgList DelegateArgs;
1746 
1747   FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1748   assert(I != E && "no parameters to constructor");
1749 
1750   // this
1751   DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
1752   ++I;
1753 
1754   // vtt
1755   if (llvm::Value *VTT = GetVTTParameter(GlobalDecl(Ctor, CtorType),
1756                                          /*ForVirtualBase=*/false,
1757                                          /*Delegating=*/true)) {
1758     QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
1759     DelegateArgs.add(RValue::get(VTT), VoidPP);
1760 
1761     if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
1762       assert(I != E && "cannot skip vtt parameter, already done with args");
1763       assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
1764       ++I;
1765     }
1766   }
1767 
1768   // Explicit arguments.
1769   for (; I != E; ++I) {
1770     const VarDecl *param = *I;
1771     EmitDelegateCallArg(DelegateArgs, param);
1772   }
1773 
1774   llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(Ctor, CtorType);
1775   EmitCall(CGM.getTypes().arrangeCXXConstructorDeclaration(Ctor, CtorType),
1776            Callee, ReturnValueSlot(), DelegateArgs, Ctor);
1777 }
1778 
1779 namespace {
1780   struct CallDelegatingCtorDtor : EHScopeStack::Cleanup {
1781     const CXXDestructorDecl *Dtor;
1782     llvm::Value *Addr;
1783     CXXDtorType Type;
1784 
1785     CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr,
1786                            CXXDtorType Type)
1787       : Dtor(D), Addr(Addr), Type(Type) {}
1788 
1789     void Emit(CodeGenFunction &CGF, Flags flags) {
1790       CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
1791                                 /*Delegating=*/true, Addr);
1792     }
1793   };
1794 }
1795 
1796 void
1797 CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
1798                                                   const FunctionArgList &Args) {
1799   assert(Ctor->isDelegatingConstructor());
1800 
1801   llvm::Value *ThisPtr = LoadCXXThis();
1802 
1803   QualType Ty = getContext().getTagDeclType(Ctor->getParent());
1804   CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
1805   AggValueSlot AggSlot =
1806     AggValueSlot::forAddr(ThisPtr, Alignment, Qualifiers(),
1807                           AggValueSlot::IsDestructed,
1808                           AggValueSlot::DoesNotNeedGCBarriers,
1809                           AggValueSlot::IsNotAliased);
1810 
1811   EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
1812 
1813   const CXXRecordDecl *ClassDecl = Ctor->getParent();
1814   if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
1815     CXXDtorType Type =
1816       CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
1817 
1818     EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
1819                                                 ClassDecl->getDestructor(),
1820                                                 ThisPtr, Type);
1821   }
1822 }
1823 
1824 void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1825                                             CXXDtorType Type,
1826                                             bool ForVirtualBase,
1827                                             bool Delegating,
1828                                             llvm::Value *This) {
1829   llvm::Value *VTT = GetVTTParameter(GlobalDecl(DD, Type),
1830                                      ForVirtualBase, Delegating);
1831   llvm::Value *Callee = 0;
1832   if (getLangOpts().AppleKext)
1833     Callee = BuildAppleKextVirtualDestructorCall(DD, Type,
1834                                                  DD->getParent());
1835 
1836   if (!Callee)
1837     Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
1838 
1839   // FIXME: Provide a source location here.
1840   EmitCXXMemberCall(DD, SourceLocation(), Callee, ReturnValueSlot(), This,
1841                     VTT, getContext().getPointerType(getContext().VoidPtrTy),
1842                     0, 0);
1843 }
1844 
1845 namespace {
1846   struct CallLocalDtor : EHScopeStack::Cleanup {
1847     const CXXDestructorDecl *Dtor;
1848     llvm::Value *Addr;
1849 
1850     CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1851       : Dtor(D), Addr(Addr) {}
1852 
1853     void Emit(CodeGenFunction &CGF, Flags flags) {
1854       CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1855                                 /*ForVirtualBase=*/false,
1856                                 /*Delegating=*/false, Addr);
1857     }
1858   };
1859 }
1860 
1861 void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1862                                             llvm::Value *Addr) {
1863   EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
1864 }
1865 
1866 void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1867   CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1868   if (!ClassDecl) return;
1869   if (ClassDecl->hasTrivialDestructor()) return;
1870 
1871   const CXXDestructorDecl *D = ClassDecl->getDestructor();
1872   assert(D && D->isUsed() && "destructor not marked as used!");
1873   PushDestructorCleanup(D, Addr);
1874 }
1875 
1876 void
1877 CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
1878                                          const CXXRecordDecl *NearestVBase,
1879                                          CharUnits OffsetFromNearestVBase,
1880                                          const CXXRecordDecl *VTableClass) {
1881   const CXXRecordDecl *RD = Base.getBase();
1882 
1883   // Compute the address point.
1884   llvm::Value *VTableAddressPoint;
1885 
1886   bool NeedsVTTParam = CGM.getCXXABI().NeedsVTTParameter(CurGD);
1887 
1888   // Check if we need to use a vtable from the VTT.
1889   if (NeedsVTTParam && (RD->getNumVBases() || NearestVBase)) {
1890     // Get the secondary vpointer index.
1891     uint64_t VirtualPointerIndex =
1892      CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1893 
1894     /// Load the VTT.
1895     llvm::Value *VTT = LoadCXXVTT();
1896     if (VirtualPointerIndex)
1897       VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1898 
1899     // And load the address point from the VTT.
1900     VTableAddressPoint = Builder.CreateLoad(VTT);
1901   } else {
1902     llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(VTableClass);
1903     uint64_t AddressPoint =
1904       CGM.getVTableContext().getVTableLayout(VTableClass).getAddressPoint(Base);
1905     VTableAddressPoint =
1906       Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
1907   }
1908 
1909   // Compute where to store the address point.
1910   llvm::Value *VirtualOffset = 0;
1911   CharUnits NonVirtualOffset = CharUnits::Zero();
1912 
1913   if (NeedsVTTParam && NearestVBase) {
1914     // We need to use the virtual base offset offset because the virtual base
1915     // might have a different offset in the most derived class.
1916     VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(*this,
1917                                                               LoadCXXThis(),
1918                                                               VTableClass,
1919                                                               NearestVBase);
1920     NonVirtualOffset = OffsetFromNearestVBase;
1921   } else {
1922     // We can just use the base offset in the complete class.
1923     NonVirtualOffset = Base.getBaseOffset();
1924   }
1925 
1926   // Apply the offsets.
1927   llvm::Value *VTableField = LoadCXXThis();
1928 
1929   if (!NonVirtualOffset.isZero() || VirtualOffset)
1930     VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
1931                                                   NonVirtualOffset,
1932                                                   VirtualOffset);
1933 
1934   // Finally, store the address point.
1935   llvm::Type *AddressPointPtrTy =
1936     VTableAddressPoint->getType()->getPointerTo();
1937   VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
1938   llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
1939   CGM.DecorateInstruction(Store, CGM.getTBAAInfoForVTablePtr());
1940 }
1941 
1942 void
1943 CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
1944                                           const CXXRecordDecl *NearestVBase,
1945                                           CharUnits OffsetFromNearestVBase,
1946                                           bool BaseIsNonVirtualPrimaryBase,
1947                                           const CXXRecordDecl *VTableClass,
1948                                           VisitedVirtualBasesSetTy& VBases) {
1949   // If this base is a non-virtual primary base the address point has already
1950   // been set.
1951   if (!BaseIsNonVirtualPrimaryBase) {
1952     // Initialize the vtable pointer for this base.
1953     InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
1954                             VTableClass);
1955   }
1956 
1957   const CXXRecordDecl *RD = Base.getBase();
1958 
1959   // Traverse bases.
1960   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1961        E = RD->bases_end(); I != E; ++I) {
1962     CXXRecordDecl *BaseDecl
1963       = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1964 
1965     // Ignore classes without a vtable.
1966     if (!BaseDecl->isDynamicClass())
1967       continue;
1968 
1969     CharUnits BaseOffset;
1970     CharUnits BaseOffsetFromNearestVBase;
1971     bool BaseDeclIsNonVirtualPrimaryBase;
1972 
1973     if (I->isVirtual()) {
1974       // Check if we've visited this virtual base before.
1975       if (!VBases.insert(BaseDecl))
1976         continue;
1977 
1978       const ASTRecordLayout &Layout =
1979         getContext().getASTRecordLayout(VTableClass);
1980 
1981       BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
1982       BaseOffsetFromNearestVBase = CharUnits::Zero();
1983       BaseDeclIsNonVirtualPrimaryBase = false;
1984     } else {
1985       const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1986 
1987       BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
1988       BaseOffsetFromNearestVBase =
1989         OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
1990       BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
1991     }
1992 
1993     InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
1994                              I->isVirtual() ? BaseDecl : NearestVBase,
1995                              BaseOffsetFromNearestVBase,
1996                              BaseDeclIsNonVirtualPrimaryBase,
1997                              VTableClass, VBases);
1998   }
1999 }
2000 
2001 void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
2002   // Ignore classes without a vtable.
2003   if (!RD->isDynamicClass())
2004     return;
2005 
2006   // Initialize the vtable pointers for this class and all of its bases.
2007   VisitedVirtualBasesSetTy VBases;
2008   InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
2009                            /*NearestVBase=*/0,
2010                            /*OffsetFromNearestVBase=*/CharUnits::Zero(),
2011                            /*BaseIsNonVirtualPrimaryBase=*/false, RD, VBases);
2012 }
2013 
2014 llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
2015                                            llvm::Type *Ty) {
2016   llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
2017   llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
2018   CGM.DecorateInstruction(VTable, CGM.getTBAAInfoForVTablePtr());
2019   return VTable;
2020 }
2021 
2022 
2023 // FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
2024 // quite what we want.
2025 static const Expr *skipNoOpCastsAndParens(const Expr *E) {
2026   while (true) {
2027     if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
2028       E = PE->getSubExpr();
2029       continue;
2030     }
2031 
2032     if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
2033       if (CE->getCastKind() == CK_NoOp) {
2034         E = CE->getSubExpr();
2035         continue;
2036       }
2037     }
2038     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2039       if (UO->getOpcode() == UO_Extension) {
2040         E = UO->getSubExpr();
2041         continue;
2042       }
2043     }
2044     return E;
2045   }
2046 }
2047 
2048 bool
2049 CodeGenFunction::CanDevirtualizeMemberFunctionCall(const Expr *Base,
2050                                                    const CXXMethodDecl *MD) {
2051   // When building with -fapple-kext, all calls must go through the vtable since
2052   // the kernel linker can do runtime patching of vtables.
2053   if (getLangOpts().AppleKext)
2054     return false;
2055 
2056   // If the most derived class is marked final, we know that no subclass can
2057   // override this member function and so we can devirtualize it. For example:
2058   //
2059   // struct A { virtual void f(); }
2060   // struct B final : A { };
2061   //
2062   // void f(B *b) {
2063   //   b->f();
2064   // }
2065   //
2066   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
2067   if (MostDerivedClassDecl->hasAttr<FinalAttr>())
2068     return true;
2069 
2070   // If the member function is marked 'final', we know that it can't be
2071   // overridden and can therefore devirtualize it.
2072   if (MD->hasAttr<FinalAttr>())
2073     return true;
2074 
2075   // Similarly, if the class itself is marked 'final' it can't be overridden
2076   // and we can therefore devirtualize the member function call.
2077   if (MD->getParent()->hasAttr<FinalAttr>())
2078     return true;
2079 
2080   Base = skipNoOpCastsAndParens(Base);
2081   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
2082     if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
2083       // This is a record decl. We know the type and can devirtualize it.
2084       return VD->getType()->isRecordType();
2085     }
2086 
2087     return false;
2088   }
2089 
2090   // We can devirtualize calls on an object accessed by a class member access
2091   // expression, since by C++11 [basic.life]p6 we know that it can't refer to
2092   // a derived class object constructed in the same location.
2093   if (const MemberExpr *ME = dyn_cast<MemberExpr>(Base))
2094     if (const ValueDecl *VD = dyn_cast<ValueDecl>(ME->getMemberDecl()))
2095       return VD->getType()->isRecordType();
2096 
2097   // We can always devirtualize calls on temporary object expressions.
2098   if (isa<CXXConstructExpr>(Base))
2099     return true;
2100 
2101   // And calls on bound temporaries.
2102   if (isa<CXXBindTemporaryExpr>(Base))
2103     return true;
2104 
2105   // Check if this is a call expr that returns a record type.
2106   if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
2107     return CE->getCallReturnType()->isRecordType();
2108 
2109   // We can't devirtualize the call.
2110   return false;
2111 }
2112 
2113 llvm::Value *
2114 CodeGenFunction::EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
2115                                              const CXXMethodDecl *MD,
2116                                              llvm::Value *This) {
2117   llvm::FunctionType *fnType =
2118     CGM.getTypes().GetFunctionType(
2119                              CGM.getTypes().arrangeCXXMethodDeclaration(MD));
2120 
2121   if (MD->isVirtual() && !CanDevirtualizeMemberFunctionCall(E->getArg(0), MD))
2122     return CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, fnType);
2123 
2124   return CGM.GetAddrOfFunction(MD, fnType);
2125 }
2126 
2127 void CodeGenFunction::EmitForwardingCallToLambda(const CXXRecordDecl *lambda,
2128                                                  CallArgList &callArgs) {
2129   // Lookup the call operator
2130   DeclarationName operatorName
2131     = getContext().DeclarationNames.getCXXOperatorName(OO_Call);
2132   CXXMethodDecl *callOperator =
2133     cast<CXXMethodDecl>(lambda->lookup(operatorName).front());
2134 
2135   // Get the address of the call operator.
2136   const CGFunctionInfo &calleeFnInfo =
2137     CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
2138   llvm::Value *callee =
2139     CGM.GetAddrOfFunction(GlobalDecl(callOperator),
2140                           CGM.getTypes().GetFunctionType(calleeFnInfo));
2141 
2142   // Prepare the return slot.
2143   const FunctionProtoType *FPT =
2144     callOperator->getType()->castAs<FunctionProtoType>();
2145   QualType resultType = FPT->getResultType();
2146   ReturnValueSlot returnSlot;
2147   if (!resultType->isVoidType() &&
2148       calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
2149       !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
2150     returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
2151 
2152   // We don't need to separately arrange the call arguments because
2153   // the call can't be variadic anyway --- it's impossible to forward
2154   // variadic arguments.
2155 
2156   // Now emit our call.
2157   RValue RV = EmitCall(calleeFnInfo, callee, returnSlot,
2158                        callArgs, callOperator);
2159 
2160   // If necessary, copy the returned value into the slot.
2161   if (!resultType->isVoidType() && returnSlot.isNull())
2162     EmitReturnOfRValue(RV, resultType);
2163   else
2164     EmitBranchThroughCleanup(ReturnBlock);
2165 }
2166 
2167 void CodeGenFunction::EmitLambdaBlockInvokeBody() {
2168   const BlockDecl *BD = BlockInfo->getBlockDecl();
2169   const VarDecl *variable = BD->capture_begin()->getVariable();
2170   const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
2171 
2172   // Start building arguments for forwarding call
2173   CallArgList CallArgs;
2174 
2175   QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2176   llvm::Value *ThisPtr = GetAddrOfBlockDecl(variable, false);
2177   CallArgs.add(RValue::get(ThisPtr), ThisType);
2178 
2179   // Add the rest of the parameters.
2180   for (BlockDecl::param_const_iterator I = BD->param_begin(),
2181        E = BD->param_end(); I != E; ++I) {
2182     ParmVarDecl *param = *I;
2183     EmitDelegateCallArg(CallArgs, param);
2184   }
2185 
2186   EmitForwardingCallToLambda(Lambda, CallArgs);
2187 }
2188 
2189 void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) {
2190   if (cast<CXXMethodDecl>(CurCodeDecl)->isVariadic()) {
2191     // FIXME: Making this work correctly is nasty because it requires either
2192     // cloning the body of the call operator or making the call operator forward.
2193     CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
2194     return;
2195   }
2196 
2197   EmitFunctionBody(Args);
2198 }
2199 
2200 void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
2201   const CXXRecordDecl *Lambda = MD->getParent();
2202 
2203   // Start building arguments for forwarding call
2204   CallArgList CallArgs;
2205 
2206   QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2207   llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
2208   CallArgs.add(RValue::get(ThisPtr), ThisType);
2209 
2210   // Add the rest of the parameters.
2211   for (FunctionDecl::param_const_iterator I = MD->param_begin(),
2212        E = MD->param_end(); I != E; ++I) {
2213     ParmVarDecl *param = *I;
2214     EmitDelegateCallArg(CallArgs, param);
2215   }
2216 
2217   EmitForwardingCallToLambda(Lambda, CallArgs);
2218 }
2219 
2220 void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) {
2221   if (MD->isVariadic()) {
2222     // FIXME: Making this work correctly is nasty because it requires either
2223     // cloning the body of the call operator or making the call operator forward.
2224     CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
2225     return;
2226   }
2227 
2228   EmitLambdaDelegatingInvokeBody(MD);
2229 }
2230