blob: 2c8c1f31ad6224c3ba582afeb5f89e61e81220ce [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 Jahanian86328d22009-08-21 18:30:26 +00001096/// EmitClassAggrMemberwiseCopy - This routine generates code to copy a class
1097/// array of objects from SrcValue to DestValue. Copying can be either a bitwise
1098/// copy or via a copy constructor call.
1099void CodeGenFunction::EmitClassAggrMemberwiseCopy(llvm::Value *Dest,
1100 llvm::Value *Src,
1101 const ArrayType *Array,
1102 const CXXRecordDecl *BaseClassDecl,
1103 QualType Ty) {
1104 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1105 assert(CA && "VLA cannot be copied over");
1106 bool BitwiseCopy = BaseClassDecl->hasTrivialCopyConstructor();
1107
1108 // Create a temporary for the loop index and initialize it with 0.
1109 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1110 "loop.index");
1111 llvm::Value* zeroConstant =
1112 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
1113 Builder.CreateStore(zeroConstant, IndexPtr, false);
1114 // Start the loop with a block that tests the condition.
1115 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1116 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1117
1118 EmitBlock(CondBlock);
1119
1120 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1121 // Generate: if (loop-index < number-of-elements fall to the loop body,
1122 // otherwise, go to the block after the for-loop.
1123 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
1124 llvm::Value * NumElementsPtr =
1125 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1126 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1127 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
1128 "isless");
1129 // If the condition is true, execute the body.
1130 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1131
1132 EmitBlock(ForBody);
1133 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1134 // Inside the loop body, emit the constructor call on the array element.
1135 Counter = Builder.CreateLoad(IndexPtr);
1136 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1137 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1138 if (BitwiseCopy)
1139 EmitAggregateCopy(Dest, Src, Ty);
1140 else if (CXXConstructorDecl *BaseCopyCtor =
1141 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
1142 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
1143 Ctor_Complete);
1144 CallArgList CallArgs;
1145 // Push the this (Dest) ptr.
1146 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1147 BaseCopyCtor->getThisType(getContext())));
1148
1149 // Push the Src ptr.
1150 CallArgs.push_back(std::make_pair(RValue::get(Src),
1151 BaseCopyCtor->getParamDecl(0)->getType()));
1152 QualType ResultType =
1153 BaseCopyCtor->getType()->getAsFunctionType()->getResultType();
1154 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1155 Callee, CallArgs, BaseCopyCtor);
1156 }
1157 EmitBlock(ContinueBlock);
1158
1159 // Emit the increment of the loop counter.
1160 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1161 Counter = Builder.CreateLoad(IndexPtr);
1162 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1163 Builder.CreateStore(NextVal, IndexPtr, false);
1164
1165 // Finally, branch back up to the condition for the next iteration.
1166 EmitBranch(CondBlock);
1167
1168 // Emit the fall-through block.
1169 EmitBlock(AfterFor, true);
1170}
1171
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001172/// EmitClassAggrCopyAssignment - This routine generates code to assign a class
1173/// array of objects from SrcValue to DestValue. Assignment can be either a
1174/// bitwise assignment or via a copy assignment operator function call.
1175/// FIXME. This can be consolidated with EmitClassAggrMemberwiseCopy
1176void CodeGenFunction::EmitClassAggrCopyAssignment(llvm::Value *Dest,
1177 llvm::Value *Src,
1178 const ArrayType *Array,
1179 const CXXRecordDecl *BaseClassDecl,
1180 QualType Ty) {
1181 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1182 assert(CA && "VLA cannot be asssigned");
1183 bool BitwiseAssign = BaseClassDecl->hasTrivialCopyAssignment();
1184
1185 // Create a temporary for the loop index and initialize it with 0.
1186 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1187 "loop.index");
1188 llvm::Value* zeroConstant =
1189 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
1190 Builder.CreateStore(zeroConstant, IndexPtr, false);
1191 // Start the loop with a block that tests the condition.
1192 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1193 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1194
1195 EmitBlock(CondBlock);
1196
1197 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1198 // Generate: if (loop-index < number-of-elements fall to the loop body,
1199 // otherwise, go to the block after the for-loop.
1200 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
1201 llvm::Value * NumElementsPtr =
1202 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1203 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1204 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
1205 "isless");
1206 // If the condition is true, execute the body.
1207 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1208
1209 EmitBlock(ForBody);
1210 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1211 // Inside the loop body, emit the assignment operator call on array element.
1212 Counter = Builder.CreateLoad(IndexPtr);
1213 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1214 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1215 const CXXMethodDecl *MD = 0;
1216 if (BitwiseAssign)
1217 EmitAggregateCopy(Dest, Src, Ty);
1218 else {
1219 bool hasCopyAssign = BaseClassDecl->hasConstCopyAssignment(getContext(),
1220 MD);
1221 assert(hasCopyAssign && "EmitClassAggrCopyAssignment - No user assign");
1222 (void)hasCopyAssign;
1223 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
1224 const llvm::Type *LTy =
1225 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1226 FPT->isVariadic());
1227 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), LTy);
1228
1229 CallArgList CallArgs;
1230 // Push the this (Dest) ptr.
1231 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1232 MD->getThisType(getContext())));
1233
1234 // Push the Src ptr.
1235 CallArgs.push_back(std::make_pair(RValue::get(Src),
1236 MD->getParamDecl(0)->getType()));
1237 QualType ResultType =
1238 MD->getType()->getAsFunctionType()->getResultType();
1239 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1240 Callee, CallArgs, MD);
1241 }
1242 EmitBlock(ContinueBlock);
1243
1244 // Emit the increment of the loop counter.
1245 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1246 Counter = Builder.CreateLoad(IndexPtr);
1247 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1248 Builder.CreateStore(NextVal, IndexPtr, false);
1249
1250 // Finally, branch back up to the condition for the next iteration.
1251 EmitBranch(CondBlock);
1252
1253 // Emit the fall-through block.
1254 EmitBlock(AfterFor, true);
1255}
1256
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001257/// EmitClassMemberwiseCopy - This routine generates code to copy a class
1258/// object from SrcValue to DestValue. Copying can be either a bitwise copy
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001259/// or via a copy constructor call.
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001260void CodeGenFunction::EmitClassMemberwiseCopy(
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001261 llvm::Value *Dest, llvm::Value *Src,
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001262 const CXXRecordDecl *ClassDecl,
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001263 const CXXRecordDecl *BaseClassDecl, QualType Ty) {
1264 if (ClassDecl) {
1265 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
1266 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
1267 }
1268 if (BaseClassDecl->hasTrivialCopyConstructor()) {
1269 EmitAggregateCopy(Dest, Src, Ty);
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001270 return;
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001271 }
1272
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001273 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanianfbe08772009-08-08 00:59:58 +00001274 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001275 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
1276 Ctor_Complete);
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001277 CallArgList CallArgs;
1278 // Push the this (Dest) ptr.
1279 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1280 BaseCopyCtor->getThisType(getContext())));
1281
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001282 // Push the Src ptr.
1283 CallArgs.push_back(std::make_pair(RValue::get(Src),
Fariborz Jahanian0dfaec42009-08-10 17:20:45 +00001284 BaseCopyCtor->getParamDecl(0)->getType()));
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001285 QualType ResultType =
1286 BaseCopyCtor->getType()->getAsFunctionType()->getResultType();
1287 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1288 Callee, CallArgs, BaseCopyCtor);
1289 }
1290}
Fariborz Jahaniane39fab62009-08-10 18:46:38 +00001291
Fariborz Jahanian04500242009-08-12 23:34:46 +00001292/// EmitClassCopyAssignment - This routine generates code to copy assign a class
1293/// object from SrcValue to DestValue. Assignment can be either a bitwise
1294/// assignment of via an assignment operator call.
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001295// FIXME. Consolidate this with EmitClassMemberwiseCopy as they share a lot.
Fariborz Jahanian04500242009-08-12 23:34:46 +00001296void CodeGenFunction::EmitClassCopyAssignment(
1297 llvm::Value *Dest, llvm::Value *Src,
1298 const CXXRecordDecl *ClassDecl,
1299 const CXXRecordDecl *BaseClassDecl,
1300 QualType Ty) {
1301 if (ClassDecl) {
1302 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
1303 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
1304 }
1305 if (BaseClassDecl->hasTrivialCopyAssignment()) {
1306 EmitAggregateCopy(Dest, Src, Ty);
1307 return;
1308 }
1309
1310 const CXXMethodDecl *MD = 0;
Fariborz Jahanian84bd6532009-08-13 00:53:36 +00001311 bool ConstCopyAssignOp = BaseClassDecl->hasConstCopyAssignment(getContext(),
1312 MD);
1313 assert(ConstCopyAssignOp && "EmitClassCopyAssignment - missing copy assign");
1314 (void)ConstCopyAssignOp;
1315
1316 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
1317 const llvm::Type *LTy =
1318 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1319 FPT->isVariadic());
1320 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), LTy);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001321
Fariborz Jahanian84bd6532009-08-13 00:53:36 +00001322 CallArgList CallArgs;
1323 // Push the this (Dest) ptr.
1324 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1325 MD->getThisType(getContext())));
Fariborz Jahanian04500242009-08-12 23:34:46 +00001326
Fariborz Jahanian84bd6532009-08-13 00:53:36 +00001327 // Push the Src ptr.
1328 CallArgs.push_back(std::make_pair(RValue::get(Src),
1329 MD->getParamDecl(0)->getType()));
1330 QualType ResultType =
1331 MD->getType()->getAsFunctionType()->getResultType();
1332 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1333 Callee, CallArgs, MD);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001334}
1335
Fariborz Jahaniane39fab62009-08-10 18:46:38 +00001336/// SynthesizeDefaultConstructor - synthesize a default constructor
1337void
1338CodeGenFunction::SynthesizeDefaultConstructor(const CXXConstructorDecl *CD,
1339 const FunctionDecl *FD,
1340 llvm::Function *Fn,
1341 const FunctionArgList &Args) {
1342 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1343 EmitCtorPrologue(CD);
1344 FinishFunction();
1345}
1346
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001347/// SynthesizeCXXCopyConstructor - This routine implicitly defines body of a copy
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001348/// constructor, in accordance with section 12.8 (p7 and p8) of C++03
1349/// The implicitly-defined copy constructor for class X performs a memberwise
1350/// copy of its subobjects. The order of copying is the same as the order
1351/// of initialization of bases and members in a user-defined constructor
1352/// Each subobject is copied in the manner appropriate to its type:
1353/// if the subobject is of class type, the copy constructor for the class is
1354/// used;
1355/// if the subobject is an array, each element is copied, in the manner
1356/// appropriate to the element type;
1357/// if the subobject is of scalar type, the built-in assignment operator is
1358/// used.
1359/// Virtual base class subobjects shall be copied only once by the
1360/// implicitly-defined copy constructor
1361
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001362void CodeGenFunction::SynthesizeCXXCopyConstructor(const CXXConstructorDecl *CD,
1363 const FunctionDecl *FD,
1364 llvm::Function *Fn,
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001365 const FunctionArgList &Args) {
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001366 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1367 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001368 "SynthesizeCXXCopyConstructor - copy constructor has definition already");
1369 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001370
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001371 FunctionArgList::const_iterator i = Args.begin();
1372 const VarDecl *ThisArg = i->first;
1373 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1374 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1375 const VarDecl *SrcArg = (i+1)->first;
1376 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1377 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1378
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001379 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1380 Base != ClassDecl->bases_end(); ++Base) {
1381 // FIXME. copy constrution of virtual base NYI
1382 if (Base->isVirtual())
1383 continue;
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001384
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001385 CXXRecordDecl *BaseClassDecl
1386 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001387 EmitClassMemberwiseCopy(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1388 Base->getType());
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001389 }
1390
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001391 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1392 FieldEnd = ClassDecl->field_end();
1393 Field != FieldEnd; ++Field) {
1394 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001395 const ConstantArrayType *Array =
1396 getContext().getAsConstantArrayType(FieldType);
1397 if (Array)
1398 FieldType = getContext().getBaseElementType(FieldType);
1399
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001400 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1401 CXXRecordDecl *FieldClassDecl
1402 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1403 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1404 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001405 if (Array) {
1406 const llvm::Type *BasePtr = ConvertType(FieldType);
1407 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1408 llvm::Value *DestBaseAddrPtr =
1409 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1410 llvm::Value *SrcBaseAddrPtr =
1411 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1412 EmitClassAggrMemberwiseCopy(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1413 FieldClassDecl, FieldType);
1414 }
1415 else
1416 EmitClassMemberwiseCopy(LHS.getAddress(), RHS.getAddress(),
1417 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001418 continue;
1419 }
Fariborz Jahanian08d99e92009-08-10 18:34:26 +00001420 // Do a built-in assignment of scalar data members.
1421 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1422 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1423 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1424 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001425 }
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001426 FinishFunction();
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001427}
1428
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001429/// SynthesizeCXXCopyAssignment - Implicitly define copy assignment operator.
1430/// Before the implicitly-declared copy assignment operator for a class is
1431/// implicitly defined, all implicitly- declared copy assignment operators for
1432/// its direct base classes and its nonstatic data members shall have been
1433/// implicitly defined. [12.8-p12]
1434/// The implicitly-defined copy assignment operator for class X performs
1435/// memberwise assignment of its subob- jects. The direct base classes of X are
1436/// assigned first, in the order of their declaration in
1437/// the base-specifier-list, and then the immediate nonstatic data members of X
1438/// are assigned, in the order in which they were declared in the class
1439/// definition.Each subobject is assigned in the manner appropriate to its type:
Fariborz Jahanian04500242009-08-12 23:34:46 +00001440/// if the subobject is of class type, the copy assignment operator for the
1441/// class is used (as if by explicit qualification; that is, ignoring any
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001442/// possible virtual overriding functions in more derived classes);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001443///
1444/// if the subobject is an array, each element is assigned, in the manner
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001445/// appropriate to the element type;
Fariborz Jahanian04500242009-08-12 23:34:46 +00001446///
1447/// if the subobject is of scalar type, the built-in assignment operator is
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001448/// used.
1449void CodeGenFunction::SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD,
1450 const FunctionDecl *FD,
1451 llvm::Function *Fn,
1452 const FunctionArgList &Args) {
Fariborz Jahanian04500242009-08-12 23:34:46 +00001453
1454 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1455 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
1456 "SynthesizeCXXCopyAssignment - copy assignment has user declaration");
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001457 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1458
Fariborz Jahanian04500242009-08-12 23:34:46 +00001459 FunctionArgList::const_iterator i = Args.begin();
1460 const VarDecl *ThisArg = i->first;
1461 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1462 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1463 const VarDecl *SrcArg = (i+1)->first;
1464 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1465 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1466
1467 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1468 Base != ClassDecl->bases_end(); ++Base) {
1469 // FIXME. copy assignment of virtual base NYI
1470 if (Base->isVirtual())
1471 continue;
1472
1473 CXXRecordDecl *BaseClassDecl
1474 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1475 EmitClassCopyAssignment(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1476 Base->getType());
1477 }
1478
1479 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1480 FieldEnd = ClassDecl->field_end();
1481 Field != FieldEnd; ++Field) {
1482 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001483 const ConstantArrayType *Array =
1484 getContext().getAsConstantArrayType(FieldType);
1485 if (Array)
1486 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001487
1488 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1489 CXXRecordDecl *FieldClassDecl
1490 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1491 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1492 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001493 if (Array) {
1494 const llvm::Type *BasePtr = ConvertType(FieldType);
1495 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1496 llvm::Value *DestBaseAddrPtr =
1497 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1498 llvm::Value *SrcBaseAddrPtr =
1499 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1500 EmitClassAggrCopyAssignment(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1501 FieldClassDecl, FieldType);
1502 }
1503 else
1504 EmitClassCopyAssignment(LHS.getAddress(), RHS.getAddress(),
1505 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001506 continue;
1507 }
1508 // Do a built-in assignment of scalar data members.
1509 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1510 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1511 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1512 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanianc47460d2009-08-14 00:01:54 +00001513 }
1514
1515 // return *this;
1516 Builder.CreateStore(LoadOfThis, ReturnValue);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001517
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001518 FinishFunction();
1519}
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001520
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001521/// EmitCtorPrologue - This routine generates necessary code to initialize
1522/// base classes and non-static data members belonging to this constructor.
1523void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD) {
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001524 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
Mike Stump05207212009-08-06 13:41:24 +00001525 // FIXME: Add vbase initialization
Mike Stump7e8c9932009-07-31 18:25:34 +00001526 llvm::Value *LoadOfThis = 0;
Fariborz Jahanian70277012009-07-28 18:09:28 +00001527
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001528 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001529 E = CD->init_end();
1530 B != E; ++B) {
1531 CXXBaseOrMemberInitializer *Member = (*B);
1532 if (Member->isBaseInitializer()) {
Mike Stump7e8c9932009-07-31 18:25:34 +00001533 LoadOfThis = LoadCXXThis();
Fariborz Jahanian70277012009-07-28 18:09:28 +00001534 Type *BaseType = Member->getBaseClass();
1535 CXXRecordDecl *BaseClassDecl =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001536 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
Fariborz Jahanian70277012009-07-28 18:09:28 +00001537 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1538 BaseClassDecl);
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001539 EmitCXXConstructorCall(Member->getConstructor(),
1540 Ctor_Complete, V,
1541 Member->const_arg_begin(),
1542 Member->const_arg_end());
Mike Stump487ce382009-07-30 22:28:39 +00001543 } else {
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001544 // non-static data member initilaizers.
1545 FieldDecl *Field = Member->getMember();
1546 QualType FieldType = getContext().getCanonicalType((Field)->getType());
Fariborz Jahanianc7b8d9a2009-08-21 17:09:38 +00001547 const ConstantArrayType *Array =
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001548 getContext().getAsConstantArrayType(FieldType);
Fariborz Jahanianc7b8d9a2009-08-21 17:09:38 +00001549 if (Array)
1550 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian32cea8b2009-08-10 23:56:17 +00001551
Mike Stump7e8c9932009-07-31 18:25:34 +00001552 LoadOfThis = LoadCXXThis();
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001553 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001554 if (FieldType->getAs<RecordType>()) {
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +00001555 if (!Field->isAnonymousStructOrUnion()) {
Fariborz Jahanian56baceb2009-07-24 17:57:02 +00001556 assert(Member->getConstructor() &&
1557 "EmitCtorPrologue - no constructor to initialize member");
Fariborz Jahanianc7b8d9a2009-08-21 17:09:38 +00001558 if (Array) {
1559 const llvm::Type *BasePtr = ConvertType(FieldType);
1560 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1561 llvm::Value *BaseAddrPtr =
1562 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1563 EmitCXXAggrConstructorCall(Member->getConstructor(),
1564 Array, BaseAddrPtr);
1565 }
1566 else
1567 EmitCXXConstructorCall(Member->getConstructor(),
1568 Ctor_Complete, LHS.getAddress(),
1569 Member->const_arg_begin(),
1570 Member->const_arg_end());
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +00001571 continue;
1572 }
1573 else {
1574 // Initializing an anonymous union data member.
1575 FieldDecl *anonMember = Member->getAnonUnionMember();
1576 LHS = EmitLValueForField(LHS.getAddress(), anonMember, false, 0);
1577 FieldType = anonMember->getType();
1578 }
Fariborz Jahanian56baceb2009-07-24 17:57:02 +00001579 }
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001580
1581 assert(Member->getNumArgs() == 1 && "Initializer count must be 1 only");
Fariborz Jahanian56baceb2009-07-24 17:57:02 +00001582 Expr *RhsExpr = *Member->arg_begin();
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001583 llvm::Value *RHS = EmitScalarExpr(RhsExpr, true);
Fariborz Jahanian32cea8b2009-08-10 23:56:17 +00001584 EmitStoreThroughLValue(RValue::get(RHS), LHS, FieldType);
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001585 }
1586 }
Mike Stump7e8c9932009-07-31 18:25:34 +00001587
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001588 if (!CD->getNumBaseOrMemberInitializers() && !CD->isTrivial()) {
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001589 // Nontrivial default constructor with no initializer list. It may still
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001590 // have bases classes and/or contain non-static data members which require
1591 // construction.
1592 for (CXXRecordDecl::base_class_const_iterator Base =
1593 ClassDecl->bases_begin();
1594 Base != ClassDecl->bases_end(); ++Base) {
1595 // FIXME. copy assignment of virtual base NYI
1596 if (Base->isVirtual())
1597 continue;
1598
1599 CXXRecordDecl *BaseClassDecl
1600 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1601 if (BaseClassDecl->hasTrivialConstructor())
1602 continue;
1603 if (CXXConstructorDecl *BaseCX =
1604 BaseClassDecl->getDefaultConstructor(getContext())) {
1605 LoadOfThis = LoadCXXThis();
1606 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1607 BaseClassDecl);
1608 EmitCXXConstructorCall(BaseCX, Ctor_Complete, V, 0, 0);
1609 }
1610 }
1611
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001612 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1613 FieldEnd = ClassDecl->field_end();
1614 Field != FieldEnd; ++Field) {
1615 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +00001616 const ConstantArrayType *Array =
1617 getContext().getAsConstantArrayType(FieldType);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001618 if (Array)
1619 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001620 if (!FieldType->getAs<RecordType>() || Field->isAnonymousStructOrUnion())
1621 continue;
1622 const RecordType *ClassRec = FieldType->getAs<RecordType>();
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001623 CXXRecordDecl *MemberClassDecl =
1624 dyn_cast<CXXRecordDecl>(ClassRec->getDecl());
1625 if (!MemberClassDecl || MemberClassDecl->hasTrivialConstructor())
1626 continue;
1627 if (CXXConstructorDecl *MamberCX =
1628 MemberClassDecl->getDefaultConstructor(getContext())) {
1629 LoadOfThis = LoadCXXThis();
1630 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +00001631 if (Array) {
1632 const llvm::Type *BasePtr = ConvertType(FieldType);
1633 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1634 llvm::Value *BaseAddrPtr =
1635 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1636 EmitCXXAggrConstructorCall(MamberCX, Array, BaseAddrPtr);
1637 }
1638 else
1639 EmitCXXConstructorCall(MamberCX, Ctor_Complete, LHS.getAddress(),
1640 0, 0);
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001641 }
1642 }
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001643 }
1644
Mike Stump7e8c9932009-07-31 18:25:34 +00001645 // Initialize the vtable pointer
Mike Stumpeec46a72009-08-05 22:59:44 +00001646 if (ClassDecl->isDynamicClass()) {
Mike Stump7e8c9932009-07-31 18:25:34 +00001647 if (!LoadOfThis)
1648 LoadOfThis = LoadCXXThis();
1649 llvm::Value *VtableField;
1650 llvm::Type *Ptr8Ty, *PtrPtr8Ty;
Owen Anderson3f5cc0a2009-08-13 21:57:51 +00001651 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Mike Stump7e8c9932009-07-31 18:25:34 +00001652 PtrPtr8Ty = llvm::PointerType::get(Ptr8Ty, 0);
1653 VtableField = Builder.CreateBitCast(LoadOfThis, PtrPtr8Ty);
1654 llvm::Value *vtable = GenerateVtable(ClassDecl);
1655 Builder.CreateStore(vtable, VtableField);
1656 }
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001657}
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001658
1659/// EmitDtorEpilogue - Emit all code that comes at the end of class's
1660/// destructor. This is to call destructors on members and base classes
1661/// in reverse order of their construction.
1662void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD) {
1663 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(DD->getDeclContext());
1664 assert(!ClassDecl->isPolymorphic() &&
1665 "FIXME. polymorphic destruction not supported");
1666 (void)ClassDecl; // prevent warning.
1667
1668 for (CXXDestructorDecl::destr_const_iterator *B = DD->destr_begin(),
1669 *E = DD->destr_end(); B != E; ++B) {
1670 uintptr_t BaseOrMember = (*B);
1671 if (DD->isMemberToDestroy(BaseOrMember)) {
1672 FieldDecl *FD = DD->getMemberToDestroy(BaseOrMember);
1673 QualType FieldType = getContext().getCanonicalType((FD)->getType());
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001674 const ConstantArrayType *Array =
1675 getContext().getAsConstantArrayType(FieldType);
1676 if (Array)
1677 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001678 const RecordType *RT = FieldType->getAs<RecordType>();
1679 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1680 if (FieldClassDecl->hasTrivialDestructor())
1681 continue;
1682 llvm::Value *LoadOfThis = LoadCXXThis();
1683 LValue LHS = EmitLValueForField(LoadOfThis, FD, false, 0);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001684 if (Array) {
1685 const llvm::Type *BasePtr = ConvertType(FieldType);
1686 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1687 llvm::Value *BaseAddrPtr =
1688 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1689 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1690 Array, BaseAddrPtr);
1691 }
1692 else
1693 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1694 Dtor_Complete, LHS.getAddress());
Mike Stump487ce382009-07-30 22:28:39 +00001695 } else {
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001696 const RecordType *RT =
1697 DD->getAnyBaseClassToDestroy(BaseOrMember)->getAs<RecordType>();
1698 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1699 if (BaseClassDecl->hasTrivialDestructor())
1700 continue;
1701 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
1702 ClassDecl,BaseClassDecl);
1703 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1704 Dtor_Complete, V);
1705 }
1706 }
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001707 if (DD->getNumBaseOrMemberDestructions() || DD->isTrivial())
1708 return;
1709 // Case of destructor synthesis with fields and base classes
1710 // which have non-trivial destructors. They must be destructed in
1711 // reverse order of their construction.
1712 llvm::SmallVector<FieldDecl *, 16> DestructedFields;
1713
1714 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1715 FieldEnd = ClassDecl->field_end();
1716 Field != FieldEnd; ++Field) {
1717 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001718 if (getContext().getAsConstantArrayType(FieldType))
1719 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001720 if (const RecordType *RT = FieldType->getAs<RecordType>()) {
1721 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1722 if (FieldClassDecl->hasTrivialDestructor())
1723 continue;
1724 DestructedFields.push_back(*Field);
1725 }
1726 }
1727 if (!DestructedFields.empty())
1728 for (int i = DestructedFields.size() -1; i >= 0; --i) {
1729 FieldDecl *Field = DestructedFields[i];
1730 QualType FieldType = Field->getType();
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001731 const ConstantArrayType *Array =
1732 getContext().getAsConstantArrayType(FieldType);
1733 if (Array)
1734 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001735 const RecordType *RT = FieldType->getAs<RecordType>();
1736 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1737 llvm::Value *LoadOfThis = LoadCXXThis();
1738 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001739 if (Array) {
1740 const llvm::Type *BasePtr = ConvertType(FieldType);
1741 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1742 llvm::Value *BaseAddrPtr =
1743 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1744 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1745 Array, BaseAddrPtr);
1746 }
1747 else
1748 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1749 Dtor_Complete, LHS.getAddress());
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001750 }
1751
1752 llvm::SmallVector<CXXRecordDecl*, 4> DestructedBases;
1753 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1754 Base != ClassDecl->bases_end(); ++Base) {
1755 // FIXME. copy assignment of virtual base NYI
1756 if (Base->isVirtual())
1757 continue;
1758
1759 CXXRecordDecl *BaseClassDecl
1760 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1761 if (BaseClassDecl->hasTrivialDestructor())
1762 continue;
1763 DestructedBases.push_back(BaseClassDecl);
1764 }
1765 if (DestructedBases.empty())
1766 return;
1767 for (int i = DestructedBases.size() -1; i >= 0; --i) {
1768 CXXRecordDecl *BaseClassDecl = DestructedBases[i];
1769 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
1770 ClassDecl,BaseClassDecl);
1771 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1772 Dtor_Complete, V);
1773 }
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001774}
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001775
1776void CodeGenFunction::SynthesizeDefaultDestructor(const CXXDestructorDecl *CD,
1777 const FunctionDecl *FD,
1778 llvm::Function *Fn,
1779 const FunctionArgList &Args) {
1780
1781 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1782 assert(!ClassDecl->hasUserDeclaredDestructor() &&
1783 "SynthesizeDefaultDestructor - destructor has user declaration");
1784 (void) ClassDecl;
1785
1786 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1787 EmitDtorEpilogue(CD);
1788 FinishFunction();
1789}