CGCXX.cpp revision ae013b9da64b48f22ca82828aa3c7a909f99dbd7
1//===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
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.
11//
12//===----------------------------------------------------------------------===//
13
14// We might split this into multiple files if it gets too unwieldy
15
16#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
18#include "Mangle.h"
19#include "clang/AST/ASTContext.h"
20#include "clang/AST/RecordLayout.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclCXX.h"
23#include "clang/AST/DeclObjC.h"
24#include "clang/AST/StmtCXX.h"
25#include "llvm/ADT/StringExtras.h"
26using namespace clang;
27using namespace CodeGen;
28
29void
30CodeGenFunction::EmitCXXGlobalDtorRegistration(const CXXDestructorDecl *Dtor,
31                                               llvm::Constant *DeclPtr) {
32  const llvm::Type *Int8PtrTy =
33    llvm::Type::getInt8Ty(VMContext)->getPointerTo();
34
35  std::vector<const llvm::Type *> Params;
36  Params.push_back(Int8PtrTy);
37
38  // Get the destructor function type
39  const llvm::Type *DtorFnTy =
40    llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Params, false);
41  DtorFnTy = llvm::PointerType::getUnqual(DtorFnTy);
42
43  Params.clear();
44  Params.push_back(DtorFnTy);
45  Params.push_back(Int8PtrTy);
46  Params.push_back(Int8PtrTy);
47
48  // Get the __cxa_atexit function type
49  // extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
50  const llvm::FunctionType *AtExitFnTy =
51    llvm::FunctionType::get(ConvertType(getContext().IntTy), Params, false);
52
53  llvm::Constant *AtExitFn = CGM.CreateRuntimeFunction(AtExitFnTy,
54                                                       "__cxa_atexit");
55
56  llvm::Constant *Handle = CGM.CreateRuntimeVariable(Int8PtrTy,
57                                                     "__dso_handle");
58
59  llvm::Constant *DtorFn = CGM.GetAddrOfCXXDestructor(Dtor, Dtor_Complete);
60
61  llvm::Value *Args[3] = { llvm::ConstantExpr::getBitCast(DtorFn, DtorFnTy),
62                           llvm::ConstantExpr::getBitCast(DeclPtr, Int8PtrTy),
63                           llvm::ConstantExpr::getBitCast(Handle, Int8PtrTy) };
64  Builder.CreateCall(AtExitFn, &Args[0], llvm::array_endof(Args));
65}
66
67void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
68                                               llvm::Constant *DeclPtr) {
69  assert(D.hasGlobalStorage() &&
70         "VarDecl must have global storage!");
71
72  const Expr *Init = D.getInit();
73  QualType T = D.getType();
74
75  if (T->isReferenceType()) {
76    ErrorUnsupported(Init, "global variable that binds to a reference");
77  } else if (!hasAggregateLLVMType(T)) {
78    llvm::Value *V = EmitScalarExpr(Init);
79    EmitStoreOfScalar(V, DeclPtr, T.isVolatileQualified(), T);
80  } else if (T->isAnyComplexType()) {
81    EmitComplexExprIntoAddr(Init, DeclPtr, T.isVolatileQualified());
82  } else {
83    EmitAggExpr(Init, DeclPtr, T.isVolatileQualified());
84
85    if (const RecordType *RT = T->getAs<RecordType>()) {
86      CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
87      if (!RD->hasTrivialDestructor())
88        EmitCXXGlobalDtorRegistration(RD->getDestructor(getContext()), DeclPtr);
89    }
90  }
91}
92
93void
94CodeGenModule::EmitCXXGlobalInitFunc() {
95  if (CXXGlobalInits.empty())
96    return;
97
98  const llvm::FunctionType *FTy = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
99                                                          false);
100
101  // Create our global initialization function.
102  // FIXME: Should this be tweakable by targets?
103  llvm::Function *Fn =
104    llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
105                           "__cxx_global_initialization", &TheModule);
106
107  CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
108                                                   &CXXGlobalInits[0],
109                                                   CXXGlobalInits.size());
110  AddGlobalCtor(Fn);
111}
112
113void CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
114                                                const VarDecl **Decls,
115                                                unsigned NumDecls) {
116  StartFunction(GlobalDecl(), getContext().VoidTy, Fn, FunctionArgList(),
117                SourceLocation());
118
119  for (unsigned i = 0; i != NumDecls; ++i) {
120    const VarDecl *D = Decls[i];
121
122    llvm::Constant *DeclPtr = CGM.GetAddrOfGlobalVar(D);
123    EmitCXXGlobalVarDeclInit(*D, DeclPtr);
124  }
125  FinishFunction();
126}
127
128void
129CodeGenFunction::EmitStaticCXXBlockVarDeclInit(const VarDecl &D,
130                                               llvm::GlobalVariable *GV) {
131  // FIXME: This should use __cxa_guard_{acquire,release}?
132
133  assert(!getContext().getLangOptions().ThreadsafeStatics &&
134         "thread safe statics are currently not supported!");
135
136  llvm::SmallString<256> GuardVName;
137  llvm::raw_svector_ostream GuardVOut(GuardVName);
138  mangleGuardVariable(CGM.getMangleContext(), &D, GuardVOut);
139
140  // Create the guard variable.
141  llvm::GlobalValue *GuardV =
142    new llvm::GlobalVariable(CGM.getModule(), llvm::Type::getInt64Ty(VMContext), false,
143                             GV->getLinkage(),
144                             llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext)),
145                             GuardVName.str());
146
147  // Load the first byte of the guard variable.
148  const llvm::Type *PtrTy = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
149  llvm::Value *V = Builder.CreateLoad(Builder.CreateBitCast(GuardV, PtrTy),
150                                      "tmp");
151
152  // Compare it against 0.
153  llvm::Value *nullValue = llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext));
154  llvm::Value *ICmp = Builder.CreateICmpEQ(V, nullValue , "tobool");
155
156  llvm::BasicBlock *InitBlock = createBasicBlock("init");
157  llvm::BasicBlock *EndBlock = createBasicBlock("init.end");
158
159  // If the guard variable is 0, jump to the initializer code.
160  Builder.CreateCondBr(ICmp, InitBlock, EndBlock);
161
162  EmitBlock(InitBlock);
163
164  EmitCXXGlobalVarDeclInit(D, GV);
165
166  Builder.CreateStore(llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext), 1),
167                      Builder.CreateBitCast(GuardV, PtrTy));
168
169  EmitBlock(EndBlock);
170}
171
172RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
173                                          llvm::Value *Callee,
174                                          llvm::Value *This,
175                                          CallExpr::const_arg_iterator ArgBeg,
176                                          CallExpr::const_arg_iterator ArgEnd) {
177  assert(MD->isInstance() &&
178         "Trying to emit a member call expr on a static method!");
179
180  // A call to a trivial destructor requires no code generation.
181  if (const CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(MD))
182    if (Destructor->isTrivial())
183      return RValue::get(0);
184
185  const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
186
187  CallArgList Args;
188
189  // Push the this ptr.
190  Args.push_back(std::make_pair(RValue::get(This),
191                                MD->getThisType(getContext())));
192
193  // And the rest of the call args
194  EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
195
196  QualType ResultType = MD->getType()->getAs<FunctionType>()->getResultType();
197  return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args),
198                  Callee, Args, MD);
199}
200
201/// canDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
202/// expr can be devirtualized.
203static bool canDevirtualizeMemberFunctionCalls(const Expr *Base) {
204  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
205    if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
206      // This is a record decl. We know the type and can devirtualize it.
207      return VD->getType()->isRecordType();
208    }
209
210    return false;
211  }
212
213  // We can always devirtualize calls on temporary object expressions.
214  if (isa<CXXTemporaryObjectExpr>(Base))
215    return true;
216
217  // And calls on bound temporaries.
218  if (isa<CXXBindTemporaryExpr>(Base))
219    return true;
220
221  // Check if this is a call expr that returns a record type.
222  if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
223    return CE->getCallReturnType()->isRecordType();
224
225  // We can't devirtualize the call.
226  return false;
227}
228
229RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE) {
230  if (isa<BinaryOperator>(CE->getCallee()))
231    return EmitCXXMemberPointerCallExpr(CE);
232
233  const MemberExpr *ME = cast<MemberExpr>(CE->getCallee());
234  const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
235
236  if (MD->isStatic()) {
237    // The method is static, emit it as we would a regular call.
238    llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
239    return EmitCall(Callee, getContext().getPointerType(MD->getType()),
240                    CE->arg_begin(), CE->arg_end(), 0);
241
242  }
243
244  const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
245
246  const llvm::Type *Ty =
247    CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
248                                   FPT->isVariadic());
249  llvm::Value *This;
250
251  if (ME->isArrow())
252    This = EmitScalarExpr(ME->getBase());
253  else {
254    LValue BaseLV = EmitLValue(ME->getBase());
255    This = BaseLV.getAddress();
256  }
257
258  // C++ [class.virtual]p12:
259  //   Explicit qualification with the scope operator (5.1) suppresses the
260  //   virtual call mechanism.
261  //
262  // We also don't emit a virtual call if the base expression has a record type
263  // because then we know what the type is.
264  llvm::Value *Callee;
265  if (MD->isVirtual() && !ME->hasQualifier() &&
266      !canDevirtualizeMemberFunctionCalls(ME->getBase()))
267    Callee = BuildVirtualCall(MD, This, Ty);
268  else if (const CXXDestructorDecl *Destructor
269             = dyn_cast<CXXDestructorDecl>(MD))
270    Callee = CGM.GetAddrOfFunction(GlobalDecl(Destructor, Dtor_Complete), Ty);
271  else
272    Callee = CGM.GetAddrOfFunction(MD, Ty);
273
274  return EmitCXXMemberCall(MD, Callee, This,
275                           CE->arg_begin(), CE->arg_end());
276}
277
278RValue
279CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E) {
280  const BinaryOperator *BO = cast<BinaryOperator>(E->getCallee());
281  const Expr *BaseExpr = BO->getLHS();
282  const Expr *MemFnExpr = BO->getRHS();
283
284  const MemberPointerType *MPT =
285    MemFnExpr->getType()->getAs<MemberPointerType>();
286  const FunctionProtoType *FPT =
287    MPT->getPointeeType()->getAs<FunctionProtoType>();
288  const CXXRecordDecl *RD =
289    cast<CXXRecordDecl>(cast<RecordType>(MPT->getClass())->getDecl());
290
291  const llvm::FunctionType *FTy =
292    CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(RD, FPT),
293                                   FPT->isVariadic());
294
295  const llvm::Type *Int8PtrTy =
296    llvm::Type::getInt8Ty(VMContext)->getPointerTo();
297
298  // Get the member function pointer.
299  llvm::Value *MemFnPtr =
300    CreateTempAlloca(ConvertType(MemFnExpr->getType()), "mem.fn");
301  EmitAggExpr(MemFnExpr, MemFnPtr, /*VolatileDest=*/false);
302
303  // Emit the 'this' pointer.
304  llvm::Value *This;
305
306  if (BO->getOpcode() == BinaryOperator::PtrMemI)
307    This = EmitScalarExpr(BaseExpr);
308  else
309    This = EmitLValue(BaseExpr).getAddress();
310
311  // Adjust it.
312  llvm::Value *Adj = Builder.CreateStructGEP(MemFnPtr, 1);
313  Adj = Builder.CreateLoad(Adj, "mem.fn.adj");
314
315  llvm::Value *Ptr = Builder.CreateBitCast(This, Int8PtrTy, "ptr");
316  Ptr = Builder.CreateGEP(Ptr, Adj, "adj");
317
318  This = Builder.CreateBitCast(Ptr, This->getType(), "this");
319
320  llvm::Value *FnPtr = Builder.CreateStructGEP(MemFnPtr, 0, "mem.fn.ptr");
321
322  const llvm::Type *PtrDiffTy = ConvertType(getContext().getPointerDiffType());
323
324  llvm::Value *FnAsInt = Builder.CreateLoad(FnPtr, "fn");
325
326  // If the LSB in the function pointer is 1, the function pointer points to
327  // a virtual function.
328  llvm::Value *IsVirtual
329    = Builder.CreateAnd(FnAsInt, llvm::ConstantInt::get(PtrDiffTy, 1),
330                        "and");
331
332  IsVirtual = Builder.CreateTrunc(IsVirtual,
333                                  llvm::Type::getInt1Ty(VMContext));
334
335  llvm::BasicBlock *FnVirtual = createBasicBlock("fn.virtual");
336  llvm::BasicBlock *FnNonVirtual = createBasicBlock("fn.nonvirtual");
337  llvm::BasicBlock *FnEnd = createBasicBlock("fn.end");
338
339  Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
340  EmitBlock(FnVirtual);
341
342  const llvm::Type *VTableTy =
343    FTy->getPointerTo()->getPointerTo()->getPointerTo();
344
345  llvm::Value *VTable = Builder.CreateBitCast(This, VTableTy);
346  VTable = Builder.CreateLoad(VTable);
347
348  VTable = Builder.CreateGEP(VTable, FnAsInt, "fn");
349
350  // Since the function pointer is 1 plus the virtual table offset, we
351  // subtract 1 by using a GEP.
352  VTable = Builder.CreateConstGEP1_64(VTable, (uint64_t)-1);
353
354  llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "virtualfn");
355
356  EmitBranch(FnEnd);
357  EmitBlock(FnNonVirtual);
358
359  // If the function is not virtual, just load the pointer.
360  llvm::Value *NonVirtualFn = Builder.CreateLoad(FnPtr, "fn");
361  NonVirtualFn = Builder.CreateIntToPtr(NonVirtualFn, FTy->getPointerTo());
362
363  EmitBlock(FnEnd);
364
365  llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo());
366  Callee->reserveOperandSpace(2);
367  Callee->addIncoming(VirtualFn, FnVirtual);
368  Callee->addIncoming(NonVirtualFn, FnNonVirtual);
369
370  CallArgList Args;
371
372  QualType ThisType =
373    getContext().getPointerType(getContext().getTagDeclType(RD));
374
375  // Push the this ptr.
376  Args.push_back(std::make_pair(RValue::get(This), ThisType));
377
378  // And the rest of the call args
379  EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
380  QualType ResultType = BO->getType()->getAs<FunctionType>()->getResultType();
381  return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args),
382                  Callee, Args, 0);
383}
384
385RValue
386CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
387                                               const CXXMethodDecl *MD) {
388  assert(MD->isInstance() &&
389         "Trying to emit a member call expr on a static method!");
390
391  if (MD->isCopyAssignment()) {
392    const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(MD->getDeclContext());
393    if (ClassDecl->hasTrivialCopyAssignment()) {
394      assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
395             "EmitCXXOperatorMemberCallExpr - user declared copy assignment");
396      llvm::Value *This = EmitLValue(E->getArg(0)).getAddress();
397      llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
398      QualType Ty = E->getType();
399      EmitAggregateCopy(This, Src, Ty);
400      return RValue::get(This);
401    }
402  }
403
404  const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
405  const llvm::Type *Ty =
406    CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
407                                   FPT->isVariadic());
408  llvm::Constant *Callee = CGM.GetAddrOfFunction(MD, Ty);
409
410  llvm::Value *This = EmitLValue(E->getArg(0)).getAddress();
411
412  return EmitCXXMemberCall(MD, Callee, This,
413                           E->arg_begin() + 1, E->arg_end());
414}
415
416llvm::Value *CodeGenFunction::LoadCXXThis() {
417  assert(isa<CXXMethodDecl>(CurFuncDecl) &&
418         "Must be in a C++ member function decl to load 'this'");
419  assert(cast<CXXMethodDecl>(CurFuncDecl)->isInstance() &&
420         "Must be in a C++ member function decl to load 'this'");
421
422  // FIXME: What if we're inside a block?
423  // ans: See how CodeGenFunction::LoadObjCSelf() uses
424  // CodeGenFunction::BlockForwardSelf() for how to do this.
425  return Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
426}
427
428/// EmitCXXAggrConstructorCall - This routine essentially creates a (nested)
429/// for-loop to call the default constructor on individual members of the
430/// array.
431/// 'D' is the default constructor for elements of the array, 'ArrayTy' is the
432/// array type and 'ArrayPtr' points to the beginning fo the array.
433/// It is assumed that all relevant checks have been made by the caller.
434void
435CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
436                                            const ConstantArrayType *ArrayTy,
437                                            llvm::Value *ArrayPtr) {
438  const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
439  llvm::Value * NumElements =
440    llvm::ConstantInt::get(SizeTy,
441                           getContext().getConstantArrayElementCount(ArrayTy));
442
443  EmitCXXAggrConstructorCall(D, NumElements, ArrayPtr);
444}
445
446void
447CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
448                                            llvm::Value *NumElements,
449                                            llvm::Value *ArrayPtr) {
450  const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
451
452  // Create a temporary for the loop index and initialize it with 0.
453  llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
454  llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
455  Builder.CreateStore(Zero, IndexPtr, false);
456
457  // Start the loop with a block that tests the condition.
458  llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
459  llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
460
461  EmitBlock(CondBlock);
462
463  llvm::BasicBlock *ForBody = createBasicBlock("for.body");
464
465  // Generate: if (loop-index < number-of-elements fall to the loop body,
466  // otherwise, go to the block after the for-loop.
467  llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
468  llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
469  // If the condition is true, execute the body.
470  Builder.CreateCondBr(IsLess, ForBody, AfterFor);
471
472  EmitBlock(ForBody);
473
474  llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
475  // Inside the loop body, emit the constructor call on the array element.
476  Counter = Builder.CreateLoad(IndexPtr);
477  llvm::Value *Address = Builder.CreateInBoundsGEP(ArrayPtr, Counter,
478                                                   "arrayidx");
479  EmitCXXConstructorCall(D, Ctor_Complete, Address, 0, 0);
480
481  EmitBlock(ContinueBlock);
482
483  // Emit the increment of the loop counter.
484  llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
485  Counter = Builder.CreateLoad(IndexPtr);
486  NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
487  Builder.CreateStore(NextVal, IndexPtr, false);
488
489  // Finally, branch back up to the condition for the next iteration.
490  EmitBranch(CondBlock);
491
492  // Emit the fall-through block.
493  EmitBlock(AfterFor, true);
494}
495
496/// EmitCXXAggrDestructorCall - calls the default destructor on array
497/// elements in reverse order of construction.
498void
499CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
500                                           const ArrayType *Array,
501                                           llvm::Value *This) {
502  const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
503  assert(CA && "Do we support VLA for destruction ?");
504  llvm::Value *One = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
505                                            1);
506  uint64_t ElementCount = getContext().getConstantArrayElementCount(CA);
507  // Create a temporary for the loop index and initialize it with count of
508  // array elements.
509  llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
510                                           "loop.index");
511  // Index = ElementCount;
512  llvm::Value* UpperCount =
513    llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), ElementCount);
514  Builder.CreateStore(UpperCount, IndexPtr, false);
515
516  // Start the loop with a block that tests the condition.
517  llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
518  llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
519
520  EmitBlock(CondBlock);
521
522  llvm::BasicBlock *ForBody = createBasicBlock("for.body");
523
524  // Generate: if (loop-index != 0 fall to the loop body,
525  // otherwise, go to the block after the for-loop.
526  llvm::Value* zeroConstant =
527    llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
528  llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
529  llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant,
530                                            "isne");
531  // If the condition is true, execute the body.
532  Builder.CreateCondBr(IsNE, ForBody, AfterFor);
533
534  EmitBlock(ForBody);
535
536  llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
537  // Inside the loop body, emit the constructor call on the array element.
538  Counter = Builder.CreateLoad(IndexPtr);
539  Counter = Builder.CreateSub(Counter, One);
540  llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
541  EmitCXXDestructorCall(D, Dtor_Complete, Address);
542
543  EmitBlock(ContinueBlock);
544
545  // Emit the decrement of the loop counter.
546  Counter = Builder.CreateLoad(IndexPtr);
547  Counter = Builder.CreateSub(Counter, One, "dec");
548  Builder.CreateStore(Counter, IndexPtr, false);
549
550  // Finally, branch back up to the condition for the next iteration.
551  EmitBranch(CondBlock);
552
553  // Emit the fall-through block.
554  EmitBlock(AfterFor, true);
555}
556
557void
558CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
559                                        CXXCtorType Type,
560                                        llvm::Value *This,
561                                        CallExpr::const_arg_iterator ArgBeg,
562                                        CallExpr::const_arg_iterator ArgEnd) {
563  if (D->isCopyConstructor(getContext())) {
564    const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D->getDeclContext());
565    if (ClassDecl->hasTrivialCopyConstructor()) {
566      assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
567             "EmitCXXConstructorCall - user declared copy constructor");
568      const Expr *E = (*ArgBeg);
569      QualType Ty = E->getType();
570      llvm::Value *Src = EmitLValue(E).getAddress();
571      EmitAggregateCopy(This, Src, Ty);
572      return;
573    }
574  }
575
576  llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
577
578  EmitCXXMemberCall(D, Callee, This, ArgBeg, ArgEnd);
579}
580
581void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *D,
582                                            CXXDtorType Type,
583                                            llvm::Value *This) {
584  llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(D, Type);
585
586  EmitCXXMemberCall(D, Callee, This, 0, 0);
587}
588
589void
590CodeGenFunction::EmitCXXConstructExpr(llvm::Value *Dest,
591                                      const CXXConstructExpr *E) {
592  assert(Dest && "Must have a destination!");
593  const CXXConstructorDecl *CD = E->getConstructor();
594  // For a copy constructor, even if it is trivial, must fall thru so
595  // its argument is code-gen'ed.
596  if (!CD->isCopyConstructor(getContext())) {
597    QualType InitType = E->getType();
598    if (const ArrayType *Array = getContext().getAsArrayType(InitType))
599      InitType = getContext().getBaseElementType(Array);
600    const CXXRecordDecl *RD =
601      cast<CXXRecordDecl>(InitType->getAs<RecordType>()->getDecl());
602    if (RD->hasTrivialConstructor())
603    return;
604  }
605  // Code gen optimization to eliminate copy constructor and return
606  // its first argument instead.
607  if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
608    CXXConstructExpr::const_arg_iterator i = E->arg_begin();
609    EmitAggExpr((*i), Dest, false);
610    return;
611  }
612  if (const ConstantArrayType *Array =
613      getContext().getAsConstantArrayType(E->getType())) {
614    QualType BaseElementTy = getContext().getBaseElementType(Array);
615    const llvm::Type *BasePtr = ConvertType(BaseElementTy);
616    BasePtr = llvm::PointerType::getUnqual(BasePtr);
617    llvm::Value *BaseAddrPtr =
618      Builder.CreateBitCast(Dest, BasePtr);
619    EmitCXXAggrConstructorCall(CD, Array, BaseAddrPtr);
620  }
621  else
622    // Call the constructor.
623    EmitCXXConstructorCall(CD, Ctor_Complete, Dest,
624                           E->arg_begin(), E->arg_end());
625}
626
627void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) {
628  EmitGlobal(GlobalDecl(D, Ctor_Complete));
629  EmitGlobal(GlobalDecl(D, Ctor_Base));
630}
631
632void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D,
633                                       CXXCtorType Type) {
634
635  llvm::Function *Fn = GetAddrOfCXXConstructor(D, Type);
636
637  CodeGenFunction(*this).GenerateCode(GlobalDecl(D, Type), Fn);
638
639  SetFunctionDefinitionAttributes(D, Fn);
640  SetLLVMFunctionAttributesForDefinition(D, Fn);
641}
642
643llvm::Function *
644CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
645                                       CXXCtorType Type) {
646  const llvm::FunctionType *FTy =
647    getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false);
648
649  const char *Name = getMangledCXXCtorName(D, Type);
650  return cast<llvm::Function>(
651                      GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
652}
653
654const char *CodeGenModule::getMangledCXXCtorName(const CXXConstructorDecl *D,
655                                                 CXXCtorType Type) {
656  llvm::SmallString<256> Name;
657  llvm::raw_svector_ostream Out(Name);
658  mangleCXXCtor(getMangleContext(), D, Type, Out);
659
660  Name += '\0';
661  return UniqueMangledName(Name.begin(), Name.end());
662}
663
664void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) {
665  EmitCXXDestructor(D, Dtor_Complete);
666  EmitCXXDestructor(D, Dtor_Base);
667}
668
669void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D,
670                                      CXXDtorType Type) {
671  llvm::Function *Fn = GetAddrOfCXXDestructor(D, Type);
672
673  CodeGenFunction(*this).GenerateCode(GlobalDecl(D, Type), Fn);
674
675  SetFunctionDefinitionAttributes(D, Fn);
676  SetLLVMFunctionAttributesForDefinition(D, Fn);
677}
678
679llvm::Function *
680CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D,
681                                      CXXDtorType Type) {
682  const llvm::FunctionType *FTy =
683    getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false);
684
685  const char *Name = getMangledCXXDtorName(D, Type);
686  return cast<llvm::Function>(
687                      GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
688}
689
690const char *CodeGenModule::getMangledCXXDtorName(const CXXDestructorDecl *D,
691                                                 CXXDtorType Type) {
692  llvm::SmallString<256> Name;
693  llvm::raw_svector_ostream Out(Name);
694  mangleCXXDtor(getMangleContext(), D, Type, Out);
695
696  Name += '\0';
697  return UniqueMangledName(Name.begin(), Name.end());
698}
699
700llvm::Constant *CodeGenFunction::GenerateThunk(llvm::Function *Fn,
701                                               const CXXMethodDecl *MD,
702                                               bool Extern, int64_t nv,
703                                               int64_t v) {
704  QualType R = MD->getType()->getAs<FunctionType>()->getResultType();
705
706  FunctionArgList Args;
707  ImplicitParamDecl *ThisDecl =
708    ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
709                              MD->getThisType(getContext()));
710  Args.push_back(std::make_pair(ThisDecl, ThisDecl->getType()));
711  for (FunctionDecl::param_const_iterator i = MD->param_begin(),
712         e = MD->param_end();
713       i != e; ++i) {
714    ParmVarDecl *D = *i;
715    Args.push_back(std::make_pair(D, D->getType()));
716  }
717  IdentifierInfo *II
718    = &CGM.getContext().Idents.get("__thunk_named_foo_");
719  FunctionDecl *FD = FunctionDecl::Create(getContext(),
720                                          getContext().getTranslationUnitDecl(),
721                                          SourceLocation(), II, R, 0,
722                                          Extern
723                                            ? FunctionDecl::Extern
724                                            : FunctionDecl::Static,
725                                          false, true);
726  StartFunction(FD, R, Fn, Args, SourceLocation());
727  // FIXME: generate body
728  FinishFunction();
729  return Fn;
730}
731
732llvm::Constant *CodeGenFunction::GenerateCovariantThunk(llvm::Function *Fn,
733                                                        const CXXMethodDecl *MD,
734                                                        bool Extern,
735                                                        int64_t nv_t,
736                                                        int64_t v_t,
737                                                        int64_t nv_r,
738                                                        int64_t v_r) {
739  QualType R = MD->getType()->getAs<FunctionType>()->getResultType();
740
741  FunctionArgList Args;
742  ImplicitParamDecl *ThisDecl =
743    ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
744                              MD->getThisType(getContext()));
745  Args.push_back(std::make_pair(ThisDecl, ThisDecl->getType()));
746  for (FunctionDecl::param_const_iterator i = MD->param_begin(),
747         e = MD->param_end();
748       i != e; ++i) {
749    ParmVarDecl *D = *i;
750    Args.push_back(std::make_pair(D, D->getType()));
751  }
752  IdentifierInfo *II
753    = &CGM.getContext().Idents.get("__thunk_named_foo_");
754  FunctionDecl *FD = FunctionDecl::Create(getContext(),
755                                          getContext().getTranslationUnitDecl(),
756                                          SourceLocation(), II, R, 0,
757                                          Extern
758                                            ? FunctionDecl::Extern
759                                            : FunctionDecl::Static,
760                                          false, true);
761  StartFunction(FD, R, Fn, Args, SourceLocation());
762  // FIXME: generate body
763  FinishFunction();
764  return Fn;
765}
766
767llvm::Constant *CodeGenModule::BuildThunk(const CXXMethodDecl *MD, bool Extern,
768                                          int64_t nv, int64_t v) {
769  llvm::SmallString<256> OutName;
770  llvm::raw_svector_ostream Out(OutName);
771  mangleThunk(getMangleContext(), MD, nv, v, Out);
772  llvm::GlobalVariable::LinkageTypes linktype;
773  linktype = llvm::GlobalValue::WeakAnyLinkage;
774  if (!Extern)
775    linktype = llvm::GlobalValue::InternalLinkage;
776  llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
777  const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
778  const llvm::FunctionType *FTy =
779    getTypes().GetFunctionType(getTypes().getFunctionInfo(MD),
780                               FPT->isVariadic());
781
782  llvm::Function *Fn = llvm::Function::Create(FTy, linktype, Out.str(),
783                                              &getModule());
784  CodeGenFunction(*this).GenerateThunk(Fn, MD, Extern, nv, v);
785  // Fn = Builder.CreateBitCast(Fn, Ptr8Ty);
786  llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty);
787  return m;
788}
789
790llvm::Constant *CodeGenModule::BuildCovariantThunk(const CXXMethodDecl *MD,
791                                                   bool Extern, int64_t nv_t,
792                                                   int64_t v_t, int64_t nv_r,
793                                                   int64_t v_r) {
794  llvm::SmallString<256> OutName;
795  llvm::raw_svector_ostream Out(OutName);
796  mangleCovariantThunk(getMangleContext(), MD, nv_t, v_t, nv_r, v_r, Out);
797  llvm::GlobalVariable::LinkageTypes linktype;
798  linktype = llvm::GlobalValue::WeakAnyLinkage;
799  if (!Extern)
800    linktype = llvm::GlobalValue::InternalLinkage;
801  llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
802  const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
803  const llvm::FunctionType *FTy =
804    getTypes().GetFunctionType(getTypes().getFunctionInfo(MD),
805                               FPT->isVariadic());
806
807  llvm::Function *Fn = llvm::Function::Create(FTy, linktype, Out.str(),
808                                              &getModule());
809  CodeGenFunction(*this).GenerateCovariantThunk(Fn, MD, Extern, nv_t, v_t, nv_r,
810                                               v_r);
811  // Fn = Builder.CreateBitCast(Fn, Ptr8Ty);
812  llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty);
813  return m;
814}
815
816llvm::Value *
817CodeGenFunction::GetVirtualCXXBaseClassOffset(llvm::Value *This,
818                                              const CXXRecordDecl *ClassDecl,
819                                           const CXXRecordDecl *BaseClassDecl) {
820  const llvm::Type *Int8PtrTy =
821    llvm::Type::getInt8Ty(VMContext)->getPointerTo();
822
823  llvm::Value *VTablePtr = Builder.CreateBitCast(This,
824                                                 Int8PtrTy->getPointerTo());
825  VTablePtr = Builder.CreateLoad(VTablePtr, "vtable");
826
827  int64_t VBaseOffsetIndex =
828    CGM.getVtableInfo().getVirtualBaseOffsetIndex(ClassDecl, BaseClassDecl);
829
830  llvm::Value *VBaseOffsetPtr =
831    Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetIndex, "vbase.offset.ptr");
832  const llvm::Type *PtrDiffTy =
833    ConvertType(getContext().getPointerDiffType());
834
835  VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
836                                         PtrDiffTy->getPointerTo());
837
838  llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
839
840  return VBaseOffset;
841}
842
843llvm::Value *
844CodeGenFunction::BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *&This,
845                                  const llvm::Type *Ty) {
846  int64_t Index = CGM.getVtableInfo().getMethodVtableIndex(MD);
847
848  Ty = llvm::PointerType::get(Ty, 0);
849  Ty = llvm::PointerType::get(Ty, 0);
850  Ty = llvm::PointerType::get(Ty, 0);
851  llvm::Value *vtbl = Builder.CreateBitCast(This, Ty);
852  vtbl = Builder.CreateLoad(vtbl);
853  llvm::Value *vfn = Builder.CreateConstInBoundsGEP1_64(vtbl,
854                                                        Index, "vfn");
855  vfn = Builder.CreateLoad(vfn);
856  return vfn;
857}
858
859/// EmitClassAggrMemberwiseCopy - This routine generates code to copy a class
860/// array of objects from SrcValue to DestValue. Copying can be either a bitwise
861/// copy or via a copy constructor call.
862//  FIXME. Consolidate this with EmitCXXAggrConstructorCall.
863void CodeGenFunction::EmitClassAggrMemberwiseCopy(llvm::Value *Dest,
864                                            llvm::Value *Src,
865                                            const ArrayType *Array,
866                                            const CXXRecordDecl *BaseClassDecl,
867                                            QualType Ty) {
868  const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
869  assert(CA && "VLA cannot be copied over");
870  bool BitwiseCopy = BaseClassDecl->hasTrivialCopyConstructor();
871
872  // Create a temporary for the loop index and initialize it with 0.
873  llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
874                                           "loop.index");
875  llvm::Value* zeroConstant =
876    llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
877  Builder.CreateStore(zeroConstant, IndexPtr, false);
878  // Start the loop with a block that tests the condition.
879  llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
880  llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
881
882  EmitBlock(CondBlock);
883
884  llvm::BasicBlock *ForBody = createBasicBlock("for.body");
885  // Generate: if (loop-index < number-of-elements fall to the loop body,
886  // otherwise, go to the block after the for-loop.
887  uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
888  llvm::Value * NumElementsPtr =
889    llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
890  llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
891  llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
892                                              "isless");
893  // If the condition is true, execute the body.
894  Builder.CreateCondBr(IsLess, ForBody, AfterFor);
895
896  EmitBlock(ForBody);
897  llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
898  // Inside the loop body, emit the constructor call on the array element.
899  Counter = Builder.CreateLoad(IndexPtr);
900  Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
901  Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
902  if (BitwiseCopy)
903    EmitAggregateCopy(Dest, Src, Ty);
904  else if (CXXConstructorDecl *BaseCopyCtor =
905           BaseClassDecl->getCopyConstructor(getContext(), 0)) {
906    llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
907                                                      Ctor_Complete);
908    CallArgList CallArgs;
909    // Push the this (Dest) ptr.
910    CallArgs.push_back(std::make_pair(RValue::get(Dest),
911                                      BaseCopyCtor->getThisType(getContext())));
912
913    // Push the Src ptr.
914    CallArgs.push_back(std::make_pair(RValue::get(Src),
915                                      BaseCopyCtor->getParamDecl(0)->getType()));
916    QualType ResultType =
917      BaseCopyCtor->getType()->getAs<FunctionType>()->getResultType();
918    EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
919             Callee, CallArgs, BaseCopyCtor);
920  }
921  EmitBlock(ContinueBlock);
922
923  // Emit the increment of the loop counter.
924  llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
925  Counter = Builder.CreateLoad(IndexPtr);
926  NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
927  Builder.CreateStore(NextVal, IndexPtr, false);
928
929  // Finally, branch back up to the condition for the next iteration.
930  EmitBranch(CondBlock);
931
932  // Emit the fall-through block.
933  EmitBlock(AfterFor, true);
934}
935
936/// EmitClassAggrCopyAssignment - This routine generates code to assign a class
937/// array of objects from SrcValue to DestValue. Assignment can be either a
938/// bitwise assignment or via a copy assignment operator function call.
939/// FIXME. This can be consolidated with EmitClassAggrMemberwiseCopy
940void CodeGenFunction::EmitClassAggrCopyAssignment(llvm::Value *Dest,
941                                            llvm::Value *Src,
942                                            const ArrayType *Array,
943                                            const CXXRecordDecl *BaseClassDecl,
944                                            QualType Ty) {
945  const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
946  assert(CA && "VLA cannot be asssigned");
947  bool BitwiseAssign = BaseClassDecl->hasTrivialCopyAssignment();
948
949  // Create a temporary for the loop index and initialize it with 0.
950  llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
951                                           "loop.index");
952  llvm::Value* zeroConstant =
953  llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
954  Builder.CreateStore(zeroConstant, IndexPtr, false);
955  // Start the loop with a block that tests the condition.
956  llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
957  llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
958
959  EmitBlock(CondBlock);
960
961  llvm::BasicBlock *ForBody = createBasicBlock("for.body");
962  // Generate: if (loop-index < number-of-elements fall to the loop body,
963  // otherwise, go to the block after the for-loop.
964  uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
965  llvm::Value * NumElementsPtr =
966  llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
967  llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
968  llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
969                                              "isless");
970  // If the condition is true, execute the body.
971  Builder.CreateCondBr(IsLess, ForBody, AfterFor);
972
973  EmitBlock(ForBody);
974  llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
975  // Inside the loop body, emit the assignment operator call on array element.
976  Counter = Builder.CreateLoad(IndexPtr);
977  Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
978  Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
979  const CXXMethodDecl *MD = 0;
980  if (BitwiseAssign)
981    EmitAggregateCopy(Dest, Src, Ty);
982  else {
983    bool hasCopyAssign = BaseClassDecl->hasConstCopyAssignment(getContext(),
984                                                               MD);
985    assert(hasCopyAssign && "EmitClassAggrCopyAssignment - No user assign");
986    (void)hasCopyAssign;
987    const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
988    const llvm::Type *LTy =
989    CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
990                                   FPT->isVariadic());
991    llvm::Constant *Callee = CGM.GetAddrOfFunction(MD, LTy);
992
993    CallArgList CallArgs;
994    // Push the this (Dest) ptr.
995    CallArgs.push_back(std::make_pair(RValue::get(Dest),
996                                      MD->getThisType(getContext())));
997
998    // Push the Src ptr.
999    CallArgs.push_back(std::make_pair(RValue::get(Src),
1000                                      MD->getParamDecl(0)->getType()));
1001    QualType ResultType = MD->getType()->getAs<FunctionType>()->getResultType();
1002    EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1003             Callee, CallArgs, MD);
1004  }
1005  EmitBlock(ContinueBlock);
1006
1007  // Emit the increment of the loop counter.
1008  llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1009  Counter = Builder.CreateLoad(IndexPtr);
1010  NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1011  Builder.CreateStore(NextVal, IndexPtr, false);
1012
1013  // Finally, branch back up to the condition for the next iteration.
1014  EmitBranch(CondBlock);
1015
1016  // Emit the fall-through block.
1017  EmitBlock(AfterFor, true);
1018}
1019
1020/// EmitClassMemberwiseCopy - This routine generates code to copy a class
1021/// object from SrcValue to DestValue. Copying can be either a bitwise copy
1022/// or via a copy constructor call.
1023void CodeGenFunction::EmitClassMemberwiseCopy(
1024                        llvm::Value *Dest, llvm::Value *Src,
1025                        const CXXRecordDecl *ClassDecl,
1026                        const CXXRecordDecl *BaseClassDecl, QualType Ty) {
1027  if (ClassDecl) {
1028    Dest = GetAddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl,
1029                                    /*NullCheckValue=*/false);
1030    Src = GetAddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl,
1031                                   /*NullCheckValue=*/false);
1032  }
1033  if (BaseClassDecl->hasTrivialCopyConstructor()) {
1034    EmitAggregateCopy(Dest, Src, Ty);
1035    return;
1036  }
1037
1038  if (CXXConstructorDecl *BaseCopyCtor =
1039      BaseClassDecl->getCopyConstructor(getContext(), 0)) {
1040    llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
1041                                                      Ctor_Complete);
1042    CallArgList CallArgs;
1043    // Push the this (Dest) ptr.
1044    CallArgs.push_back(std::make_pair(RValue::get(Dest),
1045                                      BaseCopyCtor->getThisType(getContext())));
1046
1047    // Push the Src ptr.
1048    CallArgs.push_back(std::make_pair(RValue::get(Src),
1049                       BaseCopyCtor->getParamDecl(0)->getType()));
1050    QualType ResultType =
1051    BaseCopyCtor->getType()->getAs<FunctionType>()->getResultType();
1052    EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1053             Callee, CallArgs, BaseCopyCtor);
1054  }
1055}
1056
1057/// EmitClassCopyAssignment - This routine generates code to copy assign a class
1058/// object from SrcValue to DestValue. Assignment can be either a bitwise
1059/// assignment of via an assignment operator call.
1060// FIXME. Consolidate this with EmitClassMemberwiseCopy as they share a lot.
1061void CodeGenFunction::EmitClassCopyAssignment(
1062                                        llvm::Value *Dest, llvm::Value *Src,
1063                                        const CXXRecordDecl *ClassDecl,
1064                                        const CXXRecordDecl *BaseClassDecl,
1065                                        QualType Ty) {
1066  if (ClassDecl) {
1067    Dest = GetAddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl,
1068                                    /*NullCheckValue=*/false);
1069    Src = GetAddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl,
1070                                   /*NullCheckValue=*/false);
1071  }
1072  if (BaseClassDecl->hasTrivialCopyAssignment()) {
1073    EmitAggregateCopy(Dest, Src, Ty);
1074    return;
1075  }
1076
1077  const CXXMethodDecl *MD = 0;
1078  bool ConstCopyAssignOp = BaseClassDecl->hasConstCopyAssignment(getContext(),
1079                                                                 MD);
1080  assert(ConstCopyAssignOp && "EmitClassCopyAssignment - missing copy assign");
1081  (void)ConstCopyAssignOp;
1082
1083  const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
1084  const llvm::Type *LTy =
1085    CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1086                                   FPT->isVariadic());
1087  llvm::Constant *Callee = CGM.GetAddrOfFunction(MD, LTy);
1088
1089  CallArgList CallArgs;
1090  // Push the this (Dest) ptr.
1091  CallArgs.push_back(std::make_pair(RValue::get(Dest),
1092                                    MD->getThisType(getContext())));
1093
1094  // Push the Src ptr.
1095  CallArgs.push_back(std::make_pair(RValue::get(Src),
1096                                    MD->getParamDecl(0)->getType()));
1097  QualType ResultType =
1098    MD->getType()->getAs<FunctionType>()->getResultType();
1099  EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1100           Callee, CallArgs, MD);
1101}
1102
1103/// SynthesizeDefaultConstructor - synthesize a default constructor
1104void
1105CodeGenFunction::SynthesizeDefaultConstructor(const CXXConstructorDecl *Ctor,
1106                                              CXXCtorType Type,
1107                                              llvm::Function *Fn,
1108                                              const FunctionArgList &Args) {
1109  StartFunction(GlobalDecl(Ctor, Type), Ctor->getResultType(), Fn, Args,
1110                SourceLocation());
1111  EmitCtorPrologue(Ctor, Type);
1112  FinishFunction();
1113}
1114
1115/// SynthesizeCXXCopyConstructor - This routine implicitly defines body of a copy
1116/// constructor, in accordance with section 12.8 (p7 and p8) of C++03
1117/// The implicitly-defined copy constructor for class X performs a memberwise
1118/// copy of its subobjects. The order of copying is the same as the order
1119/// of initialization of bases and members in a user-defined constructor
1120/// Each subobject is copied in the manner appropriate to its type:
1121///  if the subobject is of class type, the copy constructor for the class is
1122///  used;
1123///  if the subobject is an array, each element is copied, in the manner
1124///  appropriate to the element type;
1125///  if the subobject is of scalar type, the built-in assignment operator is
1126///  used.
1127/// Virtual base class subobjects shall be copied only once by the
1128/// implicitly-defined copy constructor
1129
1130void
1131CodeGenFunction::SynthesizeCXXCopyConstructor(const CXXConstructorDecl *Ctor,
1132                                              CXXCtorType Type,
1133                                              llvm::Function *Fn,
1134                                              const FunctionArgList &Args) {
1135  const CXXRecordDecl *ClassDecl = Ctor->getParent();
1136  assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
1137         "SynthesizeCXXCopyConstructor - copy constructor has definition already");
1138  StartFunction(GlobalDecl(Ctor, Type), Ctor->getResultType(), Fn, Args,
1139                SourceLocation());
1140
1141  FunctionArgList::const_iterator i = Args.begin();
1142  const VarDecl *ThisArg = i->first;
1143  llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1144  llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1145  const VarDecl *SrcArg = (i+1)->first;
1146  llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1147  llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1148
1149  for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1150       Base != ClassDecl->bases_end(); ++Base) {
1151    // FIXME. copy constrution of virtual base NYI
1152    if (Base->isVirtual())
1153      continue;
1154
1155    CXXRecordDecl *BaseClassDecl
1156      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1157    EmitClassMemberwiseCopy(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1158                            Base->getType());
1159  }
1160
1161  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1162       FieldEnd = ClassDecl->field_end();
1163       Field != FieldEnd; ++Field) {
1164    QualType FieldType = getContext().getCanonicalType((*Field)->getType());
1165    const ConstantArrayType *Array =
1166      getContext().getAsConstantArrayType(FieldType);
1167    if (Array)
1168      FieldType = getContext().getBaseElementType(FieldType);
1169
1170    if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1171      CXXRecordDecl *FieldClassDecl
1172        = cast<CXXRecordDecl>(FieldClassType->getDecl());
1173      LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1174      LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1175      if (Array) {
1176        const llvm::Type *BasePtr = ConvertType(FieldType);
1177        BasePtr = llvm::PointerType::getUnqual(BasePtr);
1178        llvm::Value *DestBaseAddrPtr =
1179          Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1180        llvm::Value *SrcBaseAddrPtr =
1181          Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1182        EmitClassAggrMemberwiseCopy(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1183                                    FieldClassDecl, FieldType);
1184      }
1185      else
1186        EmitClassMemberwiseCopy(LHS.getAddress(), RHS.getAddress(),
1187                                0 /*ClassDecl*/, FieldClassDecl, FieldType);
1188      continue;
1189    }
1190    // Do a built-in assignment of scalar data members.
1191    LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1192    LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1193    RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1194    EmitStoreThroughLValue(RVRHS, LHS, FieldType);
1195  }
1196  FinishFunction();
1197}
1198
1199/// SynthesizeCXXCopyAssignment - Implicitly define copy assignment operator.
1200/// Before the implicitly-declared copy assignment operator for a class is
1201/// implicitly defined, all implicitly- declared copy assignment operators for
1202/// its direct base classes and its nonstatic data members shall have been
1203/// implicitly defined. [12.8-p12]
1204/// The implicitly-defined copy assignment operator for class X performs
1205/// memberwise assignment of its subob- jects. The direct base classes of X are
1206/// assigned first, in the order of their declaration in
1207/// the base-specifier-list, and then the immediate nonstatic data members of X
1208/// are assigned, in the order in which they were declared in the class
1209/// definition.Each subobject is assigned in the manner appropriate to its type:
1210///   if the subobject is of class type, the copy assignment operator for the
1211///   class is used (as if by explicit qualification; that is, ignoring any
1212///   possible virtual overriding functions in more derived classes);
1213///
1214///   if the subobject is an array, each element is assigned, in the manner
1215///   appropriate to the element type;
1216///
1217///   if the subobject is of scalar type, the built-in assignment operator is
1218///   used.
1219void CodeGenFunction::SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD,
1220                                                  llvm::Function *Fn,
1221                                                  const FunctionArgList &Args) {
1222
1223  const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1224  assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
1225         "SynthesizeCXXCopyAssignment - copy assignment has user declaration");
1226  StartFunction(CD, CD->getResultType(), Fn, Args, SourceLocation());
1227
1228  FunctionArgList::const_iterator i = Args.begin();
1229  const VarDecl *ThisArg = i->first;
1230  llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1231  llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1232  const VarDecl *SrcArg = (i+1)->first;
1233  llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1234  llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1235
1236  for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1237       Base != ClassDecl->bases_end(); ++Base) {
1238    // FIXME. copy assignment of virtual base NYI
1239    if (Base->isVirtual())
1240      continue;
1241
1242    CXXRecordDecl *BaseClassDecl
1243      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1244    EmitClassCopyAssignment(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1245                            Base->getType());
1246  }
1247
1248  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1249       FieldEnd = ClassDecl->field_end();
1250       Field != FieldEnd; ++Field) {
1251    QualType FieldType = getContext().getCanonicalType((*Field)->getType());
1252    const ConstantArrayType *Array =
1253      getContext().getAsConstantArrayType(FieldType);
1254    if (Array)
1255      FieldType = getContext().getBaseElementType(FieldType);
1256
1257    if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1258      CXXRecordDecl *FieldClassDecl
1259      = cast<CXXRecordDecl>(FieldClassType->getDecl());
1260      LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1261      LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1262      if (Array) {
1263        const llvm::Type *BasePtr = ConvertType(FieldType);
1264        BasePtr = llvm::PointerType::getUnqual(BasePtr);
1265        llvm::Value *DestBaseAddrPtr =
1266          Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1267        llvm::Value *SrcBaseAddrPtr =
1268          Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1269        EmitClassAggrCopyAssignment(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1270                                    FieldClassDecl, FieldType);
1271      }
1272      else
1273        EmitClassCopyAssignment(LHS.getAddress(), RHS.getAddress(),
1274                               0 /*ClassDecl*/, FieldClassDecl, FieldType);
1275      continue;
1276    }
1277    // Do a built-in assignment of scalar data members.
1278    LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1279    LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1280    RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1281    EmitStoreThroughLValue(RVRHS, LHS, FieldType);
1282  }
1283
1284  // return *this;
1285  Builder.CreateStore(LoadOfThis, ReturnValue);
1286
1287  FinishFunction();
1288}
1289
1290/// EmitCtorPrologue - This routine generates necessary code to initialize
1291/// base classes and non-static data members belonging to this constructor.
1292/// FIXME: This needs to take a CXXCtorType.
1293void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
1294                                       CXXCtorType CtorType) {
1295  const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1296  // FIXME: Add vbase initialization
1297  llvm::Value *LoadOfThis = 0;
1298
1299  for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1300       E = CD->init_end();
1301       B != E; ++B) {
1302    CXXBaseOrMemberInitializer *Member = (*B);
1303    if (Member->isBaseInitializer()) {
1304      LoadOfThis = LoadCXXThis();
1305      Type *BaseType = Member->getBaseClass();
1306      CXXRecordDecl *BaseClassDecl =
1307        cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
1308      llvm::Value *V = GetAddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1309                                                BaseClassDecl,
1310                                                /*NullCheckValue=*/false);
1311      EmitCXXConstructorCall(Member->getConstructor(),
1312                             CtorType, V,
1313                             Member->const_arg_begin(),
1314                             Member->const_arg_end());
1315    } else {
1316      // non-static data member initilaizers.
1317      FieldDecl *Field = Member->getMember();
1318      QualType FieldType = getContext().getCanonicalType((Field)->getType());
1319      const ConstantArrayType *Array =
1320        getContext().getAsConstantArrayType(FieldType);
1321      if (Array)
1322        FieldType = getContext().getBaseElementType(FieldType);
1323
1324      LoadOfThis = LoadCXXThis();
1325      LValue LHS;
1326      if (FieldType->isReferenceType()) {
1327        // FIXME: This is really ugly; should be refactored somehow
1328        unsigned idx = CGM.getTypes().getLLVMFieldNo(Field);
1329        llvm::Value *V = Builder.CreateStructGEP(LoadOfThis, idx, "tmp");
1330        assert(!FieldType.getObjCGCAttr() && "fields cannot have GC attrs");
1331        LHS = LValue::MakeAddr(V, MakeQualifiers(FieldType));
1332      } else {
1333        LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
1334      }
1335      if (FieldType->getAs<RecordType>()) {
1336        if (!Field->isAnonymousStructOrUnion()) {
1337          assert(Member->getConstructor() &&
1338                 "EmitCtorPrologue - no constructor to initialize member");
1339          if (Array) {
1340            const llvm::Type *BasePtr = ConvertType(FieldType);
1341            BasePtr = llvm::PointerType::getUnqual(BasePtr);
1342            llvm::Value *BaseAddrPtr =
1343            Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1344            EmitCXXAggrConstructorCall(Member->getConstructor(),
1345                                       Array, BaseAddrPtr);
1346          }
1347          else
1348            EmitCXXConstructorCall(Member->getConstructor(),
1349                                   Ctor_Complete, LHS.getAddress(),
1350                                   Member->const_arg_begin(),
1351                                   Member->const_arg_end());
1352          continue;
1353        }
1354        else {
1355          // Initializing an anonymous union data member.
1356          FieldDecl *anonMember = Member->getAnonUnionMember();
1357          LHS = EmitLValueForField(LHS.getAddress(), anonMember,
1358                                   /*IsUnion=*/true, 0);
1359          FieldType = anonMember->getType();
1360        }
1361      }
1362
1363      assert(Member->getNumArgs() == 1 && "Initializer count must be 1 only");
1364      Expr *RhsExpr = *Member->arg_begin();
1365      RValue RHS;
1366      if (FieldType->isReferenceType())
1367        RHS = EmitReferenceBindingToExpr(RhsExpr, FieldType,
1368                                        /*IsInitializer=*/true);
1369      else
1370        RHS = RValue::get(EmitScalarExpr(RhsExpr, true));
1371      EmitStoreThroughLValue(RHS, LHS, FieldType);
1372    }
1373  }
1374
1375  if (!CD->getNumBaseOrMemberInitializers() && !CD->isTrivial()) {
1376    // Nontrivial default constructor with no initializer list. It may still
1377    // have bases classes and/or contain non-static data members which require
1378    // construction.
1379    for (CXXRecordDecl::base_class_const_iterator Base =
1380          ClassDecl->bases_begin();
1381          Base != ClassDecl->bases_end(); ++Base) {
1382      // FIXME. copy assignment of virtual base NYI
1383      if (Base->isVirtual())
1384        continue;
1385
1386      CXXRecordDecl *BaseClassDecl
1387        = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1388      if (BaseClassDecl->hasTrivialConstructor())
1389        continue;
1390      if (CXXConstructorDecl *BaseCX =
1391            BaseClassDecl->getDefaultConstructor(getContext())) {
1392        LoadOfThis = LoadCXXThis();
1393        llvm::Value *V = GetAddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1394                                                  BaseClassDecl,
1395                                                  /*NullCheckValue=*/false);
1396        EmitCXXConstructorCall(BaseCX, Ctor_Complete, V, 0, 0);
1397      }
1398    }
1399
1400    for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1401         FieldEnd = ClassDecl->field_end();
1402         Field != FieldEnd; ++Field) {
1403      QualType FieldType = getContext().getCanonicalType((*Field)->getType());
1404      const ConstantArrayType *Array =
1405        getContext().getAsConstantArrayType(FieldType);
1406      if (Array)
1407        FieldType = getContext().getBaseElementType(FieldType);
1408      if (!FieldType->getAs<RecordType>() || Field->isAnonymousStructOrUnion())
1409        continue;
1410      const RecordType *ClassRec = FieldType->getAs<RecordType>();
1411      CXXRecordDecl *MemberClassDecl =
1412        dyn_cast<CXXRecordDecl>(ClassRec->getDecl());
1413      if (!MemberClassDecl || MemberClassDecl->hasTrivialConstructor())
1414        continue;
1415      if (CXXConstructorDecl *MamberCX =
1416            MemberClassDecl->getDefaultConstructor(getContext())) {
1417        LoadOfThis = LoadCXXThis();
1418        LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1419        if (Array) {
1420          const llvm::Type *BasePtr = ConvertType(FieldType);
1421          BasePtr = llvm::PointerType::getUnqual(BasePtr);
1422          llvm::Value *BaseAddrPtr =
1423            Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1424          EmitCXXAggrConstructorCall(MamberCX, Array, BaseAddrPtr);
1425        }
1426        else
1427          EmitCXXConstructorCall(MamberCX, Ctor_Complete, LHS.getAddress(),
1428                                 0, 0);
1429      }
1430    }
1431  }
1432
1433  // Initialize the vtable pointer
1434  if (ClassDecl->isDynamicClass()) {
1435    if (!LoadOfThis)
1436      LoadOfThis = LoadCXXThis();
1437    llvm::Value *VtableField;
1438    llvm::Type *Ptr8Ty, *PtrPtr8Ty;
1439    Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
1440    PtrPtr8Ty = llvm::PointerType::get(Ptr8Ty, 0);
1441    VtableField = Builder.CreateBitCast(LoadOfThis, PtrPtr8Ty);
1442    llvm::Value *vtable = GenerateVtable(ClassDecl);
1443    Builder.CreateStore(vtable, VtableField);
1444  }
1445}
1446
1447/// EmitDtorEpilogue - Emit all code that comes at the end of class's
1448/// destructor. This is to call destructors on members and base classes
1449/// in reverse order of their construction.
1450/// FIXME: This needs to take a CXXDtorType.
1451void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD,
1452                                       CXXDtorType DtorType) {
1453  const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(DD->getDeclContext());
1454  assert(!ClassDecl->getNumVBases() &&
1455         "FIXME: Destruction of virtual bases not supported");
1456  (void)ClassDecl;  // prevent warning.
1457
1458  for (CXXDestructorDecl::destr_const_iterator *B = DD->destr_begin(),
1459       *E = DD->destr_end(); B != E; ++B) {
1460    uintptr_t BaseOrMember = (*B);
1461    if (DD->isMemberToDestroy(BaseOrMember)) {
1462      FieldDecl *FD = DD->getMemberToDestroy(BaseOrMember);
1463      QualType FieldType = getContext().getCanonicalType((FD)->getType());
1464      const ConstantArrayType *Array =
1465        getContext().getAsConstantArrayType(FieldType);
1466      if (Array)
1467        FieldType = getContext().getBaseElementType(FieldType);
1468      const RecordType *RT = FieldType->getAs<RecordType>();
1469      CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1470      if (FieldClassDecl->hasTrivialDestructor())
1471        continue;
1472      llvm::Value *LoadOfThis = LoadCXXThis();
1473      LValue LHS = EmitLValueForField(LoadOfThis, FD, false, 0);
1474      if (Array) {
1475        const llvm::Type *BasePtr = ConvertType(FieldType);
1476        BasePtr = llvm::PointerType::getUnqual(BasePtr);
1477        llvm::Value *BaseAddrPtr =
1478          Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1479        EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1480                                  Array, BaseAddrPtr);
1481      }
1482      else
1483        EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1484                              Dtor_Complete, LHS.getAddress());
1485    } else {
1486      const RecordType *RT =
1487        DD->getAnyBaseClassToDestroy(BaseOrMember)->getAs<RecordType>();
1488      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1489      if (BaseClassDecl->hasTrivialDestructor())
1490        continue;
1491      llvm::Value *V = GetAddressCXXOfBaseClass(LoadCXXThis(),
1492                                                ClassDecl, BaseClassDecl,
1493                                                /*NullCheckValue=*/false);
1494      EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1495                            DtorType, V);
1496    }
1497  }
1498  if (DD->getNumBaseOrMemberDestructions() || DD->isTrivial())
1499    return;
1500  // Case of destructor synthesis with fields and base classes
1501  // which have non-trivial destructors. They must be destructed in
1502  // reverse order of their construction.
1503  llvm::SmallVector<FieldDecl *, 16> DestructedFields;
1504
1505  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1506       FieldEnd = ClassDecl->field_end();
1507       Field != FieldEnd; ++Field) {
1508    QualType FieldType = getContext().getCanonicalType((*Field)->getType());
1509    if (getContext().getAsConstantArrayType(FieldType))
1510      FieldType = getContext().getBaseElementType(FieldType);
1511    if (const RecordType *RT = FieldType->getAs<RecordType>()) {
1512      CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1513      if (FieldClassDecl->hasTrivialDestructor())
1514        continue;
1515      DestructedFields.push_back(*Field);
1516    }
1517  }
1518  if (!DestructedFields.empty())
1519    for (int i = DestructedFields.size() -1; i >= 0; --i) {
1520      FieldDecl *Field = DestructedFields[i];
1521      QualType FieldType = Field->getType();
1522      const ConstantArrayType *Array =
1523        getContext().getAsConstantArrayType(FieldType);
1524        if (Array)
1525          FieldType = getContext().getBaseElementType(FieldType);
1526      const RecordType *RT = FieldType->getAs<RecordType>();
1527      CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1528      llvm::Value *LoadOfThis = LoadCXXThis();
1529      LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
1530      if (Array) {
1531        const llvm::Type *BasePtr = ConvertType(FieldType);
1532        BasePtr = llvm::PointerType::getUnqual(BasePtr);
1533        llvm::Value *BaseAddrPtr =
1534        Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1535        EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1536                                  Array, BaseAddrPtr);
1537      }
1538      else
1539        EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1540                              Dtor_Complete, LHS.getAddress());
1541    }
1542
1543  llvm::SmallVector<CXXRecordDecl*, 4> DestructedBases;
1544  for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1545       Base != ClassDecl->bases_end(); ++Base) {
1546    // FIXME. copy assignment of virtual base NYI
1547    if (Base->isVirtual())
1548      continue;
1549
1550    CXXRecordDecl *BaseClassDecl
1551      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1552    if (BaseClassDecl->hasTrivialDestructor())
1553      continue;
1554    DestructedBases.push_back(BaseClassDecl);
1555  }
1556  if (DestructedBases.empty())
1557    return;
1558  for (int i = DestructedBases.size() -1; i >= 0; --i) {
1559    CXXRecordDecl *BaseClassDecl = DestructedBases[i];
1560    llvm::Value *V = GetAddressCXXOfBaseClass(LoadCXXThis(),
1561                                              ClassDecl,BaseClassDecl,
1562                                              /*NullCheckValue=*/false);
1563    EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1564                          Dtor_Complete, V);
1565  }
1566}
1567
1568void CodeGenFunction::SynthesizeDefaultDestructor(const CXXDestructorDecl *Dtor,
1569                                                  CXXDtorType DtorType,
1570                                                  llvm::Function *Fn,
1571                                                  const FunctionArgList &Args) {
1572
1573  const CXXRecordDecl *ClassDecl = Dtor->getParent();
1574  assert(!ClassDecl->hasUserDeclaredDestructor() &&
1575         "SynthesizeDefaultDestructor - destructor has user declaration");
1576  (void) ClassDecl;
1577
1578  StartFunction(GlobalDecl(Dtor, DtorType), Dtor->getResultType(), Fn, Args,
1579                SourceLocation());
1580  EmitDtorEpilogue(Dtor, DtorType);
1581  FinishFunction();
1582}
1583
1584// FIXME: Move this to CGCXXStmt.cpp
1585void CodeGenFunction::EmitCXXTryStmt(const CXXTryStmt &S) {
1586  // FIXME: We need to do more here.
1587  EmitStmt(S.getTryBlock());
1588}
1589