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 "CGDebugInfo.h"
15 #include "CodeGenFunction.h"
16 #include "clang/AST/CXXInheritance.h"
17 #include "clang/AST/EvaluatedExprVisitor.h"
18 #include "clang/AST/RecordLayout.h"
19 #include "clang/AST/StmtCXX.h"
20 #include "clang/Frontend/CodeGenOptions.h"
21 
22 using namespace clang;
23 using namespace CodeGen;
24 
25 static CharUnits
26 ComputeNonVirtualBaseClassOffset(ASTContext &Context,
27                                  const CXXRecordDecl *DerivedClass,
28                                  CastExpr::path_const_iterator Start,
29                                  CastExpr::path_const_iterator End) {
30   CharUnits Offset = CharUnits::Zero();
31 
32   const CXXRecordDecl *RD = DerivedClass;
33 
34   for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
35     const CXXBaseSpecifier *Base = *I;
36     assert(!Base->isVirtual() && "Should not see virtual bases here!");
37 
38     // Get the layout.
39     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
40 
41     const CXXRecordDecl *BaseDecl =
42       cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
43 
44     // Add the offset.
45     Offset += Layout.getBaseClassOffset(BaseDecl);
46 
47     RD = BaseDecl;
48   }
49 
50   return Offset;
51 }
52 
53 llvm::Constant *
54 CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
55                                    CastExpr::path_const_iterator PathBegin,
56                                    CastExpr::path_const_iterator PathEnd) {
57   assert(PathBegin != PathEnd && "Base path should not be empty!");
58 
59   CharUnits Offset =
60     ComputeNonVirtualBaseClassOffset(getContext(), ClassDecl,
61                                      PathBegin, PathEnd);
62   if (Offset.isZero())
63     return 0;
64 
65   const llvm::Type *PtrDiffTy =
66   Types.ConvertType(getContext().getPointerDiffType());
67 
68   return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
69 }
70 
71 /// Gets the address of a direct base class within a complete object.
72 /// This should only be used for (1) non-virtual bases or (2) virtual bases
73 /// when the type is known to be complete (e.g. in complete destructors).
74 ///
75 /// The object pointed to by 'This' is assumed to be non-null.
76 llvm::Value *
77 CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(llvm::Value *This,
78                                                    const CXXRecordDecl *Derived,
79                                                    const CXXRecordDecl *Base,
80                                                    bool BaseIsVirtual) {
81   // 'this' must be a pointer (in some address space) to Derived.
82   assert(This->getType()->isPointerTy() &&
83          cast<llvm::PointerType>(This->getType())->getElementType()
84            == ConvertType(Derived));
85 
86   // Compute the offset of the virtual base.
87   CharUnits Offset;
88   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
89   if (BaseIsVirtual)
90     Offset = Layout.getVBaseClassOffset(Base);
91   else
92     Offset = Layout.getBaseClassOffset(Base);
93 
94   // Shift and cast down to the base type.
95   // TODO: for complete types, this should be possible with a GEP.
96   llvm::Value *V = This;
97   if (Offset.isPositive()) {
98     const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
99     V = Builder.CreateBitCast(V, Int8PtrTy);
100     V = Builder.CreateConstInBoundsGEP1_64(V, Offset.getQuantity());
101   }
102   V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo());
103 
104   return V;
105 }
106 
107 static llvm::Value *
108 ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, llvm::Value *ThisPtr,
109                                 CharUnits NonVirtual, llvm::Value *Virtual) {
110   const llvm::Type *PtrDiffTy =
111     CGF.ConvertType(CGF.getContext().getPointerDiffType());
112 
113   llvm::Value *NonVirtualOffset = 0;
114   if (!NonVirtual.isZero())
115     NonVirtualOffset = llvm::ConstantInt::get(PtrDiffTy,
116                                               NonVirtual.getQuantity());
117 
118   llvm::Value *BaseOffset;
119   if (Virtual) {
120     if (NonVirtualOffset)
121       BaseOffset = CGF.Builder.CreateAdd(Virtual, NonVirtualOffset);
122     else
123       BaseOffset = Virtual;
124   } else
125     BaseOffset = NonVirtualOffset;
126 
127   // Apply the base offset.
128   const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
129   ThisPtr = CGF.Builder.CreateBitCast(ThisPtr, Int8PtrTy);
130   ThisPtr = CGF.Builder.CreateGEP(ThisPtr, BaseOffset, "add.ptr");
131 
132   return ThisPtr;
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   // Get the virtual base.
147   if ((*Start)->isVirtual()) {
148     VBase =
149       cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
150     ++Start;
151   }
152 
153   CharUnits NonVirtualOffset =
154     ComputeNonVirtualBaseClassOffset(getContext(), VBase ? VBase : Derived,
155                                      Start, PathEnd);
156 
157   // Get the base pointer type.
158   const llvm::Type *BasePtrTy =
159     ConvertType((PathEnd[-1])->getType())->getPointerTo();
160 
161   if (NonVirtualOffset.isZero() && !VBase) {
162     // Just cast back.
163     return Builder.CreateBitCast(Value, BasePtrTy);
164   }
165 
166   llvm::BasicBlock *CastNull = 0;
167   llvm::BasicBlock *CastNotNull = 0;
168   llvm::BasicBlock *CastEnd = 0;
169 
170   if (NullCheckValue) {
171     CastNull = createBasicBlock("cast.null");
172     CastNotNull = createBasicBlock("cast.notnull");
173     CastEnd = createBasicBlock("cast.end");
174 
175     llvm::Value *IsNull = Builder.CreateIsNull(Value);
176     Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
177     EmitBlock(CastNotNull);
178   }
179 
180   llvm::Value *VirtualOffset = 0;
181 
182   if (VBase) {
183     if (Derived->hasAttr<FinalAttr>()) {
184       VirtualOffset = 0;
185 
186       const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
187 
188       CharUnits VBaseOffset = Layout.getVBaseClassOffset(VBase);
189       NonVirtualOffset += VBaseOffset;
190     } else
191       VirtualOffset = GetVirtualBaseClassOffset(Value, Derived, VBase);
192   }
193 
194   // Apply the offsets.
195   Value = ApplyNonVirtualAndVirtualOffset(*this, Value,
196                                           NonVirtualOffset,
197                                           VirtualOffset);
198 
199   // Cast back.
200   Value = Builder.CreateBitCast(Value, BasePtrTy);
201 
202   if (NullCheckValue) {
203     Builder.CreateBr(CastEnd);
204     EmitBlock(CastNull);
205     Builder.CreateBr(CastEnd);
206     EmitBlock(CastEnd);
207 
208     llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
209     PHI->addIncoming(Value, CastNotNull);
210     PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
211                      CastNull);
212     Value = PHI;
213   }
214 
215   return Value;
216 }
217 
218 llvm::Value *
219 CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
220                                           const CXXRecordDecl *Derived,
221                                         CastExpr::path_const_iterator PathBegin,
222                                           CastExpr::path_const_iterator PathEnd,
223                                           bool NullCheckValue) {
224   assert(PathBegin != PathEnd && "Base path should not be empty!");
225 
226   QualType DerivedTy =
227     getContext().getCanonicalType(getContext().getTagDeclType(Derived));
228   const llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
229 
230   llvm::Value *NonVirtualOffset =
231     CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
232 
233   if (!NonVirtualOffset) {
234     // No offset, we can just cast back.
235     return Builder.CreateBitCast(Value, DerivedPtrTy);
236   }
237 
238   llvm::BasicBlock *CastNull = 0;
239   llvm::BasicBlock *CastNotNull = 0;
240   llvm::BasicBlock *CastEnd = 0;
241 
242   if (NullCheckValue) {
243     CastNull = createBasicBlock("cast.null");
244     CastNotNull = createBasicBlock("cast.notnull");
245     CastEnd = createBasicBlock("cast.end");
246 
247     llvm::Value *IsNull = Builder.CreateIsNull(Value);
248     Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
249     EmitBlock(CastNotNull);
250   }
251 
252   // Apply the offset.
253   Value = Builder.CreatePtrToInt(Value, NonVirtualOffset->getType());
254   Value = Builder.CreateSub(Value, NonVirtualOffset);
255   Value = Builder.CreateIntToPtr(Value, DerivedPtrTy);
256 
257   // Just cast.
258   Value = Builder.CreateBitCast(Value, DerivedPtrTy);
259 
260   if (NullCheckValue) {
261     Builder.CreateBr(CastEnd);
262     EmitBlock(CastNull);
263     Builder.CreateBr(CastEnd);
264     EmitBlock(CastEnd);
265 
266     llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
267     PHI->addIncoming(Value, CastNotNull);
268     PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
269                      CastNull);
270     Value = PHI;
271   }
272 
273   return Value;
274 }
275 
276 /// GetVTTParameter - Return the VTT parameter that should be passed to a
277 /// base constructor/destructor with virtual bases.
278 static llvm::Value *GetVTTParameter(CodeGenFunction &CGF, GlobalDecl GD,
279                                     bool ForVirtualBase) {
280   if (!CodeGenVTables::needsVTTParameter(GD)) {
281     // This constructor/destructor does not need a VTT parameter.
282     return 0;
283   }
284 
285   const CXXRecordDecl *RD = cast<CXXMethodDecl>(CGF.CurFuncDecl)->getParent();
286   const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
287 
288   llvm::Value *VTT;
289 
290   uint64_t SubVTTIndex;
291 
292   // If the record matches the base, this is the complete ctor/dtor
293   // variant calling the base variant in a class with virtual bases.
294   if (RD == Base) {
295     assert(!CodeGenVTables::needsVTTParameter(CGF.CurGD) &&
296            "doing no-op VTT offset in base dtor/ctor?");
297     assert(!ForVirtualBase && "Can't have same class as virtual base!");
298     SubVTTIndex = 0;
299   } else {
300     const ASTRecordLayout &Layout =
301       CGF.getContext().getASTRecordLayout(RD);
302     CharUnits BaseOffset = ForVirtualBase ?
303       Layout.getVBaseClassOffset(Base) :
304       Layout.getBaseClassOffset(Base);
305 
306     SubVTTIndex =
307       CGF.CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
308     assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
309   }
310 
311   if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) {
312     // A VTT parameter was passed to the constructor, use it.
313     VTT = CGF.LoadCXXVTT();
314     VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
315   } else {
316     // We're the complete constructor, so get the VTT by name.
317     VTT = CGF.CGM.getVTables().GetAddrOfVTT(RD);
318     VTT = CGF.Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
319   }
320 
321   return VTT;
322 }
323 
324 namespace {
325   /// Call the destructor for a direct base class.
326   struct CallBaseDtor : EHScopeStack::Cleanup {
327     const CXXRecordDecl *BaseClass;
328     bool BaseIsVirtual;
329     CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
330       : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
331 
332     void Emit(CodeGenFunction &CGF, bool IsForEH) {
333       const CXXRecordDecl *DerivedClass =
334         cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
335 
336       const CXXDestructorDecl *D = BaseClass->getDestructor();
337       llvm::Value *Addr =
338         CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(),
339                                                   DerivedClass, BaseClass,
340                                                   BaseIsVirtual);
341       CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual, Addr);
342     }
343   };
344 
345   /// A visitor which checks whether an initializer uses 'this' in a
346   /// way which requires the vtable to be properly set.
347   struct DynamicThisUseChecker : EvaluatedExprVisitor<DynamicThisUseChecker> {
348     typedef EvaluatedExprVisitor<DynamicThisUseChecker> super;
349 
350     bool UsesThis;
351 
352     DynamicThisUseChecker(ASTContext &C) : super(C), UsesThis(false) {}
353 
354     // Black-list all explicit and implicit references to 'this'.
355     //
356     // Do we need to worry about external references to 'this' derived
357     // from arbitrary code?  If so, then anything which runs arbitrary
358     // external code might potentially access the vtable.
359     void VisitCXXThisExpr(CXXThisExpr *E) { UsesThis = true; }
360   };
361 }
362 
363 static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
364   DynamicThisUseChecker Checker(C);
365   Checker.Visit(const_cast<Expr*>(Init));
366   return Checker.UsesThis;
367 }
368 
369 static void EmitBaseInitializer(CodeGenFunction &CGF,
370                                 const CXXRecordDecl *ClassDecl,
371                                 CXXCtorInitializer *BaseInit,
372                                 CXXCtorType CtorType) {
373   assert(BaseInit->isBaseInitializer() &&
374          "Must have base initializer!");
375 
376   llvm::Value *ThisPtr = CGF.LoadCXXThis();
377 
378   const Type *BaseType = BaseInit->getBaseClass();
379   CXXRecordDecl *BaseClassDecl =
380     cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
381 
382   bool isBaseVirtual = BaseInit->isBaseVirtual();
383 
384   // The base constructor doesn't construct virtual bases.
385   if (CtorType == Ctor_Base && isBaseVirtual)
386     return;
387 
388   // If the initializer for the base (other than the constructor
389   // itself) accesses 'this' in any way, we need to initialize the
390   // vtables.
391   if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
392     CGF.InitializeVTablePointers(ClassDecl);
393 
394   // We can pretend to be a complete class because it only matters for
395   // virtual bases, and we only do virtual bases for complete ctors.
396   llvm::Value *V =
397     CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
398                                               BaseClassDecl,
399                                               isBaseVirtual);
400 
401   AggValueSlot AggSlot = AggValueSlot::forAddr(V, false, /*Lifetime*/ true);
402 
403   CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
404 
405   if (CGF.CGM.getLangOptions().Exceptions &&
406       !BaseClassDecl->hasTrivialDestructor())
407     CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
408                                           isBaseVirtual);
409 }
410 
411 static void EmitAggMemberInitializer(CodeGenFunction &CGF,
412                                      LValue LHS,
413                                      llvm::Value *ArrayIndexVar,
414                                      CXXCtorInitializer *MemberInit,
415                                      QualType T,
416                                      unsigned Index) {
417   if (Index == MemberInit->getNumArrayIndices()) {
418     CodeGenFunction::RunCleanupsScope Cleanups(CGF);
419 
420     llvm::Value *Dest = LHS.getAddress();
421     if (ArrayIndexVar) {
422       // If we have an array index variable, load it and use it as an offset.
423       // Then, increment the value.
424       llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
425       Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
426       llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
427       Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
428       CGF.Builder.CreateStore(Next, ArrayIndexVar);
429     }
430 
431     AggValueSlot Slot = AggValueSlot::forAddr(Dest, LHS.isVolatileQualified(),
432                                               /*Lifetime*/ true);
433 
434     CGF.EmitAggExpr(MemberInit->getInit(), Slot);
435 
436     return;
437   }
438 
439   const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
440   assert(Array && "Array initialization without the array type?");
441   llvm::Value *IndexVar
442     = CGF.GetAddrOfLocalVar(MemberInit->getArrayIndex(Index));
443   assert(IndexVar && "Array index variable not loaded");
444 
445   // Initialize this index variable to zero.
446   llvm::Value* Zero
447     = llvm::Constant::getNullValue(
448                               CGF.ConvertType(CGF.getContext().getSizeType()));
449   CGF.Builder.CreateStore(Zero, IndexVar);
450 
451   // Start the loop with a block that tests the condition.
452   llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
453   llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
454 
455   CGF.EmitBlock(CondBlock);
456 
457   llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
458   // Generate: if (loop-index < number-of-elements) fall to the loop body,
459   // otherwise, go to the block after the for-loop.
460   uint64_t NumElements = Array->getSize().getZExtValue();
461   llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
462   llvm::Value *NumElementsPtr =
463     llvm::ConstantInt::get(Counter->getType(), NumElements);
464   llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
465                                                   "isless");
466 
467   // If the condition is true, execute the body.
468   CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
469 
470   CGF.EmitBlock(ForBody);
471   llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
472 
473   {
474     CodeGenFunction::RunCleanupsScope Cleanups(CGF);
475 
476     // Inside the loop body recurse to emit the inner loop or, eventually, the
477     // constructor call.
478     EmitAggMemberInitializer(CGF, LHS, ArrayIndexVar, MemberInit,
479                              Array->getElementType(), Index + 1);
480   }
481 
482   CGF.EmitBlock(ContinueBlock);
483 
484   // Emit the increment of the loop counter.
485   llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
486   Counter = CGF.Builder.CreateLoad(IndexVar);
487   NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
488   CGF.Builder.CreateStore(NextVal, IndexVar);
489 
490   // Finally, branch back up to the condition for the next iteration.
491   CGF.EmitBranch(CondBlock);
492 
493   // Emit the fall-through block.
494   CGF.EmitBlock(AfterFor, true);
495 }
496 
497 namespace {
498   struct CallMemberDtor : EHScopeStack::Cleanup {
499     FieldDecl *Field;
500     CXXDestructorDecl *Dtor;
501 
502     CallMemberDtor(FieldDecl *Field, CXXDestructorDecl *Dtor)
503       : Field(Field), Dtor(Dtor) {}
504 
505     void Emit(CodeGenFunction &CGF, bool IsForEH) {
506       // FIXME: Is this OK for C++0x delegating constructors?
507       llvm::Value *ThisPtr = CGF.LoadCXXThis();
508       LValue LHS = CGF.EmitLValueForField(ThisPtr, Field, 0);
509 
510       CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
511                                 LHS.getAddress());
512     }
513   };
514 }
515 
516 static void EmitMemberInitializer(CodeGenFunction &CGF,
517                                   const CXXRecordDecl *ClassDecl,
518                                   CXXCtorInitializer *MemberInit,
519                                   const CXXConstructorDecl *Constructor,
520                                   FunctionArgList &Args) {
521   assert(MemberInit->isAnyMemberInitializer() &&
522          "Must have member initializer!");
523 
524   // non-static data member initializers.
525   FieldDecl *Field = MemberInit->getAnyMember();
526   QualType FieldType = CGF.getContext().getCanonicalType(Field->getType());
527 
528   llvm::Value *ThisPtr = CGF.LoadCXXThis();
529   LValue LHS;
530 
531   // If we are initializing an anonymous union field, drill down to the field.
532   if (MemberInit->isIndirectMemberInitializer()) {
533     LHS = CGF.EmitLValueForAnonRecordField(ThisPtr,
534                                            MemberInit->getIndirectMember(), 0);
535     FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
536   } else {
537     LHS = CGF.EmitLValueForFieldInitialization(ThisPtr, Field, 0);
538   }
539 
540   // FIXME: If there's no initializer and the CXXCtorInitializer
541   // was implicitly generated, we shouldn't be zeroing memory.
542   RValue RHS;
543   if (FieldType->isReferenceType()) {
544     RHS = CGF.EmitReferenceBindingToExpr(MemberInit->getInit(), Field);
545     CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
546   } else if (FieldType->isArrayType() && !MemberInit->getInit()) {
547     CGF.EmitNullInitialization(LHS.getAddress(), Field->getType());
548   } else if (!CGF.hasAggregateLLVMType(Field->getType())) {
549     RHS = RValue::get(CGF.EmitScalarExpr(MemberInit->getInit()));
550     CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
551   } else if (MemberInit->getInit()->getType()->isAnyComplexType()) {
552     CGF.EmitComplexExprIntoAddr(MemberInit->getInit(), LHS.getAddress(),
553                                 LHS.isVolatileQualified());
554   } else {
555     llvm::Value *ArrayIndexVar = 0;
556     const ConstantArrayType *Array
557       = CGF.getContext().getAsConstantArrayType(FieldType);
558     if (Array && Constructor->isImplicit() &&
559         Constructor->isCopyConstructor()) {
560       const llvm::Type *SizeTy
561         = CGF.ConvertType(CGF.getContext().getSizeType());
562 
563       // The LHS is a pointer to the first object we'll be constructing, as
564       // a flat array.
565       QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
566       const llvm::Type *BasePtr = CGF.ConvertType(BaseElementTy);
567       BasePtr = llvm::PointerType::getUnqual(BasePtr);
568       llvm::Value *BaseAddrPtr = CGF.Builder.CreateBitCast(LHS.getAddress(),
569                                                            BasePtr);
570       LHS = CGF.MakeAddrLValue(BaseAddrPtr, BaseElementTy);
571 
572       // Create an array index that will be used to walk over all of the
573       // objects we're constructing.
574       ArrayIndexVar = CGF.CreateTempAlloca(SizeTy, "object.index");
575       llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
576       CGF.Builder.CreateStore(Zero, ArrayIndexVar);
577 
578       // If we are copying an array of scalars or classes with trivial copy
579       // constructors, perform a single aggregate copy.
580       const RecordType *Record = BaseElementTy->getAs<RecordType>();
581       if (!Record ||
582           cast<CXXRecordDecl>(Record->getDecl())->hasTrivialCopyConstructor()) {
583         // Find the source pointer. We knows it's the last argument because
584         // we know we're in a copy constructor.
585         unsigned SrcArgIndex = Args.size() - 1;
586         llvm::Value *SrcPtr
587           = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
588         LValue Src = CGF.EmitLValueForFieldInitialization(SrcPtr, Field, 0);
589 
590         // Copy the aggregate.
591         CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
592                               LHS.isVolatileQualified());
593         return;
594       }
595 
596       // Emit the block variables for the array indices, if any.
597       for (unsigned I = 0, N = MemberInit->getNumArrayIndices(); I != N; ++I)
598         CGF.EmitAutoVarDecl(*MemberInit->getArrayIndex(I));
599     }
600 
601     EmitAggMemberInitializer(CGF, LHS, ArrayIndexVar, MemberInit, FieldType, 0);
602 
603     if (!CGF.CGM.getLangOptions().Exceptions)
604       return;
605 
606     // FIXME: If we have an array of classes w/ non-trivial destructors,
607     // we need to destroy in reverse order of construction along the exception
608     // path.
609     const RecordType *RT = FieldType->getAs<RecordType>();
610     if (!RT)
611       return;
612 
613     CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
614     if (!RD->hasTrivialDestructor())
615       CGF.EHStack.pushCleanup<CallMemberDtor>(EHCleanup, Field,
616                                               RD->getDestructor());
617   }
618 }
619 
620 /// Checks whether the given constructor is a valid subject for the
621 /// complete-to-base constructor delegation optimization, i.e.
622 /// emitting the complete constructor as a simple call to the base
623 /// constructor.
624 static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
625 
626   // Currently we disable the optimization for classes with virtual
627   // bases because (1) the addresses of parameter variables need to be
628   // consistent across all initializers but (2) the delegate function
629   // call necessarily creates a second copy of the parameter variable.
630   //
631   // The limiting example (purely theoretical AFAIK):
632   //   struct A { A(int &c) { c++; } };
633   //   struct B : virtual A {
634   //     B(int count) : A(count) { printf("%d\n", count); }
635   //   };
636   // ...although even this example could in principle be emitted as a
637   // delegation since the address of the parameter doesn't escape.
638   if (Ctor->getParent()->getNumVBases()) {
639     // TODO: white-list trivial vbase initializers.  This case wouldn't
640     // be subject to the restrictions below.
641 
642     // TODO: white-list cases where:
643     //  - there are no non-reference parameters to the constructor
644     //  - the initializers don't access any non-reference parameters
645     //  - the initializers don't take the address of non-reference
646     //    parameters
647     //  - etc.
648     // If we ever add any of the above cases, remember that:
649     //  - function-try-blocks will always blacklist this optimization
650     //  - we need to perform the constructor prologue and cleanup in
651     //    EmitConstructorBody.
652 
653     return false;
654   }
655 
656   // We also disable the optimization for variadic functions because
657   // it's impossible to "re-pass" varargs.
658   if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
659     return false;
660 
661   return true;
662 }
663 
664 /// EmitConstructorBody - Emits the body of the current constructor.
665 void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
666   const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
667   CXXCtorType CtorType = CurGD.getCtorType();
668 
669   // Before we go any further, try the complete->base constructor
670   // delegation optimization.
671   if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor)) {
672     if (CGDebugInfo *DI = getDebugInfo())
673       DI->EmitStopPoint(Builder);
674     EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args);
675     return;
676   }
677 
678   Stmt *Body = Ctor->getBody();
679 
680   // Enter the function-try-block before the constructor prologue if
681   // applicable.
682   bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
683   if (IsTryBody)
684     EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
685 
686   EHScopeStack::stable_iterator CleanupDepth = EHStack.stable_begin();
687 
688   // Emit the constructor prologue, i.e. the base and member
689   // initializers.
690   EmitCtorPrologue(Ctor, CtorType, Args);
691 
692   // Emit the body of the statement.
693   if (IsTryBody)
694     EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
695   else if (Body)
696     EmitStmt(Body);
697 
698   // Emit any cleanup blocks associated with the member or base
699   // initializers, which includes (along the exceptional path) the
700   // destructors for those members and bases that were fully
701   // constructed.
702   PopCleanupBlocks(CleanupDepth);
703 
704   if (IsTryBody)
705     ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
706 }
707 
708 /// EmitCtorPrologue - This routine generates necessary code to initialize
709 /// base classes and non-static data members belonging to this constructor.
710 void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
711                                        CXXCtorType CtorType,
712                                        FunctionArgList &Args) {
713   const CXXRecordDecl *ClassDecl = CD->getParent();
714 
715   llvm::SmallVector<CXXCtorInitializer *, 8> MemberInitializers;
716 
717   for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
718        E = CD->init_end();
719        B != E; ++B) {
720     CXXCtorInitializer *Member = (*B);
721 
722     if (Member->isBaseInitializer())
723       EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
724     else
725       MemberInitializers.push_back(Member);
726   }
727 
728   InitializeVTablePointers(ClassDecl);
729 
730   for (unsigned I = 0, E = MemberInitializers.size(); I != E; ++I)
731     EmitMemberInitializer(*this, ClassDecl, MemberInitializers[I], CD, Args);
732 }
733 
734 /// EmitDestructorBody - Emits the body of the current destructor.
735 void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
736   const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
737   CXXDtorType DtorType = CurGD.getDtorType();
738 
739   // The call to operator delete in a deleting destructor happens
740   // outside of the function-try-block, which means it's always
741   // possible to delegate the destructor body to the complete
742   // destructor.  Do so.
743   if (DtorType == Dtor_Deleting) {
744     EnterDtorCleanups(Dtor, Dtor_Deleting);
745     EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
746                           LoadCXXThis());
747     PopCleanupBlock();
748     return;
749   }
750 
751   Stmt *Body = Dtor->getBody();
752 
753   // If the body is a function-try-block, enter the try before
754   // anything else.
755   bool isTryBody = (Body && isa<CXXTryStmt>(Body));
756   if (isTryBody)
757     EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
758 
759   // Enter the epilogue cleanups.
760   RunCleanupsScope DtorEpilogue(*this);
761 
762   // If this is the complete variant, just invoke the base variant;
763   // the epilogue will destruct the virtual bases.  But we can't do
764   // this optimization if the body is a function-try-block, because
765   // we'd introduce *two* handler blocks.
766   switch (DtorType) {
767   case Dtor_Deleting: llvm_unreachable("already handled deleting case");
768 
769   case Dtor_Complete:
770     // Enter the cleanup scopes for virtual bases.
771     EnterDtorCleanups(Dtor, Dtor_Complete);
772 
773     if (!isTryBody) {
774       EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
775                             LoadCXXThis());
776       break;
777     }
778     // Fallthrough: act like we're in the base variant.
779 
780   case Dtor_Base:
781     // Enter the cleanup scopes for fields and non-virtual bases.
782     EnterDtorCleanups(Dtor, Dtor_Base);
783 
784     // Initialize the vtable pointers before entering the body.
785     InitializeVTablePointers(Dtor->getParent());
786 
787     if (isTryBody)
788       EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
789     else if (Body)
790       EmitStmt(Body);
791     else {
792       assert(Dtor->isImplicit() && "bodyless dtor not implicit");
793       // nothing to do besides what's in the epilogue
794     }
795     // -fapple-kext must inline any call to this dtor into
796     // the caller's body.
797     if (getContext().getLangOptions().AppleKext)
798       CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
799     break;
800   }
801 
802   // Jump out through the epilogue cleanups.
803   DtorEpilogue.ForceCleanup();
804 
805   // Exit the try if applicable.
806   if (isTryBody)
807     ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
808 }
809 
810 namespace {
811   /// Call the operator delete associated with the current destructor.
812   struct CallDtorDelete : EHScopeStack::Cleanup {
813     CallDtorDelete() {}
814 
815     void Emit(CodeGenFunction &CGF, bool IsForEH) {
816       const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
817       const CXXRecordDecl *ClassDecl = Dtor->getParent();
818       CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
819                          CGF.getContext().getTagDeclType(ClassDecl));
820     }
821   };
822 
823   struct CallArrayFieldDtor : EHScopeStack::Cleanup {
824     const FieldDecl *Field;
825     CallArrayFieldDtor(const FieldDecl *Field) : Field(Field) {}
826 
827     void Emit(CodeGenFunction &CGF, bool IsForEH) {
828       QualType FieldType = Field->getType();
829       const ConstantArrayType *Array =
830         CGF.getContext().getAsConstantArrayType(FieldType);
831 
832       QualType BaseType =
833         CGF.getContext().getBaseElementType(Array->getElementType());
834       const CXXRecordDecl *FieldClassDecl = BaseType->getAsCXXRecordDecl();
835 
836       llvm::Value *ThisPtr = CGF.LoadCXXThis();
837       LValue LHS = CGF.EmitLValueForField(ThisPtr, Field,
838                                           // FIXME: Qualifiers?
839                                           /*CVRQualifiers=*/0);
840 
841       const llvm::Type *BasePtr = CGF.ConvertType(BaseType)->getPointerTo();
842       llvm::Value *BaseAddrPtr =
843         CGF.Builder.CreateBitCast(LHS.getAddress(), BasePtr);
844       CGF.EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(),
845                                     Array, BaseAddrPtr);
846     }
847   };
848 
849   struct CallFieldDtor : EHScopeStack::Cleanup {
850     const FieldDecl *Field;
851     CallFieldDtor(const FieldDecl *Field) : Field(Field) {}
852 
853     void Emit(CodeGenFunction &CGF, bool IsForEH) {
854       const CXXRecordDecl *FieldClassDecl =
855         Field->getType()->getAsCXXRecordDecl();
856 
857       llvm::Value *ThisPtr = CGF.LoadCXXThis();
858       LValue LHS = CGF.EmitLValueForField(ThisPtr, Field,
859                                           // FIXME: Qualifiers?
860                                           /*CVRQualifiers=*/0);
861 
862       CGF.EmitCXXDestructorCall(FieldClassDecl->getDestructor(),
863                                 Dtor_Complete, /*ForVirtualBase=*/false,
864                                 LHS.getAddress());
865     }
866   };
867 }
868 
869 /// EmitDtorEpilogue - Emit all code that comes at the end of class's
870 /// destructor. This is to call destructors on members and base classes
871 /// in reverse order of their construction.
872 void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
873                                         CXXDtorType DtorType) {
874   assert(!DD->isTrivial() &&
875          "Should not emit dtor epilogue for trivial dtor!");
876 
877   // The deleting-destructor phase just needs to call the appropriate
878   // operator delete that Sema picked up.
879   if (DtorType == Dtor_Deleting) {
880     assert(DD->getOperatorDelete() &&
881            "operator delete missing - EmitDtorEpilogue");
882     EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
883     return;
884   }
885 
886   const CXXRecordDecl *ClassDecl = DD->getParent();
887 
888   // The complete-destructor phase just destructs all the virtual bases.
889   if (DtorType == Dtor_Complete) {
890 
891     // We push them in the forward order so that they'll be popped in
892     // the reverse order.
893     for (CXXRecordDecl::base_class_const_iterator I =
894            ClassDecl->vbases_begin(), E = ClassDecl->vbases_end();
895               I != E; ++I) {
896       const CXXBaseSpecifier &Base = *I;
897       CXXRecordDecl *BaseClassDecl
898         = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
899 
900       // Ignore trivial destructors.
901       if (BaseClassDecl->hasTrivialDestructor())
902         continue;
903 
904       EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
905                                         BaseClassDecl,
906                                         /*BaseIsVirtual*/ true);
907     }
908 
909     return;
910   }
911 
912   assert(DtorType == Dtor_Base);
913 
914   // Destroy non-virtual bases.
915   for (CXXRecordDecl::base_class_const_iterator I =
916         ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
917     const CXXBaseSpecifier &Base = *I;
918 
919     // Ignore virtual bases.
920     if (Base.isVirtual())
921       continue;
922 
923     CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
924 
925     // Ignore trivial destructors.
926     if (BaseClassDecl->hasTrivialDestructor())
927       continue;
928 
929     EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
930                                       BaseClassDecl,
931                                       /*BaseIsVirtual*/ false);
932   }
933 
934   // Destroy direct fields.
935   llvm::SmallVector<const FieldDecl *, 16> FieldDecls;
936   for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
937        E = ClassDecl->field_end(); I != E; ++I) {
938     const FieldDecl *Field = *I;
939 
940     QualType FieldType = getContext().getCanonicalType(Field->getType());
941     const ConstantArrayType *Array =
942       getContext().getAsConstantArrayType(FieldType);
943     if (Array)
944       FieldType = getContext().getBaseElementType(Array->getElementType());
945 
946     const RecordType *RT = FieldType->getAs<RecordType>();
947     if (!RT)
948       continue;
949 
950     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
951     if (FieldClassDecl->hasTrivialDestructor())
952         continue;
953 
954     if (Array)
955       EHStack.pushCleanup<CallArrayFieldDtor>(NormalAndEHCleanup, Field);
956     else
957       EHStack.pushCleanup<CallFieldDtor>(NormalAndEHCleanup, Field);
958   }
959 }
960 
961 /// EmitCXXAggrConstructorCall - This routine essentially creates a (nested)
962 /// for-loop to call the default constructor on individual members of the
963 /// array.
964 /// 'D' is the default constructor for elements of the array, 'ArrayTy' is the
965 /// array type and 'ArrayPtr' points to the beginning fo the array.
966 /// It is assumed that all relevant checks have been made by the caller.
967 ///
968 /// \param ZeroInitialization True if each element should be zero-initialized
969 /// before it is constructed.
970 void
971 CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
972                                             const ConstantArrayType *ArrayTy,
973                                             llvm::Value *ArrayPtr,
974                                             CallExpr::const_arg_iterator ArgBeg,
975                                             CallExpr::const_arg_iterator ArgEnd,
976                                             bool ZeroInitialization) {
977 
978   const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
979   llvm::Value * NumElements =
980     llvm::ConstantInt::get(SizeTy,
981                            getContext().getConstantArrayElementCount(ArrayTy));
982 
983   EmitCXXAggrConstructorCall(D, NumElements, ArrayPtr, ArgBeg, ArgEnd,
984                              ZeroInitialization);
985 }
986 
987 void
988 CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
989                                           llvm::Value *NumElements,
990                                           llvm::Value *ArrayPtr,
991                                           CallExpr::const_arg_iterator ArgBeg,
992                                           CallExpr::const_arg_iterator ArgEnd,
993                                             bool ZeroInitialization) {
994   const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
995 
996   // Create a temporary for the loop index and initialize it with 0.
997   llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
998   llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
999   Builder.CreateStore(Zero, IndexPtr);
1000 
1001   // Start the loop with a block that tests the condition.
1002   llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1003   llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1004 
1005   EmitBlock(CondBlock);
1006 
1007   llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1008 
1009   // Generate: if (loop-index < number-of-elements fall to the loop body,
1010   // otherwise, go to the block after the for-loop.
1011   llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1012   llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
1013   // If the condition is true, execute the body.
1014   Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1015 
1016   EmitBlock(ForBody);
1017 
1018   llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1019   // Inside the loop body, emit the constructor call on the array element.
1020   Counter = Builder.CreateLoad(IndexPtr);
1021   llvm::Value *Address = Builder.CreateInBoundsGEP(ArrayPtr, Counter,
1022                                                    "arrayidx");
1023 
1024   // Zero initialize the storage, if requested.
1025   if (ZeroInitialization)
1026     EmitNullInitialization(Address,
1027                            getContext().getTypeDeclType(D->getParent()));
1028 
1029   // C++ [class.temporary]p4:
1030   // There are two contexts in which temporaries are destroyed at a different
1031   // point than the end of the full-expression. The first context is when a
1032   // default constructor is called to initialize an element of an array.
1033   // If the constructor has one or more default arguments, the destruction of
1034   // every temporary created in a default argument expression is sequenced
1035   // before the construction of the next array element, if any.
1036 
1037   // Keep track of the current number of live temporaries.
1038   {
1039     RunCleanupsScope Scope(*this);
1040 
1041     EmitCXXConstructorCall(D, Ctor_Complete, /*ForVirtualBase=*/false, Address,
1042                            ArgBeg, ArgEnd);
1043   }
1044 
1045   EmitBlock(ContinueBlock);
1046 
1047   // Emit the increment of the loop counter.
1048   llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
1049   Counter = Builder.CreateLoad(IndexPtr);
1050   NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1051   Builder.CreateStore(NextVal, IndexPtr);
1052 
1053   // Finally, branch back up to the condition for the next iteration.
1054   EmitBranch(CondBlock);
1055 
1056   // Emit the fall-through block.
1057   EmitBlock(AfterFor, true);
1058 }
1059 
1060 /// EmitCXXAggrDestructorCall - calls the default destructor on array
1061 /// elements in reverse order of construction.
1062 void
1063 CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1064                                            const ArrayType *Array,
1065                                            llvm::Value *This) {
1066   const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1067   assert(CA && "Do we support VLA for destruction ?");
1068   uint64_t ElementCount = getContext().getConstantArrayElementCount(CA);
1069 
1070   const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
1071   llvm::Value* ElementCountPtr = llvm::ConstantInt::get(SizeLTy, ElementCount);
1072   EmitCXXAggrDestructorCall(D, ElementCountPtr, This);
1073 }
1074 
1075 /// EmitCXXAggrDestructorCall - calls the default destructor on array
1076 /// elements in reverse order of construction.
1077 void
1078 CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1079                                            llvm::Value *UpperCount,
1080                                            llvm::Value *This) {
1081   const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
1082   llvm::Value *One = llvm::ConstantInt::get(SizeLTy, 1);
1083 
1084   // Create a temporary for the loop index and initialize it with count of
1085   // array elements.
1086   llvm::Value *IndexPtr = CreateTempAlloca(SizeLTy, "loop.index");
1087 
1088   // Store the number of elements in the index pointer.
1089   Builder.CreateStore(UpperCount, IndexPtr);
1090 
1091   // Start the loop with a block that tests the condition.
1092   llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1093   llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1094 
1095   EmitBlock(CondBlock);
1096 
1097   llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1098 
1099   // Generate: if (loop-index != 0 fall to the loop body,
1100   // otherwise, go to the block after the for-loop.
1101   llvm::Value* zeroConstant =
1102     llvm::Constant::getNullValue(SizeLTy);
1103   llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1104   llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant,
1105                                             "isne");
1106   // If the condition is true, execute the body.
1107   Builder.CreateCondBr(IsNE, ForBody, AfterFor);
1108 
1109   EmitBlock(ForBody);
1110 
1111   llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1112   // Inside the loop body, emit the constructor call on the array element.
1113   Counter = Builder.CreateLoad(IndexPtr);
1114   Counter = Builder.CreateSub(Counter, One);
1115   llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
1116   EmitCXXDestructorCall(D, Dtor_Complete, /*ForVirtualBase=*/false, Address);
1117 
1118   EmitBlock(ContinueBlock);
1119 
1120   // Emit the decrement of the loop counter.
1121   Counter = Builder.CreateLoad(IndexPtr);
1122   Counter = Builder.CreateSub(Counter, One, "dec");
1123   Builder.CreateStore(Counter, IndexPtr);
1124 
1125   // Finally, branch back up to the condition for the next iteration.
1126   EmitBranch(CondBlock);
1127 
1128   // Emit the fall-through block.
1129   EmitBlock(AfterFor, true);
1130 }
1131 
1132 void
1133 CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
1134                                         CXXCtorType Type, bool ForVirtualBase,
1135                                         llvm::Value *This,
1136                                         CallExpr::const_arg_iterator ArgBeg,
1137                                         CallExpr::const_arg_iterator ArgEnd) {
1138 
1139   CGDebugInfo *DI = getDebugInfo();
1140   if (DI && CGM.getCodeGenOpts().LimitDebugInfo) {
1141     // If debug info for this class has been emitted then this is the right time
1142     // to do so.
1143     const CXXRecordDecl *Parent = D->getParent();
1144     DI->getOrCreateRecordType(CGM.getContext().getTypeDeclType(Parent),
1145                               Parent->getLocation());
1146   }
1147 
1148   if (D->isTrivial()) {
1149     if (ArgBeg == ArgEnd) {
1150       // Trivial default constructor, no codegen required.
1151       assert(D->isDefaultConstructor() &&
1152              "trivial 0-arg ctor not a default ctor");
1153       return;
1154     }
1155 
1156     assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
1157     assert(D->isCopyConstructor() && "trivial 1-arg ctor not a copy ctor");
1158 
1159     const Expr *E = (*ArgBeg);
1160     QualType Ty = E->getType();
1161     llvm::Value *Src = EmitLValue(E).getAddress();
1162     EmitAggregateCopy(This, Src, Ty);
1163     return;
1164   }
1165 
1166   llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(D, Type), ForVirtualBase);
1167   llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
1168 
1169   EmitCXXMemberCall(D, Callee, ReturnValueSlot(), This, VTT, ArgBeg, ArgEnd);
1170 }
1171 
1172 void
1173 CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1174                                         llvm::Value *This, llvm::Value *Src,
1175                                         CallExpr::const_arg_iterator ArgBeg,
1176                                         CallExpr::const_arg_iterator ArgEnd) {
1177   if (D->isTrivial()) {
1178     assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
1179     assert(D->isCopyConstructor() && "trivial 1-arg ctor not a copy ctor");
1180     EmitAggregateCopy(This, Src, (*ArgBeg)->getType());
1181     return;
1182   }
1183   llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D,
1184                                                     clang::Ctor_Complete);
1185   assert(D->isInstance() &&
1186          "Trying to emit a member call expr on a static method!");
1187 
1188   const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
1189 
1190   CallArgList Args;
1191 
1192   // Push the this ptr.
1193   Args.push_back(std::make_pair(RValue::get(This),
1194                                 D->getThisType(getContext())));
1195 
1196 
1197   // Push the src ptr.
1198   QualType QT = *(FPT->arg_type_begin());
1199   const llvm::Type *t = CGM.getTypes().ConvertType(QT);
1200   Src = Builder.CreateBitCast(Src, t);
1201   Args.push_back(std::make_pair(RValue::get(Src), QT));
1202 
1203   // Skip over first argument (Src).
1204   ++ArgBeg;
1205   CallExpr::const_arg_iterator Arg = ArgBeg;
1206   for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin()+1,
1207        E = FPT->arg_type_end(); I != E; ++I, ++Arg) {
1208     assert(Arg != ArgEnd && "Running over edge of argument list!");
1209     EmitCallArg(Args, *Arg, *I);
1210   }
1211   // Either we've emitted all the call args, or we have a call to a
1212   // variadic function.
1213   assert((Arg == ArgEnd || FPT->isVariadic()) &&
1214          "Extra arguments in non-variadic function!");
1215   // If we still have any arguments, emit them using the type of the argument.
1216   for (; Arg != ArgEnd; ++Arg) {
1217     QualType ArgType = Arg->getType();
1218     EmitCallArg(Args, *Arg, ArgType);
1219   }
1220 
1221   QualType ResultType = FPT->getResultType();
1222   EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args,
1223                                           FPT->getExtInfo()),
1224                   Callee, ReturnValueSlot(), Args, D);
1225 }
1226 
1227 void
1228 CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1229                                                 CXXCtorType CtorType,
1230                                                 const FunctionArgList &Args) {
1231   CallArgList DelegateArgs;
1232 
1233   FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1234   assert(I != E && "no parameters to constructor");
1235 
1236   // this
1237   DelegateArgs.push_back(std::make_pair(RValue::get(LoadCXXThis()),
1238                                         (*I)->getType()));
1239   ++I;
1240 
1241   // vtt
1242   if (llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(Ctor, CtorType),
1243                                          /*ForVirtualBase=*/false)) {
1244     QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
1245     DelegateArgs.push_back(std::make_pair(RValue::get(VTT), VoidPP));
1246 
1247     if (CodeGenVTables::needsVTTParameter(CurGD)) {
1248       assert(I != E && "cannot skip vtt parameter, already done with args");
1249       assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
1250       ++I;
1251     }
1252   }
1253 
1254   // Explicit arguments.
1255   for (; I != E; ++I) {
1256     const VarDecl *param = *I;
1257     EmitDelegateCallArg(DelegateArgs, param);
1258   }
1259 
1260   EmitCall(CGM.getTypes().getFunctionInfo(Ctor, CtorType),
1261            CGM.GetAddrOfCXXConstructor(Ctor, CtorType),
1262            ReturnValueSlot(), DelegateArgs, Ctor);
1263 }
1264 
1265 void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1266                                             CXXDtorType Type,
1267                                             bool ForVirtualBase,
1268                                             llvm::Value *This) {
1269   llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(DD, Type),
1270                                      ForVirtualBase);
1271   llvm::Value *Callee = 0;
1272   if (getContext().getLangOptions().AppleKext)
1273     Callee = BuildAppleKextVirtualDestructorCall(DD, Type,
1274                                                  DD->getParent());
1275 
1276   if (!Callee)
1277     Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
1278 
1279   EmitCXXMemberCall(DD, Callee, ReturnValueSlot(), This, VTT, 0, 0);
1280 }
1281 
1282 namespace {
1283   struct CallLocalDtor : EHScopeStack::Cleanup {
1284     const CXXDestructorDecl *Dtor;
1285     llvm::Value *Addr;
1286 
1287     CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1288       : Dtor(D), Addr(Addr) {}
1289 
1290     void Emit(CodeGenFunction &CGF, bool IsForEH) {
1291       CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1292                                 /*ForVirtualBase=*/false, Addr);
1293     }
1294   };
1295 }
1296 
1297 void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1298                                             llvm::Value *Addr) {
1299   EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
1300 }
1301 
1302 void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1303   CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1304   if (!ClassDecl) return;
1305   if (ClassDecl->hasTrivialDestructor()) return;
1306 
1307   const CXXDestructorDecl *D = ClassDecl->getDestructor();
1308   PushDestructorCleanup(D, Addr);
1309 }
1310 
1311 llvm::Value *
1312 CodeGenFunction::GetVirtualBaseClassOffset(llvm::Value *This,
1313                                            const CXXRecordDecl *ClassDecl,
1314                                            const CXXRecordDecl *BaseClassDecl) {
1315   llvm::Value *VTablePtr = GetVTablePtr(This, Int8PtrTy);
1316   CharUnits VBaseOffsetOffset =
1317     CGM.getVTables().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
1318 
1319   llvm::Value *VBaseOffsetPtr =
1320     Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1321                                "vbase.offset.ptr");
1322   const llvm::Type *PtrDiffTy =
1323     ConvertType(getContext().getPointerDiffType());
1324 
1325   VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
1326                                          PtrDiffTy->getPointerTo());
1327 
1328   llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1329 
1330   return VBaseOffset;
1331 }
1332 
1333 void
1334 CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
1335                                          const CXXRecordDecl *NearestVBase,
1336                                          CharUnits OffsetFromNearestVBase,
1337                                          llvm::Constant *VTable,
1338                                          const CXXRecordDecl *VTableClass) {
1339   const CXXRecordDecl *RD = Base.getBase();
1340 
1341   // Compute the address point.
1342   llvm::Value *VTableAddressPoint;
1343 
1344   // Check if we need to use a vtable from the VTT.
1345   if (CodeGenVTables::needsVTTParameter(CurGD) &&
1346       (RD->getNumVBases() || NearestVBase)) {
1347     // Get the secondary vpointer index.
1348     uint64_t VirtualPointerIndex =
1349      CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1350 
1351     /// Load the VTT.
1352     llvm::Value *VTT = LoadCXXVTT();
1353     if (VirtualPointerIndex)
1354       VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1355 
1356     // And load the address point from the VTT.
1357     VTableAddressPoint = Builder.CreateLoad(VTT);
1358   } else {
1359     uint64_t AddressPoint = CGM.getVTables().getAddressPoint(Base, VTableClass);
1360     VTableAddressPoint =
1361       Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
1362   }
1363 
1364   // Compute where to store the address point.
1365   llvm::Value *VirtualOffset = 0;
1366   CharUnits NonVirtualOffset = CharUnits::Zero();
1367 
1368   if (CodeGenVTables::needsVTTParameter(CurGD) && NearestVBase) {
1369     // We need to use the virtual base offset offset because the virtual base
1370     // might have a different offset in the most derived class.
1371     VirtualOffset = GetVirtualBaseClassOffset(LoadCXXThis(), VTableClass,
1372                                               NearestVBase);
1373     NonVirtualOffset = OffsetFromNearestVBase;
1374   } else {
1375     // We can just use the base offset in the complete class.
1376     NonVirtualOffset = Base.getBaseOffset();
1377   }
1378 
1379   // Apply the offsets.
1380   llvm::Value *VTableField = LoadCXXThis();
1381 
1382   if (!NonVirtualOffset.isZero() || VirtualOffset)
1383     VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
1384                                                   NonVirtualOffset,
1385                                                   VirtualOffset);
1386 
1387   // Finally, store the address point.
1388   const llvm::Type *AddressPointPtrTy =
1389     VTableAddressPoint->getType()->getPointerTo();
1390   VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
1391   Builder.CreateStore(VTableAddressPoint, VTableField);
1392 }
1393 
1394 void
1395 CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
1396                                           const CXXRecordDecl *NearestVBase,
1397                                           CharUnits OffsetFromNearestVBase,
1398                                           bool BaseIsNonVirtualPrimaryBase,
1399                                           llvm::Constant *VTable,
1400                                           const CXXRecordDecl *VTableClass,
1401                                           VisitedVirtualBasesSetTy& VBases) {
1402   // If this base is a non-virtual primary base the address point has already
1403   // been set.
1404   if (!BaseIsNonVirtualPrimaryBase) {
1405     // Initialize the vtable pointer for this base.
1406     InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
1407                             VTable, VTableClass);
1408   }
1409 
1410   const CXXRecordDecl *RD = Base.getBase();
1411 
1412   // Traverse bases.
1413   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1414        E = RD->bases_end(); I != E; ++I) {
1415     CXXRecordDecl *BaseDecl
1416       = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1417 
1418     // Ignore classes without a vtable.
1419     if (!BaseDecl->isDynamicClass())
1420       continue;
1421 
1422     CharUnits BaseOffset;
1423     CharUnits BaseOffsetFromNearestVBase;
1424     bool BaseDeclIsNonVirtualPrimaryBase;
1425 
1426     if (I->isVirtual()) {
1427       // Check if we've visited this virtual base before.
1428       if (!VBases.insert(BaseDecl))
1429         continue;
1430 
1431       const ASTRecordLayout &Layout =
1432         getContext().getASTRecordLayout(VTableClass);
1433 
1434       BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
1435       BaseOffsetFromNearestVBase = CharUnits::Zero();
1436       BaseDeclIsNonVirtualPrimaryBase = false;
1437     } else {
1438       const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1439 
1440       BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
1441       BaseOffsetFromNearestVBase =
1442         OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
1443       BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
1444     }
1445 
1446     InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
1447                              I->isVirtual() ? BaseDecl : NearestVBase,
1448                              BaseOffsetFromNearestVBase,
1449                              BaseDeclIsNonVirtualPrimaryBase,
1450                              VTable, VTableClass, VBases);
1451   }
1452 }
1453 
1454 void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
1455   // Ignore classes without a vtable.
1456   if (!RD->isDynamicClass())
1457     return;
1458 
1459   // Get the VTable.
1460   llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(RD);
1461 
1462   // Initialize the vtable pointers for this class and all of its bases.
1463   VisitedVirtualBasesSetTy VBases;
1464   InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
1465                            /*NearestVBase=*/0,
1466                            /*OffsetFromNearestVBase=*/CharUnits::Zero(),
1467                            /*BaseIsNonVirtualPrimaryBase=*/false,
1468                            VTable, RD, VBases);
1469 }
1470 
1471 llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
1472                                            const llvm::Type *Ty) {
1473   llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
1474   return Builder.CreateLoad(VTablePtrSrc, "vtable");
1475 }
1476