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