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 "CodeGenFunction.h"
15 #include "clang/AST/CXXInheritance.h"
16 #include "clang/AST/RecordLayout.h"
17 
18 using namespace clang;
19 using namespace CodeGen;
20 
21 static uint64_t
22 ComputeNonVirtualBaseClassOffset(ASTContext &Context, CXXBasePaths &Paths,
23                                  unsigned Start) {
24   uint64_t Offset = 0;
25 
26   const CXXBasePath &Path = Paths.front();
27   for (unsigned i = Start, e = Path.size(); i != e; ++i) {
28     const CXXBasePathElement& Element = Path[i];
29 
30     // Get the layout.
31     const ASTRecordLayout &Layout = Context.getASTRecordLayout(Element.Class);
32 
33     const CXXBaseSpecifier *BS = Element.Base;
34     assert(!BS->isVirtual() && "Should not see virtual bases here!");
35 
36     const CXXRecordDecl *Base =
37       cast<CXXRecordDecl>(BS->getType()->getAs<RecordType>()->getDecl());
38 
39     // Add the offset.
40     Offset += Layout.getBaseClassOffset(Base) / 8;
41   }
42 
43   return Offset;
44 }
45 
46 llvm::Constant *
47 CodeGenModule::GetCXXBaseClassOffset(const CXXRecordDecl *ClassDecl,
48                                      const CXXRecordDecl *BaseClassDecl) {
49   if (ClassDecl == BaseClassDecl)
50     return 0;
51 
52   CXXBasePaths Paths(/*FindAmbiguities=*/false,
53                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
54   if (!const_cast<CXXRecordDecl *>(ClassDecl)->
55         isDerivedFrom(const_cast<CXXRecordDecl *>(BaseClassDecl), Paths)) {
56     assert(false && "Class must be derived from the passed in base class!");
57     return 0;
58   }
59 
60   uint64_t Offset = ComputeNonVirtualBaseClassOffset(getContext(), Paths, 0);
61   if (!Offset)
62     return 0;
63 
64   const llvm::Type *PtrDiffTy =
65     Types.ConvertType(getContext().getPointerDiffType());
66 
67   return llvm::ConstantInt::get(PtrDiffTy, Offset);
68 }
69 
70 static llvm::Value *GetCXXBaseClassOffset(CodeGenFunction &CGF,
71                                           llvm::Value *BaseValue,
72                                           const CXXRecordDecl *ClassDecl,
73                                           const CXXRecordDecl *BaseClassDecl) {
74   CXXBasePaths Paths(/*FindAmbiguities=*/false,
75                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
76   if (!const_cast<CXXRecordDecl *>(ClassDecl)->
77         isDerivedFrom(const_cast<CXXRecordDecl *>(BaseClassDecl), Paths)) {
78     assert(false && "Class must be derived from the passed in base class!");
79     return 0;
80   }
81 
82   unsigned Start = 0;
83   llvm::Value *VirtualOffset = 0;
84 
85   const CXXBasePath &Path = Paths.front();
86   const CXXRecordDecl *VBase = 0;
87   for (unsigned i = 0, e = Path.size(); i != e; ++i) {
88     const CXXBasePathElement& Element = Path[i];
89     if (Element.Base->isVirtual()) {
90       Start = i+1;
91       QualType VBaseType = Element.Base->getType();
92       VBase = cast<CXXRecordDecl>(VBaseType->getAs<RecordType>()->getDecl());
93     }
94   }
95   if (VBase)
96     VirtualOffset =
97       CGF.GetVirtualCXXBaseClassOffset(BaseValue, ClassDecl, VBase);
98 
99   uint64_t Offset =
100     ComputeNonVirtualBaseClassOffset(CGF.getContext(), Paths, Start);
101 
102   if (!Offset)
103     return VirtualOffset;
104 
105   const llvm::Type *PtrDiffTy =
106     CGF.ConvertType(CGF.getContext().getPointerDiffType());
107   llvm::Value *NonVirtualOffset = llvm::ConstantInt::get(PtrDiffTy, Offset);
108 
109   if (VirtualOffset)
110     return CGF.Builder.CreateAdd(VirtualOffset, NonVirtualOffset);
111 
112   return NonVirtualOffset;
113 }
114 
115 // FIXME: This probably belongs in CGVtable, but it relies on
116 // the static function ComputeNonVirtualBaseClassOffset, so we should make that
117 // a CodeGenModule member function as well.
118 ThunkAdjustment
119 CodeGenModule::ComputeThunkAdjustment(const CXXRecordDecl *ClassDecl,
120                                       const CXXRecordDecl *BaseClassDecl) {
121   CXXBasePaths Paths(/*FindAmbiguities=*/false,
122                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
123   if (!const_cast<CXXRecordDecl *>(ClassDecl)->
124         isDerivedFrom(const_cast<CXXRecordDecl *>(BaseClassDecl), Paths)) {
125     assert(false && "Class must be derived from the passed in base class!");
126     return ThunkAdjustment();
127   }
128 
129   unsigned Start = 0;
130   uint64_t VirtualOffset = 0;
131 
132   const CXXBasePath &Path = Paths.front();
133   const CXXRecordDecl *VBase = 0;
134   for (unsigned i = 0, e = Path.size(); i != e; ++i) {
135     const CXXBasePathElement& Element = Path[i];
136     if (Element.Base->isVirtual()) {
137       Start = i+1;
138       QualType VBaseType = Element.Base->getType();
139       VBase = cast<CXXRecordDecl>(VBaseType->getAs<RecordType>()->getDecl());
140     }
141   }
142   if (VBase)
143     VirtualOffset =
144       getVtableInfo().getVirtualBaseOffsetIndex(ClassDecl, BaseClassDecl);
145 
146   uint64_t Offset =
147     ComputeNonVirtualBaseClassOffset(getContext(), Paths, Start);
148   return ThunkAdjustment(Offset, VirtualOffset);
149 }
150 
151 llvm::Value *
152 CodeGenFunction::GetAddressOfBaseClass(llvm::Value *Value,
153                                        const CXXRecordDecl *ClassDecl,
154                                        const CXXRecordDecl *BaseClassDecl,
155                                        bool NullCheckValue) {
156   QualType BTy =
157     getContext().getCanonicalType(
158       getContext().getTypeDeclType(const_cast<CXXRecordDecl*>(BaseClassDecl)));
159   const llvm::Type *BasePtrTy = llvm::PointerType::getUnqual(ConvertType(BTy));
160 
161   if (ClassDecl == BaseClassDecl) {
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 =
176       Builder.CreateICmpEQ(Value,
177                            llvm::Constant::getNullValue(Value->getType()));
178     Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
179     EmitBlock(CastNotNull);
180   }
181 
182   const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
183 
184   llvm::Value *Offset =
185     GetCXXBaseClassOffset(*this, Value, ClassDecl, BaseClassDecl);
186 
187   if (Offset) {
188     // Apply the offset.
189     Value = Builder.CreateBitCast(Value, Int8PtrTy);
190     Value = Builder.CreateGEP(Value, Offset, "add.ptr");
191   }
192 
193   // Cast back.
194   Value = Builder.CreateBitCast(Value, BasePtrTy);
195 
196   if (NullCheckValue) {
197     Builder.CreateBr(CastEnd);
198     EmitBlock(CastNull);
199     Builder.CreateBr(CastEnd);
200     EmitBlock(CastEnd);
201 
202     llvm::PHINode *PHI = Builder.CreatePHI(Value->getType());
203     PHI->reserveOperandSpace(2);
204     PHI->addIncoming(Value, CastNotNull);
205     PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
206                      CastNull);
207     Value = PHI;
208   }
209 
210   return Value;
211 }
212 
213 llvm::Value *
214 CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
215                                           const CXXRecordDecl *ClassDecl,
216                                           const CXXRecordDecl *DerivedClassDecl,
217                                           bool NullCheckValue) {
218   QualType DerivedTy =
219     getContext().getCanonicalType(
220     getContext().getTypeDeclType(const_cast<CXXRecordDecl*>(DerivedClassDecl)));
221   const llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
222 
223   if (ClassDecl == DerivedClassDecl) {
224     // Just cast back.
225     return Builder.CreateBitCast(Value, DerivedPtrTy);
226   }
227 
228   llvm::BasicBlock *CastNull = 0;
229   llvm::BasicBlock *CastNotNull = 0;
230   llvm::BasicBlock *CastEnd = 0;
231 
232   if (NullCheckValue) {
233     CastNull = createBasicBlock("cast.null");
234     CastNotNull = createBasicBlock("cast.notnull");
235     CastEnd = createBasicBlock("cast.end");
236 
237     llvm::Value *IsNull =
238     Builder.CreateICmpEQ(Value,
239                          llvm::Constant::getNullValue(Value->getType()));
240     Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
241     EmitBlock(CastNotNull);
242   }
243 
244   llvm::Value *Offset = GetCXXBaseClassOffset(*this, Value, DerivedClassDecl,
245                                               ClassDecl);
246   if (Offset) {
247     // Apply the offset.
248     Value = Builder.CreatePtrToInt(Value, Offset->getType());
249     Value = Builder.CreateSub(Value, Offset);
250     Value = Builder.CreateIntToPtr(Value, DerivedPtrTy);
251   } else {
252     // Just cast.
253     Value = Builder.CreateBitCast(Value, DerivedPtrTy);
254   }
255 
256   if (NullCheckValue) {
257     Builder.CreateBr(CastEnd);
258     EmitBlock(CastNull);
259     Builder.CreateBr(CastEnd);
260     EmitBlock(CastEnd);
261 
262     llvm::PHINode *PHI = Builder.CreatePHI(Value->getType());
263     PHI->reserveOperandSpace(2);
264     PHI->addIncoming(Value, CastNotNull);
265     PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
266                      CastNull);
267     Value = PHI;
268   }
269 
270   return Value;
271 }
272 
273 /// EmitClassAggrMemberwiseCopy - This routine generates code to copy a class
274 /// array of objects from SrcValue to DestValue. Copying can be either a bitwise
275 /// copy or via a copy constructor call.
276 //  FIXME. Consolidate this with EmitCXXAggrConstructorCall.
277 void CodeGenFunction::EmitClassAggrMemberwiseCopy(llvm::Value *Dest,
278                                             llvm::Value *Src,
279                                             const ArrayType *Array,
280                                             const CXXRecordDecl *BaseClassDecl,
281                                             QualType Ty) {
282   const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
283   assert(CA && "VLA cannot be copied over");
284   bool BitwiseCopy = BaseClassDecl->hasTrivialCopyConstructor();
285 
286   // Create a temporary for the loop index and initialize it with 0.
287   llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
288                                            "loop.index");
289   llvm::Value* zeroConstant =
290     llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
291   Builder.CreateStore(zeroConstant, IndexPtr);
292   // Start the loop with a block that tests the condition.
293   llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
294   llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
295 
296   EmitBlock(CondBlock);
297 
298   llvm::BasicBlock *ForBody = createBasicBlock("for.body");
299   // Generate: if (loop-index < number-of-elements fall to the loop body,
300   // otherwise, go to the block after the for-loop.
301   uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
302   llvm::Value * NumElementsPtr =
303     llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
304   llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
305   llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
306                                               "isless");
307   // If the condition is true, execute the body.
308   Builder.CreateCondBr(IsLess, ForBody, AfterFor);
309 
310   EmitBlock(ForBody);
311   llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
312   // Inside the loop body, emit the constructor call on the array element.
313   Counter = Builder.CreateLoad(IndexPtr);
314   Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
315   Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
316   if (BitwiseCopy)
317     EmitAggregateCopy(Dest, Src, Ty);
318   else if (CXXConstructorDecl *BaseCopyCtor =
319            BaseClassDecl->getCopyConstructor(getContext(), 0)) {
320     llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
321                                                       Ctor_Complete);
322     CallArgList CallArgs;
323     // Push the this (Dest) ptr.
324     CallArgs.push_back(std::make_pair(RValue::get(Dest),
325                                       BaseCopyCtor->getThisType(getContext())));
326 
327     // Push the Src ptr.
328     CallArgs.push_back(std::make_pair(RValue::get(Src),
329                                      BaseCopyCtor->getParamDecl(0)->getType()));
330     QualType ResultType =
331       BaseCopyCtor->getType()->getAs<FunctionType>()->getResultType();
332     EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
333              Callee, ReturnValueSlot(), CallArgs, BaseCopyCtor);
334   }
335   EmitBlock(ContinueBlock);
336 
337   // Emit the increment of the loop counter.
338   llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
339   Counter = Builder.CreateLoad(IndexPtr);
340   NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
341   Builder.CreateStore(NextVal, IndexPtr);
342 
343   // Finally, branch back up to the condition for the next iteration.
344   EmitBranch(CondBlock);
345 
346   // Emit the fall-through block.
347   EmitBlock(AfterFor, true);
348 }
349 
350 /// EmitClassAggrCopyAssignment - This routine generates code to assign a class
351 /// array of objects from SrcValue to DestValue. Assignment can be either a
352 /// bitwise assignment or via a copy assignment operator function call.
353 /// FIXME. This can be consolidated with EmitClassAggrMemberwiseCopy
354 void CodeGenFunction::EmitClassAggrCopyAssignment(llvm::Value *Dest,
355                                             llvm::Value *Src,
356                                             const ArrayType *Array,
357                                             const CXXRecordDecl *BaseClassDecl,
358                                             QualType Ty) {
359   const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
360   assert(CA && "VLA cannot be asssigned");
361   bool BitwiseAssign = BaseClassDecl->hasTrivialCopyAssignment();
362 
363   // Create a temporary for the loop index and initialize it with 0.
364   llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
365                                            "loop.index");
366   llvm::Value* zeroConstant =
367   llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
368   Builder.CreateStore(zeroConstant, IndexPtr);
369   // Start the loop with a block that tests the condition.
370   llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
371   llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
372 
373   EmitBlock(CondBlock);
374 
375   llvm::BasicBlock *ForBody = createBasicBlock("for.body");
376   // Generate: if (loop-index < number-of-elements fall to the loop body,
377   // otherwise, go to the block after the for-loop.
378   uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
379   llvm::Value * NumElementsPtr =
380   llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
381   llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
382   llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
383                                               "isless");
384   // If the condition is true, execute the body.
385   Builder.CreateCondBr(IsLess, ForBody, AfterFor);
386 
387   EmitBlock(ForBody);
388   llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
389   // Inside the loop body, emit the assignment operator call on array element.
390   Counter = Builder.CreateLoad(IndexPtr);
391   Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
392   Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
393   const CXXMethodDecl *MD = 0;
394   if (BitwiseAssign)
395     EmitAggregateCopy(Dest, Src, Ty);
396   else {
397     BaseClassDecl->hasConstCopyAssignment(getContext(), MD);
398     assert(MD && "EmitClassAggrCopyAssignment - No user assign");
399     const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
400     const llvm::Type *LTy =
401     CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
402                                    FPT->isVariadic());
403     llvm::Constant *Callee = CGM.GetAddrOfFunction(MD, LTy);
404 
405     CallArgList CallArgs;
406     // Push the this (Dest) ptr.
407     CallArgs.push_back(std::make_pair(RValue::get(Dest),
408                                       MD->getThisType(getContext())));
409 
410     // Push the Src ptr.
411     QualType SrcTy = MD->getParamDecl(0)->getType();
412     RValue SrcValue = SrcTy->isReferenceType() ? RValue::get(Src) :
413                                                  RValue::getAggregate(Src);
414     CallArgs.push_back(std::make_pair(SrcValue, SrcTy));
415     QualType ResultType = MD->getType()->getAs<FunctionType>()->getResultType();
416     EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
417              Callee, ReturnValueSlot(), CallArgs, MD);
418   }
419   EmitBlock(ContinueBlock);
420 
421   // Emit the increment of the loop counter.
422   llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
423   Counter = Builder.CreateLoad(IndexPtr);
424   NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
425   Builder.CreateStore(NextVal, IndexPtr);
426 
427   // Finally, branch back up to the condition for the next iteration.
428   EmitBranch(CondBlock);
429 
430   // Emit the fall-through block.
431   EmitBlock(AfterFor, true);
432 }
433 
434 /// GetVTTParameter - Return the VTT parameter that should be passed to a
435 /// base constructor/destructor with virtual bases.
436 static llvm::Value *GetVTTParameter(CodeGenFunction &CGF, GlobalDecl GD) {
437   if (!CGVtableInfo::needsVTTParameter(GD)) {
438     // This constructor/destructor does not need a VTT parameter.
439     return 0;
440   }
441 
442   const CXXRecordDecl *RD = cast<CXXMethodDecl>(CGF.CurFuncDecl)->getParent();
443   const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
444 
445   llvm::Value *VTT;
446 
447   uint64_t SubVTTIndex =
448     CGF.CGM.getVtableInfo().getSubVTTIndex(RD, Base);
449   assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
450 
451   if (CGVtableInfo::needsVTTParameter(CGF.CurGD)) {
452     // A VTT parameter was passed to the constructor, use it.
453     VTT = CGF.LoadCXXVTT();
454     VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
455   } else {
456     // We're the complete constructor, so get the VTT by name.
457     VTT = CGF.CGM.getVtableInfo().getVTT(RD);
458     VTT = CGF.Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
459   }
460 
461   return VTT;
462 }
463 
464 
465 /// EmitClassMemberwiseCopy - This routine generates code to copy a class
466 /// object from SrcValue to DestValue. Copying can be either a bitwise copy
467 /// or via a copy constructor call.
468 void CodeGenFunction::EmitClassMemberwiseCopy(
469                         llvm::Value *Dest, llvm::Value *Src,
470                         const CXXRecordDecl *ClassDecl,
471                         const CXXRecordDecl *BaseClassDecl, QualType Ty) {
472   CXXCtorType CtorType = Ctor_Complete;
473 
474   if (ClassDecl) {
475     Dest = GetAddressOfBaseClass(Dest, ClassDecl, BaseClassDecl,
476                                  /*NullCheckValue=*/false);
477     Src = GetAddressOfBaseClass(Src, ClassDecl, BaseClassDecl,
478                                 /*NullCheckValue=*/false);
479 
480     // We want to call the base constructor.
481     CtorType = Ctor_Base;
482   }
483   if (BaseClassDecl->hasTrivialCopyConstructor()) {
484     EmitAggregateCopy(Dest, Src, Ty);
485     return;
486   }
487 
488   if (CXXConstructorDecl *BaseCopyCtor =
489       BaseClassDecl->getCopyConstructor(getContext(), 0)) {
490     llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor, CtorType);
491     CallArgList CallArgs;
492     // Push the this (Dest) ptr.
493     CallArgs.push_back(std::make_pair(RValue::get(Dest),
494                                       BaseCopyCtor->getThisType(getContext())));
495 
496     // Push the VTT parameter, if necessary.
497     if (llvm::Value *VTT =
498           GetVTTParameter(*this, GlobalDecl(BaseCopyCtor, CtorType))) {
499       QualType T = getContext().getPointerType(getContext().VoidPtrTy);
500       CallArgs.push_back(std::make_pair(RValue::get(VTT), T));
501     }
502 
503     // Push the Src ptr.
504     CallArgs.push_back(std::make_pair(RValue::get(Src),
505                        BaseCopyCtor->getParamDecl(0)->getType()));
506     QualType ResultType =
507     BaseCopyCtor->getType()->getAs<FunctionType>()->getResultType();
508     EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
509              Callee, ReturnValueSlot(), CallArgs, BaseCopyCtor);
510   }
511 }
512 
513 /// EmitClassCopyAssignment - This routine generates code to copy assign a class
514 /// object from SrcValue to DestValue. Assignment can be either a bitwise
515 /// assignment of via an assignment operator call.
516 // FIXME. Consolidate this with EmitClassMemberwiseCopy as they share a lot.
517 void CodeGenFunction::EmitClassCopyAssignment(
518                                         llvm::Value *Dest, llvm::Value *Src,
519                                         const CXXRecordDecl *ClassDecl,
520                                         const CXXRecordDecl *BaseClassDecl,
521                                         QualType Ty) {
522   if (ClassDecl) {
523     Dest = GetAddressOfBaseClass(Dest, ClassDecl, BaseClassDecl,
524                                  /*NullCheckValue=*/false);
525     Src = GetAddressOfBaseClass(Src, ClassDecl, BaseClassDecl,
526                                 /*NullCheckValue=*/false);
527   }
528   if (BaseClassDecl->hasTrivialCopyAssignment()) {
529     EmitAggregateCopy(Dest, Src, Ty);
530     return;
531   }
532 
533   const CXXMethodDecl *MD = 0;
534   BaseClassDecl->hasConstCopyAssignment(getContext(), MD);
535   assert(MD && "EmitClassCopyAssignment - missing copy assign");
536 
537   const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
538   const llvm::Type *LTy =
539     CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
540                                    FPT->isVariadic());
541   llvm::Constant *Callee = CGM.GetAddrOfFunction(MD, LTy);
542 
543   CallArgList CallArgs;
544   // Push the this (Dest) ptr.
545   CallArgs.push_back(std::make_pair(RValue::get(Dest),
546                                     MD->getThisType(getContext())));
547 
548   // Push the Src ptr.
549   QualType SrcTy = MD->getParamDecl(0)->getType();
550   RValue SrcValue = SrcTy->isReferenceType() ? RValue::get(Src) :
551                                                RValue::getAggregate(Src);
552   CallArgs.push_back(std::make_pair(SrcValue, SrcTy));
553   QualType ResultType =
554     MD->getType()->getAs<FunctionType>()->getResultType();
555   EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
556            Callee, ReturnValueSlot(), CallArgs, MD);
557 }
558 
559 /// SynthesizeDefaultConstructor - synthesize a default constructor
560 void
561 CodeGenFunction::SynthesizeDefaultConstructor(const CXXConstructorDecl *Ctor,
562                                               CXXCtorType Type,
563                                               llvm::Function *Fn,
564                                               const FunctionArgList &Args) {
565   assert(!Ctor->isTrivial() && "shouldn't need to generate trivial ctor");
566   StartFunction(GlobalDecl(Ctor, Type), Ctor->getResultType(), Fn, Args,
567                 SourceLocation());
568   EmitCtorPrologue(Ctor, Type);
569   FinishFunction();
570 }
571 
572 /// SynthesizeCXXCopyConstructor - This routine implicitly defines body of a
573 /// copy constructor, in accordance with section 12.8 (p7 and p8) of C++03
574 /// The implicitly-defined copy constructor for class X performs a memberwise
575 /// copy of its subobjects. The order of copying is the same as the order of
576 /// initialization of bases and members in a user-defined constructor
577 /// Each subobject is copied in the manner appropriate to its type:
578 ///  if the subobject is of class type, the copy constructor for the class is
579 ///  used;
580 ///  if the subobject is an array, each element is copied, in the manner
581 ///  appropriate to the element type;
582 ///  if the subobject is of scalar type, the built-in assignment operator is
583 ///  used.
584 /// Virtual base class subobjects shall be copied only once by the
585 /// implicitly-defined copy constructor
586 
587 void
588 CodeGenFunction::SynthesizeCXXCopyConstructor(const CXXConstructorDecl *Ctor,
589                                               CXXCtorType Type,
590                                               llvm::Function *Fn,
591                                               const FunctionArgList &Args) {
592   const CXXRecordDecl *ClassDecl = Ctor->getParent();
593   assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
594       "SynthesizeCXXCopyConstructor - copy constructor has definition already");
595   assert(!Ctor->isTrivial() && "shouldn't need to generate trivial ctor");
596   StartFunction(GlobalDecl(Ctor, Type), Ctor->getResultType(), Fn, Args,
597                 SourceLocation());
598 
599   FunctionArgList::const_iterator i = Args.begin();
600   const VarDecl *ThisArg = i->first;
601   llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
602   llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
603   const VarDecl *SrcArg = (i+1)->first;
604   llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
605   llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
606 
607   for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
608        Base != ClassDecl->bases_end(); ++Base) {
609     // FIXME. copy constrution of virtual base NYI
610     if (Base->isVirtual())
611       continue;
612 
613     CXXRecordDecl *BaseClassDecl
614       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
615     EmitClassMemberwiseCopy(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
616                             Base->getType());
617   }
618 
619   for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
620        E = ClassDecl->field_end(); I != E; ++I) {
621     const FieldDecl *Field = *I;
622 
623     QualType FieldType = getContext().getCanonicalType(Field->getType());
624     const ConstantArrayType *Array =
625       getContext().getAsConstantArrayType(FieldType);
626     if (Array)
627       FieldType = getContext().getBaseElementType(FieldType);
628 
629     if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
630       CXXRecordDecl *FieldClassDecl
631         = cast<CXXRecordDecl>(FieldClassType->getDecl());
632       LValue LHS = EmitLValueForField(LoadOfThis, Field, 0);
633       LValue RHS = EmitLValueForField(LoadOfSrc, Field, 0);
634       if (Array) {
635         const llvm::Type *BasePtr = ConvertType(FieldType);
636         BasePtr = llvm::PointerType::getUnqual(BasePtr);
637         llvm::Value *DestBaseAddrPtr =
638           Builder.CreateBitCast(LHS.getAddress(), BasePtr);
639         llvm::Value *SrcBaseAddrPtr =
640           Builder.CreateBitCast(RHS.getAddress(), BasePtr);
641         EmitClassAggrMemberwiseCopy(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
642                                     FieldClassDecl, FieldType);
643       }
644       else
645         EmitClassMemberwiseCopy(LHS.getAddress(), RHS.getAddress(),
646                                 0 /*ClassDecl*/, FieldClassDecl, FieldType);
647       continue;
648     }
649 
650     // Do a built-in assignment of scalar data members.
651     LValue LHS = EmitLValueForFieldInitialization(LoadOfThis, Field, 0);
652     LValue RHS = EmitLValueForFieldInitialization(LoadOfSrc, Field, 0);
653 
654     if (!hasAggregateLLVMType(Field->getType())) {
655       RValue RVRHS = EmitLoadOfLValue(RHS, Field->getType());
656       EmitStoreThroughLValue(RVRHS, LHS, Field->getType());
657     } else if (Field->getType()->isAnyComplexType()) {
658       ComplexPairTy Pair = LoadComplexFromAddr(RHS.getAddress(),
659                                                RHS.isVolatileQualified());
660       StoreComplexToAddr(Pair, LHS.getAddress(), LHS.isVolatileQualified());
661     } else {
662       EmitAggregateCopy(LHS.getAddress(), RHS.getAddress(), Field->getType());
663     }
664   }
665 
666   InitializeVtablePtrs(ClassDecl);
667   FinishFunction();
668 }
669 
670 /// SynthesizeCXXCopyAssignment - Implicitly define copy assignment operator.
671 /// Before the implicitly-declared copy assignment operator for a class is
672 /// implicitly defined, all implicitly- declared copy assignment operators for
673 /// its direct base classes and its nonstatic data members shall have been
674 /// implicitly defined. [12.8-p12]
675 /// The implicitly-defined copy assignment operator for class X performs
676 /// memberwise assignment of its subob- jects. The direct base classes of X are
677 /// assigned first, in the order of their declaration in
678 /// the base-specifier-list, and then the immediate nonstatic data members of X
679 /// are assigned, in the order in which they were declared in the class
680 /// definition.Each subobject is assigned in the manner appropriate to its type:
681 ///   if the subobject is of class type, the copy assignment operator for the
682 ///   class is used (as if by explicit qualification; that is, ignoring any
683 ///   possible virtual overriding functions in more derived classes);
684 ///
685 ///   if the subobject is an array, each element is assigned, in the manner
686 ///   appropriate to the element type;
687 ///
688 ///   if the subobject is of scalar type, the built-in assignment operator is
689 ///   used.
690 void CodeGenFunction::SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD,
691                                                   llvm::Function *Fn,
692                                                   const FunctionArgList &Args) {
693 
694   const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
695   assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
696          "SynthesizeCXXCopyAssignment - copy assignment has user declaration");
697   StartFunction(CD, CD->getResultType(), Fn, Args, SourceLocation());
698 
699   FunctionArgList::const_iterator i = Args.begin();
700   const VarDecl *ThisArg = i->first;
701   llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
702   llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
703   const VarDecl *SrcArg = (i+1)->first;
704   llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
705   llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
706 
707   for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
708        Base != ClassDecl->bases_end(); ++Base) {
709     // FIXME. copy assignment of virtual base NYI
710     if (Base->isVirtual())
711       continue;
712 
713     CXXRecordDecl *BaseClassDecl
714       = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
715     EmitClassCopyAssignment(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
716                             Base->getType());
717   }
718 
719   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
720        FieldEnd = ClassDecl->field_end();
721        Field != FieldEnd; ++Field) {
722     QualType FieldType = getContext().getCanonicalType((*Field)->getType());
723     const ConstantArrayType *Array =
724       getContext().getAsConstantArrayType(FieldType);
725     if (Array)
726       FieldType = getContext().getBaseElementType(FieldType);
727 
728     if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
729       CXXRecordDecl *FieldClassDecl
730       = cast<CXXRecordDecl>(FieldClassType->getDecl());
731       LValue LHS = EmitLValueForField(LoadOfThis, *Field, 0);
732       LValue RHS = EmitLValueForField(LoadOfSrc, *Field, 0);
733       if (Array) {
734         const llvm::Type *BasePtr = ConvertType(FieldType);
735         BasePtr = llvm::PointerType::getUnqual(BasePtr);
736         llvm::Value *DestBaseAddrPtr =
737           Builder.CreateBitCast(LHS.getAddress(), BasePtr);
738         llvm::Value *SrcBaseAddrPtr =
739           Builder.CreateBitCast(RHS.getAddress(), BasePtr);
740         EmitClassAggrCopyAssignment(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
741                                     FieldClassDecl, FieldType);
742       }
743       else
744         EmitClassCopyAssignment(LHS.getAddress(), RHS.getAddress(),
745                                0 /*ClassDecl*/, FieldClassDecl, FieldType);
746       continue;
747     }
748     // Do a built-in assignment of scalar data members.
749     LValue LHS = EmitLValueForField(LoadOfThis, *Field, 0);
750     LValue RHS = EmitLValueForField(LoadOfSrc, *Field, 0);
751     if (!hasAggregateLLVMType(Field->getType())) {
752       RValue RVRHS = EmitLoadOfLValue(RHS, Field->getType());
753       EmitStoreThroughLValue(RVRHS, LHS, Field->getType());
754     } else if (Field->getType()->isAnyComplexType()) {
755       ComplexPairTy Pair = LoadComplexFromAddr(RHS.getAddress(),
756                                                RHS.isVolatileQualified());
757       StoreComplexToAddr(Pair, LHS.getAddress(), LHS.isVolatileQualified());
758     } else {
759       EmitAggregateCopy(LHS.getAddress(), RHS.getAddress(), Field->getType());
760     }
761   }
762 
763   // return *this;
764   Builder.CreateStore(LoadOfThis, ReturnValue);
765 
766   FinishFunction();
767 }
768 
769 static void EmitBaseInitializer(CodeGenFunction &CGF,
770                                 const CXXRecordDecl *ClassDecl,
771                                 CXXBaseOrMemberInitializer *BaseInit,
772                                 CXXCtorType CtorType) {
773   assert(BaseInit->isBaseInitializer() &&
774          "Must have base initializer!");
775 
776   llvm::Value *ThisPtr = CGF.LoadCXXThis();
777 
778   const Type *BaseType = BaseInit->getBaseClass();
779   CXXRecordDecl *BaseClassDecl =
780     cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
781 
782   // FIXME: This method of determining whether a base is virtual is ridiculous;
783   // it should be part of BaseInit.
784   bool isBaseVirtual = false;
785   for (CXXRecordDecl::base_class_const_iterator I = ClassDecl->vbases_begin(),
786        E = ClassDecl->vbases_end(); I != E; ++I)
787     if (I->getType()->getAs<RecordType>()->getDecl() == BaseClassDecl) {
788       isBaseVirtual = true;
789       break;
790     }
791 
792   // The base constructor doesn't construct virtual bases.
793   if (CtorType == Ctor_Base && isBaseVirtual)
794     return;
795 
796   // Compute the offset to the base; we do this directly instead of using
797   // GetAddressOfBaseClass because the class doesn't have a vtable pointer
798   // at this point.
799   // FIXME: This could be refactored back into GetAddressOfBaseClass if it took
800   // an extra parameter for whether the derived class is the complete object
801   // class.
802   const ASTRecordLayout &Layout =
803       CGF.getContext().getASTRecordLayout(ClassDecl);
804   uint64_t Offset;
805   if (isBaseVirtual)
806     Offset = Layout.getVBaseClassOffset(BaseClassDecl);
807   else
808     Offset = Layout.getBaseClassOffset(BaseClassDecl);
809   const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
810   const llvm::Type *BaseClassType = CGF.ConvertType(QualType(BaseType, 0));
811   llvm::Value *V = CGF.Builder.CreateBitCast(ThisPtr, Int8PtrTy);
812   V = CGF.Builder.CreateConstInBoundsGEP1_64(V, Offset/8);
813   V = CGF.Builder.CreateBitCast(V, BaseClassType->getPointerTo());
814 
815   CGF.EmitCXXConstructorCall(BaseInit->getConstructor(),
816                              Ctor_Base, V,
817                              BaseInit->const_arg_begin(),
818                              BaseInit->const_arg_end());
819 }
820 
821 static void EmitMemberInitializer(CodeGenFunction &CGF,
822                                   const CXXRecordDecl *ClassDecl,
823                                   CXXBaseOrMemberInitializer *MemberInit) {
824   assert(MemberInit->isMemberInitializer() &&
825          "Must have member initializer!");
826 
827   // non-static data member initializers.
828   FieldDecl *Field = MemberInit->getMember();
829   QualType FieldType = CGF.getContext().getCanonicalType(Field->getType());
830 
831   llvm::Value *ThisPtr = CGF.LoadCXXThis();
832   LValue LHS = CGF.EmitLValueForFieldInitialization(ThisPtr, Field, 0);
833 
834   // If we are initializing an anonymous union field, drill down to the field.
835   if (MemberInit->getAnonUnionMember()) {
836     Field = MemberInit->getAnonUnionMember();
837     LHS = CGF.EmitLValueForField(LHS.getAddress(), Field, 0);
838     FieldType = Field->getType();
839   }
840 
841   // If the field is an array, branch based on the element type.
842   const ConstantArrayType *Array =
843     CGF.getContext().getAsConstantArrayType(FieldType);
844   if (Array)
845     FieldType = CGF.getContext().getBaseElementType(FieldType);
846 
847   // We lose the constructor for anonymous union members, so handle them
848   // explicitly.
849   // FIXME: This is somwhat ugly.
850   if (MemberInit->getAnonUnionMember() && FieldType->getAs<RecordType>()) {
851     if (MemberInit->getNumArgs())
852       CGF.EmitAggExpr(*MemberInit->arg_begin(), LHS.getAddress(),
853                       LHS.isVolatileQualified());
854     else
855       CGF.EmitAggregateClear(LHS.getAddress(), Field->getType());
856     return;
857   }
858 
859   if (FieldType->getAs<RecordType>()) {
860     assert(MemberInit->getConstructor() &&
861            "EmitCtorPrologue - no constructor to initialize member");
862     if (Array) {
863       const llvm::Type *BasePtr = CGF.ConvertType(FieldType);
864       BasePtr = llvm::PointerType::getUnqual(BasePtr);
865       llvm::Value *BaseAddrPtr =
866         CGF.Builder.CreateBitCast(LHS.getAddress(), BasePtr);
867       CGF.EmitCXXAggrConstructorCall(MemberInit->getConstructor(),
868                                      Array, BaseAddrPtr,
869                                      MemberInit->const_arg_begin(),
870                                      MemberInit->const_arg_end());
871     }
872     else
873       CGF.EmitCXXConstructorCall(MemberInit->getConstructor(),
874                                  Ctor_Complete, LHS.getAddress(),
875                                  MemberInit->const_arg_begin(),
876                                  MemberInit->const_arg_end());
877     return;
878   }
879 
880   assert(MemberInit->getNumArgs() == 1 && "Initializer count must be 1 only");
881   Expr *RhsExpr = *MemberInit->arg_begin();
882   RValue RHS;
883   if (FieldType->isReferenceType()) {
884     RHS = CGF.EmitReferenceBindingToExpr(RhsExpr, FieldType,
885                                     /*IsInitializer=*/true);
886     CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
887   } else if (Array) {
888     CGF.EmitMemSetToZero(LHS.getAddress(), Field->getType());
889   } else if (!CGF.hasAggregateLLVMType(RhsExpr->getType())) {
890     RHS = RValue::get(CGF.EmitScalarExpr(RhsExpr, true));
891     CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
892   } else if (RhsExpr->getType()->isAnyComplexType()) {
893     CGF.EmitComplexExprIntoAddr(RhsExpr, LHS.getAddress(),
894                                 LHS.isVolatileQualified());
895   } else {
896     // Handle member function pointers; other aggregates shouldn't get this far.
897     CGF.EmitAggExpr(RhsExpr, LHS.getAddress(), LHS.isVolatileQualified());
898   }
899 }
900 
901 /// EmitCtorPrologue - This routine generates necessary code to initialize
902 /// base classes and non-static data members belonging to this constructor.
903 /// FIXME: This needs to take a CXXCtorType.
904 void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
905                                        CXXCtorType CtorType) {
906   const CXXRecordDecl *ClassDecl = CD->getParent();
907 
908   // FIXME: Add vbase initialization
909 
910   for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
911        E = CD->init_end();
912        B != E; ++B) {
913     CXXBaseOrMemberInitializer *Member = (*B);
914 
915     assert(LiveTemporaries.empty() &&
916            "Should not have any live temporaries at initializer start!");
917 
918     if (Member->isBaseInitializer())
919       EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
920     else
921       EmitMemberInitializer(*this, ClassDecl, Member);
922 
923     // Pop any live temporaries that the initializers might have pushed.
924     while (!LiveTemporaries.empty())
925       PopCXXTemporary();
926   }
927 
928   InitializeVtablePtrs(ClassDecl);
929 }
930 
931 /// EmitDtorEpilogue - Emit all code that comes at the end of class's
932 /// destructor. This is to call destructors on members and base classes
933 /// in reverse order of their construction.
934 /// FIXME: This needs to take a CXXDtorType.
935 void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD,
936                                        CXXDtorType DtorType) {
937   assert(!DD->isTrivial() &&
938          "Should not emit dtor epilogue for trivial dtor!");
939 
940   const CXXRecordDecl *ClassDecl = DD->getParent();
941 
942   // Collect the fields.
943   llvm::SmallVector<const FieldDecl *, 16> FieldDecls;
944   for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
945        E = ClassDecl->field_end(); I != E; ++I) {
946     const FieldDecl *Field = *I;
947 
948     QualType FieldType = getContext().getCanonicalType(Field->getType());
949     FieldType = getContext().getBaseElementType(FieldType);
950 
951     const RecordType *RT = FieldType->getAs<RecordType>();
952     if (!RT)
953       continue;
954 
955     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
956     if (FieldClassDecl->hasTrivialDestructor())
957         continue;
958 
959     FieldDecls.push_back(Field);
960   }
961 
962   // Now destroy the fields.
963   for (size_t i = FieldDecls.size(); i > 0; --i) {
964     const FieldDecl *Field = FieldDecls[i - 1];
965 
966     QualType FieldType = Field->getType();
967     const ConstantArrayType *Array =
968       getContext().getAsConstantArrayType(FieldType);
969     if (Array)
970       FieldType = getContext().getBaseElementType(FieldType);
971 
972     const RecordType *RT = FieldType->getAs<RecordType>();
973     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
974 
975     llvm::Value *ThisPtr = LoadCXXThis();
976 
977     LValue LHS = EmitLValueForField(ThisPtr, Field,
978                                     // FIXME: Qualifiers?
979                                     /*CVRQualifiers=*/0);
980     if (Array) {
981       const llvm::Type *BasePtr = ConvertType(FieldType);
982       BasePtr = llvm::PointerType::getUnqual(BasePtr);
983       llvm::Value *BaseAddrPtr =
984         Builder.CreateBitCast(LHS.getAddress(), BasePtr);
985       EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
986                                 Array, BaseAddrPtr);
987     } else
988       EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
989                             Dtor_Complete, LHS.getAddress());
990   }
991 
992   // Destroy non-virtual bases.
993   for (CXXRecordDecl::reverse_base_class_const_iterator I =
994         ClassDecl->bases_rbegin(), E = ClassDecl->bases_rend(); I != E; ++I) {
995     const CXXBaseSpecifier &Base = *I;
996 
997     // Ignore virtual bases.
998     if (Base.isVirtual())
999       continue;
1000 
1001     CXXRecordDecl *BaseClassDecl
1002       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1003 
1004     // Ignore trivial destructors.
1005     if (BaseClassDecl->hasTrivialDestructor())
1006       continue;
1007     const CXXDestructorDecl *D = BaseClassDecl->getDestructor(getContext());
1008 
1009     llvm::Value *V = GetAddressOfBaseClass(LoadCXXThis(),
1010                                            ClassDecl, BaseClassDecl,
1011                                            /*NullCheckValue=*/false);
1012     EmitCXXDestructorCall(D, Dtor_Base, V);
1013   }
1014 
1015   // If we're emitting a base destructor, we don't want to emit calls to the
1016   // virtual bases.
1017   if (DtorType == Dtor_Base)
1018     return;
1019 
1020   // Handle virtual bases.
1021   for (CXXRecordDecl::reverse_base_class_const_iterator I =
1022        ClassDecl->vbases_rbegin(), E = ClassDecl->vbases_rend(); I != E; ++I) {
1023     const CXXBaseSpecifier &Base = *I;
1024     CXXRecordDecl *BaseClassDecl
1025     = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1026 
1027     // Ignore trivial destructors.
1028     if (BaseClassDecl->hasTrivialDestructor())
1029       continue;
1030     const CXXDestructorDecl *D = BaseClassDecl->getDestructor(getContext());
1031     llvm::Value *V = GetAddressOfBaseClass(LoadCXXThis(),
1032                                            ClassDecl, BaseClassDecl,
1033                                            /*NullCheckValue=*/false);
1034     EmitCXXDestructorCall(D, Dtor_Base, V);
1035   }
1036 
1037   // If we have a deleting destructor, emit a call to the delete operator.
1038   if (DtorType == Dtor_Deleting) {
1039     assert(DD->getOperatorDelete() &&
1040            "operator delete missing - EmitDtorEpilogue");
1041     EmitDeleteCall(DD->getOperatorDelete(), LoadCXXThis(),
1042                    getContext().getTagDeclType(ClassDecl));
1043   }
1044 }
1045 
1046 void CodeGenFunction::SynthesizeDefaultDestructor(const CXXDestructorDecl *Dtor,
1047                                                   CXXDtorType DtorType,
1048                                                   llvm::Function *Fn,
1049                                                   const FunctionArgList &Args) {
1050   assert(!Dtor->getParent()->hasUserDeclaredDestructor() &&
1051          "SynthesizeDefaultDestructor - destructor has user declaration");
1052 
1053   StartFunction(GlobalDecl(Dtor, DtorType), Dtor->getResultType(), Fn, Args,
1054                 SourceLocation());
1055 
1056   EmitDtorEpilogue(Dtor, DtorType);
1057   FinishFunction();
1058 }
1059 
1060 /// EmitCXXAggrConstructorCall - This routine essentially creates a (nested)
1061 /// for-loop to call the default constructor on individual members of the
1062 /// array.
1063 /// 'D' is the default constructor for elements of the array, 'ArrayTy' is the
1064 /// array type and 'ArrayPtr' points to the beginning fo the array.
1065 /// It is assumed that all relevant checks have been made by the caller.
1066 void
1067 CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
1068                                           const ConstantArrayType *ArrayTy,
1069                                           llvm::Value *ArrayPtr,
1070                                           CallExpr::const_arg_iterator ArgBeg,
1071                                           CallExpr::const_arg_iterator ArgEnd) {
1072 
1073   const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
1074   llvm::Value * NumElements =
1075     llvm::ConstantInt::get(SizeTy,
1076                            getContext().getConstantArrayElementCount(ArrayTy));
1077 
1078   EmitCXXAggrConstructorCall(D, NumElements, ArrayPtr, ArgBeg, ArgEnd);
1079 }
1080 
1081 void
1082 CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
1083                                           llvm::Value *NumElements,
1084                                           llvm::Value *ArrayPtr,
1085                                           CallExpr::const_arg_iterator ArgBeg,
1086                                           CallExpr::const_arg_iterator ArgEnd) {
1087   const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
1088 
1089   // Create a temporary for the loop index and initialize it with 0.
1090   llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
1091   llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
1092   Builder.CreateStore(Zero, IndexPtr);
1093 
1094   // Start the loop with a block that tests the condition.
1095   llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1096   llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1097 
1098   EmitBlock(CondBlock);
1099 
1100   llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1101 
1102   // Generate: if (loop-index < number-of-elements fall to the loop body,
1103   // otherwise, go to the block after the for-loop.
1104   llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1105   llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
1106   // If the condition is true, execute the body.
1107   Builder.CreateCondBr(IsLess, 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   llvm::Value *Address = Builder.CreateInBoundsGEP(ArrayPtr, Counter,
1115                                                    "arrayidx");
1116 
1117   // C++ [class.temporary]p4:
1118   // There are two contexts in which temporaries are destroyed at a different
1119   // point than the end of the full-expression. The first context is when a
1120   // default constructor is called to initialize an element of an array.
1121   // If the constructor has one or more default arguments, the destruction of
1122   // every temporary created in a default argument expression is sequenced
1123   // before the construction of the next array element, if any.
1124 
1125   // Keep track of the current number of live temporaries.
1126   unsigned OldNumLiveTemporaries = LiveTemporaries.size();
1127 
1128   EmitCXXConstructorCall(D, Ctor_Complete, Address, ArgBeg, ArgEnd);
1129 
1130   // Pop temporaries.
1131   while (LiveTemporaries.size() > OldNumLiveTemporaries)
1132     PopCXXTemporary();
1133 
1134   EmitBlock(ContinueBlock);
1135 
1136   // Emit the increment of the loop counter.
1137   llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
1138   Counter = Builder.CreateLoad(IndexPtr);
1139   NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1140   Builder.CreateStore(NextVal, IndexPtr);
1141 
1142   // Finally, branch back up to the condition for the next iteration.
1143   EmitBranch(CondBlock);
1144 
1145   // Emit the fall-through block.
1146   EmitBlock(AfterFor, true);
1147 }
1148 
1149 /// EmitCXXAggrDestructorCall - calls the default destructor on array
1150 /// elements in reverse order of construction.
1151 void
1152 CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1153                                            const ArrayType *Array,
1154                                            llvm::Value *This) {
1155   const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1156   assert(CA && "Do we support VLA for destruction ?");
1157   uint64_t ElementCount = getContext().getConstantArrayElementCount(CA);
1158 
1159   const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
1160   llvm::Value* ElementCountPtr = llvm::ConstantInt::get(SizeLTy, ElementCount);
1161   EmitCXXAggrDestructorCall(D, ElementCountPtr, This);
1162 }
1163 
1164 /// EmitCXXAggrDestructorCall - calls the default destructor on array
1165 /// elements in reverse order of construction.
1166 void
1167 CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1168                                            llvm::Value *UpperCount,
1169                                            llvm::Value *This) {
1170   const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
1171   llvm::Value *One = llvm::ConstantInt::get(SizeLTy, 1);
1172 
1173   // Create a temporary for the loop index and initialize it with count of
1174   // array elements.
1175   llvm::Value *IndexPtr = CreateTempAlloca(SizeLTy, "loop.index");
1176 
1177   // Store the number of elements in the index pointer.
1178   Builder.CreateStore(UpperCount, IndexPtr);
1179 
1180   // Start the loop with a block that tests the condition.
1181   llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1182   llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1183 
1184   EmitBlock(CondBlock);
1185 
1186   llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1187 
1188   // Generate: if (loop-index != 0 fall to the loop body,
1189   // otherwise, go to the block after the for-loop.
1190   llvm::Value* zeroConstant =
1191     llvm::Constant::getNullValue(SizeLTy);
1192   llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1193   llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant,
1194                                             "isne");
1195   // If the condition is true, execute the body.
1196   Builder.CreateCondBr(IsNE, ForBody, AfterFor);
1197 
1198   EmitBlock(ForBody);
1199 
1200   llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1201   // Inside the loop body, emit the constructor call on the array element.
1202   Counter = Builder.CreateLoad(IndexPtr);
1203   Counter = Builder.CreateSub(Counter, One);
1204   llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
1205   EmitCXXDestructorCall(D, Dtor_Complete, Address);
1206 
1207   EmitBlock(ContinueBlock);
1208 
1209   // Emit the decrement of the loop counter.
1210   Counter = Builder.CreateLoad(IndexPtr);
1211   Counter = Builder.CreateSub(Counter, One, "dec");
1212   Builder.CreateStore(Counter, IndexPtr);
1213 
1214   // Finally, branch back up to the condition for the next iteration.
1215   EmitBranch(CondBlock);
1216 
1217   // Emit the fall-through block.
1218   EmitBlock(AfterFor, true);
1219 }
1220 
1221 /// GenerateCXXAggrDestructorHelper - Generates a helper function which when
1222 /// invoked, calls the default destructor on array elements in reverse order of
1223 /// construction.
1224 llvm::Constant *
1225 CodeGenFunction::GenerateCXXAggrDestructorHelper(const CXXDestructorDecl *D,
1226                                                  const ArrayType *Array,
1227                                                  llvm::Value *This) {
1228   FunctionArgList Args;
1229   ImplicitParamDecl *Dst =
1230     ImplicitParamDecl::Create(getContext(), 0,
1231                               SourceLocation(), 0,
1232                               getContext().getPointerType(getContext().VoidTy));
1233   Args.push_back(std::make_pair(Dst, Dst->getType()));
1234 
1235   llvm::SmallString<16> Name;
1236   llvm::raw_svector_ostream(Name) << "__tcf_" << (++UniqueAggrDestructorCount);
1237   QualType R = getContext().VoidTy;
1238   const CGFunctionInfo &FI = CGM.getTypes().getFunctionInfo(R, Args);
1239   const llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI, false);
1240   llvm::Function *Fn =
1241     llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
1242                            Name.str(),
1243                            &CGM.getModule());
1244   IdentifierInfo *II = &CGM.getContext().Idents.get(Name.str());
1245   FunctionDecl *FD = FunctionDecl::Create(getContext(),
1246                                           getContext().getTranslationUnitDecl(),
1247                                           SourceLocation(), II, R, 0,
1248                                           FunctionDecl::Static,
1249                                           false, true);
1250   StartFunction(FD, R, Fn, Args, SourceLocation());
1251   QualType BaseElementTy = getContext().getBaseElementType(Array);
1252   const llvm::Type *BasePtr = ConvertType(BaseElementTy);
1253   BasePtr = llvm::PointerType::getUnqual(BasePtr);
1254   llvm::Value *BaseAddrPtr = Builder.CreateBitCast(This, BasePtr);
1255   EmitCXXAggrDestructorCall(D, Array, BaseAddrPtr);
1256   FinishFunction();
1257   llvm::Type *Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),
1258                                               0);
1259   llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty);
1260   return m;
1261 }
1262 
1263 
1264 void
1265 CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
1266                                         CXXCtorType Type,
1267                                         llvm::Value *This,
1268                                         CallExpr::const_arg_iterator ArgBeg,
1269                                         CallExpr::const_arg_iterator ArgEnd) {
1270   if (D->isCopyConstructor()) {
1271     const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D->getDeclContext());
1272     if (ClassDecl->hasTrivialCopyConstructor()) {
1273       assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
1274              "EmitCXXConstructorCall - user declared copy constructor");
1275       const Expr *E = (*ArgBeg);
1276       QualType Ty = E->getType();
1277       llvm::Value *Src = EmitLValue(E).getAddress();
1278       EmitAggregateCopy(This, Src, Ty);
1279       return;
1280     }
1281   } else if (D->isTrivial()) {
1282     // FIXME: Track down why we're trying to generate calls to the trivial
1283     // default constructor!
1284     return;
1285   }
1286 
1287   llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(D, Type));
1288   llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
1289 
1290   EmitCXXMemberCall(D, Callee, ReturnValueSlot(), This, VTT, ArgBeg, ArgEnd);
1291 }
1292 
1293 void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1294                                             CXXDtorType Type,
1295                                             llvm::Value *This) {
1296   llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(DD, Type));
1297   llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
1298 
1299   EmitCXXMemberCall(DD, Callee, ReturnValueSlot(), This, VTT, 0, 0);
1300 }
1301 
1302 llvm::Value *
1303 CodeGenFunction::GetVirtualCXXBaseClassOffset(llvm::Value *This,
1304                                               const CXXRecordDecl *ClassDecl,
1305                                            const CXXRecordDecl *BaseClassDecl) {
1306   const llvm::Type *Int8PtrTy =
1307     llvm::Type::getInt8Ty(VMContext)->getPointerTo();
1308 
1309   llvm::Value *VTablePtr = Builder.CreateBitCast(This,
1310                                                  Int8PtrTy->getPointerTo());
1311   VTablePtr = Builder.CreateLoad(VTablePtr, "vtable");
1312 
1313   int64_t VBaseOffsetIndex =
1314     CGM.getVtableInfo().getVirtualBaseOffsetIndex(ClassDecl, BaseClassDecl);
1315 
1316   llvm::Value *VBaseOffsetPtr =
1317     Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetIndex, "vbase.offset.ptr");
1318   const llvm::Type *PtrDiffTy =
1319     ConvertType(getContext().getPointerDiffType());
1320 
1321   VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
1322                                          PtrDiffTy->getPointerTo());
1323 
1324   llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1325 
1326   return VBaseOffset;
1327 }
1328 
1329 void CodeGenFunction::InitializeVtablePtrs(const CXXRecordDecl *ClassDecl) {
1330   if (!ClassDecl->isDynamicClass())
1331     return;
1332 
1333   llvm::Constant *Vtable = CGM.getVtableInfo().getVtable(ClassDecl);
1334   CGVtableInfo::AddrSubMap_t& AddressPoints =
1335       *(*CGM.getVtableInfo().AddressPoints[ClassDecl])[ClassDecl];
1336   llvm::Value *ThisPtr = LoadCXXThis();
1337   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(ClassDecl);
1338 
1339   // Store address points for virtual bases
1340   for (CXXRecordDecl::base_class_const_iterator I =
1341        ClassDecl->vbases_begin(), E = ClassDecl->vbases_end(); I != E; ++I) {
1342     const CXXBaseSpecifier &Base = *I;
1343     CXXRecordDecl *BaseClassDecl
1344       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1345     uint64_t Offset = Layout.getVBaseClassOffset(BaseClassDecl);
1346     InitializeVtablePtrsRecursive(BaseClassDecl, Vtable, AddressPoints,
1347                                   ThisPtr, Offset);
1348   }
1349 
1350   // Store address points for non-virtual bases and current class
1351   InitializeVtablePtrsRecursive(ClassDecl, Vtable, AddressPoints, ThisPtr, 0);
1352 }
1353 
1354 void CodeGenFunction::InitializeVtablePtrsRecursive(
1355         const CXXRecordDecl *ClassDecl,
1356         llvm::Constant *Vtable,
1357         CGVtableInfo::AddrSubMap_t& AddressPoints,
1358         llvm::Value *ThisPtr,
1359         uint64_t Offset) {
1360   if (!ClassDecl->isDynamicClass())
1361     return;
1362 
1363   // Store address points for non-virtual bases
1364   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(ClassDecl);
1365   for (CXXRecordDecl::base_class_const_iterator I =
1366        ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
1367     const CXXBaseSpecifier &Base = *I;
1368     if (Base.isVirtual())
1369       continue;
1370     CXXRecordDecl *BaseClassDecl
1371       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1372     uint64_t NewOffset = Offset + Layout.getBaseClassOffset(BaseClassDecl);
1373     InitializeVtablePtrsRecursive(BaseClassDecl, Vtable, AddressPoints,
1374                                   ThisPtr, NewOffset);
1375   }
1376 
1377   // Compute the address point
1378   assert(AddressPoints.count(std::make_pair(ClassDecl, Offset)) &&
1379          "Missing address point for class");
1380   uint64_t AddressPoint = AddressPoints[std::make_pair(ClassDecl, Offset)];
1381   llvm::Value *VtableAddressPoint =
1382       Builder.CreateConstInBoundsGEP2_64(Vtable, 0, AddressPoint);
1383 
1384   // Compute the address to store the address point
1385   const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
1386   llvm::Value *VtableField = Builder.CreateBitCast(ThisPtr, Int8PtrTy);
1387   VtableField = Builder.CreateConstInBoundsGEP1_64(VtableField, Offset/8);
1388   const llvm::Type *AddressPointPtrTy =
1389       VtableAddressPoint->getType()->getPointerTo();
1390   VtableField = Builder.CreateBitCast(VtableField, AddressPointPtrTy);
1391 
1392   // Store address point
1393   Builder.CreateStore(VtableAddressPoint, VtableField);
1394 }
1395 
1396 llvm::Value *CodeGenFunction::LoadCXXVTT() {
1397   assert((isa<CXXConstructorDecl>(CurFuncDecl) ||
1398           isa<CXXDestructorDecl>(CurFuncDecl)) &&
1399          "Must be in a C++ ctor or dtor to load the vtt parameter");
1400 
1401   return Builder.CreateLoad(LocalDeclMap[CXXVTTDecl], "vtt");
1402 }
1403