blob: 5bc8b40c63730394973a92bb218935e88cd3fbcc [file] [log] [blame]
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +00001//===--- 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"
Anders Carlsson33e65e52009-04-13 18:03:33 +000018#include "Mangle.h"
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +000019#include "clang/AST/ASTContext.h"
Fariborz Jahaniana0107de2009-07-25 21:12:28 +000020#include "clang/AST/RecordLayout.h"
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +000021#include "clang/AST/Decl.h"
Anders Carlsson7a9b2982009-04-03 22:50:24 +000022#include "clang/AST/DeclCXX.h"
Anders Carlsson4715ebb2008-08-23 19:42:54 +000023#include "clang/AST/DeclObjC.h"
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +000024#include "llvm/ADT/StringExtras.h"
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +000025using namespace clang;
26using namespace CodeGen;
27
Daniel Dunbardea59212009-02-25 19:24:29 +000028void
Anders Carlssonf2a022a2009-08-08 21:45:14 +000029CodeGenFunction::EmitCXXGlobalDtorRegistration(const CXXDestructorDecl *Dtor,
30 llvm::Constant *DeclPtr) {
31 // FIXME: This is ABI dependent and we use the Itanium ABI.
32
33 const llvm::Type *Int8PtrTy =
Owen Anderson3f5cc0a2009-08-13 21:57:51 +000034 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Anders Carlssonf2a022a2009-08-08 21:45:14 +000035
36 std::vector<const llvm::Type *> Params;
37 Params.push_back(Int8PtrTy);
38
39 // Get the destructor function type
40 const llvm::Type *DtorFnTy =
Owen Anderson3f5cc0a2009-08-13 21:57:51 +000041 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Params, false);
Anders Carlssonf2a022a2009-08-08 21:45:14 +000042 DtorFnTy = llvm::PointerType::getUnqual(DtorFnTy);
43
44 Params.clear();
45 Params.push_back(DtorFnTy);
46 Params.push_back(Int8PtrTy);
47 Params.push_back(Int8PtrTy);
48
49 // Get the __cxa_atexit function type
50 // extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
51 const llvm::FunctionType *AtExitFnTy =
52 llvm::FunctionType::get(ConvertType(getContext().IntTy), Params, false);
53
54 llvm::Constant *AtExitFn = CGM.CreateRuntimeFunction(AtExitFnTy,
55 "__cxa_atexit");
56
57 llvm::Constant *Handle = CGM.CreateRuntimeVariable(Int8PtrTy,
58 "__dso_handle");
59
60 llvm::Constant *DtorFn = CGM.GetAddrOfCXXDestructor(Dtor, Dtor_Complete);
61
62 llvm::Value *Args[3] = { llvm::ConstantExpr::getBitCast(DtorFn, DtorFnTy),
63 llvm::ConstantExpr::getBitCast(DeclPtr, Int8PtrTy),
64 llvm::ConstantExpr::getBitCast(Handle, Int8PtrTy) };
65 Builder.CreateCall(AtExitFn, &Args[0], llvm::array_endof(Args));
66}
67
68void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
69 llvm::Constant *DeclPtr) {
70 assert(D.hasGlobalStorage() &&
71 "VarDecl must have global storage!");
72
73 const Expr *Init = D.getInit();
74 QualType T = D.getType();
75
76 if (T->isReferenceType()) {
Anders Carlssonf49ffa92009-08-17 18:24:57 +000077 ErrorUnsupported(Init, "global variable that binds to a reference");
Anders Carlssonf2a022a2009-08-08 21:45:14 +000078 } else if (!hasAggregateLLVMType(T)) {
79 llvm::Value *V = EmitScalarExpr(Init);
80 EmitStoreOfScalar(V, DeclPtr, T.isVolatileQualified(), T);
81 } else if (T->isAnyComplexType()) {
82 EmitComplexExprIntoAddr(Init, DeclPtr, T.isVolatileQualified());
83 } else {
84 EmitAggExpr(Init, DeclPtr, T.isVolatileQualified());
85
86 if (const RecordType *RT = T->getAs<RecordType>()) {
87 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
88 if (!RD->hasTrivialDestructor())
89 EmitCXXGlobalDtorRegistration(RD->getDestructor(getContext()), DeclPtr);
90 }
91 }
92}
93
Anders Carlssoncde4a862009-08-08 23:24:23 +000094void
95CodeGenModule::EmitCXXGlobalInitFunc() {
96 if (CXXGlobalInits.empty())
97 return;
98
Owen Anderson3f5cc0a2009-08-13 21:57:51 +000099 const llvm::FunctionType *FTy = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
Anders Carlssoncde4a862009-08-08 23:24:23 +0000100 false);
101
102 // Create our global initialization function.
103 // FIXME: Should this be tweakable by targets?
104 llvm::Function *Fn =
105 llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
106 "__cxx_global_initialization", &TheModule);
107
108 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
Benjamin Kramer3c1fe262009-08-08 23:43:26 +0000109 &CXXGlobalInits[0],
Anders Carlssoncde4a862009-08-08 23:24:23 +0000110 CXXGlobalInits.size());
111 AddGlobalCtor(Fn);
112}
113
114void CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
115 const VarDecl **Decls,
116 unsigned NumDecls) {
117 StartFunction(0, getContext().VoidTy, Fn, FunctionArgList(),
118 SourceLocation());
119
120 for (unsigned i = 0; i != NumDecls; ++i) {
121 const VarDecl *D = Decls[i];
122
123 llvm::Constant *DeclPtr = CGM.GetAddrOfGlobalVar(D);
124 EmitCXXGlobalVarDeclInit(*D, DeclPtr);
125 }
126 FinishFunction();
127}
128
Anders Carlssonf2a022a2009-08-08 21:45:14 +0000129void
130CodeGenFunction::EmitStaticCXXBlockVarDeclInit(const VarDecl &D,
131 llvm::GlobalVariable *GV) {
Daniel Dunbardea59212009-02-25 19:24:29 +0000132 // FIXME: This should use __cxa_guard_{acquire,release}?
133
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000134 assert(!getContext().getLangOptions().ThreadsafeStatics &&
135 "thread safe statics are currently not supported!");
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000136
Anders Carlsson33e65e52009-04-13 18:03:33 +0000137 llvm::SmallString<256> GuardVName;
138 llvm::raw_svector_ostream GuardVOut(GuardVName);
139 mangleGuardVariable(&D, getContext(), GuardVOut);
140
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000141 // Create the guard variable.
142 llvm::GlobalValue *GuardV =
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000143 new llvm::GlobalVariable(CGM.getModule(), llvm::Type::getInt64Ty(VMContext), false,
Daniel Dunbardea59212009-02-25 19:24:29 +0000144 GV->getLinkage(),
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000145 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext)),
Daniel Dunbar0433a022009-08-19 20:04:03 +0000146 GuardVName.str());
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000147
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000148 // Load the first byte of the guard variable.
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000149 const llvm::Type *PtrTy = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000150 llvm::Value *V = Builder.CreateLoad(Builder.CreateBitCast(GuardV, PtrTy),
151 "tmp");
152
153 // Compare it against 0.
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000154 llvm::Value *nullValue = llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext));
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000155 llvm::Value *ICmp = Builder.CreateICmpEQ(V, nullValue , "tobool");
156
Daniel Dunbar72f96552008-11-11 02:29:29 +0000157 llvm::BasicBlock *InitBlock = createBasicBlock("init");
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +0000158 llvm::BasicBlock *EndBlock = createBasicBlock("init.end");
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000159
160 // If the guard variable is 0, jump to the initializer code.
161 Builder.CreateCondBr(ICmp, InitBlock, EndBlock);
162
163 EmitBlock(InitBlock);
164
Anders Carlssonf2a022a2009-08-08 21:45:14 +0000165 EmitCXXGlobalVarDeclInit(D, GV);
166
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000167 Builder.CreateStore(llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext), 1),
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000168 Builder.CreateBitCast(GuardV, PtrTy));
169
170 EmitBlock(EndBlock);
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000171}
172
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000173RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
174 llvm::Value *Callee,
175 llvm::Value *This,
176 CallExpr::const_arg_iterator ArgBeg,
177 CallExpr::const_arg_iterator ArgEnd) {
178 assert(MD->isInstance() &&
179 "Trying to emit a member call expr on a static method!");
180
181 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
182
183 CallArgList Args;
184
185 // Push the this ptr.
186 Args.push_back(std::make_pair(RValue::get(This),
187 MD->getThisType(getContext())));
188
189 // And the rest of the call args
190 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
191
192 QualType ResultType = MD->getType()->getAsFunctionType()->getResultType();
193 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args),
194 Callee, Args, MD);
195}
196
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000197RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE) {
198 const MemberExpr *ME = cast<MemberExpr>(CE->getCallee());
199 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000200
Anders Carlssonc5223142009-04-08 20:31:57 +0000201 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
Mike Stumpc37c8812009-07-30 21:47:44 +0000202
Mike Stump7e8c9932009-07-31 18:25:34 +0000203 if (MD->isVirtual()) {
Mike Stumpc37c8812009-07-30 21:47:44 +0000204 ErrorUnsupported(CE, "virtual dispatch");
205 }
206
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000207 const llvm::Type *Ty =
Anders Carlssonc5223142009-04-08 20:31:57 +0000208 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
209 FPT->isVariadic());
Chris Lattner80f39cc2009-05-12 21:21:08 +0000210 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty);
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000211
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000212 llvm::Value *This;
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000213
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000214 if (ME->isArrow())
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000215 This = EmitScalarExpr(ME->getBase());
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000216 else {
217 LValue BaseLV = EmitLValue(ME->getBase());
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000218 This = BaseLV.getAddress();
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000219 }
220
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000221 return EmitCXXMemberCall(MD, Callee, This,
222 CE->arg_begin(), CE->arg_end());
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000223}
Anders Carlsson49d4a572009-04-14 16:58:56 +0000224
Anders Carlsson85eca6f2009-05-27 04:18:27 +0000225RValue
226CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
227 const CXXMethodDecl *MD) {
228 assert(MD->isInstance() &&
229 "Trying to emit a member call expr on a static method!");
230
Fariborz Jahanian9da58e42009-08-13 21:09:41 +0000231 if (MD->isCopyAssignment()) {
232 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(MD->getDeclContext());
233 if (ClassDecl->hasTrivialCopyAssignment()) {
234 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
235 "EmitCXXOperatorMemberCallExpr - user declared copy assignment");
236 llvm::Value *This = EmitLValue(E->getArg(0)).getAddress();
237 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
238 QualType Ty = E->getType();
239 EmitAggregateCopy(This, Src, Ty);
240 return RValue::get(This);
241 }
242 }
Anders Carlsson85eca6f2009-05-27 04:18:27 +0000243
244 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
245 const llvm::Type *Ty =
246 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
247 FPT->isVariadic());
248 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty);
249
250 llvm::Value *This = EmitLValue(E->getArg(0)).getAddress();
251
252 return EmitCXXMemberCall(MD, Callee, This,
253 E->arg_begin() + 1, E->arg_end());
254}
255
Anders Carlsson49d4a572009-04-14 16:58:56 +0000256llvm::Value *CodeGenFunction::LoadCXXThis() {
257 assert(isa<CXXMethodDecl>(CurFuncDecl) &&
258 "Must be in a C++ member function decl to load 'this'");
259 assert(cast<CXXMethodDecl>(CurFuncDecl)->isInstance() &&
260 "Must be in a C++ member function decl to load 'this'");
261
262 // FIXME: What if we're inside a block?
Mike Stumpba2cb0e2009-05-16 07:57:57 +0000263 // ans: See how CodeGenFunction::LoadObjCSelf() uses
264 // CodeGenFunction::BlockForwardSelf() for how to do this.
Anders Carlsson49d4a572009-04-14 16:58:56 +0000265 return Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
266}
Anders Carlsson652951a2009-04-15 15:55:24 +0000267
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000268static bool
269GetNestedPaths(llvm::SmallVectorImpl<const CXXRecordDecl *> &NestedBasePaths,
270 const CXXRecordDecl *ClassDecl,
271 const CXXRecordDecl *BaseClassDecl) {
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000272 for (CXXRecordDecl::base_class_const_iterator i = ClassDecl->bases_begin(),
273 e = ClassDecl->bases_end(); i != e; ++i) {
274 if (i->isVirtual())
275 continue;
276 const CXXRecordDecl *Base =
Mike Stumpf3371782009-08-04 21:58:42 +0000277 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000278 if (Base == BaseClassDecl) {
279 NestedBasePaths.push_back(BaseClassDecl);
280 return true;
281 }
282 }
283 // BaseClassDecl not an immediate base of ClassDecl.
284 for (CXXRecordDecl::base_class_const_iterator i = ClassDecl->bases_begin(),
285 e = ClassDecl->bases_end(); i != e; ++i) {
286 if (i->isVirtual())
287 continue;
288 const CXXRecordDecl *Base =
289 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
290 if (GetNestedPaths(NestedBasePaths, Base, BaseClassDecl)) {
291 NestedBasePaths.push_back(Base);
292 return true;
293 }
294 }
295 return false;
296}
297
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000298llvm::Value *CodeGenFunction::AddressCXXOfBaseClass(llvm::Value *BaseValue,
Fariborz Jahanian70277012009-07-28 18:09:28 +0000299 const CXXRecordDecl *ClassDecl,
300 const CXXRecordDecl *BaseClassDecl) {
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000301 if (ClassDecl == BaseClassDecl)
302 return BaseValue;
303
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000304 llvm::Type *I8Ptr = llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000305 llvm::SmallVector<const CXXRecordDecl *, 16> NestedBasePaths;
306 GetNestedPaths(NestedBasePaths, ClassDecl, BaseClassDecl);
307 assert(NestedBasePaths.size() > 0 &&
308 "AddressCXXOfBaseClass - inheritence path failed");
309 NestedBasePaths.push_back(ClassDecl);
310 uint64_t Offset = 0;
311
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000312 // Accessing a member of the base class. Must add delata to
313 // the load of 'this'.
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000314 for (unsigned i = NestedBasePaths.size()-1; i > 0; i--) {
315 const CXXRecordDecl *DerivedClass = NestedBasePaths[i];
316 const CXXRecordDecl *BaseClass = NestedBasePaths[i-1];
317 const ASTRecordLayout &Layout =
318 getContext().getASTRecordLayout(DerivedClass);
319 Offset += Layout.getBaseClassOffset(BaseClass) / 8;
320 }
Fariborz Jahanian83a46ed2009-07-29 15:54:56 +0000321 llvm::Value *OffsetVal =
322 llvm::ConstantInt::get(
323 CGM.getTypes().ConvertType(CGM.getContext().LongTy), Offset);
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000324 BaseValue = Builder.CreateBitCast(BaseValue, I8Ptr);
325 BaseValue = Builder.CreateGEP(BaseValue, OffsetVal, "add.ptr");
326 QualType BTy =
327 getContext().getCanonicalType(
Fariborz Jahanian70277012009-07-28 18:09:28 +0000328 getContext().getTypeDeclType(const_cast<CXXRecordDecl*>(BaseClassDecl)));
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000329 const llvm::Type *BasePtr = ConvertType(BTy);
Owen Anderson7ec2d8f2009-07-29 22:16:19 +0000330 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000331 BaseValue = Builder.CreateBitCast(BaseValue, BasePtr);
332 return BaseValue;
333}
334
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000335/// EmitCXXAggrConstructorCall - This routine essentially creates a (nested)
336/// for-loop to call the default constructor on individual members of the
337/// array. 'Array' is the array type, 'This' is llvm pointer of the start
338/// of the array and 'D' is the default costructor Decl for elements of the
339/// array. It is assumed that all relevant checks have been made by the
340/// caller.
341void
342CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
343 const ArrayType *Array,
344 llvm::Value *This) {
345 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
346 assert(CA && "Do we support VLA for construction ?");
347
348 // Create a temporary for the loop index and initialize it with 0.
Fariborz Jahaniandae3e752009-08-21 16:31:06 +0000349 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000350 "loop.index");
351 llvm::Value* zeroConstant =
Fariborz Jahaniandae3e752009-08-21 16:31:06 +0000352 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000353 Builder.CreateStore(zeroConstant, IndexPtr, false);
354
355 // Start the loop with a block that tests the condition.
356 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
357 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
358
359 EmitBlock(CondBlock);
360
361 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
362
363 // Generate: if (loop-index < number-of-elements fall to the loop body,
364 // otherwise, go to the block after the for-loop.
365 uint64_t NumElements = CA->getSize().getZExtValue();
366 llvm::Value * NumElementsPtr =
Fariborz Jahaniandae3e752009-08-21 16:31:06 +0000367 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000368 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
369 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
370 "isless");
371 // If the condition is true, execute the body.
372 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
373
374 EmitBlock(ForBody);
375
376 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000377 // Inside the loop body, emit the constructor call on the array element.
Fariborz Jahaniana0ab7352009-08-20 01:01:06 +0000378 Counter = Builder.CreateLoad(IndexPtr);
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000379 if (const ConstantArrayType *CAT =
380 dyn_cast<ConstantArrayType>(Array->getElementType())) {
Fariborz Jahaniandae3e752009-08-21 16:31:06 +0000381 uint64_t delta = getContext().getConstantArrayElementCount(CAT);
Fariborz Jahaniana0ab7352009-08-20 01:01:06 +0000382 // Address = This + delta*Counter for current loop iteration.
Fariborz Jahanianf36f8d22009-08-20 00:15:15 +0000383 llvm::Value *DeltaPtr =
Fariborz Jahaniandae3e752009-08-21 16:31:06 +0000384 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), delta);
Fariborz Jahanianf36f8d22009-08-20 00:15:15 +0000385 DeltaPtr = Builder.CreateMul(Counter, DeltaPtr, "mul");
386 llvm::Value *Address =
387 Builder.CreateInBoundsGEP(This, DeltaPtr, "arrayidx");
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000388 EmitCXXAggrConstructorCall(D, CAT, Address);
389 }
Fariborz Jahanianf36f8d22009-08-20 00:15:15 +0000390 else {
Fariborz Jahanianf36f8d22009-08-20 00:15:15 +0000391 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000392 EmitCXXConstructorCall(D, Ctor_Complete, Address, 0, 0);
Fariborz Jahanianf36f8d22009-08-20 00:15:15 +0000393 }
394
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000395 EmitBlock(ContinueBlock);
396
397 // Emit the increment of the loop counter.
398 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
399 Counter = Builder.CreateLoad(IndexPtr);
400 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
401 Builder.CreateStore(NextVal, IndexPtr, false);
402
403 // Finally, branch back up to the condition for the next iteration.
404 EmitBranch(CondBlock);
405
406 // Emit the fall-through block.
407 EmitBlock(AfterFor, true);
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000408}
409
Fariborz Jahanian25879ce2009-08-20 23:02:58 +0000410/// EmitCXXAggrDestructorCall - calls the default destructor on array
411/// elements in reverse order of construction.
Anders Carlsson72f48292009-04-17 00:06:03 +0000412void
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +0000413CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
414 const ArrayType *Array,
415 llvm::Value *This) {
Fariborz Jahanian25879ce2009-08-20 23:02:58 +0000416 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
417 assert(CA && "Do we support VLA for destruction ?");
418 llvm::Value *One = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
419 1);
Fariborz Jahaniandae3e752009-08-21 16:31:06 +0000420 uint64_t ElementCount = getContext().getConstantArrayElementCount(CA);
Fariborz Jahanian25879ce2009-08-20 23:02:58 +0000421 // Create a temporary for the loop index and initialize it with count of
422 // array elements.
423 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
424 "loop.index");
425 // Index = ElementCount;
426 llvm::Value* UpperCount =
427 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), ElementCount);
428 Builder.CreateStore(UpperCount, IndexPtr, false);
429
430 // Start the loop with a block that tests the condition.
431 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
432 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
433
434 EmitBlock(CondBlock);
435
436 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
437
438 // Generate: if (loop-index != 0 fall to the loop body,
439 // otherwise, go to the block after the for-loop.
440 llvm::Value* zeroConstant =
441 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
442 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
443 llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant,
444 "isne");
445 // If the condition is true, execute the body.
446 Builder.CreateCondBr(IsNE, ForBody, AfterFor);
447
448 EmitBlock(ForBody);
449
450 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
451 // Inside the loop body, emit the constructor call on the array element.
452 Counter = Builder.CreateLoad(IndexPtr);
453 Counter = Builder.CreateSub(Counter, One);
454 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
455 EmitCXXDestructorCall(D, Dtor_Complete, Address);
456
457 EmitBlock(ContinueBlock);
458
459 // Emit the decrement of the loop counter.
460 Counter = Builder.CreateLoad(IndexPtr);
461 Counter = Builder.CreateSub(Counter, One, "dec");
462 Builder.CreateStore(Counter, IndexPtr, false);
463
464 // Finally, branch back up to the condition for the next iteration.
465 EmitBranch(CondBlock);
466
467 // Emit the fall-through block.
468 EmitBlock(AfterFor, true);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +0000469}
470
471void
Anders Carlsson72f48292009-04-17 00:06:03 +0000472CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
473 CXXCtorType Type,
474 llvm::Value *This,
475 CallExpr::const_arg_iterator ArgBeg,
476 CallExpr::const_arg_iterator ArgEnd) {
Fariborz Jahanian0fc5f252009-08-14 20:11:43 +0000477 if (D->isCopyConstructor(getContext())) {
478 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D->getDeclContext());
479 if (ClassDecl->hasTrivialCopyConstructor()) {
480 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
481 "EmitCXXConstructorCall - user declared copy constructor");
482 const Expr *E = (*ArgBeg);
483 QualType Ty = E->getType();
484 llvm::Value *Src = EmitLValue(E).getAddress();
485 EmitAggregateCopy(This, Src, Ty);
486 return;
487 }
488 }
489
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000490 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
491
492 EmitCXXMemberCall(D, Callee, This, ArgBeg, ArgEnd);
Anders Carlsson72f48292009-04-17 00:06:03 +0000493}
494
Anders Carlssond3f6b162009-05-29 21:03:38 +0000495void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *D,
496 CXXDtorType Type,
497 llvm::Value *This) {
498 llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(D, Type);
499
500 EmitCXXMemberCall(D, Callee, This, 0, 0);
501}
502
Anders Carlsson72f48292009-04-17 00:06:03 +0000503void
Anders Carlsson342aadc2009-05-03 17:47:16 +0000504CodeGenFunction::EmitCXXConstructExpr(llvm::Value *Dest,
505 const CXXConstructExpr *E) {
Anders Carlsson72f48292009-04-17 00:06:03 +0000506 assert(Dest && "Must have a destination!");
507
508 const CXXRecordDecl *RD =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000509 cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson72f48292009-04-17 00:06:03 +0000510 if (RD->hasTrivialConstructor())
511 return;
Fariborz Jahanian884036a2009-08-06 01:02:49 +0000512
513 // Code gen optimization to eliminate copy constructor and return
514 // its first argument instead.
Fariborz Jahanian325cdd82009-08-06 19:12:38 +0000515 if (E->isElidable()) {
Fariborz Jahanian884036a2009-08-06 01:02:49 +0000516 CXXConstructExpr::const_arg_iterator i = E->arg_begin();
Fariborz Jahanian325cdd82009-08-06 19:12:38 +0000517 EmitAggExpr((*i), Dest, false);
518 return;
Fariborz Jahanian884036a2009-08-06 01:02:49 +0000519 }
Anders Carlsson72f48292009-04-17 00:06:03 +0000520 // Call the constructor.
521 EmitCXXConstructorCall(E->getConstructor(), Ctor_Complete, Dest,
522 E->arg_begin(), E->arg_end());
523}
524
Anders Carlsson18e88bc2009-05-31 01:40:14 +0000525llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
Anders Carlssond5536972009-05-31 20:21:44 +0000526 if (E->isArray()) {
527 ErrorUnsupported(E, "new[] expression");
Owen Andersone0b5eff2009-07-30 23:11:26 +0000528 return llvm::UndefValue::get(ConvertType(E->getType()));
Anders Carlssond5536972009-05-31 20:21:44 +0000529 }
530
531 QualType AllocType = E->getAllocatedType();
532 FunctionDecl *NewFD = E->getOperatorNew();
533 const FunctionProtoType *NewFTy = NewFD->getType()->getAsFunctionProtoType();
534
535 CallArgList NewArgs;
536
537 // The allocation size is the first argument.
538 QualType SizeTy = getContext().getSizeType();
539 llvm::Value *AllocSize =
Owen Andersonb17ec712009-07-24 23:12:58 +0000540 llvm::ConstantInt::get(ConvertType(SizeTy),
Anders Carlssond5536972009-05-31 20:21:44 +0000541 getContext().getTypeSize(AllocType) / 8);
542
543 NewArgs.push_back(std::make_pair(RValue::get(AllocSize), SizeTy));
544
545 // Emit the rest of the arguments.
546 // FIXME: Ideally, this should just use EmitCallArgs.
547 CXXNewExpr::const_arg_iterator NewArg = E->placement_arg_begin();
548
549 // First, use the types from the function type.
550 // We start at 1 here because the first argument (the allocation size)
551 // has already been emitted.
552 for (unsigned i = 1, e = NewFTy->getNumArgs(); i != e; ++i, ++NewArg) {
553 QualType ArgType = NewFTy->getArgType(i);
554
555 assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
556 getTypePtr() ==
557 getContext().getCanonicalType(NewArg->getType()).getTypePtr() &&
558 "type mismatch in call argument!");
559
560 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
561 ArgType));
562
563 }
564
565 // Either we've emitted all the call args, or we have a call to a
566 // variadic function.
567 assert((NewArg == E->placement_arg_end() || NewFTy->isVariadic()) &&
568 "Extra arguments in non-variadic function!");
569
570 // If we still have any arguments, emit them using the type of the argument.
571 for (CXXNewExpr::const_arg_iterator NewArgEnd = E->placement_arg_end();
572 NewArg != NewArgEnd; ++NewArg) {
573 QualType ArgType = NewArg->getType();
574 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
575 ArgType));
576 }
577
578 // Emit the call to new.
579 RValue RV =
580 EmitCall(CGM.getTypes().getFunctionInfo(NewFTy->getResultType(), NewArgs),
581 CGM.GetAddrOfFunction(GlobalDecl(NewFD)),
582 NewArgs, NewFD);
583
Anders Carlsson11269042009-05-31 21:53:59 +0000584 // If an allocation function is declared with an empty exception specification
585 // it returns null to indicate failure to allocate storage. [expr.new]p13.
586 // (We don't need to check for null when there's no new initializer and
587 // we're allocating a POD type).
588 bool NullCheckResult = NewFTy->hasEmptyExceptionSpec() &&
589 !(AllocType->isPODType() && !E->hasInitializer());
Anders Carlssond5536972009-05-31 20:21:44 +0000590
Anders Carlssondbee9a52009-06-01 00:05:16 +0000591 llvm::BasicBlock *NewNull = 0;
592 llvm::BasicBlock *NewNotNull = 0;
593 llvm::BasicBlock *NewEnd = 0;
594
595 llvm::Value *NewPtr = RV.getScalarVal();
596
Anders Carlsson11269042009-05-31 21:53:59 +0000597 if (NullCheckResult) {
Anders Carlssondbee9a52009-06-01 00:05:16 +0000598 NewNull = createBasicBlock("new.null");
599 NewNotNull = createBasicBlock("new.notnull");
600 NewEnd = createBasicBlock("new.end");
601
602 llvm::Value *IsNull =
603 Builder.CreateICmpEQ(NewPtr,
Owen Andersonf37b84b2009-07-31 20:28:54 +0000604 llvm::Constant::getNullValue(NewPtr->getType()),
Anders Carlssondbee9a52009-06-01 00:05:16 +0000605 "isnull");
606
607 Builder.CreateCondBr(IsNull, NewNull, NewNotNull);
608 EmitBlock(NewNotNull);
Anders Carlsson11269042009-05-31 21:53:59 +0000609 }
610
Anders Carlssondbee9a52009-06-01 00:05:16 +0000611 NewPtr = Builder.CreateBitCast(NewPtr, ConvertType(E->getType()));
Anders Carlsson11269042009-05-31 21:53:59 +0000612
Anders Carlsson7c294782009-05-31 20:56:36 +0000613 if (AllocType->isPODType()) {
Anders Carlsson26910f62009-06-01 00:26:14 +0000614 if (E->getNumConstructorArgs() > 0) {
Anders Carlsson7c294782009-05-31 20:56:36 +0000615 assert(E->getNumConstructorArgs() == 1 &&
616 "Can only have one argument to initializer of POD type.");
617
618 const Expr *Init = E->getConstructorArg(0);
619
Anders Carlsson5f93ccf2009-05-31 21:07:58 +0000620 if (!hasAggregateLLVMType(AllocType))
Anders Carlsson7c294782009-05-31 20:56:36 +0000621 Builder.CreateStore(EmitScalarExpr(Init), NewPtr);
Anders Carlsson5f93ccf2009-05-31 21:07:58 +0000622 else if (AllocType->isAnyComplexType())
623 EmitComplexExprIntoAddr(Init, NewPtr, AllocType.isVolatileQualified());
Anders Carlssoneb39b432009-05-31 21:12:26 +0000624 else
625 EmitAggExpr(Init, NewPtr, AllocType.isVolatileQualified());
Anders Carlsson7c294782009-05-31 20:56:36 +0000626 }
Anders Carlsson11269042009-05-31 21:53:59 +0000627 } else {
628 // Call the constructor.
629 CXXConstructorDecl *Ctor = E->getConstructor();
Anders Carlsson7c294782009-05-31 20:56:36 +0000630
Anders Carlsson11269042009-05-31 21:53:59 +0000631 EmitCXXConstructorCall(Ctor, Ctor_Complete, NewPtr,
632 E->constructor_arg_begin(),
633 E->constructor_arg_end());
Anders Carlssond5536972009-05-31 20:21:44 +0000634 }
Anders Carlsson11269042009-05-31 21:53:59 +0000635
Anders Carlssondbee9a52009-06-01 00:05:16 +0000636 if (NullCheckResult) {
637 Builder.CreateBr(NewEnd);
638 EmitBlock(NewNull);
639 Builder.CreateBr(NewEnd);
640 EmitBlock(NewEnd);
641
642 llvm::PHINode *PHI = Builder.CreatePHI(NewPtr->getType());
643 PHI->reserveOperandSpace(2);
644 PHI->addIncoming(NewPtr, NewNotNull);
Owen Andersonf37b84b2009-07-31 20:28:54 +0000645 PHI->addIncoming(llvm::Constant::getNullValue(NewPtr->getType()), NewNull);
Anders Carlssondbee9a52009-06-01 00:05:16 +0000646
647 NewPtr = PHI;
648 }
649
Anders Carlsson11269042009-05-31 21:53:59 +0000650 return NewPtr;
Anders Carlsson18e88bc2009-05-31 01:40:14 +0000651}
652
Anders Carlsson133fdaf2009-08-16 21:13:42 +0000653void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
654 if (E->isArrayForm()) {
655 ErrorUnsupported(E, "delete[] expression");
656 return;
657 };
658
659 QualType DeleteTy =
660 E->getArgument()->getType()->getAs<PointerType>()->getPointeeType();
661
662 llvm::Value *Ptr = EmitScalarExpr(E->getArgument());
663
664 // Null check the pointer.
665 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
666 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
667
668 llvm::Value *IsNull =
669 Builder.CreateICmpEQ(Ptr, llvm::Constant::getNullValue(Ptr->getType()),
670 "isnull");
671
672 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
673 EmitBlock(DeleteNotNull);
674
675 // Call the destructor if necessary.
676 if (const RecordType *RT = DeleteTy->getAs<RecordType>()) {
677 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
678 if (!RD->hasTrivialDestructor()) {
679 const CXXDestructorDecl *Dtor = RD->getDestructor(getContext());
680 if (Dtor->isVirtual()) {
681 ErrorUnsupported(E, "delete expression with virtual destructor");
682 return;
683 }
684
685 EmitCXXDestructorCall(Dtor, Dtor_Complete, Ptr);
686 }
687 }
688 }
689
690 // Call delete.
691 FunctionDecl *DeleteFD = E->getOperatorDelete();
692 const FunctionProtoType *DeleteFTy =
693 DeleteFD->getType()->getAsFunctionProtoType();
694
695 CallArgList DeleteArgs;
696
697 QualType ArgTy = DeleteFTy->getArgType(0);
698 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
699 DeleteArgs.push_back(std::make_pair(RValue::get(DeletePtr), ArgTy));
700
701 // Emit the call to delete.
702 EmitCall(CGM.getTypes().getFunctionInfo(DeleteFTy->getResultType(),
703 DeleteArgs),
704 CGM.GetAddrOfFunction(GlobalDecl(DeleteFD)),
705 DeleteArgs, DeleteFD);
706
707 EmitBlock(DeleteEnd);
708}
709
Anders Carlsson4811c302009-04-17 01:58:57 +0000710static bool canGenerateCXXstructor(const CXXRecordDecl *RD,
711 ASTContext &Context) {
Anders Carlsson8496c692009-04-15 21:02:13 +0000712 // The class has base classes - we don't support that right now.
713 if (RD->getNumBases() > 0)
714 return false;
715
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000716 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
717 I != E; ++I) {
Anders Carlsson8496c692009-04-15 21:02:13 +0000718 // We don't support ctors for fields that aren't POD.
719 if (!I->getType()->isPODType())
720 return false;
721 }
722
723 return true;
724}
725
Anders Carlsson652951a2009-04-15 15:55:24 +0000726void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) {
Anders Carlsson4811c302009-04-17 01:58:57 +0000727 if (!canGenerateCXXstructor(D->getParent(), getContext())) {
Anders Carlsson8496c692009-04-15 21:02:13 +0000728 ErrorUnsupported(D, "C++ constructor", true);
729 return;
730 }
Anders Carlsson652951a2009-04-15 15:55:24 +0000731
Anders Carlsson1764af42009-05-05 04:44:02 +0000732 EmitGlobal(GlobalDecl(D, Ctor_Complete));
733 EmitGlobal(GlobalDecl(D, Ctor_Base));
Anders Carlsson652951a2009-04-15 15:55:24 +0000734}
Anders Carlsson890a9fd2009-04-16 23:57:24 +0000735
Anders Carlsson4811c302009-04-17 01:58:57 +0000736void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D,
737 CXXCtorType Type) {
738
739 llvm::Function *Fn = GetAddrOfCXXConstructor(D, Type);
740
741 CodeGenFunction(*this).GenerateCode(D, Fn);
742
743 SetFunctionDefinitionAttributes(D, Fn);
744 SetLLVMFunctionAttributesForDefinition(D, Fn);
745}
746
Anders Carlsson890a9fd2009-04-16 23:57:24 +0000747llvm::Function *
748CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
749 CXXCtorType Type) {
750 const llvm::FunctionType *FTy =
751 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false);
752
753 const char *Name = getMangledCXXCtorName(D, Type);
Chris Lattner80f39cc2009-05-12 21:21:08 +0000754 return cast<llvm::Function>(
755 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson890a9fd2009-04-16 23:57:24 +0000756}
Anders Carlsson4811c302009-04-17 01:58:57 +0000757
758const char *CodeGenModule::getMangledCXXCtorName(const CXXConstructorDecl *D,
759 CXXCtorType Type) {
760 llvm::SmallString<256> Name;
761 llvm::raw_svector_ostream Out(Name);
762 mangleCXXCtor(D, Type, Context, Out);
763
764 Name += '\0';
765 return UniqueMangledName(Name.begin(), Name.end());
766}
767
768void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) {
769 if (!canGenerateCXXstructor(D->getParent(), getContext())) {
770 ErrorUnsupported(D, "C++ destructor", true);
771 return;
772 }
773
774 EmitCXXDestructor(D, Dtor_Complete);
775 EmitCXXDestructor(D, Dtor_Base);
776}
777
778void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D,
779 CXXDtorType Type) {
780 llvm::Function *Fn = GetAddrOfCXXDestructor(D, Type);
781
782 CodeGenFunction(*this).GenerateCode(D, Fn);
783
784 SetFunctionDefinitionAttributes(D, Fn);
785 SetLLVMFunctionAttributesForDefinition(D, Fn);
786}
787
788llvm::Function *
789CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D,
790 CXXDtorType Type) {
791 const llvm::FunctionType *FTy =
792 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false);
793
794 const char *Name = getMangledCXXDtorName(D, Type);
Chris Lattner80f39cc2009-05-12 21:21:08 +0000795 return cast<llvm::Function>(
796 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson4811c302009-04-17 01:58:57 +0000797}
798
799const char *CodeGenModule::getMangledCXXDtorName(const CXXDestructorDecl *D,
800 CXXDtorType Type) {
801 llvm::SmallString<256> Name;
802 llvm::raw_svector_ostream Out(Name);
803 mangleCXXDtor(D, Type, Context, Out);
804
805 Name += '\0';
806 return UniqueMangledName(Name.begin(), Name.end());
807}
Fariborz Jahanian5400e022009-07-20 23:18:55 +0000808
Mike Stumpdca5e512009-08-18 21:49:00 +0000809llvm::Constant *CodeGenModule::GenerateRtti(const CXXRecordDecl *RD) {
Mike Stump00df7d32009-07-31 23:15:31 +0000810 llvm::Type *Ptr8Ty;
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000811 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Mike Stump69a12322009-08-04 20:06:48 +0000812 llvm::Constant *Rtti = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stump00df7d32009-07-31 23:15:31 +0000813
814 if (!getContext().getLangOptions().Rtti)
Mike Stump69a12322009-08-04 20:06:48 +0000815 return Rtti;
Mike Stump00df7d32009-07-31 23:15:31 +0000816
817 llvm::SmallString<256> OutName;
818 llvm::raw_svector_ostream Out(OutName);
819 QualType ClassTy;
Mike Stumpe7545622009-08-07 18:05:12 +0000820 ClassTy = getContext().getTagDeclType(RD);
Mike Stump00df7d32009-07-31 23:15:31 +0000821 mangleCXXRtti(ClassTy, getContext(), Out);
Mike Stump00df7d32009-07-31 23:15:31 +0000822 llvm::GlobalVariable::LinkageTypes linktype;
823 linktype = llvm::GlobalValue::WeakAnyLinkage;
824 std::vector<llvm::Constant *> info;
Mike Stump2eade572009-08-13 22:53:07 +0000825 // assert(0 && "FIXME: implement rtti descriptor");
Mike Stump00df7d32009-07-31 23:15:31 +0000826 // FIXME: descriptor
827 info.push_back(llvm::Constant::getNullValue(Ptr8Ty));
Mike Stump2eade572009-08-13 22:53:07 +0000828 // assert(0 && "FIXME: implement rtti ts");
Mike Stump00df7d32009-07-31 23:15:31 +0000829 // FIXME: TS
830 info.push_back(llvm::Constant::getNullValue(Ptr8Ty));
831
832 llvm::Constant *C;
833 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, info.size());
834 C = llvm::ConstantArray::get(type, info);
Mike Stumpdca5e512009-08-18 21:49:00 +0000835 Rtti = new llvm::GlobalVariable(getModule(), type, true, linktype, C,
Daniel Dunbar0433a022009-08-19 20:04:03 +0000836 Out.str());
Mike Stump69a12322009-08-04 20:06:48 +0000837 Rtti = llvm::ConstantExpr::getBitCast(Rtti, Ptr8Ty);
838 return Rtti;
Mike Stump00df7d32009-07-31 23:15:31 +0000839}
840
Mike Stump86a859e2009-08-19 18:10:47 +0000841class VtableBuilder {
Mike Stumpad734d12009-08-18 20:50:28 +0000842 std::vector<llvm::Constant *> &methods;
843 llvm::Type *Ptr8Ty;
Mike Stumpf07ede52009-08-21 01:45:00 +0000844 /// Class - The most derived class that this vtable is being built for.
Mike Stumpdca5e512009-08-18 21:49:00 +0000845 const CXXRecordDecl *Class;
Mike Stumpf07ede52009-08-21 01:45:00 +0000846 /// BLayout - Layout for the most derived class that this vtable is being
847 /// built for.
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000848 const ASTRecordLayout &BLayout;
Mike Stumpa7ec675d2009-08-19 14:40:47 +0000849 llvm::SmallSet<const CXXRecordDecl *, 32> IndirectPrimary;
Mike Stump2b9ba612009-08-20 02:11:48 +0000850 llvm::SmallSet<const CXXRecordDecl *, 32> SeenVBase;
Mike Stumpdca5e512009-08-18 21:49:00 +0000851 llvm::Constant *rtti;
Mike Stumpad734d12009-08-18 20:50:28 +0000852 llvm::LLVMContext &VMContext;
Mike Stump1e10cf32009-08-18 21:03:28 +0000853 CodeGenModule &CGM; // Per-module state.
Mike Stumpf07ede52009-08-21 01:45:00 +0000854 /// Index - Maps a method decl into a vtable index. Useful for virtual
855 /// dispatch codegen.
856 llvm::DenseMap<const CXXMethodDecl *, int32_t> Index;
Mike Stumpd75d3232009-08-18 22:04:08 +0000857 typedef CXXRecordDecl::method_iterator method_iter;
Mike Stumpad734d12009-08-18 20:50:28 +0000858public:
Mike Stump86a859e2009-08-19 18:10:47 +0000859 VtableBuilder(std::vector<llvm::Constant *> &meth,
860 const CXXRecordDecl *c,
861 CodeGenModule &cgm)
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000862 : methods(meth), Class(c), BLayout(cgm.getContext().getASTRecordLayout(c)),
863 rtti(cgm.GenerateRtti(c)), VMContext(cgm.getModule().getContext()),
864 CGM(cgm) {
Mike Stumpad734d12009-08-18 20:50:28 +0000865 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
866 }
Mike Stumpdca5e512009-08-18 21:49:00 +0000867
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000868 llvm::Constant *GenerateVcall(const CXXMethodDecl *MD,
869 const CXXRecordDecl *RD,
870 bool VBoundary,
871 bool SecondaryVirtual) {
872 llvm::Constant *m = 0;
873
874 // FIXME: vcall: offset for virtual base for this function
875 if (SecondaryVirtual || VBoundary)
876 m = llvm::Constant::getNullValue(Ptr8Ty);
877 return m;
878 }
879
880 void GenerateVcalls(const CXXRecordDecl *RD, bool VBoundary,
881 bool SecondaryVirtual) {
Mike Stumpad734d12009-08-18 20:50:28 +0000882 llvm::Constant *m;
Mike Stump23b238e2009-08-12 23:25:18 +0000883
Mike Stumpd75d3232009-08-18 22:04:08 +0000884 for (method_iter mi = RD->method_begin(),
Mike Stumpad734d12009-08-18 20:50:28 +0000885 me = RD->method_end(); mi != me; ++mi) {
886 if (mi->isVirtual()) {
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000887 m = GenerateVcall(*mi, RD, VBoundary, SecondaryVirtual);
888 if (m)
889 methods.push_back(m);
Mike Stumpad734d12009-08-18 20:50:28 +0000890 }
Mike Stumpf640de52009-08-12 23:14:12 +0000891 }
Mike Stump23b238e2009-08-12 23:25:18 +0000892 }
Mike Stumpf640de52009-08-12 23:14:12 +0000893
Mike Stump2b9ba612009-08-20 02:11:48 +0000894 void GenerateVBaseOffsets(std::vector<llvm::Constant *> &offsets,
Mike Stumpaf0d0452009-08-20 07:22:17 +0000895 const CXXRecordDecl *RD, uint64_t Offset) {
Mike Stump2b9ba612009-08-20 02:11:48 +0000896 for (CXXRecordDecl::base_class_const_iterator i =RD->bases_begin(),
897 e = RD->bases_end(); i != e; ++i) {
898 const CXXRecordDecl *Base =
899 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
900 if (i->isVirtual() && !SeenVBase.count(Base)) {
901 SeenVBase.insert(Base);
Mike Stumpaf0d0452009-08-20 07:22:17 +0000902 int64_t BaseOffset = -(Offset/8) + BLayout.getVBaseClassOffset(Base)/8;
Mike Stump2b9ba612009-08-20 02:11:48 +0000903 llvm::Constant *m;
Mike Stumpaf0d0452009-08-20 07:22:17 +0000904 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),BaseOffset);
Mike Stump2b9ba612009-08-20 02:11:48 +0000905 m = llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
906 offsets.push_back(m);
907 }
Mike Stumpaf0d0452009-08-20 07:22:17 +0000908 GenerateVBaseOffsets(offsets, Base, Offset);
Mike Stump2b9ba612009-08-20 02:11:48 +0000909 }
910 }
911
Mike Stumpf07ede52009-08-21 01:45:00 +0000912 void StartNewTable() {
913 SeenVBase.clear();
914 }
Mike Stumpdecd7812009-08-12 23:00:59 +0000915
Mike Stumpf07ede52009-08-21 01:45:00 +0000916 inline uint32_t nottoobig(uint64_t t) {
917 assert(t < (uint32_t)-1ULL || "vtable too big");
918 return t;
919 }
920#if 0
921 inline uint32_t nottoobig(uint32_t t) {
922 return t;
923 }
924#endif
925
926 void AddMethod(const CXXMethodDecl *MD, int32_t FirstIndex) {
927 typedef CXXMethodDecl::method_iterator meth_iter;
928
929 llvm::Constant *m;
930 m = CGM.GetAddrOfFunction(GlobalDecl(MD), Ptr8Ty);
931 m = llvm::ConstantExpr::getBitCast(m, Ptr8Ty);
932
933 // FIXME: Don't like the nested loops. For very large inheritance
934 // heirarchies we could have a table on the side with the final overridder
935 // and just replace each instance of an overridden method once. Would be
936 // nice to measure the cost/benefit on real code.
937
938 // If we can find a previously allocated slot for this, reuse it.
939 for (meth_iter mi = MD->begin_overridden_methods(),
940 e = MD->end_overridden_methods();
941 mi != e; ++mi) {
942 const CXXMethodDecl *OMD = *mi;
943 llvm::Constant *om;
944 om = CGM.GetAddrOfFunction(GlobalDecl(OMD), Ptr8Ty);
945 om = llvm::ConstantExpr::getBitCast(om, Ptr8Ty);
946
947 for (int32_t i = FirstIndex, e = nottoobig(methods.size()); i != e; ++i) {
948 // FIXME: begin_overridden_methods might be too lax, covariance */
949 if (methods[i] == om) {
950 methods[i] = m;
951 Index[MD] = i;
952 return;
953 }
Mike Stump1e10cf32009-08-18 21:03:28 +0000954 }
Mike Stumpdecd7812009-08-12 23:00:59 +0000955 }
Mike Stumpf07ede52009-08-21 01:45:00 +0000956
957 // else allocate a new slot.
958 Index[MD] = methods.size();
959 methods.push_back(m);
960 }
961
962 void GenerateMethods(const CXXRecordDecl *RD, int32_t FirstIndex) {
963 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
964 ++mi)
965 if (mi->isVirtual())
966 AddMethod(*mi, FirstIndex);
Mike Stumpdecd7812009-08-12 23:00:59 +0000967 }
Mike Stump1e10cf32009-08-18 21:03:28 +0000968
Mike Stump7bae1282009-08-18 21:30:21 +0000969 void GenerateVtableForBase(const CXXRecordDecl *RD,
970 bool forPrimary,
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000971 bool VBoundary,
Mike Stump7bae1282009-08-18 21:30:21 +0000972 int64_t Offset,
Mike Stumpf07ede52009-08-21 01:45:00 +0000973 bool ForVirtualBase,
974 int32_t FirstIndex) {
Mike Stump7bae1282009-08-18 21:30:21 +0000975 llvm::Constant *m = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stumpc57b8272009-08-16 01:46:26 +0000976
Mike Stump7bae1282009-08-18 21:30:21 +0000977 if (RD && !RD->isDynamicClass())
978 return;
979
980 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
981 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
982 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
983
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000984 if (VBoundary || forPrimary || ForVirtualBase) {
985 // then comes the the vcall offsets for all our functions...
986 GenerateVcalls(RD, VBoundary, !forPrimary && ForVirtualBase);
987 }
988
Mike Stump7bae1282009-08-18 21:30:21 +0000989 // The virtual base offsets come first...
990 // FIXME: Audit, is this right?
Mike Stump4c1c8912009-08-19 02:53:08 +0000991 if (PrimaryBase == 0 || forPrimary || !PrimaryBaseWasVirtual) {
Mike Stump7bae1282009-08-18 21:30:21 +0000992 std::vector<llvm::Constant *> offsets;
Mike Stumpaf0d0452009-08-20 07:22:17 +0000993 GenerateVBaseOffsets(offsets, RD, Offset);
Mike Stump7bae1282009-08-18 21:30:21 +0000994 for (std::vector<llvm::Constant *>::reverse_iterator i = offsets.rbegin(),
995 e = offsets.rend(); i != e; ++i)
996 methods.push_back(*i);
997 }
998
Mike Stump7bae1282009-08-18 21:30:21 +0000999 bool Top = true;
1000
1001 // vtables are composed from the chain of primaries.
1002 if (PrimaryBase) {
1003 if (PrimaryBaseWasVirtual)
1004 IndirectPrimary.insert(PrimaryBase);
1005 Top = false;
Mike Stumpb6ff81e2009-08-19 02:06:38 +00001006 GenerateVtableForBase(PrimaryBase, true, PrimaryBaseWasVirtual|VBoundary,
Mike Stumpf07ede52009-08-21 01:45:00 +00001007 Offset, PrimaryBaseWasVirtual, FirstIndex);
Mike Stump7bae1282009-08-18 21:30:21 +00001008 }
1009
1010 if (Top) {
1011 int64_t BaseOffset;
1012 if (ForVirtualBase) {
Mike Stump7bae1282009-08-18 21:30:21 +00001013 BaseOffset = -(BLayout.getVBaseClassOffset(RD) / 8);
1014 } else
1015 BaseOffset = -Offset/8;
Mike Stumpc57b8272009-08-16 01:46:26 +00001016 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), BaseOffset);
1017 m = llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
1018 methods.push_back(m);
Mike Stump7bae1282009-08-18 21:30:21 +00001019 methods.push_back(rtti);
Mike Stumpc57b8272009-08-16 01:46:26 +00001020 }
Mike Stump2eade572009-08-13 22:53:07 +00001021
Mike Stump7bae1282009-08-18 21:30:21 +00001022 // And add the virtuals for the class to the primary vtable.
Mike Stumpf07ede52009-08-21 01:45:00 +00001023 GenerateMethods(RD, FirstIndex);
Mike Stump7bae1282009-08-18 21:30:21 +00001024
1025 // and then the non-virtual bases.
1026 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1027 e = RD->bases_end(); i != e; ++i) {
1028 if (i->isVirtual())
1029 continue;
1030 const CXXRecordDecl *Base =
1031 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1032 if (Base != PrimaryBase || PrimaryBaseWasVirtual) {
1033 uint64_t o = Offset + Layout.getBaseClassOffset(Base);
Mike Stumpf07ede52009-08-21 01:45:00 +00001034 StartNewTable();
1035 FirstIndex = methods.size();
1036 GenerateVtableForBase(Base, true, false, o, false, FirstIndex);
Mike Stump7bae1282009-08-18 21:30:21 +00001037 }
1038 }
1039 }
1040
1041 void GenerateVtableForVBases(const CXXRecordDecl *RD,
Mike Stumpa7ec675d2009-08-19 14:40:47 +00001042 const CXXRecordDecl *Class) {
Mike Stump7bae1282009-08-18 21:30:21 +00001043 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1044 e = RD->bases_end(); i != e; ++i) {
1045 const CXXRecordDecl *Base =
1046 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1047 if (i->isVirtual() && !IndirectPrimary.count(Base)) {
1048 // Mark it so we don't output it twice.
1049 IndirectPrimary.insert(Base);
Mike Stumpf07ede52009-08-21 01:45:00 +00001050 StartNewTable();
Mike Stumpaf0d0452009-08-20 07:22:17 +00001051 int64_t BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stumpf07ede52009-08-21 01:45:00 +00001052 int32_t FirstIndex = methods.size();
1053 GenerateVtableForBase(Base, false, true, BaseOffset, true, FirstIndex);
Mike Stump7bae1282009-08-18 21:30:21 +00001054 }
1055 if (Base->getNumVBases())
Mike Stumpa7ec675d2009-08-19 14:40:47 +00001056 GenerateVtableForVBases(Base, Class);
Mike Stumpc57b8272009-08-16 01:46:26 +00001057 }
1058 }
Mike Stump7bae1282009-08-18 21:30:21 +00001059};
Mike Stumpd6f22d82009-08-06 15:50:11 +00001060
Mike Stump7e8c9932009-07-31 18:25:34 +00001061llvm::Value *CodeGenFunction::GenerateVtable(const CXXRecordDecl *RD) {
Mike Stump7e8c9932009-07-31 18:25:34 +00001062 llvm::SmallString<256> OutName;
1063 llvm::raw_svector_ostream Out(OutName);
1064 QualType ClassTy;
Mike Stumpe7545622009-08-07 18:05:12 +00001065 ClassTy = getContext().getTagDeclType(RD);
Mike Stump7e8c9932009-07-31 18:25:34 +00001066 mangleCXXVtable(ClassTy, getContext(), Out);
Mike Stumpd0672782009-07-31 21:43:43 +00001067 llvm::GlobalVariable::LinkageTypes linktype;
1068 linktype = llvm::GlobalValue::WeakAnyLinkage;
1069 std::vector<llvm::Constant *> methods;
Mike Stumpc57b8272009-08-16 01:46:26 +00001070 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
Mike Stump8b82eeb2009-08-05 22:37:18 +00001071 int64_t Offset = 0;
Mike Stump71e21302009-08-06 21:49:36 +00001072
1073 Offset += LLVMPointerWidth;
1074 Offset += LLVMPointerWidth;
Mike Stump8b82eeb2009-08-05 22:37:18 +00001075
Mike Stump86a859e2009-08-19 18:10:47 +00001076 VtableBuilder b(methods, RD, CGM);
Mike Stump7bae1282009-08-18 21:30:21 +00001077
Mike Stumpc57b8272009-08-16 01:46:26 +00001078 // First comes the vtables for all the non-virtual bases...
Mike Stumpf07ede52009-08-21 01:45:00 +00001079 b.GenerateVtableForBase(RD, true, false, 0, false, 0);
Mike Stump42368bb2009-08-14 01:44:03 +00001080
Mike Stumpc57b8272009-08-16 01:46:26 +00001081 // then the vtables for all the virtual bases.
Mike Stumpa7ec675d2009-08-19 14:40:47 +00001082 b.GenerateVtableForVBases(RD, RD);
Mike Stumpf3371782009-08-04 21:58:42 +00001083
Mike Stumpd0672782009-07-31 21:43:43 +00001084 llvm::Constant *C;
1085 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, methods.size());
1086 C = llvm::ConstantArray::get(type, methods);
1087 llvm::Value *vtable = new llvm::GlobalVariable(CGM.getModule(), type, true,
Daniel Dunbar0433a022009-08-19 20:04:03 +00001088 linktype, C, Out.str());
Mike Stump7e8c9932009-07-31 18:25:34 +00001089 vtable = Builder.CreateBitCast(vtable, Ptr8Ty);
Mike Stump7e8c9932009-07-31 18:25:34 +00001090 vtable = Builder.CreateGEP(vtable,
Mike Stumpc57b8272009-08-16 01:46:26 +00001091 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
Mike Stump8b82eeb2009-08-05 22:37:18 +00001092 Offset/8));
Mike Stump7e8c9932009-07-31 18:25:34 +00001093 return vtable;
1094}
1095
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001096/// EmitClassMemberwiseCopy - This routine generates code to copy a class
1097/// object from SrcValue to DestValue. Copying can be either a bitwise copy
1098/// of via a copy constructor call.
1099void CodeGenFunction::EmitClassMemberwiseCopy(
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001100 llvm::Value *Dest, llvm::Value *Src,
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001101 const CXXRecordDecl *ClassDecl,
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001102 const CXXRecordDecl *BaseClassDecl, QualType Ty) {
1103 if (ClassDecl) {
1104 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
1105 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
1106 }
1107 if (BaseClassDecl->hasTrivialCopyConstructor()) {
1108 EmitAggregateCopy(Dest, Src, Ty);
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001109 return;
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001110 }
1111
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001112 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanianfbe08772009-08-08 00:59:58 +00001113 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001114 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
1115 Ctor_Complete);
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001116 CallArgList CallArgs;
1117 // Push the this (Dest) ptr.
1118 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1119 BaseCopyCtor->getThisType(getContext())));
1120
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001121 // Push the Src ptr.
1122 CallArgs.push_back(std::make_pair(RValue::get(Src),
Fariborz Jahanian0dfaec42009-08-10 17:20:45 +00001123 BaseCopyCtor->getParamDecl(0)->getType()));
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001124 QualType ResultType =
1125 BaseCopyCtor->getType()->getAsFunctionType()->getResultType();
1126 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1127 Callee, CallArgs, BaseCopyCtor);
1128 }
1129}
Fariborz Jahaniane39fab62009-08-10 18:46:38 +00001130
Fariborz Jahanian04500242009-08-12 23:34:46 +00001131/// EmitClassCopyAssignment - This routine generates code to copy assign a class
1132/// object from SrcValue to DestValue. Assignment can be either a bitwise
1133/// assignment of via an assignment operator call.
1134void CodeGenFunction::EmitClassCopyAssignment(
1135 llvm::Value *Dest, llvm::Value *Src,
1136 const CXXRecordDecl *ClassDecl,
1137 const CXXRecordDecl *BaseClassDecl,
1138 QualType Ty) {
1139 if (ClassDecl) {
1140 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
1141 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
1142 }
1143 if (BaseClassDecl->hasTrivialCopyAssignment()) {
1144 EmitAggregateCopy(Dest, Src, Ty);
1145 return;
1146 }
1147
1148 const CXXMethodDecl *MD = 0;
Fariborz Jahanian84bd6532009-08-13 00:53:36 +00001149 bool ConstCopyAssignOp = BaseClassDecl->hasConstCopyAssignment(getContext(),
1150 MD);
1151 assert(ConstCopyAssignOp && "EmitClassCopyAssignment - missing copy assign");
1152 (void)ConstCopyAssignOp;
1153
1154 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
1155 const llvm::Type *LTy =
1156 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1157 FPT->isVariadic());
1158 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), LTy);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001159
Fariborz Jahanian84bd6532009-08-13 00:53:36 +00001160 CallArgList CallArgs;
1161 // Push the this (Dest) ptr.
1162 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1163 MD->getThisType(getContext())));
Fariborz Jahanian04500242009-08-12 23:34:46 +00001164
Fariborz Jahanian84bd6532009-08-13 00:53:36 +00001165 // Push the Src ptr.
1166 CallArgs.push_back(std::make_pair(RValue::get(Src),
1167 MD->getParamDecl(0)->getType()));
1168 QualType ResultType =
1169 MD->getType()->getAsFunctionType()->getResultType();
1170 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1171 Callee, CallArgs, MD);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001172}
1173
Fariborz Jahaniane39fab62009-08-10 18:46:38 +00001174/// SynthesizeDefaultConstructor - synthesize a default constructor
1175void
1176CodeGenFunction::SynthesizeDefaultConstructor(const CXXConstructorDecl *CD,
1177 const FunctionDecl *FD,
1178 llvm::Function *Fn,
1179 const FunctionArgList &Args) {
1180 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1181 EmitCtorPrologue(CD);
1182 FinishFunction();
1183}
1184
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001185/// SynthesizeCXXCopyConstructor - This routine implicitly defines body of a copy
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001186/// constructor, in accordance with section 12.8 (p7 and p8) of C++03
1187/// The implicitly-defined copy constructor for class X performs a memberwise
1188/// copy of its subobjects. The order of copying is the same as the order
1189/// of initialization of bases and members in a user-defined constructor
1190/// Each subobject is copied in the manner appropriate to its type:
1191/// if the subobject is of class type, the copy constructor for the class is
1192/// used;
1193/// if the subobject is an array, each element is copied, in the manner
1194/// appropriate to the element type;
1195/// if the subobject is of scalar type, the built-in assignment operator is
1196/// used.
1197/// Virtual base class subobjects shall be copied only once by the
1198/// implicitly-defined copy constructor
1199
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001200void CodeGenFunction::SynthesizeCXXCopyConstructor(const CXXConstructorDecl *CD,
1201 const FunctionDecl *FD,
1202 llvm::Function *Fn,
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001203 const FunctionArgList &Args) {
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001204 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1205 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001206 "SynthesizeCXXCopyConstructor - copy constructor has definition already");
1207 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001208
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001209 FunctionArgList::const_iterator i = Args.begin();
1210 const VarDecl *ThisArg = i->first;
1211 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1212 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1213 const VarDecl *SrcArg = (i+1)->first;
1214 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1215 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1216
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001217 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1218 Base != ClassDecl->bases_end(); ++Base) {
1219 // FIXME. copy constrution of virtual base NYI
1220 if (Base->isVirtual())
1221 continue;
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001222
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001223 CXXRecordDecl *BaseClassDecl
1224 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001225 EmitClassMemberwiseCopy(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1226 Base->getType());
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001227 }
1228
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001229 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1230 FieldEnd = ClassDecl->field_end();
1231 Field != FieldEnd; ++Field) {
1232 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
1233
1234 // FIXME. How about copying arrays!
1235 assert(!getContext().getAsArrayType(FieldType) &&
1236 "FIXME. Copying arrays NYI");
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +00001237
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001238 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1239 CXXRecordDecl *FieldClassDecl
1240 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1241 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1242 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001243
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001244 EmitClassMemberwiseCopy(LHS.getAddress(), RHS.getAddress(),
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001245 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001246 continue;
1247 }
Fariborz Jahanian08d99e92009-08-10 18:34:26 +00001248 // Do a built-in assignment of scalar data members.
1249 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1250 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1251 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1252 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001253 }
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001254 FinishFunction();
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001255}
1256
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001257/// SynthesizeCXXCopyAssignment - Implicitly define copy assignment operator.
1258/// Before the implicitly-declared copy assignment operator for a class is
1259/// implicitly defined, all implicitly- declared copy assignment operators for
1260/// its direct base classes and its nonstatic data members shall have been
1261/// implicitly defined. [12.8-p12]
1262/// The implicitly-defined copy assignment operator for class X performs
1263/// memberwise assignment of its subob- jects. The direct base classes of X are
1264/// assigned first, in the order of their declaration in
1265/// the base-specifier-list, and then the immediate nonstatic data members of X
1266/// are assigned, in the order in which they were declared in the class
1267/// definition.Each subobject is assigned in the manner appropriate to its type:
Fariborz Jahanian04500242009-08-12 23:34:46 +00001268/// if the subobject is of class type, the copy assignment operator for the
1269/// class is used (as if by explicit qualification; that is, ignoring any
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001270/// possible virtual overriding functions in more derived classes);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001271///
1272/// if the subobject is an array, each element is assigned, in the manner
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001273/// appropriate to the element type;
Fariborz Jahanian04500242009-08-12 23:34:46 +00001274///
1275/// if the subobject is of scalar type, the built-in assignment operator is
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001276/// used.
1277void CodeGenFunction::SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD,
1278 const FunctionDecl *FD,
1279 llvm::Function *Fn,
1280 const FunctionArgList &Args) {
Fariborz Jahanian04500242009-08-12 23:34:46 +00001281
1282 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1283 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
1284 "SynthesizeCXXCopyAssignment - copy assignment has user declaration");
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001285 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1286
Fariborz Jahanian04500242009-08-12 23:34:46 +00001287 FunctionArgList::const_iterator i = Args.begin();
1288 const VarDecl *ThisArg = i->first;
1289 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1290 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1291 const VarDecl *SrcArg = (i+1)->first;
1292 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1293 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1294
1295 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1296 Base != ClassDecl->bases_end(); ++Base) {
1297 // FIXME. copy assignment of virtual base NYI
1298 if (Base->isVirtual())
1299 continue;
1300
1301 CXXRecordDecl *BaseClassDecl
1302 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1303 EmitClassCopyAssignment(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1304 Base->getType());
1305 }
1306
1307 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1308 FieldEnd = ClassDecl->field_end();
1309 Field != FieldEnd; ++Field) {
1310 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
1311
1312 // FIXME. How about copy assignment of arrays!
1313 assert(!getContext().getAsArrayType(FieldType) &&
1314 "FIXME. Copy assignment of arrays NYI");
1315
1316 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1317 CXXRecordDecl *FieldClassDecl
1318 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1319 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1320 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1321
1322 EmitClassCopyAssignment(LHS.getAddress(), RHS.getAddress(),
1323 0 /*ClassDecl*/, FieldClassDecl, FieldType);
1324 continue;
1325 }
1326 // Do a built-in assignment of scalar data members.
1327 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1328 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1329 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1330 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanianc47460d2009-08-14 00:01:54 +00001331 }
1332
1333 // return *this;
1334 Builder.CreateStore(LoadOfThis, ReturnValue);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001335
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001336 FinishFunction();
1337}
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001338
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001339/// EmitCtorPrologue - This routine generates necessary code to initialize
1340/// base classes and non-static data members belonging to this constructor.
1341void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD) {
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001342 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
Mike Stump05207212009-08-06 13:41:24 +00001343 // FIXME: Add vbase initialization
Mike Stump7e8c9932009-07-31 18:25:34 +00001344 llvm::Value *LoadOfThis = 0;
Fariborz Jahanian70277012009-07-28 18:09:28 +00001345
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001346 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001347 E = CD->init_end();
1348 B != E; ++B) {
1349 CXXBaseOrMemberInitializer *Member = (*B);
1350 if (Member->isBaseInitializer()) {
Mike Stump7e8c9932009-07-31 18:25:34 +00001351 LoadOfThis = LoadCXXThis();
Fariborz Jahanian70277012009-07-28 18:09:28 +00001352 Type *BaseType = Member->getBaseClass();
1353 CXXRecordDecl *BaseClassDecl =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001354 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
Fariborz Jahanian70277012009-07-28 18:09:28 +00001355 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1356 BaseClassDecl);
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001357 EmitCXXConstructorCall(Member->getConstructor(),
1358 Ctor_Complete, V,
1359 Member->const_arg_begin(),
1360 Member->const_arg_end());
Mike Stump487ce382009-07-30 22:28:39 +00001361 } else {
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001362 // non-static data member initilaizers.
1363 FieldDecl *Field = Member->getMember();
1364 QualType FieldType = getContext().getCanonicalType((Field)->getType());
Fariborz Jahanianc7b8d9a2009-08-21 17:09:38 +00001365 const ConstantArrayType *Array =
1366 getContext().getAsConstantArrayType(FieldType);
1367 if (Array)
1368 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian32cea8b2009-08-10 23:56:17 +00001369
Mike Stump7e8c9932009-07-31 18:25:34 +00001370 LoadOfThis = LoadCXXThis();
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001371 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001372 if (FieldType->getAs<RecordType>()) {
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +00001373 if (!Field->isAnonymousStructOrUnion()) {
Fariborz Jahanian56baceb2009-07-24 17:57:02 +00001374 assert(Member->getConstructor() &&
1375 "EmitCtorPrologue - no constructor to initialize member");
Fariborz Jahanianc7b8d9a2009-08-21 17:09:38 +00001376 if (Array) {
1377 const llvm::Type *BasePtr = ConvertType(FieldType);
1378 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1379 llvm::Value *BaseAddrPtr =
1380 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1381 EmitCXXAggrConstructorCall(Member->getConstructor(),
1382 Array, BaseAddrPtr);
1383 }
1384 else
1385 EmitCXXConstructorCall(Member->getConstructor(),
1386 Ctor_Complete, LHS.getAddress(),
1387 Member->const_arg_begin(),
1388 Member->const_arg_end());
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +00001389 continue;
1390 }
1391 else {
1392 // Initializing an anonymous union data member.
1393 FieldDecl *anonMember = Member->getAnonUnionMember();
1394 LHS = EmitLValueForField(LHS.getAddress(), anonMember, false, 0);
1395 FieldType = anonMember->getType();
1396 }
Fariborz Jahanian56baceb2009-07-24 17:57:02 +00001397 }
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001398
1399 assert(Member->getNumArgs() == 1 && "Initializer count must be 1 only");
Fariborz Jahanian56baceb2009-07-24 17:57:02 +00001400 Expr *RhsExpr = *Member->arg_begin();
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001401 llvm::Value *RHS = EmitScalarExpr(RhsExpr, true);
Fariborz Jahanian32cea8b2009-08-10 23:56:17 +00001402 EmitStoreThroughLValue(RValue::get(RHS), LHS, FieldType);
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001403 }
1404 }
Mike Stump7e8c9932009-07-31 18:25:34 +00001405
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001406 if (!CD->getNumBaseOrMemberInitializers() && !CD->isTrivial()) {
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001407 // Nontrivial default constructor with no initializer list. It may still
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001408 // have bases classes and/or contain non-static data members which require
1409 // construction.
1410 for (CXXRecordDecl::base_class_const_iterator Base =
1411 ClassDecl->bases_begin();
1412 Base != ClassDecl->bases_end(); ++Base) {
1413 // FIXME. copy assignment of virtual base NYI
1414 if (Base->isVirtual())
1415 continue;
1416
1417 CXXRecordDecl *BaseClassDecl
1418 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1419 if (BaseClassDecl->hasTrivialConstructor())
1420 continue;
1421 if (CXXConstructorDecl *BaseCX =
1422 BaseClassDecl->getDefaultConstructor(getContext())) {
1423 LoadOfThis = LoadCXXThis();
1424 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1425 BaseClassDecl);
1426 EmitCXXConstructorCall(BaseCX, Ctor_Complete, V, 0, 0);
1427 }
1428 }
1429
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001430 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1431 FieldEnd = ClassDecl->field_end();
1432 Field != FieldEnd; ++Field) {
1433 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +00001434 const ConstantArrayType *Array =
1435 getContext().getAsConstantArrayType(FieldType);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001436 if (Array)
1437 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001438 if (!FieldType->getAs<RecordType>() || Field->isAnonymousStructOrUnion())
1439 continue;
1440 const RecordType *ClassRec = FieldType->getAs<RecordType>();
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001441 CXXRecordDecl *MemberClassDecl =
1442 dyn_cast<CXXRecordDecl>(ClassRec->getDecl());
1443 if (!MemberClassDecl || MemberClassDecl->hasTrivialConstructor())
1444 continue;
1445 if (CXXConstructorDecl *MamberCX =
1446 MemberClassDecl->getDefaultConstructor(getContext())) {
1447 LoadOfThis = LoadCXXThis();
1448 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +00001449 if (Array) {
1450 const llvm::Type *BasePtr = ConvertType(FieldType);
1451 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1452 llvm::Value *BaseAddrPtr =
1453 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1454 EmitCXXAggrConstructorCall(MamberCX, Array, BaseAddrPtr);
1455 }
1456 else
1457 EmitCXXConstructorCall(MamberCX, Ctor_Complete, LHS.getAddress(),
1458 0, 0);
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001459 }
1460 }
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001461 }
1462
Mike Stump7e8c9932009-07-31 18:25:34 +00001463 // Initialize the vtable pointer
Mike Stumpeec46a72009-08-05 22:59:44 +00001464 if (ClassDecl->isDynamicClass()) {
Mike Stump7e8c9932009-07-31 18:25:34 +00001465 if (!LoadOfThis)
1466 LoadOfThis = LoadCXXThis();
1467 llvm::Value *VtableField;
1468 llvm::Type *Ptr8Ty, *PtrPtr8Ty;
Owen Anderson3f5cc0a2009-08-13 21:57:51 +00001469 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Mike Stump7e8c9932009-07-31 18:25:34 +00001470 PtrPtr8Ty = llvm::PointerType::get(Ptr8Ty, 0);
1471 VtableField = Builder.CreateBitCast(LoadOfThis, PtrPtr8Ty);
1472 llvm::Value *vtable = GenerateVtable(ClassDecl);
1473 Builder.CreateStore(vtable, VtableField);
1474 }
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001475}
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001476
1477/// EmitDtorEpilogue - Emit all code that comes at the end of class's
1478/// destructor. This is to call destructors on members and base classes
1479/// in reverse order of their construction.
1480void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD) {
1481 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(DD->getDeclContext());
1482 assert(!ClassDecl->isPolymorphic() &&
1483 "FIXME. polymorphic destruction not supported");
1484 (void)ClassDecl; // prevent warning.
1485
1486 for (CXXDestructorDecl::destr_const_iterator *B = DD->destr_begin(),
1487 *E = DD->destr_end(); B != E; ++B) {
1488 uintptr_t BaseOrMember = (*B);
1489 if (DD->isMemberToDestroy(BaseOrMember)) {
1490 FieldDecl *FD = DD->getMemberToDestroy(BaseOrMember);
1491 QualType FieldType = getContext().getCanonicalType((FD)->getType());
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001492 const ConstantArrayType *Array =
1493 getContext().getAsConstantArrayType(FieldType);
1494 if (Array)
1495 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001496 const RecordType *RT = FieldType->getAs<RecordType>();
1497 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1498 if (FieldClassDecl->hasTrivialDestructor())
1499 continue;
1500 llvm::Value *LoadOfThis = LoadCXXThis();
1501 LValue LHS = EmitLValueForField(LoadOfThis, FD, false, 0);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001502 if (Array) {
1503 const llvm::Type *BasePtr = ConvertType(FieldType);
1504 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1505 llvm::Value *BaseAddrPtr =
1506 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1507 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1508 Array, BaseAddrPtr);
1509 }
1510 else
1511 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1512 Dtor_Complete, LHS.getAddress());
Mike Stump487ce382009-07-30 22:28:39 +00001513 } else {
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001514 const RecordType *RT =
1515 DD->getAnyBaseClassToDestroy(BaseOrMember)->getAs<RecordType>();
1516 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1517 if (BaseClassDecl->hasTrivialDestructor())
1518 continue;
1519 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
1520 ClassDecl,BaseClassDecl);
1521 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1522 Dtor_Complete, V);
1523 }
1524 }
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001525 if (DD->getNumBaseOrMemberDestructions() || DD->isTrivial())
1526 return;
1527 // Case of destructor synthesis with fields and base classes
1528 // which have non-trivial destructors. They must be destructed in
1529 // reverse order of their construction.
1530 llvm::SmallVector<FieldDecl *, 16> DestructedFields;
1531
1532 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1533 FieldEnd = ClassDecl->field_end();
1534 Field != FieldEnd; ++Field) {
1535 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001536 if (getContext().getAsConstantArrayType(FieldType))
1537 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001538 if (const RecordType *RT = FieldType->getAs<RecordType>()) {
1539 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1540 if (FieldClassDecl->hasTrivialDestructor())
1541 continue;
1542 DestructedFields.push_back(*Field);
1543 }
1544 }
1545 if (!DestructedFields.empty())
1546 for (int i = DestructedFields.size() -1; i >= 0; --i) {
1547 FieldDecl *Field = DestructedFields[i];
1548 QualType FieldType = Field->getType();
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001549 const ConstantArrayType *Array =
1550 getContext().getAsConstantArrayType(FieldType);
1551 if (Array)
1552 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001553 const RecordType *RT = FieldType->getAs<RecordType>();
1554 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1555 llvm::Value *LoadOfThis = LoadCXXThis();
1556 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001557 if (Array) {
1558 const llvm::Type *BasePtr = ConvertType(FieldType);
1559 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1560 llvm::Value *BaseAddrPtr =
1561 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1562 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1563 Array, BaseAddrPtr);
1564 }
1565 else
1566 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1567 Dtor_Complete, LHS.getAddress());
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001568 }
1569
1570 llvm::SmallVector<CXXRecordDecl*, 4> DestructedBases;
1571 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1572 Base != ClassDecl->bases_end(); ++Base) {
1573 // FIXME. copy assignment of virtual base NYI
1574 if (Base->isVirtual())
1575 continue;
1576
1577 CXXRecordDecl *BaseClassDecl
1578 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1579 if (BaseClassDecl->hasTrivialDestructor())
1580 continue;
1581 DestructedBases.push_back(BaseClassDecl);
1582 }
1583 if (DestructedBases.empty())
1584 return;
1585 for (int i = DestructedBases.size() -1; i >= 0; --i) {
1586 CXXRecordDecl *BaseClassDecl = DestructedBases[i];
1587 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
1588 ClassDecl,BaseClassDecl);
1589 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1590 Dtor_Complete, V);
1591 }
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001592}
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001593
1594void CodeGenFunction::SynthesizeDefaultDestructor(const CXXDestructorDecl *CD,
1595 const FunctionDecl *FD,
1596 llvm::Function *Fn,
1597 const FunctionArgList &Args) {
1598
1599 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1600 assert(!ClassDecl->hasUserDeclaredDestructor() &&
1601 "SynthesizeDefaultDestructor - destructor has user declaration");
1602 (void) ClassDecl;
1603
1604 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1605 EmitDtorEpilogue(CD);
1606 FinishFunction();
1607}