blob: 7a2c410fe894ca96da3abd57b61e4549af389b7a [file] [log] [blame]
Anders Carlssone1b29ef2008-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 Carlsson283a0622009-04-13 18:03:33 +000018#include "Mangle.h"
Anders Carlssone1b29ef2008-08-22 16:00:37 +000019#include "clang/AST/ASTContext.h"
Fariborz Jahanian742cd1b2009-07-25 21:12:28 +000020#include "clang/AST/RecordLayout.h"
Anders Carlssone1b29ef2008-08-22 16:00:37 +000021#include "clang/AST/Decl.h"
Anders Carlsson774e7c62009-04-03 22:50:24 +000022#include "clang/AST/DeclCXX.h"
Anders Carlsson86e96442008-08-23 19:42:54 +000023#include "clang/AST/DeclObjC.h"
Anders Carlssone1b29ef2008-08-22 16:00:37 +000024#include "llvm/ADT/StringExtras.h"
Anders Carlssone1b29ef2008-08-22 16:00:37 +000025using namespace clang;
26using namespace CodeGen;
27
Daniel Dunbar0096acf2009-02-25 19:24:29 +000028void
Anders Carlsson3b2e16b2009-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 Anderson0032b272009-08-13 21:57:51 +000034 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Anders Carlsson3b2e16b2009-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 Anderson0032b272009-08-13 21:57:51 +000041 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Params, false);
Anders Carlsson3b2e16b2009-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 Carlsson622f9dc2009-08-17 18:24:57 +000077 ErrorUnsupported(Init, "global variable that binds to a reference");
Anders Carlsson3b2e16b2009-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 Carlsson89ed31d2009-08-08 23:24:23 +000094void
95CodeGenModule::EmitCXXGlobalInitFunc() {
96 if (CXXGlobalInits.empty())
97 return;
98
Owen Anderson0032b272009-08-13 21:57:51 +000099 const llvm::FunctionType *FTy = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
Anders Carlsson89ed31d2009-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 Kramer10c40ee2009-08-08 23:43:26 +0000109 &CXXGlobalInits[0],
Anders Carlsson89ed31d2009-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 Carlsson3b2e16b2009-08-08 21:45:14 +0000129void
130CodeGenFunction::EmitStaticCXXBlockVarDeclInit(const VarDecl &D,
131 llvm::GlobalVariable *GV) {
Daniel Dunbar0096acf2009-02-25 19:24:29 +0000132 // FIXME: This should use __cxa_guard_{acquire,release}?
133
Anders Carlssone1b29ef2008-08-22 16:00:37 +0000134 assert(!getContext().getLangOptions().ThreadsafeStatics &&
135 "thread safe statics are currently not supported!");
Anders Carlssone1b29ef2008-08-22 16:00:37 +0000136
Anders Carlsson283a0622009-04-13 18:03:33 +0000137 llvm::SmallString<256> GuardVName;
138 llvm::raw_svector_ostream GuardVOut(GuardVName);
139 mangleGuardVariable(&D, getContext(), GuardVOut);
140
Anders Carlssone1b29ef2008-08-22 16:00:37 +0000141 // Create the guard variable.
142 llvm::GlobalValue *GuardV =
Owen Anderson0032b272009-08-13 21:57:51 +0000143 new llvm::GlobalVariable(CGM.getModule(), llvm::Type::getInt64Ty(VMContext), false,
Daniel Dunbar0096acf2009-02-25 19:24:29 +0000144 GV->getLinkage(),
Owen Anderson0032b272009-08-13 21:57:51 +0000145 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext)),
Daniel Dunbar77659342009-08-19 20:04:03 +0000146 GuardVName.str());
Anders Carlssone1b29ef2008-08-22 16:00:37 +0000147
Anders Carlssone1b29ef2008-08-22 16:00:37 +0000148 // Load the first byte of the guard variable.
Owen Anderson0032b272009-08-13 21:57:51 +0000149 const llvm::Type *PtrTy = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Anders Carlssone1b29ef2008-08-22 16:00:37 +0000150 llvm::Value *V = Builder.CreateLoad(Builder.CreateBitCast(GuardV, PtrTy),
151 "tmp");
152
153 // Compare it against 0.
Owen Anderson0032b272009-08-13 21:57:51 +0000154 llvm::Value *nullValue = llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext));
Anders Carlssone1b29ef2008-08-22 16:00:37 +0000155 llvm::Value *ICmp = Builder.CreateICmpEQ(V, nullValue , "tobool");
156
Daniel Dunbar55e87422008-11-11 02:29:29 +0000157 llvm::BasicBlock *InitBlock = createBasicBlock("init");
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000158 llvm::BasicBlock *EndBlock = createBasicBlock("init.end");
Anders Carlssone1b29ef2008-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 Carlsson3b2e16b2009-08-08 21:45:14 +0000165 EmitCXXGlobalVarDeclInit(D, GV);
166
Owen Anderson0032b272009-08-13 21:57:51 +0000167 Builder.CreateStore(llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext), 1),
Anders Carlssone1b29ef2008-08-22 16:00:37 +0000168 Builder.CreateBitCast(GuardV, PtrTy));
169
170 EmitBlock(EndBlock);
Anders Carlssone1b29ef2008-08-22 16:00:37 +0000171}
172
Anders Carlssonb9de2c52009-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 Carlsson774e7c62009-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 Carlssonb9de2c52009-05-11 23:37:08 +0000200
Anders Carlssone9918d22009-04-08 20:31:57 +0000201 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
Mike Stump7116da12009-07-30 21:47:44 +0000202
Mike Stumpf1216772009-07-31 18:25:34 +0000203 if (MD->isVirtual()) {
Mike Stump7116da12009-07-30 21:47:44 +0000204 ErrorUnsupported(CE, "virtual dispatch");
205 }
206
Anders Carlsson774e7c62009-04-03 22:50:24 +0000207 const llvm::Type *Ty =
Anders Carlssone9918d22009-04-08 20:31:57 +0000208 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
209 FPT->isVariadic());
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000210 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty);
Anders Carlsson774e7c62009-04-03 22:50:24 +0000211
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000212 llvm::Value *This;
Anders Carlsson774e7c62009-04-03 22:50:24 +0000213
Anders Carlsson774e7c62009-04-03 22:50:24 +0000214 if (ME->isArrow())
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000215 This = EmitScalarExpr(ME->getBase());
Anders Carlsson774e7c62009-04-03 22:50:24 +0000216 else {
217 LValue BaseLV = EmitLValue(ME->getBase());
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000218 This = BaseLV.getAddress();
Anders Carlsson774e7c62009-04-03 22:50:24 +0000219 }
220
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000221 return EmitCXXMemberCall(MD, Callee, This,
222 CE->arg_begin(), CE->arg_end());
Anders Carlsson774e7c62009-04-03 22:50:24 +0000223}
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000224
Anders Carlsson0f294632009-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 Jahanianad258832009-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 Carlsson0f294632009-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 Carlsson5f4307b2009-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 Stumpf5408fe2009-05-16 07:57:57 +0000263 // ans: See how CodeGenFunction::LoadObjCSelf() uses
264 // CodeGenFunction::BlockForwardSelf() for how to do this.
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000265 return Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
266}
Anders Carlsson95d4e5d2009-04-15 15:55:24 +0000267
Fariborz Jahanianc238a792009-07-30 00:10:25 +0000268static bool
269GetNestedPaths(llvm::SmallVectorImpl<const CXXRecordDecl *> &NestedBasePaths,
270 const CXXRecordDecl *ClassDecl,
271 const CXXRecordDecl *BaseClassDecl) {
Fariborz Jahanianc238a792009-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 Stump104ffaa2009-08-04 21:58:42 +0000277 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanianc238a792009-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 Jahanian9e809e72009-07-28 17:38:28 +0000298llvm::Value *CodeGenFunction::AddressCXXOfBaseClass(llvm::Value *BaseValue,
Fariborz Jahanian6d0bdaa2009-07-28 18:09:28 +0000299 const CXXRecordDecl *ClassDecl,
300 const CXXRecordDecl *BaseClassDecl) {
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000301 if (ClassDecl == BaseClassDecl)
302 return BaseValue;
303
Owen Anderson0032b272009-08-13 21:57:51 +0000304 llvm::Type *I8Ptr = llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Fariborz Jahanianc238a792009-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 Jahanian9e809e72009-07-28 17:38:28 +0000312 // Accessing a member of the base class. Must add delata to
313 // the load of 'this'.
Fariborz Jahanianc238a792009-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 Jahanian5a8503b2009-07-29 15:54:56 +0000321 llvm::Value *OffsetVal =
322 llvm::ConstantInt::get(
323 CGM.getTypes().ConvertType(CGM.getContext().LongTy), Offset);
Fariborz Jahanian9e809e72009-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 Jahanian6d0bdaa2009-07-28 18:09:28 +0000328 getContext().getTypeDeclType(const_cast<CXXRecordDecl*>(BaseClassDecl)));
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000329 const llvm::Type *BasePtr = ConvertType(BTy);
Owen Anderson96e0fc72009-07-29 22:16:19 +0000330 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000331 BaseValue = Builder.CreateBitCast(BaseValue, BasePtr);
332 return BaseValue;
333}
334
Fariborz Jahanian288dcaf2009-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 Jahanian0de78992009-08-21 16:31:06 +0000349 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000350 "loop.index");
351 llvm::Value* zeroConstant =
Fariborz Jahanian0de78992009-08-21 16:31:06 +0000352 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
Fariborz Jahanian288dcaf2009-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 Jahanian0de78992009-08-21 16:31:06 +0000367 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
Fariborz Jahanian288dcaf2009-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 Jahanian288dcaf2009-08-19 20:55:16 +0000377 // Inside the loop body, emit the constructor call on the array element.
Fariborz Jahanian995d2812009-08-20 01:01:06 +0000378 Counter = Builder.CreateLoad(IndexPtr);
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000379 if (const ConstantArrayType *CAT =
380 dyn_cast<ConstantArrayType>(Array->getElementType())) {
Fariborz Jahanian0de78992009-08-21 16:31:06 +0000381 uint64_t delta = getContext().getConstantArrayElementCount(CAT);
Fariborz Jahanian995d2812009-08-20 01:01:06 +0000382 // Address = This + delta*Counter for current loop iteration.
Fariborz Jahanian6147a902009-08-20 00:15:15 +0000383 llvm::Value *DeltaPtr =
Fariborz Jahanian0de78992009-08-21 16:31:06 +0000384 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), delta);
Fariborz Jahanian6147a902009-08-20 00:15:15 +0000385 DeltaPtr = Builder.CreateMul(Counter, DeltaPtr, "mul");
386 llvm::Value *Address =
387 Builder.CreateInBoundsGEP(This, DeltaPtr, "arrayidx");
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000388 EmitCXXAggrConstructorCall(D, CAT, Address);
389 }
Fariborz Jahanian6147a902009-08-20 00:15:15 +0000390 else {
Fariborz Jahanian6147a902009-08-20 00:15:15 +0000391 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000392 EmitCXXConstructorCall(D, Ctor_Complete, Address, 0, 0);
Fariborz Jahanian6147a902009-08-20 00:15:15 +0000393 }
394
Fariborz Jahanian288dcaf2009-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 Jahanian288dcaf2009-08-19 20:55:16 +0000408}
409
Fariborz Jahanian1c536bf2009-08-20 23:02:58 +0000410/// EmitCXXAggrDestructorCall - calls the default destructor on array
411/// elements in reverse order of construction.
Anders Carlssonb14095a2009-04-17 00:06:03 +0000412void
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +0000413CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
414 const ArrayType *Array,
415 llvm::Value *This) {
Fariborz Jahanian1c536bf2009-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 Jahanian0de78992009-08-21 16:31:06 +0000420 uint64_t ElementCount = getContext().getConstantArrayElementCount(CA);
Fariborz Jahanian1c536bf2009-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 Jahanianf800f6c2009-08-20 20:54:15 +0000469}
470
471void
Anders Carlssonb14095a2009-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 Jahanian343a3cf2009-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 Carlssonb9de2c52009-05-11 23:37:08 +0000490 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
491
492 EmitCXXMemberCall(D, Callee, This, ArgBeg, ArgEnd);
Anders Carlssonb14095a2009-04-17 00:06:03 +0000493}
494
Anders Carlsson7267c162009-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 Carlssonb14095a2009-04-17 00:06:03 +0000503void
Anders Carlsson31ccf372009-05-03 17:47:16 +0000504CodeGenFunction::EmitCXXConstructExpr(llvm::Value *Dest,
505 const CXXConstructExpr *E) {
Anders Carlssonb14095a2009-04-17 00:06:03 +0000506 assert(Dest && "Must have a destination!");
507
508 const CXXRecordDecl *RD =
Ted Kremenek6217b802009-07-29 21:53:49 +0000509 cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
Anders Carlssonb14095a2009-04-17 00:06:03 +0000510 if (RD->hasTrivialConstructor())
511 return;
Fariborz Jahanian6904cbb2009-08-06 01:02:49 +0000512
513 // Code gen optimization to eliminate copy constructor and return
514 // its first argument instead.
Anders Carlsson92f58222009-08-22 22:30:33 +0000515 if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
Fariborz Jahanian6904cbb2009-08-06 01:02:49 +0000516 CXXConstructExpr::const_arg_iterator i = E->arg_begin();
Fariborz Jahanian1cf9ff82009-08-06 19:12:38 +0000517 EmitAggExpr((*i), Dest, false);
518 return;
Fariborz Jahanian6904cbb2009-08-06 01:02:49 +0000519 }
Anders Carlssonb14095a2009-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 Carlssona00703d2009-05-31 01:40:14 +0000525llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
Anders Carlssoned4e3672009-05-31 20:21:44 +0000526 if (E->isArray()) {
527 ErrorUnsupported(E, "new[] expression");
Owen Anderson03e20502009-07-30 23:11:26 +0000528 return llvm::UndefValue::get(ConvertType(E->getType()));
Anders Carlssoned4e3672009-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 Anderson4a28d5d2009-07-24 23:12:58 +0000540 llvm::ConstantInt::get(ConvertType(SizeTy),
Anders Carlssoned4e3672009-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 Carlssond3fd6ba2009-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 Carlssoned4e3672009-05-31 20:21:44 +0000590
Anders Carlssonf1108532009-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 Carlssond3fd6ba2009-05-31 21:53:59 +0000597 if (NullCheckResult) {
Anders Carlssonf1108532009-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 Andersonc9c88b42009-07-31 20:28:54 +0000604 llvm::Constant::getNullValue(NewPtr->getType()),
Anders Carlssonf1108532009-06-01 00:05:16 +0000605 "isnull");
606
607 Builder.CreateCondBr(IsNull, NewNull, NewNotNull);
608 EmitBlock(NewNotNull);
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000609 }
610
Anders Carlssonf1108532009-06-01 00:05:16 +0000611 NewPtr = Builder.CreateBitCast(NewPtr, ConvertType(E->getType()));
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000612
Anders Carlsson6d0ffad2009-05-31 20:56:36 +0000613 if (AllocType->isPODType()) {
Anders Carlsson215bd202009-06-01 00:26:14 +0000614 if (E->getNumConstructorArgs() > 0) {
Anders Carlsson6d0ffad2009-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 Carlsson3923e952009-05-31 21:07:58 +0000620 if (!hasAggregateLLVMType(AllocType))
Anders Carlsson6d0ffad2009-05-31 20:56:36 +0000621 Builder.CreateStore(EmitScalarExpr(Init), NewPtr);
Anders Carlsson3923e952009-05-31 21:07:58 +0000622 else if (AllocType->isAnyComplexType())
623 EmitComplexExprIntoAddr(Init, NewPtr, AllocType.isVolatileQualified());
Anders Carlsson627a3e52009-05-31 21:12:26 +0000624 else
625 EmitAggExpr(Init, NewPtr, AllocType.isVolatileQualified());
Anders Carlsson6d0ffad2009-05-31 20:56:36 +0000626 }
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000627 } else {
628 // Call the constructor.
629 CXXConstructorDecl *Ctor = E->getConstructor();
Anders Carlsson6d0ffad2009-05-31 20:56:36 +0000630
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000631 EmitCXXConstructorCall(Ctor, Ctor_Complete, NewPtr,
632 E->constructor_arg_begin(),
633 E->constructor_arg_end());
Anders Carlssoned4e3672009-05-31 20:21:44 +0000634 }
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000635
Anders Carlssonf1108532009-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 Andersonc9c88b42009-07-31 20:28:54 +0000645 PHI->addIncoming(llvm::Constant::getNullValue(NewPtr->getType()), NewNull);
Anders Carlssonf1108532009-06-01 00:05:16 +0000646
647 NewPtr = PHI;
648 }
649
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000650 return NewPtr;
Anders Carlssona00703d2009-05-31 01:40:14 +0000651}
652
Anders Carlsson60e282c2009-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 Carlsson27ae5362009-04-17 01:58:57 +0000710static bool canGenerateCXXstructor(const CXXRecordDecl *RD,
711 ASTContext &Context) {
Anders Carlsson59d8e0f2009-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
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000716 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
717 I != E; ++I) {
Anders Carlsson59d8e0f2009-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 Carlsson95d4e5d2009-04-15 15:55:24 +0000726void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) {
Anders Carlsson27ae5362009-04-17 01:58:57 +0000727 if (!canGenerateCXXstructor(D->getParent(), getContext())) {
Anders Carlsson59d8e0f2009-04-15 21:02:13 +0000728 ErrorUnsupported(D, "C++ constructor", true);
729 return;
730 }
Anders Carlsson95d4e5d2009-04-15 15:55:24 +0000731
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000732 EmitGlobal(GlobalDecl(D, Ctor_Complete));
733 EmitGlobal(GlobalDecl(D, Ctor_Base));
Anders Carlsson95d4e5d2009-04-15 15:55:24 +0000734}
Anders Carlsson363c1842009-04-16 23:57:24 +0000735
Anders Carlsson27ae5362009-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 Carlsson363c1842009-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 Lattnerb4880ba2009-05-12 21:21:08 +0000754 return cast<llvm::Function>(
755 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson363c1842009-04-16 23:57:24 +0000756}
Anders Carlsson27ae5362009-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 Lattnerb4880ba2009-05-12 21:21:08 +0000795 return cast<llvm::Function>(
796 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson27ae5362009-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 Jahaniane7d346b2009-07-20 23:18:55 +0000808
Mike Stump32f37012009-08-18 21:49:00 +0000809llvm::Constant *CodeGenModule::GenerateRtti(const CXXRecordDecl *RD) {
Mike Stump738f8c22009-07-31 23:15:31 +0000810 llvm::Type *Ptr8Ty;
Owen Anderson0032b272009-08-13 21:57:51 +0000811 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Mike Stumpcb1b5d32009-08-04 20:06:48 +0000812 llvm::Constant *Rtti = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stump738f8c22009-07-31 23:15:31 +0000813
814 if (!getContext().getLangOptions().Rtti)
Mike Stumpcb1b5d32009-08-04 20:06:48 +0000815 return Rtti;
Mike Stump738f8c22009-07-31 23:15:31 +0000816
817 llvm::SmallString<256> OutName;
818 llvm::raw_svector_ostream Out(OutName);
819 QualType ClassTy;
Mike Stumpe607ed02009-08-07 18:05:12 +0000820 ClassTy = getContext().getTagDeclType(RD);
Mike Stump738f8c22009-07-31 23:15:31 +0000821 mangleCXXRtti(ClassTy, getContext(), Out);
Mike Stump738f8c22009-07-31 23:15:31 +0000822 llvm::GlobalVariable::LinkageTypes linktype;
823 linktype = llvm::GlobalValue::WeakAnyLinkage;
824 std::vector<llvm::Constant *> info;
Mike Stump4ef98092009-08-13 22:53:07 +0000825 // assert(0 && "FIXME: implement rtti descriptor");
Mike Stump738f8c22009-07-31 23:15:31 +0000826 // FIXME: descriptor
827 info.push_back(llvm::Constant::getNullValue(Ptr8Ty));
Mike Stump4ef98092009-08-13 22:53:07 +0000828 // assert(0 && "FIXME: implement rtti ts");
Mike Stump738f8c22009-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 Stump32f37012009-08-18 21:49:00 +0000835 Rtti = new llvm::GlobalVariable(getModule(), type, true, linktype, C,
Daniel Dunbar77659342009-08-19 20:04:03 +0000836 Out.str());
Mike Stumpcb1b5d32009-08-04 20:06:48 +0000837 Rtti = llvm::ConstantExpr::getBitCast(Rtti, Ptr8Ty);
838 return Rtti;
Mike Stump738f8c22009-07-31 23:15:31 +0000839}
840
Mike Stumpeb7e9c32009-08-19 18:10:47 +0000841class VtableBuilder {
Mike Stump7c435fa2009-08-18 20:50:28 +0000842 std::vector<llvm::Constant *> &methods;
843 llvm::Type *Ptr8Ty;
Mike Stumpb9871a22009-08-21 01:45:00 +0000844 /// Class - The most derived class that this vtable is being built for.
Mike Stump32f37012009-08-18 21:49:00 +0000845 const CXXRecordDecl *Class;
Mike Stumpb9871a22009-08-21 01:45:00 +0000846 /// BLayout - Layout for the most derived class that this vtable is being
847 /// built for.
Mike Stumpb46c92d2009-08-19 02:06:38 +0000848 const ASTRecordLayout &BLayout;
Mike Stumpee560f32009-08-19 14:40:47 +0000849 llvm::SmallSet<const CXXRecordDecl *, 32> IndirectPrimary;
Mike Stump7fa0d932009-08-20 02:11:48 +0000850 llvm::SmallSet<const CXXRecordDecl *, 32> SeenVBase;
Mike Stump32f37012009-08-18 21:49:00 +0000851 llvm::Constant *rtti;
Mike Stump7c435fa2009-08-18 20:50:28 +0000852 llvm::LLVMContext &VMContext;
Mike Stump65defe32009-08-18 21:03:28 +0000853 CodeGenModule &CGM; // Per-module state.
Mike Stumpb9871a22009-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 Stump552b2752009-08-18 22:04:08 +0000857 typedef CXXRecordDecl::method_iterator method_iter;
Mike Stump7c435fa2009-08-18 20:50:28 +0000858public:
Mike Stumpeb7e9c32009-08-19 18:10:47 +0000859 VtableBuilder(std::vector<llvm::Constant *> &meth,
860 const CXXRecordDecl *c,
861 CodeGenModule &cgm)
Mike Stumpb46c92d2009-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 Stump7c435fa2009-08-18 20:50:28 +0000865 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
866 }
Mike Stump32f37012009-08-18 21:49:00 +0000867
Mike Stumpb46c92d2009-08-19 02:06:38 +0000868 llvm::Constant *GenerateVcall(const CXXMethodDecl *MD,
869 const CXXRecordDecl *RD,
870 bool VBoundary,
871 bool SecondaryVirtual) {
Mike Stump263b3522009-08-21 23:09:30 +0000872 typedef CXXMethodDecl::method_iterator meth_iter;
873 // No vcall for methods that don't override in primary vtables.
Mike Stumpb46c92d2009-08-19 02:06:38 +0000874 llvm::Constant *m = 0;
875
Mike Stumpb46c92d2009-08-19 02:06:38 +0000876 if (SecondaryVirtual || VBoundary)
877 m = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stump263b3522009-08-21 23:09:30 +0000878
879 int64_t Offset = 0;
880 int64_t BaseOffset = 0;
881 for (meth_iter mi = MD->begin_overridden_methods(),
882 me = MD->end_overridden_methods();
883 mi != me; ++mi) {
884 const CXXRecordDecl *DefBase = (*mi)->getParent();
885 // FIXME: vcall: offset for virtual base for this function
886 // m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), 900);
887 // m = llvm::Constant::getNullValue(Ptr8Ty);
888 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
889 e = RD->bases_end(); i != e; ++i) {
890 const CXXRecordDecl *Base =
891 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
892 if (DefBase == Base) {
893 if (!i->isVirtual())
894 break;
895
896 // FIXME: drop the 700-, just for debugging
897 BaseOffset = 700- -(BLayout.getVBaseClassOffset(Base) / 8);
898 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
899 BaseOffset);
900 m = llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
901 break;
902 } else {
903 // FIXME: more searching.
904 (void)Offset;
905 }
906 }
907 }
908
Mike Stumpb46c92d2009-08-19 02:06:38 +0000909 return m;
910 }
911
912 void GenerateVcalls(const CXXRecordDecl *RD, bool VBoundary,
913 bool SecondaryVirtual) {
Mike Stump7c435fa2009-08-18 20:50:28 +0000914 llvm::Constant *m;
Mike Stump80a0e322009-08-12 23:25:18 +0000915
Mike Stump552b2752009-08-18 22:04:08 +0000916 for (method_iter mi = RD->method_begin(),
Mike Stump7c435fa2009-08-18 20:50:28 +0000917 me = RD->method_end(); mi != me; ++mi) {
918 if (mi->isVirtual()) {
Mike Stumpb46c92d2009-08-19 02:06:38 +0000919 m = GenerateVcall(*mi, RD, VBoundary, SecondaryVirtual);
920 if (m)
921 methods.push_back(m);
Mike Stump7c435fa2009-08-18 20:50:28 +0000922 }
Mike Stump4c3aedd2009-08-12 23:14:12 +0000923 }
Mike Stump80a0e322009-08-12 23:25:18 +0000924 }
Mike Stump4c3aedd2009-08-12 23:14:12 +0000925
Mike Stump7fa0d932009-08-20 02:11:48 +0000926 void GenerateVBaseOffsets(std::vector<llvm::Constant *> &offsets,
Mike Stumpb9837442009-08-20 07:22:17 +0000927 const CXXRecordDecl *RD, uint64_t Offset) {
Mike Stump7fa0d932009-08-20 02:11:48 +0000928 for (CXXRecordDecl::base_class_const_iterator i =RD->bases_begin(),
929 e = RD->bases_end(); i != e; ++i) {
930 const CXXRecordDecl *Base =
931 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
932 if (i->isVirtual() && !SeenVBase.count(Base)) {
933 SeenVBase.insert(Base);
Mike Stumpb9837442009-08-20 07:22:17 +0000934 int64_t BaseOffset = -(Offset/8) + BLayout.getVBaseClassOffset(Base)/8;
Mike Stump7fa0d932009-08-20 02:11:48 +0000935 llvm::Constant *m;
Mike Stumpb9837442009-08-20 07:22:17 +0000936 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),BaseOffset);
Mike Stump7fa0d932009-08-20 02:11:48 +0000937 m = llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
938 offsets.push_back(m);
939 }
Mike Stumpb9837442009-08-20 07:22:17 +0000940 GenerateVBaseOffsets(offsets, Base, Offset);
Mike Stump7fa0d932009-08-20 02:11:48 +0000941 }
942 }
943
Mike Stumpb9871a22009-08-21 01:45:00 +0000944 void StartNewTable() {
945 SeenVBase.clear();
946 }
Mike Stumpbc16aea2009-08-12 23:00:59 +0000947
Mike Stumpb9871a22009-08-21 01:45:00 +0000948 inline uint32_t nottoobig(uint64_t t) {
949 assert(t < (uint32_t)-1ULL || "vtable too big");
950 return t;
951 }
952#if 0
953 inline uint32_t nottoobig(uint32_t t) {
954 return t;
955 }
956#endif
957
958 void AddMethod(const CXXMethodDecl *MD, int32_t FirstIndex) {
959 typedef CXXMethodDecl::method_iterator meth_iter;
960
961 llvm::Constant *m;
962 m = CGM.GetAddrOfFunction(GlobalDecl(MD), Ptr8Ty);
963 m = llvm::ConstantExpr::getBitCast(m, Ptr8Ty);
964
965 // FIXME: Don't like the nested loops. For very large inheritance
966 // heirarchies we could have a table on the side with the final overridder
967 // and just replace each instance of an overridden method once. Would be
968 // nice to measure the cost/benefit on real code.
969
970 // If we can find a previously allocated slot for this, reuse it.
971 for (meth_iter mi = MD->begin_overridden_methods(),
972 e = MD->end_overridden_methods();
973 mi != e; ++mi) {
974 const CXXMethodDecl *OMD = *mi;
975 llvm::Constant *om;
976 om = CGM.GetAddrOfFunction(GlobalDecl(OMD), Ptr8Ty);
977 om = llvm::ConstantExpr::getBitCast(om, Ptr8Ty);
978
979 for (int32_t i = FirstIndex, e = nottoobig(methods.size()); i != e; ++i) {
980 // FIXME: begin_overridden_methods might be too lax, covariance */
981 if (methods[i] == om) {
982 methods[i] = m;
983 Index[MD] = i;
984 return;
985 }
Mike Stump65defe32009-08-18 21:03:28 +0000986 }
Mike Stumpbc16aea2009-08-12 23:00:59 +0000987 }
Mike Stumpb9871a22009-08-21 01:45:00 +0000988
989 // else allocate a new slot.
990 Index[MD] = methods.size();
991 methods.push_back(m);
992 }
993
994 void GenerateMethods(const CXXRecordDecl *RD, int32_t FirstIndex) {
995 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
996 ++mi)
997 if (mi->isVirtual())
998 AddMethod(*mi, FirstIndex);
Mike Stumpbc16aea2009-08-12 23:00:59 +0000999 }
Mike Stump65defe32009-08-18 21:03:28 +00001000
Mike Stump263b3522009-08-21 23:09:30 +00001001 int64_t GenerateVtableForBase(const CXXRecordDecl *RD,
1002 bool forPrimary,
1003 bool VBoundary,
1004 int64_t Offset,
1005 bool ForVirtualBase,
1006 int32_t FirstIndex) {
Mike Stump109b13d2009-08-18 21:30:21 +00001007 llvm::Constant *m = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stump263b3522009-08-21 23:09:30 +00001008 int64_t AddressPoint=0;
Mike Stump276b9f12009-08-16 01:46:26 +00001009
Mike Stump109b13d2009-08-18 21:30:21 +00001010 if (RD && !RD->isDynamicClass())
Mike Stump263b3522009-08-21 23:09:30 +00001011 return 0;
Mike Stump109b13d2009-08-18 21:30:21 +00001012
1013 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1014 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1015 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
1016
Mike Stumpb46c92d2009-08-19 02:06:38 +00001017 if (VBoundary || forPrimary || ForVirtualBase) {
1018 // then comes the the vcall offsets for all our functions...
1019 GenerateVcalls(RD, VBoundary, !forPrimary && ForVirtualBase);
1020 }
1021
Mike Stump109b13d2009-08-18 21:30:21 +00001022 // The virtual base offsets come first...
1023 // FIXME: Audit, is this right?
Mike Stump09765ec2009-08-19 02:53:08 +00001024 if (PrimaryBase == 0 || forPrimary || !PrimaryBaseWasVirtual) {
Mike Stump109b13d2009-08-18 21:30:21 +00001025 std::vector<llvm::Constant *> offsets;
Mike Stumpb9837442009-08-20 07:22:17 +00001026 GenerateVBaseOffsets(offsets, RD, Offset);
Mike Stump109b13d2009-08-18 21:30:21 +00001027 for (std::vector<llvm::Constant *>::reverse_iterator i = offsets.rbegin(),
1028 e = offsets.rend(); i != e; ++i)
1029 methods.push_back(*i);
1030 }
1031
Mike Stump109b13d2009-08-18 21:30:21 +00001032 bool Top = true;
1033
1034 // vtables are composed from the chain of primaries.
1035 if (PrimaryBase) {
1036 if (PrimaryBaseWasVirtual)
1037 IndirectPrimary.insert(PrimaryBase);
1038 Top = false;
Mike Stump263b3522009-08-21 23:09:30 +00001039 AddressPoint = GenerateVtableForBase(PrimaryBase, true, PrimaryBaseWasVirtual|VBoundary,
1040 Offset, PrimaryBaseWasVirtual, FirstIndex);
Mike Stump109b13d2009-08-18 21:30:21 +00001041 }
1042
1043 if (Top) {
1044 int64_t BaseOffset;
1045 if (ForVirtualBase) {
Mike Stump109b13d2009-08-18 21:30:21 +00001046 BaseOffset = -(BLayout.getVBaseClassOffset(RD) / 8);
1047 } else
1048 BaseOffset = -Offset/8;
Mike Stump276b9f12009-08-16 01:46:26 +00001049 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), BaseOffset);
1050 m = llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
1051 methods.push_back(m);
Mike Stump109b13d2009-08-18 21:30:21 +00001052 methods.push_back(rtti);
Mike Stump263b3522009-08-21 23:09:30 +00001053 AddressPoint = methods.size();
Mike Stump276b9f12009-08-16 01:46:26 +00001054 }
Mike Stump4ef98092009-08-13 22:53:07 +00001055
Mike Stump109b13d2009-08-18 21:30:21 +00001056 // And add the virtuals for the class to the primary vtable.
Mike Stumpb9871a22009-08-21 01:45:00 +00001057 GenerateMethods(RD, FirstIndex);
Mike Stump109b13d2009-08-18 21:30:21 +00001058
1059 // and then the non-virtual bases.
1060 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1061 e = RD->bases_end(); i != e; ++i) {
1062 if (i->isVirtual())
1063 continue;
1064 const CXXRecordDecl *Base =
1065 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1066 if (Base != PrimaryBase || PrimaryBaseWasVirtual) {
1067 uint64_t o = Offset + Layout.getBaseClassOffset(Base);
Mike Stumpb9871a22009-08-21 01:45:00 +00001068 StartNewTable();
1069 FirstIndex = methods.size();
1070 GenerateVtableForBase(Base, true, false, o, false, FirstIndex);
Mike Stump109b13d2009-08-18 21:30:21 +00001071 }
1072 }
Mike Stump263b3522009-08-21 23:09:30 +00001073 return AddressPoint;
Mike Stump109b13d2009-08-18 21:30:21 +00001074 }
1075
1076 void GenerateVtableForVBases(const CXXRecordDecl *RD,
Mike Stumpee560f32009-08-19 14:40:47 +00001077 const CXXRecordDecl *Class) {
Mike Stump109b13d2009-08-18 21:30:21 +00001078 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1079 e = RD->bases_end(); i != e; ++i) {
1080 const CXXRecordDecl *Base =
1081 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1082 if (i->isVirtual() && !IndirectPrimary.count(Base)) {
1083 // Mark it so we don't output it twice.
1084 IndirectPrimary.insert(Base);
Mike Stumpb9871a22009-08-21 01:45:00 +00001085 StartNewTable();
Mike Stumpb9837442009-08-20 07:22:17 +00001086 int64_t BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stumpb9871a22009-08-21 01:45:00 +00001087 int32_t FirstIndex = methods.size();
1088 GenerateVtableForBase(Base, false, true, BaseOffset, true, FirstIndex);
Mike Stump109b13d2009-08-18 21:30:21 +00001089 }
1090 if (Base->getNumVBases())
Mike Stumpee560f32009-08-19 14:40:47 +00001091 GenerateVtableForVBases(Base, Class);
Mike Stump276b9f12009-08-16 01:46:26 +00001092 }
1093 }
Mike Stump109b13d2009-08-18 21:30:21 +00001094};
Mike Stump8a12b562009-08-06 15:50:11 +00001095
Mike Stumpf1216772009-07-31 18:25:34 +00001096llvm::Value *CodeGenFunction::GenerateVtable(const CXXRecordDecl *RD) {
Mike Stumpf1216772009-07-31 18:25:34 +00001097 llvm::SmallString<256> OutName;
1098 llvm::raw_svector_ostream Out(OutName);
1099 QualType ClassTy;
Mike Stumpe607ed02009-08-07 18:05:12 +00001100 ClassTy = getContext().getTagDeclType(RD);
Mike Stumpf1216772009-07-31 18:25:34 +00001101 mangleCXXVtable(ClassTy, getContext(), Out);
Mike Stump82b56962009-07-31 21:43:43 +00001102 llvm::GlobalVariable::LinkageTypes linktype;
1103 linktype = llvm::GlobalValue::WeakAnyLinkage;
1104 std::vector<llvm::Constant *> methods;
Mike Stump276b9f12009-08-16 01:46:26 +00001105 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
Mike Stump263b3522009-08-21 23:09:30 +00001106 int64_t Offset;
Mike Stump6f376332009-08-05 22:37:18 +00001107
Mike Stumpeb7e9c32009-08-19 18:10:47 +00001108 VtableBuilder b(methods, RD, CGM);
Mike Stump109b13d2009-08-18 21:30:21 +00001109
Mike Stump276b9f12009-08-16 01:46:26 +00001110 // First comes the vtables for all the non-virtual bases...
Mike Stump263b3522009-08-21 23:09:30 +00001111 Offset = b.GenerateVtableForBase(RD, true, false, 0, false, 0);
Mike Stump21538912009-08-14 01:44:03 +00001112
Mike Stump276b9f12009-08-16 01:46:26 +00001113 // then the vtables for all the virtual bases.
Mike Stumpee560f32009-08-19 14:40:47 +00001114 b.GenerateVtableForVBases(RD, RD);
Mike Stump104ffaa2009-08-04 21:58:42 +00001115
Mike Stump82b56962009-07-31 21:43:43 +00001116 llvm::Constant *C;
1117 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, methods.size());
1118 C = llvm::ConstantArray::get(type, methods);
1119 llvm::Value *vtable = new llvm::GlobalVariable(CGM.getModule(), type, true,
Daniel Dunbar77659342009-08-19 20:04:03 +00001120 linktype, C, Out.str());
Mike Stumpf1216772009-07-31 18:25:34 +00001121 vtable = Builder.CreateBitCast(vtable, Ptr8Ty);
Mike Stumpf1216772009-07-31 18:25:34 +00001122 vtable = Builder.CreateGEP(vtable,
Mike Stump276b9f12009-08-16 01:46:26 +00001123 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
Mike Stump263b3522009-08-21 23:09:30 +00001124 Offset*LLVMPointerWidth/8));
Mike Stumpf1216772009-07-31 18:25:34 +00001125 return vtable;
1126}
1127
Fariborz Jahanianeb0b6d52009-08-21 18:30:26 +00001128/// EmitClassAggrMemberwiseCopy - This routine generates code to copy a class
1129/// array of objects from SrcValue to DestValue. Copying can be either a bitwise
1130/// copy or via a copy constructor call.
1131void CodeGenFunction::EmitClassAggrMemberwiseCopy(llvm::Value *Dest,
1132 llvm::Value *Src,
1133 const ArrayType *Array,
1134 const CXXRecordDecl *BaseClassDecl,
1135 QualType Ty) {
1136 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1137 assert(CA && "VLA cannot be copied over");
1138 bool BitwiseCopy = BaseClassDecl->hasTrivialCopyConstructor();
1139
1140 // Create a temporary for the loop index and initialize it with 0.
1141 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1142 "loop.index");
1143 llvm::Value* zeroConstant =
1144 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
1145 Builder.CreateStore(zeroConstant, IndexPtr, false);
1146 // Start the loop with a block that tests the condition.
1147 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1148 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1149
1150 EmitBlock(CondBlock);
1151
1152 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1153 // Generate: if (loop-index < number-of-elements fall to the loop body,
1154 // otherwise, go to the block after the for-loop.
1155 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
1156 llvm::Value * NumElementsPtr =
1157 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1158 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1159 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
1160 "isless");
1161 // If the condition is true, execute the body.
1162 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1163
1164 EmitBlock(ForBody);
1165 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1166 // Inside the loop body, emit the constructor call on the array element.
1167 Counter = Builder.CreateLoad(IndexPtr);
1168 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1169 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1170 if (BitwiseCopy)
1171 EmitAggregateCopy(Dest, Src, Ty);
1172 else if (CXXConstructorDecl *BaseCopyCtor =
1173 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
1174 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
1175 Ctor_Complete);
1176 CallArgList CallArgs;
1177 // Push the this (Dest) ptr.
1178 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1179 BaseCopyCtor->getThisType(getContext())));
1180
1181 // Push the Src ptr.
1182 CallArgs.push_back(std::make_pair(RValue::get(Src),
1183 BaseCopyCtor->getParamDecl(0)->getType()));
1184 QualType ResultType =
1185 BaseCopyCtor->getType()->getAsFunctionType()->getResultType();
1186 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1187 Callee, CallArgs, BaseCopyCtor);
1188 }
1189 EmitBlock(ContinueBlock);
1190
1191 // Emit the increment of the loop counter.
1192 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1193 Counter = Builder.CreateLoad(IndexPtr);
1194 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1195 Builder.CreateStore(NextVal, IndexPtr, false);
1196
1197 // Finally, branch back up to the condition for the next iteration.
1198 EmitBranch(CondBlock);
1199
1200 // Emit the fall-through block.
1201 EmitBlock(AfterFor, true);
1202}
1203
Fariborz Jahanianc28bbc22009-08-21 22:34:55 +00001204/// EmitClassAggrCopyAssignment - This routine generates code to assign a class
1205/// array of objects from SrcValue to DestValue. Assignment can be either a
1206/// bitwise assignment or via a copy assignment operator function call.
1207/// FIXME. This can be consolidated with EmitClassAggrMemberwiseCopy
1208void CodeGenFunction::EmitClassAggrCopyAssignment(llvm::Value *Dest,
1209 llvm::Value *Src,
1210 const ArrayType *Array,
1211 const CXXRecordDecl *BaseClassDecl,
1212 QualType Ty) {
1213 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1214 assert(CA && "VLA cannot be asssigned");
1215 bool BitwiseAssign = BaseClassDecl->hasTrivialCopyAssignment();
1216
1217 // Create a temporary for the loop index and initialize it with 0.
1218 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1219 "loop.index");
1220 llvm::Value* zeroConstant =
1221 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
1222 Builder.CreateStore(zeroConstant, IndexPtr, false);
1223 // Start the loop with a block that tests the condition.
1224 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1225 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1226
1227 EmitBlock(CondBlock);
1228
1229 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1230 // Generate: if (loop-index < number-of-elements fall to the loop body,
1231 // otherwise, go to the block after the for-loop.
1232 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
1233 llvm::Value * NumElementsPtr =
1234 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1235 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1236 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
1237 "isless");
1238 // If the condition is true, execute the body.
1239 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1240
1241 EmitBlock(ForBody);
1242 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1243 // Inside the loop body, emit the assignment operator call on array element.
1244 Counter = Builder.CreateLoad(IndexPtr);
1245 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1246 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1247 const CXXMethodDecl *MD = 0;
1248 if (BitwiseAssign)
1249 EmitAggregateCopy(Dest, Src, Ty);
1250 else {
1251 bool hasCopyAssign = BaseClassDecl->hasConstCopyAssignment(getContext(),
1252 MD);
1253 assert(hasCopyAssign && "EmitClassAggrCopyAssignment - No user assign");
1254 (void)hasCopyAssign;
1255 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
1256 const llvm::Type *LTy =
1257 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1258 FPT->isVariadic());
1259 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), LTy);
1260
1261 CallArgList CallArgs;
1262 // Push the this (Dest) ptr.
1263 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1264 MD->getThisType(getContext())));
1265
1266 // Push the Src ptr.
1267 CallArgs.push_back(std::make_pair(RValue::get(Src),
1268 MD->getParamDecl(0)->getType()));
1269 QualType ResultType =
1270 MD->getType()->getAsFunctionType()->getResultType();
1271 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1272 Callee, CallArgs, MD);
1273 }
1274 EmitBlock(ContinueBlock);
1275
1276 // Emit the increment of the loop counter.
1277 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1278 Counter = Builder.CreateLoad(IndexPtr);
1279 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1280 Builder.CreateStore(NextVal, IndexPtr, false);
1281
1282 // Finally, branch back up to the condition for the next iteration.
1283 EmitBranch(CondBlock);
1284
1285 // Emit the fall-through block.
1286 EmitBlock(AfterFor, true);
1287}
1288
Fariborz Jahanianca283612009-08-07 23:51:33 +00001289/// EmitClassMemberwiseCopy - This routine generates code to copy a class
1290/// object from SrcValue to DestValue. Copying can be either a bitwise copy
Fariborz Jahanianeb0b6d52009-08-21 18:30:26 +00001291/// or via a copy constructor call.
Fariborz Jahanianca283612009-08-07 23:51:33 +00001292void CodeGenFunction::EmitClassMemberwiseCopy(
Fariborz Jahanian942f4f32009-08-08 23:32:22 +00001293 llvm::Value *Dest, llvm::Value *Src,
Fariborz Jahanianca283612009-08-07 23:51:33 +00001294 const CXXRecordDecl *ClassDecl,
Fariborz Jahanian942f4f32009-08-08 23:32:22 +00001295 const CXXRecordDecl *BaseClassDecl, QualType Ty) {
1296 if (ClassDecl) {
1297 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
1298 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
1299 }
1300 if (BaseClassDecl->hasTrivialCopyConstructor()) {
1301 EmitAggregateCopy(Dest, Src, Ty);
Fariborz Jahanianca283612009-08-07 23:51:33 +00001302 return;
Fariborz Jahanian942f4f32009-08-08 23:32:22 +00001303 }
1304
Fariborz Jahanianca283612009-08-07 23:51:33 +00001305 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian80e4b9e2009-08-08 00:59:58 +00001306 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
Fariborz Jahanianca283612009-08-07 23:51:33 +00001307 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
1308 Ctor_Complete);
Fariborz Jahanianca283612009-08-07 23:51:33 +00001309 CallArgList CallArgs;
1310 // Push the this (Dest) ptr.
1311 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1312 BaseCopyCtor->getThisType(getContext())));
1313
Fariborz Jahanianca283612009-08-07 23:51:33 +00001314 // Push the Src ptr.
1315 CallArgs.push_back(std::make_pair(RValue::get(Src),
Fariborz Jahanian370c8842009-08-10 17:20:45 +00001316 BaseCopyCtor->getParamDecl(0)->getType()));
Fariborz Jahanianca283612009-08-07 23:51:33 +00001317 QualType ResultType =
1318 BaseCopyCtor->getType()->getAsFunctionType()->getResultType();
1319 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1320 Callee, CallArgs, BaseCopyCtor);
1321 }
1322}
Fariborz Jahanian06f598a2009-08-10 18:46:38 +00001323
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001324/// EmitClassCopyAssignment - This routine generates code to copy assign a class
1325/// object from SrcValue to DestValue. Assignment can be either a bitwise
1326/// assignment of via an assignment operator call.
Fariborz Jahanianc28bbc22009-08-21 22:34:55 +00001327// FIXME. Consolidate this with EmitClassMemberwiseCopy as they share a lot.
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001328void CodeGenFunction::EmitClassCopyAssignment(
1329 llvm::Value *Dest, llvm::Value *Src,
1330 const CXXRecordDecl *ClassDecl,
1331 const CXXRecordDecl *BaseClassDecl,
1332 QualType Ty) {
1333 if (ClassDecl) {
1334 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
1335 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
1336 }
1337 if (BaseClassDecl->hasTrivialCopyAssignment()) {
1338 EmitAggregateCopy(Dest, Src, Ty);
1339 return;
1340 }
1341
1342 const CXXMethodDecl *MD = 0;
Fariborz Jahaniane82c3e22009-08-13 00:53:36 +00001343 bool ConstCopyAssignOp = BaseClassDecl->hasConstCopyAssignment(getContext(),
1344 MD);
1345 assert(ConstCopyAssignOp && "EmitClassCopyAssignment - missing copy assign");
1346 (void)ConstCopyAssignOp;
1347
1348 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
1349 const llvm::Type *LTy =
1350 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1351 FPT->isVariadic());
1352 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), LTy);
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001353
Fariborz Jahaniane82c3e22009-08-13 00:53:36 +00001354 CallArgList CallArgs;
1355 // Push the this (Dest) ptr.
1356 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1357 MD->getThisType(getContext())));
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001358
Fariborz Jahaniane82c3e22009-08-13 00:53:36 +00001359 // Push the Src ptr.
1360 CallArgs.push_back(std::make_pair(RValue::get(Src),
1361 MD->getParamDecl(0)->getType()));
1362 QualType ResultType =
1363 MD->getType()->getAsFunctionType()->getResultType();
1364 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1365 Callee, CallArgs, MD);
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001366}
1367
Fariborz Jahanian06f598a2009-08-10 18:46:38 +00001368/// SynthesizeDefaultConstructor - synthesize a default constructor
1369void
1370CodeGenFunction::SynthesizeDefaultConstructor(const CXXConstructorDecl *CD,
1371 const FunctionDecl *FD,
1372 llvm::Function *Fn,
1373 const FunctionArgList &Args) {
1374 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1375 EmitCtorPrologue(CD);
1376 FinishFunction();
1377}
1378
Fariborz Jahanian8c241a22009-08-08 19:31:03 +00001379/// SynthesizeCXXCopyConstructor - This routine implicitly defines body of a copy
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001380/// constructor, in accordance with section 12.8 (p7 and p8) of C++03
1381/// The implicitly-defined copy constructor for class X performs a memberwise
1382/// copy of its subobjects. The order of copying is the same as the order
1383/// of initialization of bases and members in a user-defined constructor
1384/// Each subobject is copied in the manner appropriate to its type:
1385/// if the subobject is of class type, the copy constructor for the class is
1386/// used;
1387/// if the subobject is an array, each element is copied, in the manner
1388/// appropriate to the element type;
1389/// if the subobject is of scalar type, the built-in assignment operator is
1390/// used.
1391/// Virtual base class subobjects shall be copied only once by the
1392/// implicitly-defined copy constructor
1393
Fariborz Jahanian8c241a22009-08-08 19:31:03 +00001394void CodeGenFunction::SynthesizeCXXCopyConstructor(const CXXConstructorDecl *CD,
1395 const FunctionDecl *FD,
1396 llvm::Function *Fn,
Fariborz Jahanianca283612009-08-07 23:51:33 +00001397 const FunctionArgList &Args) {
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001398 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1399 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
Fariborz Jahanian8c241a22009-08-08 19:31:03 +00001400 "SynthesizeCXXCopyConstructor - copy constructor has definition already");
1401 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001402
Fariborz Jahanian1e4edd52009-08-08 00:15:41 +00001403 FunctionArgList::const_iterator i = Args.begin();
1404 const VarDecl *ThisArg = i->first;
1405 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1406 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1407 const VarDecl *SrcArg = (i+1)->first;
1408 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1409 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1410
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001411 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1412 Base != ClassDecl->bases_end(); ++Base) {
1413 // FIXME. copy constrution of virtual base NYI
1414 if (Base->isVirtual())
1415 continue;
Fariborz Jahanianca283612009-08-07 23:51:33 +00001416
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001417 CXXRecordDecl *BaseClassDecl
1418 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian942f4f32009-08-08 23:32:22 +00001419 EmitClassMemberwiseCopy(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1420 Base->getType());
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001421 }
1422
Fariborz Jahanian1e4edd52009-08-08 00:15:41 +00001423 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1424 FieldEnd = ClassDecl->field_end();
1425 Field != FieldEnd; ++Field) {
1426 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanianeb0b6d52009-08-21 18:30:26 +00001427 const ConstantArrayType *Array =
1428 getContext().getAsConstantArrayType(FieldType);
1429 if (Array)
1430 FieldType = getContext().getBaseElementType(FieldType);
1431
Fariborz Jahanian1e4edd52009-08-08 00:15:41 +00001432 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1433 CXXRecordDecl *FieldClassDecl
1434 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1435 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1436 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Fariborz Jahanianeb0b6d52009-08-21 18:30:26 +00001437 if (Array) {
1438 const llvm::Type *BasePtr = ConvertType(FieldType);
1439 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1440 llvm::Value *DestBaseAddrPtr =
1441 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1442 llvm::Value *SrcBaseAddrPtr =
1443 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1444 EmitClassAggrMemberwiseCopy(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1445 FieldClassDecl, FieldType);
1446 }
1447 else
1448 EmitClassMemberwiseCopy(LHS.getAddress(), RHS.getAddress(),
1449 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanian1e4edd52009-08-08 00:15:41 +00001450 continue;
1451 }
Fariborz Jahanianf05fe652009-08-10 18:34:26 +00001452 // Do a built-in assignment of scalar data members.
1453 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1454 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1455 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1456 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanian1e4edd52009-08-08 00:15:41 +00001457 }
Fariborz Jahanian8c241a22009-08-08 19:31:03 +00001458 FinishFunction();
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001459}
1460
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001461/// SynthesizeCXXCopyAssignment - Implicitly define copy assignment operator.
1462/// Before the implicitly-declared copy assignment operator for a class is
1463/// implicitly defined, all implicitly- declared copy assignment operators for
1464/// its direct base classes and its nonstatic data members shall have been
1465/// implicitly defined. [12.8-p12]
1466/// The implicitly-defined copy assignment operator for class X performs
1467/// memberwise assignment of its subob- jects. The direct base classes of X are
1468/// assigned first, in the order of their declaration in
1469/// the base-specifier-list, and then the immediate nonstatic data members of X
1470/// are assigned, in the order in which they were declared in the class
1471/// definition.Each subobject is assigned in the manner appropriate to its type:
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001472/// if the subobject is of class type, the copy assignment operator for the
1473/// class is used (as if by explicit qualification; that is, ignoring any
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001474/// possible virtual overriding functions in more derived classes);
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001475///
1476/// if the subobject is an array, each element is assigned, in the manner
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001477/// appropriate to the element type;
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001478///
1479/// if the subobject is of scalar type, the built-in assignment operator is
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001480/// used.
1481void CodeGenFunction::SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD,
1482 const FunctionDecl *FD,
1483 llvm::Function *Fn,
1484 const FunctionArgList &Args) {
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001485
1486 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1487 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
1488 "SynthesizeCXXCopyAssignment - copy assignment has user declaration");
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001489 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1490
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001491 FunctionArgList::const_iterator i = Args.begin();
1492 const VarDecl *ThisArg = i->first;
1493 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1494 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1495 const VarDecl *SrcArg = (i+1)->first;
1496 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1497 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1498
1499 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1500 Base != ClassDecl->bases_end(); ++Base) {
1501 // FIXME. copy assignment of virtual base NYI
1502 if (Base->isVirtual())
1503 continue;
1504
1505 CXXRecordDecl *BaseClassDecl
1506 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1507 EmitClassCopyAssignment(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1508 Base->getType());
1509 }
1510
1511 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1512 FieldEnd = ClassDecl->field_end();
1513 Field != FieldEnd; ++Field) {
1514 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanianc28bbc22009-08-21 22:34:55 +00001515 const ConstantArrayType *Array =
1516 getContext().getAsConstantArrayType(FieldType);
1517 if (Array)
1518 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001519
1520 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1521 CXXRecordDecl *FieldClassDecl
1522 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1523 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1524 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Fariborz Jahanianc28bbc22009-08-21 22:34:55 +00001525 if (Array) {
1526 const llvm::Type *BasePtr = ConvertType(FieldType);
1527 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1528 llvm::Value *DestBaseAddrPtr =
1529 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1530 llvm::Value *SrcBaseAddrPtr =
1531 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1532 EmitClassAggrCopyAssignment(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1533 FieldClassDecl, FieldType);
1534 }
1535 else
1536 EmitClassCopyAssignment(LHS.getAddress(), RHS.getAddress(),
1537 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001538 continue;
1539 }
1540 // Do a built-in assignment of scalar data members.
1541 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1542 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1543 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1544 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanian183d7182009-08-14 00:01:54 +00001545 }
1546
1547 // return *this;
1548 Builder.CreateStore(LoadOfThis, ReturnValue);
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001549
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001550 FinishFunction();
1551}
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001552
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001553/// EmitCtorPrologue - This routine generates necessary code to initialize
1554/// base classes and non-static data members belonging to this constructor.
1555void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD) {
Fariborz Jahanian742cd1b2009-07-25 21:12:28 +00001556 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
Mike Stumpeb19fa92009-08-06 13:41:24 +00001557 // FIXME: Add vbase initialization
Mike Stumpf1216772009-07-31 18:25:34 +00001558 llvm::Value *LoadOfThis = 0;
Fariborz Jahanian6d0bdaa2009-07-28 18:09:28 +00001559
Fariborz Jahanian742cd1b2009-07-25 21:12:28 +00001560 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001561 E = CD->init_end();
1562 B != E; ++B) {
1563 CXXBaseOrMemberInitializer *Member = (*B);
1564 if (Member->isBaseInitializer()) {
Mike Stumpf1216772009-07-31 18:25:34 +00001565 LoadOfThis = LoadCXXThis();
Fariborz Jahanian6d0bdaa2009-07-28 18:09:28 +00001566 Type *BaseType = Member->getBaseClass();
1567 CXXRecordDecl *BaseClassDecl =
Ted Kremenek6217b802009-07-29 21:53:49 +00001568 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
Fariborz Jahanian6d0bdaa2009-07-28 18:09:28 +00001569 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1570 BaseClassDecl);
Fariborz Jahanian742cd1b2009-07-25 21:12:28 +00001571 EmitCXXConstructorCall(Member->getConstructor(),
1572 Ctor_Complete, V,
1573 Member->const_arg_begin(),
1574 Member->const_arg_end());
Mike Stumpb3589f42009-07-30 22:28:39 +00001575 } else {
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001576 // non-static data member initilaizers.
1577 FieldDecl *Field = Member->getMember();
1578 QualType FieldType = getContext().getCanonicalType((Field)->getType());
Fariborz Jahanian64a54ad2009-08-21 17:09:38 +00001579 const ConstantArrayType *Array =
Fariborz Jahanianeb0b6d52009-08-21 18:30:26 +00001580 getContext().getAsConstantArrayType(FieldType);
Fariborz Jahanian64a54ad2009-08-21 17:09:38 +00001581 if (Array)
1582 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian8c64e002009-08-10 23:56:17 +00001583
Mike Stumpf1216772009-07-31 18:25:34 +00001584 LoadOfThis = LoadCXXThis();
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001585 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
Ted Kremenek6217b802009-07-29 21:53:49 +00001586 if (FieldType->getAs<RecordType>()) {
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001587 if (!Field->isAnonymousStructOrUnion()) {
Fariborz Jahanian50b8eea2009-07-24 17:57:02 +00001588 assert(Member->getConstructor() &&
1589 "EmitCtorPrologue - no constructor to initialize member");
Fariborz Jahanian64a54ad2009-08-21 17:09:38 +00001590 if (Array) {
1591 const llvm::Type *BasePtr = ConvertType(FieldType);
1592 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1593 llvm::Value *BaseAddrPtr =
1594 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1595 EmitCXXAggrConstructorCall(Member->getConstructor(),
1596 Array, BaseAddrPtr);
1597 }
1598 else
1599 EmitCXXConstructorCall(Member->getConstructor(),
1600 Ctor_Complete, LHS.getAddress(),
1601 Member->const_arg_begin(),
1602 Member->const_arg_end());
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001603 continue;
1604 }
1605 else {
1606 // Initializing an anonymous union data member.
1607 FieldDecl *anonMember = Member->getAnonUnionMember();
1608 LHS = EmitLValueForField(LHS.getAddress(), anonMember, false, 0);
1609 FieldType = anonMember->getType();
1610 }
Fariborz Jahanian50b8eea2009-07-24 17:57:02 +00001611 }
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001612
1613 assert(Member->getNumArgs() == 1 && "Initializer count must be 1 only");
Fariborz Jahanian50b8eea2009-07-24 17:57:02 +00001614 Expr *RhsExpr = *Member->arg_begin();
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001615 llvm::Value *RHS = EmitScalarExpr(RhsExpr, true);
Fariborz Jahanian8c64e002009-08-10 23:56:17 +00001616 EmitStoreThroughLValue(RValue::get(RHS), LHS, FieldType);
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001617 }
1618 }
Mike Stumpf1216772009-07-31 18:25:34 +00001619
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001620 if (!CD->getNumBaseOrMemberInitializers() && !CD->isTrivial()) {
Fariborz Jahanian1d9b5ef2009-08-15 18:55:17 +00001621 // Nontrivial default constructor with no initializer list. It may still
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001622 // have bases classes and/or contain non-static data members which require
1623 // construction.
1624 for (CXXRecordDecl::base_class_const_iterator Base =
1625 ClassDecl->bases_begin();
1626 Base != ClassDecl->bases_end(); ++Base) {
1627 // FIXME. copy assignment of virtual base NYI
1628 if (Base->isVirtual())
1629 continue;
1630
1631 CXXRecordDecl *BaseClassDecl
1632 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1633 if (BaseClassDecl->hasTrivialConstructor())
1634 continue;
1635 if (CXXConstructorDecl *BaseCX =
1636 BaseClassDecl->getDefaultConstructor(getContext())) {
1637 LoadOfThis = LoadCXXThis();
1638 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1639 BaseClassDecl);
1640 EmitCXXConstructorCall(BaseCX, Ctor_Complete, V, 0, 0);
1641 }
1642 }
1643
Fariborz Jahanian1d9b5ef2009-08-15 18:55:17 +00001644 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1645 FieldEnd = ClassDecl->field_end();
1646 Field != FieldEnd; ++Field) {
1647 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +00001648 const ConstantArrayType *Array =
1649 getContext().getAsConstantArrayType(FieldType);
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +00001650 if (Array)
1651 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian1d9b5ef2009-08-15 18:55:17 +00001652 if (!FieldType->getAs<RecordType>() || Field->isAnonymousStructOrUnion())
1653 continue;
1654 const RecordType *ClassRec = FieldType->getAs<RecordType>();
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001655 CXXRecordDecl *MemberClassDecl =
1656 dyn_cast<CXXRecordDecl>(ClassRec->getDecl());
1657 if (!MemberClassDecl || MemberClassDecl->hasTrivialConstructor())
1658 continue;
1659 if (CXXConstructorDecl *MamberCX =
1660 MemberClassDecl->getDefaultConstructor(getContext())) {
1661 LoadOfThis = LoadCXXThis();
1662 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +00001663 if (Array) {
1664 const llvm::Type *BasePtr = ConvertType(FieldType);
1665 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1666 llvm::Value *BaseAddrPtr =
1667 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1668 EmitCXXAggrConstructorCall(MamberCX, Array, BaseAddrPtr);
1669 }
1670 else
1671 EmitCXXConstructorCall(MamberCX, Ctor_Complete, LHS.getAddress(),
1672 0, 0);
Fariborz Jahanian1d9b5ef2009-08-15 18:55:17 +00001673 }
1674 }
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001675 }
1676
Mike Stumpf1216772009-07-31 18:25:34 +00001677 // Initialize the vtable pointer
Mike Stumpb502d832009-08-05 22:59:44 +00001678 if (ClassDecl->isDynamicClass()) {
Mike Stumpf1216772009-07-31 18:25:34 +00001679 if (!LoadOfThis)
1680 LoadOfThis = LoadCXXThis();
1681 llvm::Value *VtableField;
1682 llvm::Type *Ptr8Ty, *PtrPtr8Ty;
Owen Anderson0032b272009-08-13 21:57:51 +00001683 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Mike Stumpf1216772009-07-31 18:25:34 +00001684 PtrPtr8Ty = llvm::PointerType::get(Ptr8Ty, 0);
1685 VtableField = Builder.CreateBitCast(LoadOfThis, PtrPtr8Ty);
1686 llvm::Value *vtable = GenerateVtable(ClassDecl);
1687 Builder.CreateStore(vtable, VtableField);
1688 }
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001689}
Fariborz Jahanian426cc382009-07-30 17:49:11 +00001690
1691/// EmitDtorEpilogue - Emit all code that comes at the end of class's
1692/// destructor. This is to call destructors on members and base classes
1693/// in reverse order of their construction.
1694void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD) {
1695 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(DD->getDeclContext());
1696 assert(!ClassDecl->isPolymorphic() &&
1697 "FIXME. polymorphic destruction not supported");
1698 (void)ClassDecl; // prevent warning.
1699
1700 for (CXXDestructorDecl::destr_const_iterator *B = DD->destr_begin(),
1701 *E = DD->destr_end(); B != E; ++B) {
1702 uintptr_t BaseOrMember = (*B);
1703 if (DD->isMemberToDestroy(BaseOrMember)) {
1704 FieldDecl *FD = DD->getMemberToDestroy(BaseOrMember);
1705 QualType FieldType = getContext().getCanonicalType((FD)->getType());
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +00001706 const ConstantArrayType *Array =
1707 getContext().getAsConstantArrayType(FieldType);
1708 if (Array)
1709 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian426cc382009-07-30 17:49:11 +00001710 const RecordType *RT = FieldType->getAs<RecordType>();
1711 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1712 if (FieldClassDecl->hasTrivialDestructor())
1713 continue;
1714 llvm::Value *LoadOfThis = LoadCXXThis();
1715 LValue LHS = EmitLValueForField(LoadOfThis, FD, false, 0);
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +00001716 if (Array) {
1717 const llvm::Type *BasePtr = ConvertType(FieldType);
1718 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1719 llvm::Value *BaseAddrPtr =
1720 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1721 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1722 Array, BaseAddrPtr);
1723 }
1724 else
1725 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1726 Dtor_Complete, LHS.getAddress());
Mike Stumpb3589f42009-07-30 22:28:39 +00001727 } else {
Fariborz Jahanian426cc382009-07-30 17:49:11 +00001728 const RecordType *RT =
1729 DD->getAnyBaseClassToDestroy(BaseOrMember)->getAs<RecordType>();
1730 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1731 if (BaseClassDecl->hasTrivialDestructor())
1732 continue;
1733 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
1734 ClassDecl,BaseClassDecl);
1735 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1736 Dtor_Complete, V);
1737 }
1738 }
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001739 if (DD->getNumBaseOrMemberDestructions() || DD->isTrivial())
1740 return;
1741 // Case of destructor synthesis with fields and base classes
1742 // which have non-trivial destructors. They must be destructed in
1743 // reverse order of their construction.
1744 llvm::SmallVector<FieldDecl *, 16> DestructedFields;
1745
1746 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1747 FieldEnd = ClassDecl->field_end();
1748 Field != FieldEnd; ++Field) {
1749 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +00001750 if (getContext().getAsConstantArrayType(FieldType))
1751 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001752 if (const RecordType *RT = FieldType->getAs<RecordType>()) {
1753 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1754 if (FieldClassDecl->hasTrivialDestructor())
1755 continue;
1756 DestructedFields.push_back(*Field);
1757 }
1758 }
1759 if (!DestructedFields.empty())
1760 for (int i = DestructedFields.size() -1; i >= 0; --i) {
1761 FieldDecl *Field = DestructedFields[i];
1762 QualType FieldType = Field->getType();
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +00001763 const ConstantArrayType *Array =
1764 getContext().getAsConstantArrayType(FieldType);
1765 if (Array)
1766 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001767 const RecordType *RT = FieldType->getAs<RecordType>();
1768 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1769 llvm::Value *LoadOfThis = LoadCXXThis();
1770 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +00001771 if (Array) {
1772 const llvm::Type *BasePtr = ConvertType(FieldType);
1773 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1774 llvm::Value *BaseAddrPtr =
1775 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1776 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1777 Array, BaseAddrPtr);
1778 }
1779 else
1780 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1781 Dtor_Complete, LHS.getAddress());
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001782 }
1783
1784 llvm::SmallVector<CXXRecordDecl*, 4> DestructedBases;
1785 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1786 Base != ClassDecl->bases_end(); ++Base) {
1787 // FIXME. copy assignment of virtual base NYI
1788 if (Base->isVirtual())
1789 continue;
1790
1791 CXXRecordDecl *BaseClassDecl
1792 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1793 if (BaseClassDecl->hasTrivialDestructor())
1794 continue;
1795 DestructedBases.push_back(BaseClassDecl);
1796 }
1797 if (DestructedBases.empty())
1798 return;
1799 for (int i = DestructedBases.size() -1; i >= 0; --i) {
1800 CXXRecordDecl *BaseClassDecl = DestructedBases[i];
1801 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
1802 ClassDecl,BaseClassDecl);
1803 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1804 Dtor_Complete, V);
1805 }
Fariborz Jahanian426cc382009-07-30 17:49:11 +00001806}
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001807
1808void CodeGenFunction::SynthesizeDefaultDestructor(const CXXDestructorDecl *CD,
1809 const FunctionDecl *FD,
1810 llvm::Function *Fn,
1811 const FunctionArgList &Args) {
1812
1813 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1814 assert(!ClassDecl->hasUserDeclaredDestructor() &&
1815 "SynthesizeDefaultDestructor - destructor has user declaration");
1816 (void) ClassDecl;
1817
1818 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1819 EmitDtorEpilogue(CD);
1820 FinishFunction();
1821}