blob: 4bf6a49774eba7f2351f506de8ff4ac90f456377 [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
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000203 const llvm::Type *Ty =
Anders Carlssonc5223142009-04-08 20:31:57 +0000204 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
205 FPT->isVariadic());
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000206 llvm::Value *This;
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000207
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000208 if (ME->isArrow())
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000209 This = EmitScalarExpr(ME->getBase());
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000210 else {
211 LValue BaseLV = EmitLValue(ME->getBase());
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000212 This = BaseLV.getAddress();
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000213 }
Mike Stump48cf0392009-08-26 01:54:35 +0000214
215 llvm::Value *Callee;
216 if (MD->isVirtual())
217 Callee = BuildVirtualCall(MD, This, Ty);
218 else
219 Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty);
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000220
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.
Fariborz Jahanian58a7eca2009-08-26 00:23:27 +0000365 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000366 llvm::Value * NumElementsPtr =
Fariborz Jahanian58a7eca2009-08-26 00:23:27 +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 Jahanian58a7eca2009-08-26 00:23:27 +0000379 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
380 EmitCXXConstructorCall(D, Ctor_Complete, Address, 0, 0);
Fariborz Jahanianf36f8d22009-08-20 00:15:15 +0000381
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000382 EmitBlock(ContinueBlock);
383
384 // Emit the increment of the loop counter.
385 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
386 Counter = Builder.CreateLoad(IndexPtr);
387 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
388 Builder.CreateStore(NextVal, IndexPtr, false);
389
390 // Finally, branch back up to the condition for the next iteration.
391 EmitBranch(CondBlock);
392
393 // Emit the fall-through block.
394 EmitBlock(AfterFor, true);
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000395}
396
Fariborz Jahanian25879ce2009-08-20 23:02:58 +0000397/// EmitCXXAggrDestructorCall - calls the default destructor on array
398/// elements in reverse order of construction.
Anders Carlsson72f48292009-04-17 00:06:03 +0000399void
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +0000400CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
401 const ArrayType *Array,
402 llvm::Value *This) {
Fariborz Jahanian25879ce2009-08-20 23:02:58 +0000403 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
404 assert(CA && "Do we support VLA for destruction ?");
405 llvm::Value *One = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
406 1);
Fariborz Jahaniandae3e752009-08-21 16:31:06 +0000407 uint64_t ElementCount = getContext().getConstantArrayElementCount(CA);
Fariborz Jahanian25879ce2009-08-20 23:02:58 +0000408 // Create a temporary for the loop index and initialize it with count of
409 // array elements.
410 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
411 "loop.index");
412 // Index = ElementCount;
413 llvm::Value* UpperCount =
414 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), ElementCount);
415 Builder.CreateStore(UpperCount, IndexPtr, false);
416
417 // Start the loop with a block that tests the condition.
418 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
419 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
420
421 EmitBlock(CondBlock);
422
423 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
424
425 // Generate: if (loop-index != 0 fall to the loop body,
426 // otherwise, go to the block after the for-loop.
427 llvm::Value* zeroConstant =
428 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
429 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
430 llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant,
431 "isne");
432 // If the condition is true, execute the body.
433 Builder.CreateCondBr(IsNE, ForBody, AfterFor);
434
435 EmitBlock(ForBody);
436
437 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
438 // Inside the loop body, emit the constructor call on the array element.
439 Counter = Builder.CreateLoad(IndexPtr);
440 Counter = Builder.CreateSub(Counter, One);
441 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
442 EmitCXXDestructorCall(D, Dtor_Complete, Address);
443
444 EmitBlock(ContinueBlock);
445
446 // Emit the decrement of the loop counter.
447 Counter = Builder.CreateLoad(IndexPtr);
448 Counter = Builder.CreateSub(Counter, One, "dec");
449 Builder.CreateStore(Counter, IndexPtr, false);
450
451 // Finally, branch back up to the condition for the next iteration.
452 EmitBranch(CondBlock);
453
454 // Emit the fall-through block.
455 EmitBlock(AfterFor, true);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +0000456}
457
458void
Anders Carlsson72f48292009-04-17 00:06:03 +0000459CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
460 CXXCtorType Type,
461 llvm::Value *This,
462 CallExpr::const_arg_iterator ArgBeg,
463 CallExpr::const_arg_iterator ArgEnd) {
Fariborz Jahanian0fc5f252009-08-14 20:11:43 +0000464 if (D->isCopyConstructor(getContext())) {
465 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D->getDeclContext());
466 if (ClassDecl->hasTrivialCopyConstructor()) {
467 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
468 "EmitCXXConstructorCall - user declared copy constructor");
469 const Expr *E = (*ArgBeg);
470 QualType Ty = E->getType();
471 llvm::Value *Src = EmitLValue(E).getAddress();
472 EmitAggregateCopy(This, Src, Ty);
473 return;
474 }
475 }
476
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000477 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
478
479 EmitCXXMemberCall(D, Callee, This, ArgBeg, ArgEnd);
Anders Carlsson72f48292009-04-17 00:06:03 +0000480}
481
Anders Carlssond3f6b162009-05-29 21:03:38 +0000482void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *D,
483 CXXDtorType Type,
484 llvm::Value *This) {
485 llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(D, Type);
486
487 EmitCXXMemberCall(D, Callee, This, 0, 0);
488}
489
Anders Carlsson72f48292009-04-17 00:06:03 +0000490void
Anders Carlsson342aadc2009-05-03 17:47:16 +0000491CodeGenFunction::EmitCXXConstructExpr(llvm::Value *Dest,
492 const CXXConstructExpr *E) {
Anders Carlsson72f48292009-04-17 00:06:03 +0000493 assert(Dest && "Must have a destination!");
494
495 const CXXRecordDecl *RD =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000496 cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson72f48292009-04-17 00:06:03 +0000497 if (RD->hasTrivialConstructor())
498 return;
Fariborz Jahanian884036a2009-08-06 01:02:49 +0000499
500 // Code gen optimization to eliminate copy constructor and return
501 // its first argument instead.
Anders Carlsson9a0c2a52009-08-22 22:30:33 +0000502 if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
Fariborz Jahanian884036a2009-08-06 01:02:49 +0000503 CXXConstructExpr::const_arg_iterator i = E->arg_begin();
Fariborz Jahanian325cdd82009-08-06 19:12:38 +0000504 EmitAggExpr((*i), Dest, false);
505 return;
Fariborz Jahanian884036a2009-08-06 01:02:49 +0000506 }
Anders Carlsson72f48292009-04-17 00:06:03 +0000507 // Call the constructor.
508 EmitCXXConstructorCall(E->getConstructor(), Ctor_Complete, Dest,
509 E->arg_begin(), E->arg_end());
510}
511
Anders Carlsson18e88bc2009-05-31 01:40:14 +0000512llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
Anders Carlssond5536972009-05-31 20:21:44 +0000513 if (E->isArray()) {
514 ErrorUnsupported(E, "new[] expression");
Owen Andersone0b5eff2009-07-30 23:11:26 +0000515 return llvm::UndefValue::get(ConvertType(E->getType()));
Anders Carlssond5536972009-05-31 20:21:44 +0000516 }
517
518 QualType AllocType = E->getAllocatedType();
519 FunctionDecl *NewFD = E->getOperatorNew();
520 const FunctionProtoType *NewFTy = NewFD->getType()->getAsFunctionProtoType();
521
522 CallArgList NewArgs;
523
524 // The allocation size is the first argument.
525 QualType SizeTy = getContext().getSizeType();
526 llvm::Value *AllocSize =
Owen Andersonb17ec712009-07-24 23:12:58 +0000527 llvm::ConstantInt::get(ConvertType(SizeTy),
Anders Carlssond5536972009-05-31 20:21:44 +0000528 getContext().getTypeSize(AllocType) / 8);
529
530 NewArgs.push_back(std::make_pair(RValue::get(AllocSize), SizeTy));
531
532 // Emit the rest of the arguments.
533 // FIXME: Ideally, this should just use EmitCallArgs.
534 CXXNewExpr::const_arg_iterator NewArg = E->placement_arg_begin();
535
536 // First, use the types from the function type.
537 // We start at 1 here because the first argument (the allocation size)
538 // has already been emitted.
539 for (unsigned i = 1, e = NewFTy->getNumArgs(); i != e; ++i, ++NewArg) {
540 QualType ArgType = NewFTy->getArgType(i);
541
542 assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
543 getTypePtr() ==
544 getContext().getCanonicalType(NewArg->getType()).getTypePtr() &&
545 "type mismatch in call argument!");
546
547 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
548 ArgType));
549
550 }
551
552 // Either we've emitted all the call args, or we have a call to a
553 // variadic function.
554 assert((NewArg == E->placement_arg_end() || NewFTy->isVariadic()) &&
555 "Extra arguments in non-variadic function!");
556
557 // If we still have any arguments, emit them using the type of the argument.
558 for (CXXNewExpr::const_arg_iterator NewArgEnd = E->placement_arg_end();
559 NewArg != NewArgEnd; ++NewArg) {
560 QualType ArgType = NewArg->getType();
561 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
562 ArgType));
563 }
564
565 // Emit the call to new.
566 RValue RV =
567 EmitCall(CGM.getTypes().getFunctionInfo(NewFTy->getResultType(), NewArgs),
568 CGM.GetAddrOfFunction(GlobalDecl(NewFD)),
569 NewArgs, NewFD);
570
Anders Carlsson11269042009-05-31 21:53:59 +0000571 // If an allocation function is declared with an empty exception specification
572 // it returns null to indicate failure to allocate storage. [expr.new]p13.
573 // (We don't need to check for null when there's no new initializer and
574 // we're allocating a POD type).
575 bool NullCheckResult = NewFTy->hasEmptyExceptionSpec() &&
576 !(AllocType->isPODType() && !E->hasInitializer());
Anders Carlssond5536972009-05-31 20:21:44 +0000577
Anders Carlssondbee9a52009-06-01 00:05:16 +0000578 llvm::BasicBlock *NewNull = 0;
579 llvm::BasicBlock *NewNotNull = 0;
580 llvm::BasicBlock *NewEnd = 0;
581
582 llvm::Value *NewPtr = RV.getScalarVal();
583
Anders Carlsson11269042009-05-31 21:53:59 +0000584 if (NullCheckResult) {
Anders Carlssondbee9a52009-06-01 00:05:16 +0000585 NewNull = createBasicBlock("new.null");
586 NewNotNull = createBasicBlock("new.notnull");
587 NewEnd = createBasicBlock("new.end");
588
589 llvm::Value *IsNull =
590 Builder.CreateICmpEQ(NewPtr,
Owen Andersonf37b84b2009-07-31 20:28:54 +0000591 llvm::Constant::getNullValue(NewPtr->getType()),
Anders Carlssondbee9a52009-06-01 00:05:16 +0000592 "isnull");
593
594 Builder.CreateCondBr(IsNull, NewNull, NewNotNull);
595 EmitBlock(NewNotNull);
Anders Carlsson11269042009-05-31 21:53:59 +0000596 }
597
Anders Carlssondbee9a52009-06-01 00:05:16 +0000598 NewPtr = Builder.CreateBitCast(NewPtr, ConvertType(E->getType()));
Anders Carlsson11269042009-05-31 21:53:59 +0000599
Anders Carlsson7c294782009-05-31 20:56:36 +0000600 if (AllocType->isPODType()) {
Anders Carlsson26910f62009-06-01 00:26:14 +0000601 if (E->getNumConstructorArgs() > 0) {
Anders Carlsson7c294782009-05-31 20:56:36 +0000602 assert(E->getNumConstructorArgs() == 1 &&
603 "Can only have one argument to initializer of POD type.");
604
605 const Expr *Init = E->getConstructorArg(0);
606
Anders Carlsson5f93ccf2009-05-31 21:07:58 +0000607 if (!hasAggregateLLVMType(AllocType))
Anders Carlsson7c294782009-05-31 20:56:36 +0000608 Builder.CreateStore(EmitScalarExpr(Init), NewPtr);
Anders Carlsson5f93ccf2009-05-31 21:07:58 +0000609 else if (AllocType->isAnyComplexType())
610 EmitComplexExprIntoAddr(Init, NewPtr, AllocType.isVolatileQualified());
Anders Carlssoneb39b432009-05-31 21:12:26 +0000611 else
612 EmitAggExpr(Init, NewPtr, AllocType.isVolatileQualified());
Anders Carlsson7c294782009-05-31 20:56:36 +0000613 }
Anders Carlsson11269042009-05-31 21:53:59 +0000614 } else {
615 // Call the constructor.
616 CXXConstructorDecl *Ctor = E->getConstructor();
Anders Carlsson7c294782009-05-31 20:56:36 +0000617
Anders Carlsson11269042009-05-31 21:53:59 +0000618 EmitCXXConstructorCall(Ctor, Ctor_Complete, NewPtr,
619 E->constructor_arg_begin(),
620 E->constructor_arg_end());
Anders Carlssond5536972009-05-31 20:21:44 +0000621 }
Anders Carlsson11269042009-05-31 21:53:59 +0000622
Anders Carlssondbee9a52009-06-01 00:05:16 +0000623 if (NullCheckResult) {
624 Builder.CreateBr(NewEnd);
625 EmitBlock(NewNull);
626 Builder.CreateBr(NewEnd);
627 EmitBlock(NewEnd);
628
629 llvm::PHINode *PHI = Builder.CreatePHI(NewPtr->getType());
630 PHI->reserveOperandSpace(2);
631 PHI->addIncoming(NewPtr, NewNotNull);
Owen Andersonf37b84b2009-07-31 20:28:54 +0000632 PHI->addIncoming(llvm::Constant::getNullValue(NewPtr->getType()), NewNull);
Anders Carlssondbee9a52009-06-01 00:05:16 +0000633
634 NewPtr = PHI;
635 }
636
Anders Carlsson11269042009-05-31 21:53:59 +0000637 return NewPtr;
Anders Carlsson18e88bc2009-05-31 01:40:14 +0000638}
639
Anders Carlsson133fdaf2009-08-16 21:13:42 +0000640void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
641 if (E->isArrayForm()) {
642 ErrorUnsupported(E, "delete[] expression");
643 return;
644 };
645
646 QualType DeleteTy =
647 E->getArgument()->getType()->getAs<PointerType>()->getPointeeType();
648
649 llvm::Value *Ptr = EmitScalarExpr(E->getArgument());
650
651 // Null check the pointer.
652 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
653 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
654
655 llvm::Value *IsNull =
656 Builder.CreateICmpEQ(Ptr, llvm::Constant::getNullValue(Ptr->getType()),
657 "isnull");
658
659 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
660 EmitBlock(DeleteNotNull);
661
662 // Call the destructor if necessary.
663 if (const RecordType *RT = DeleteTy->getAs<RecordType>()) {
664 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
665 if (!RD->hasTrivialDestructor()) {
666 const CXXDestructorDecl *Dtor = RD->getDestructor(getContext());
667 if (Dtor->isVirtual()) {
668 ErrorUnsupported(E, "delete expression with virtual destructor");
669 return;
670 }
671
672 EmitCXXDestructorCall(Dtor, Dtor_Complete, Ptr);
673 }
674 }
675 }
676
677 // Call delete.
678 FunctionDecl *DeleteFD = E->getOperatorDelete();
679 const FunctionProtoType *DeleteFTy =
680 DeleteFD->getType()->getAsFunctionProtoType();
681
682 CallArgList DeleteArgs;
683
684 QualType ArgTy = DeleteFTy->getArgType(0);
685 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
686 DeleteArgs.push_back(std::make_pair(RValue::get(DeletePtr), ArgTy));
687
688 // Emit the call to delete.
689 EmitCall(CGM.getTypes().getFunctionInfo(DeleteFTy->getResultType(),
690 DeleteArgs),
691 CGM.GetAddrOfFunction(GlobalDecl(DeleteFD)),
692 DeleteArgs, DeleteFD);
693
694 EmitBlock(DeleteEnd);
695}
696
Anders Carlsson4811c302009-04-17 01:58:57 +0000697static bool canGenerateCXXstructor(const CXXRecordDecl *RD,
698 ASTContext &Context) {
Anders Carlsson8496c692009-04-15 21:02:13 +0000699 // The class has base classes - we don't support that right now.
700 if (RD->getNumBases() > 0)
701 return false;
702
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000703 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
704 I != E; ++I) {
Anders Carlsson8496c692009-04-15 21:02:13 +0000705 // We don't support ctors for fields that aren't POD.
706 if (!I->getType()->isPODType())
707 return false;
708 }
709
710 return true;
711}
712
Anders Carlsson652951a2009-04-15 15:55:24 +0000713void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) {
Anders Carlsson4811c302009-04-17 01:58:57 +0000714 if (!canGenerateCXXstructor(D->getParent(), getContext())) {
Anders Carlsson8496c692009-04-15 21:02:13 +0000715 ErrorUnsupported(D, "C++ constructor", true);
716 return;
717 }
Anders Carlsson652951a2009-04-15 15:55:24 +0000718
Anders Carlsson1764af42009-05-05 04:44:02 +0000719 EmitGlobal(GlobalDecl(D, Ctor_Complete));
720 EmitGlobal(GlobalDecl(D, Ctor_Base));
Anders Carlsson652951a2009-04-15 15:55:24 +0000721}
Anders Carlsson890a9fd2009-04-16 23:57:24 +0000722
Anders Carlsson4811c302009-04-17 01:58:57 +0000723void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D,
724 CXXCtorType Type) {
725
726 llvm::Function *Fn = GetAddrOfCXXConstructor(D, Type);
727
728 CodeGenFunction(*this).GenerateCode(D, Fn);
729
730 SetFunctionDefinitionAttributes(D, Fn);
731 SetLLVMFunctionAttributesForDefinition(D, Fn);
732}
733
Anders Carlsson890a9fd2009-04-16 23:57:24 +0000734llvm::Function *
735CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
736 CXXCtorType Type) {
737 const llvm::FunctionType *FTy =
738 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false);
739
740 const char *Name = getMangledCXXCtorName(D, Type);
Chris Lattner80f39cc2009-05-12 21:21:08 +0000741 return cast<llvm::Function>(
742 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson890a9fd2009-04-16 23:57:24 +0000743}
Anders Carlsson4811c302009-04-17 01:58:57 +0000744
745const char *CodeGenModule::getMangledCXXCtorName(const CXXConstructorDecl *D,
746 CXXCtorType Type) {
747 llvm::SmallString<256> Name;
748 llvm::raw_svector_ostream Out(Name);
749 mangleCXXCtor(D, Type, Context, Out);
750
751 Name += '\0';
752 return UniqueMangledName(Name.begin(), Name.end());
753}
754
755void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) {
756 if (!canGenerateCXXstructor(D->getParent(), getContext())) {
757 ErrorUnsupported(D, "C++ destructor", true);
758 return;
759 }
760
761 EmitCXXDestructor(D, Dtor_Complete);
762 EmitCXXDestructor(D, Dtor_Base);
763}
764
765void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D,
766 CXXDtorType Type) {
767 llvm::Function *Fn = GetAddrOfCXXDestructor(D, Type);
768
769 CodeGenFunction(*this).GenerateCode(D, Fn);
770
771 SetFunctionDefinitionAttributes(D, Fn);
772 SetLLVMFunctionAttributesForDefinition(D, Fn);
773}
774
775llvm::Function *
776CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D,
777 CXXDtorType Type) {
778 const llvm::FunctionType *FTy =
779 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false);
780
781 const char *Name = getMangledCXXDtorName(D, Type);
Chris Lattner80f39cc2009-05-12 21:21:08 +0000782 return cast<llvm::Function>(
783 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson4811c302009-04-17 01:58:57 +0000784}
785
786const char *CodeGenModule::getMangledCXXDtorName(const CXXDestructorDecl *D,
787 CXXDtorType Type) {
788 llvm::SmallString<256> Name;
789 llvm::raw_svector_ostream Out(Name);
790 mangleCXXDtor(D, Type, Context, Out);
791
792 Name += '\0';
793 return UniqueMangledName(Name.begin(), Name.end());
794}
Fariborz Jahanian5400e022009-07-20 23:18:55 +0000795
Mike Stumpdca5e512009-08-18 21:49:00 +0000796llvm::Constant *CodeGenModule::GenerateRtti(const CXXRecordDecl *RD) {
Mike Stump00df7d32009-07-31 23:15:31 +0000797 llvm::Type *Ptr8Ty;
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000798 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Mike Stump69a12322009-08-04 20:06:48 +0000799 llvm::Constant *Rtti = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stump00df7d32009-07-31 23:15:31 +0000800
801 if (!getContext().getLangOptions().Rtti)
Mike Stump69a12322009-08-04 20:06:48 +0000802 return Rtti;
Mike Stump00df7d32009-07-31 23:15:31 +0000803
804 llvm::SmallString<256> OutName;
805 llvm::raw_svector_ostream Out(OutName);
806 QualType ClassTy;
Mike Stumpe7545622009-08-07 18:05:12 +0000807 ClassTy = getContext().getTagDeclType(RD);
Mike Stump00df7d32009-07-31 23:15:31 +0000808 mangleCXXRtti(ClassTy, getContext(), Out);
Mike Stump00df7d32009-07-31 23:15:31 +0000809 llvm::GlobalVariable::LinkageTypes linktype;
810 linktype = llvm::GlobalValue::WeakAnyLinkage;
811 std::vector<llvm::Constant *> info;
Mike Stump2eade572009-08-13 22:53:07 +0000812 // assert(0 && "FIXME: implement rtti descriptor");
Mike Stump00df7d32009-07-31 23:15:31 +0000813 // FIXME: descriptor
814 info.push_back(llvm::Constant::getNullValue(Ptr8Ty));
Mike Stump2eade572009-08-13 22:53:07 +0000815 // assert(0 && "FIXME: implement rtti ts");
Mike Stump00df7d32009-07-31 23:15:31 +0000816 // FIXME: TS
817 info.push_back(llvm::Constant::getNullValue(Ptr8Ty));
818
819 llvm::Constant *C;
820 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, info.size());
821 C = llvm::ConstantArray::get(type, info);
Mike Stumpdca5e512009-08-18 21:49:00 +0000822 Rtti = new llvm::GlobalVariable(getModule(), type, true, linktype, C,
Daniel Dunbar0433a022009-08-19 20:04:03 +0000823 Out.str());
Mike Stump69a12322009-08-04 20:06:48 +0000824 Rtti = llvm::ConstantExpr::getBitCast(Rtti, Ptr8Ty);
825 return Rtti;
Mike Stump00df7d32009-07-31 23:15:31 +0000826}
827
Mike Stump86a859e2009-08-19 18:10:47 +0000828class VtableBuilder {
Mike Stump48cf0392009-08-26 01:54:35 +0000829public:
830 /// Index_t - Vtable index type.
831 typedef uint64_t Index_t;
832private:
Mike Stumpad734d12009-08-18 20:50:28 +0000833 std::vector<llvm::Constant *> &methods;
834 llvm::Type *Ptr8Ty;
Mike Stumpf07ede52009-08-21 01:45:00 +0000835 /// Class - The most derived class that this vtable is being built for.
Mike Stumpdca5e512009-08-18 21:49:00 +0000836 const CXXRecordDecl *Class;
Mike Stumpf07ede52009-08-21 01:45:00 +0000837 /// BLayout - Layout for the most derived class that this vtable is being
838 /// built for.
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000839 const ASTRecordLayout &BLayout;
Mike Stumpa7ec675d2009-08-19 14:40:47 +0000840 llvm::SmallSet<const CXXRecordDecl *, 32> IndirectPrimary;
Mike Stump2b9ba612009-08-20 02:11:48 +0000841 llvm::SmallSet<const CXXRecordDecl *, 32> SeenVBase;
Mike Stumpdca5e512009-08-18 21:49:00 +0000842 llvm::Constant *rtti;
Mike Stumpad734d12009-08-18 20:50:28 +0000843 llvm::LLVMContext &VMContext;
Mike Stump1e10cf32009-08-18 21:03:28 +0000844 CodeGenModule &CGM; // Per-module state.
Mike Stumpf07ede52009-08-21 01:45:00 +0000845 /// Index - Maps a method decl into a vtable index. Useful for virtual
846 /// dispatch codegen.
Mike Stump48cf0392009-08-26 01:54:35 +0000847 llvm::DenseMap<const CXXMethodDecl *, Index_t> Index;
Mike Stumpd75d3232009-08-18 22:04:08 +0000848 typedef CXXRecordDecl::method_iterator method_iter;
Mike Stumpad734d12009-08-18 20:50:28 +0000849public:
Mike Stump86a859e2009-08-19 18:10:47 +0000850 VtableBuilder(std::vector<llvm::Constant *> &meth,
851 const CXXRecordDecl *c,
852 CodeGenModule &cgm)
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000853 : methods(meth), Class(c), BLayout(cgm.getContext().getASTRecordLayout(c)),
854 rtti(cgm.GenerateRtti(c)), VMContext(cgm.getModule().getContext()),
855 CGM(cgm) {
Mike Stumpad734d12009-08-18 20:50:28 +0000856 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
857 }
Mike Stumpdca5e512009-08-18 21:49:00 +0000858
Mike Stump48cf0392009-08-26 01:54:35 +0000859 llvm::DenseMap<const CXXMethodDecl *, Index_t> &getIndex() { return Index; }
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000860 llvm::Constant *GenerateVcall(const CXXMethodDecl *MD,
861 const CXXRecordDecl *RD,
862 bool VBoundary,
863 bool SecondaryVirtual) {
Mike Stump00962322009-08-21 23:09:30 +0000864 typedef CXXMethodDecl::method_iterator meth_iter;
865 // No vcall for methods that don't override in primary vtables.
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000866 llvm::Constant *m = 0;
867
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000868 if (SecondaryVirtual || VBoundary)
869 m = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stump00962322009-08-21 23:09:30 +0000870
871 int64_t Offset = 0;
872 int64_t BaseOffset = 0;
873 for (meth_iter mi = MD->begin_overridden_methods(),
874 me = MD->end_overridden_methods();
875 mi != me; ++mi) {
876 const CXXRecordDecl *DefBase = (*mi)->getParent();
877 // FIXME: vcall: offset for virtual base for this function
878 // m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), 900);
879 // m = llvm::Constant::getNullValue(Ptr8Ty);
880 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
881 e = RD->bases_end(); i != e; ++i) {
882 const CXXRecordDecl *Base =
883 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
884 if (DefBase == Base) {
885 if (!i->isVirtual())
886 break;
887
888 // FIXME: drop the 700-, just for debugging
889 BaseOffset = 700- -(BLayout.getVBaseClassOffset(Base) / 8);
890 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
891 BaseOffset);
892 m = llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
893 break;
894 } else {
895 // FIXME: more searching.
896 (void)Offset;
897 }
898 }
899 }
900
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000901 return m;
902 }
903
904 void GenerateVcalls(const CXXRecordDecl *RD, bool VBoundary,
905 bool SecondaryVirtual) {
Mike Stumpad734d12009-08-18 20:50:28 +0000906 llvm::Constant *m;
Mike Stump23b238e2009-08-12 23:25:18 +0000907
Mike Stumpd75d3232009-08-18 22:04:08 +0000908 for (method_iter mi = RD->method_begin(),
Mike Stumpad734d12009-08-18 20:50:28 +0000909 me = RD->method_end(); mi != me; ++mi) {
910 if (mi->isVirtual()) {
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000911 m = GenerateVcall(*mi, RD, VBoundary, SecondaryVirtual);
912 if (m)
913 methods.push_back(m);
Mike Stumpad734d12009-08-18 20:50:28 +0000914 }
Mike Stumpf640de52009-08-12 23:14:12 +0000915 }
Mike Stump23b238e2009-08-12 23:25:18 +0000916 }
Mike Stumpf640de52009-08-12 23:14:12 +0000917
Mike Stump2b9ba612009-08-20 02:11:48 +0000918 void GenerateVBaseOffsets(std::vector<llvm::Constant *> &offsets,
Mike Stumpaf0d0452009-08-20 07:22:17 +0000919 const CXXRecordDecl *RD, uint64_t Offset) {
Mike Stump2b9ba612009-08-20 02:11:48 +0000920 for (CXXRecordDecl::base_class_const_iterator i =RD->bases_begin(),
921 e = RD->bases_end(); i != e; ++i) {
922 const CXXRecordDecl *Base =
923 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
924 if (i->isVirtual() && !SeenVBase.count(Base)) {
925 SeenVBase.insert(Base);
Mike Stumpaf0d0452009-08-20 07:22:17 +0000926 int64_t BaseOffset = -(Offset/8) + BLayout.getVBaseClassOffset(Base)/8;
Mike Stump2b9ba612009-08-20 02:11:48 +0000927 llvm::Constant *m;
Mike Stumpaf0d0452009-08-20 07:22:17 +0000928 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),BaseOffset);
Mike Stump2b9ba612009-08-20 02:11:48 +0000929 m = llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
930 offsets.push_back(m);
931 }
Mike Stumpaf0d0452009-08-20 07:22:17 +0000932 GenerateVBaseOffsets(offsets, Base, Offset);
Mike Stump2b9ba612009-08-20 02:11:48 +0000933 }
934 }
935
Mike Stumpf07ede52009-08-21 01:45:00 +0000936 void StartNewTable() {
937 SeenVBase.clear();
938 }
Mike Stumpdecd7812009-08-12 23:00:59 +0000939
Mike Stump48cf0392009-08-26 01:54:35 +0000940 inline Index_t nottoobig(uint64_t t) {
941 assert(t < (Index_t)-1ULL || "vtable too big");
Mike Stumpf07ede52009-08-21 01:45:00 +0000942 return t;
943 }
944#if 0
Mike Stump48cf0392009-08-26 01:54:35 +0000945 inline Index_t nottoobig(Index_t t) {
Mike Stumpf07ede52009-08-21 01:45:00 +0000946 return t;
947 }
948#endif
949
Mike Stump48cf0392009-08-26 01:54:35 +0000950 void AddMethod(const CXXMethodDecl *MD, Index_t AddressPoint) {
Mike Stumpf07ede52009-08-21 01:45:00 +0000951 typedef CXXMethodDecl::method_iterator meth_iter;
952
953 llvm::Constant *m;
954 m = CGM.GetAddrOfFunction(GlobalDecl(MD), Ptr8Ty);
955 m = llvm::ConstantExpr::getBitCast(m, Ptr8Ty);
956
957 // FIXME: Don't like the nested loops. For very large inheritance
958 // heirarchies we could have a table on the side with the final overridder
959 // and just replace each instance of an overridden method once. Would be
960 // nice to measure the cost/benefit on real code.
961
962 // If we can find a previously allocated slot for this, reuse it.
963 for (meth_iter mi = MD->begin_overridden_methods(),
964 e = MD->end_overridden_methods();
965 mi != e; ++mi) {
966 const CXXMethodDecl *OMD = *mi;
967 llvm::Constant *om;
968 om = CGM.GetAddrOfFunction(GlobalDecl(OMD), Ptr8Ty);
969 om = llvm::ConstantExpr::getBitCast(om, Ptr8Ty);
970
Mike Stump48cf0392009-08-26 01:54:35 +0000971 for (Index_t i = AddressPoint, e = methods.size();
972 i != e; ++i) {
Mike Stumpf07ede52009-08-21 01:45:00 +0000973 // FIXME: begin_overridden_methods might be too lax, covariance */
974 if (methods[i] == om) {
975 methods[i] = m;
Mike Stump48cf0392009-08-26 01:54:35 +0000976 Index[MD] = i - AddressPoint;
Mike Stumpf07ede52009-08-21 01:45:00 +0000977 return;
978 }
Mike Stump1e10cf32009-08-18 21:03:28 +0000979 }
Mike Stumpdecd7812009-08-12 23:00:59 +0000980 }
Mike Stumpf07ede52009-08-21 01:45:00 +0000981
982 // else allocate a new slot.
Mike Stump48cf0392009-08-26 01:54:35 +0000983 Index[MD] = methods.size() - AddressPoint;
Mike Stumpf07ede52009-08-21 01:45:00 +0000984 methods.push_back(m);
985 }
986
Mike Stump48cf0392009-08-26 01:54:35 +0000987 void GenerateMethods(const CXXRecordDecl *RD, Index_t AddressPoint) {
Mike Stumpf07ede52009-08-21 01:45:00 +0000988 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
989 ++mi)
990 if (mi->isVirtual())
Mike Stump48cf0392009-08-26 01:54:35 +0000991 AddMethod(*mi, AddressPoint);
Mike Stumpdecd7812009-08-12 23:00:59 +0000992 }
Mike Stump1e10cf32009-08-18 21:03:28 +0000993
Mike Stump00962322009-08-21 23:09:30 +0000994 int64_t GenerateVtableForBase(const CXXRecordDecl *RD,
995 bool forPrimary,
996 bool VBoundary,
997 int64_t Offset,
Mike Stump48cf0392009-08-26 01:54:35 +0000998 bool ForVirtualBase) {
Mike Stump7bae1282009-08-18 21:30:21 +0000999 llvm::Constant *m = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stump00962322009-08-21 23:09:30 +00001000 int64_t AddressPoint=0;
Mike Stumpc57b8272009-08-16 01:46:26 +00001001
Mike Stump7bae1282009-08-18 21:30:21 +00001002 if (RD && !RD->isDynamicClass())
Mike Stump00962322009-08-21 23:09:30 +00001003 return 0;
Mike Stump7bae1282009-08-18 21:30:21 +00001004
1005 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1006 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1007 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
1008
Mike Stumpb6ff81e2009-08-19 02:06:38 +00001009 if (VBoundary || forPrimary || ForVirtualBase) {
1010 // then comes the the vcall offsets for all our functions...
1011 GenerateVcalls(RD, VBoundary, !forPrimary && ForVirtualBase);
1012 }
1013
Mike Stump7bae1282009-08-18 21:30:21 +00001014 // The virtual base offsets come first...
1015 // FIXME: Audit, is this right?
Mike Stump4c1c8912009-08-19 02:53:08 +00001016 if (PrimaryBase == 0 || forPrimary || !PrimaryBaseWasVirtual) {
Mike Stump7bae1282009-08-18 21:30:21 +00001017 std::vector<llvm::Constant *> offsets;
Mike Stumpaf0d0452009-08-20 07:22:17 +00001018 GenerateVBaseOffsets(offsets, RD, Offset);
Mike Stump7bae1282009-08-18 21:30:21 +00001019 for (std::vector<llvm::Constant *>::reverse_iterator i = offsets.rbegin(),
1020 e = offsets.rend(); i != e; ++i)
1021 methods.push_back(*i);
1022 }
1023
Mike Stump7bae1282009-08-18 21:30:21 +00001024 bool Top = true;
1025
1026 // vtables are composed from the chain of primaries.
1027 if (PrimaryBase) {
1028 if (PrimaryBaseWasVirtual)
1029 IndirectPrimary.insert(PrimaryBase);
1030 Top = false;
Mike Stump48cf0392009-08-26 01:54:35 +00001031 AddressPoint = GenerateVtableForBase(PrimaryBase, true,
1032 PrimaryBaseWasVirtual|VBoundary,
1033 Offset, PrimaryBaseWasVirtual);
Mike Stump7bae1282009-08-18 21:30:21 +00001034 }
1035
1036 if (Top) {
1037 int64_t BaseOffset;
1038 if (ForVirtualBase) {
Mike Stump7bae1282009-08-18 21:30:21 +00001039 BaseOffset = -(BLayout.getVBaseClassOffset(RD) / 8);
1040 } else
1041 BaseOffset = -Offset/8;
Mike Stumpc57b8272009-08-16 01:46:26 +00001042 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), BaseOffset);
1043 m = llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
1044 methods.push_back(m);
Mike Stump7bae1282009-08-18 21:30:21 +00001045 methods.push_back(rtti);
Mike Stump00962322009-08-21 23:09:30 +00001046 AddressPoint = methods.size();
Mike Stumpc57b8272009-08-16 01:46:26 +00001047 }
Mike Stump2eade572009-08-13 22:53:07 +00001048
Mike Stump7bae1282009-08-18 21:30:21 +00001049 // And add the virtuals for the class to the primary vtable.
Mike Stump48cf0392009-08-26 01:54:35 +00001050 GenerateMethods(RD, AddressPoint);
Mike Stump7bae1282009-08-18 21:30:21 +00001051
1052 // and then the non-virtual bases.
1053 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1054 e = RD->bases_end(); i != e; ++i) {
1055 if (i->isVirtual())
1056 continue;
1057 const CXXRecordDecl *Base =
1058 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1059 if (Base != PrimaryBase || PrimaryBaseWasVirtual) {
1060 uint64_t o = Offset + Layout.getBaseClassOffset(Base);
Mike Stumpf07ede52009-08-21 01:45:00 +00001061 StartNewTable();
Mike Stump48cf0392009-08-26 01:54:35 +00001062 GenerateVtableForBase(Base, true, false, o, false);
Mike Stump7bae1282009-08-18 21:30:21 +00001063 }
1064 }
Mike Stump00962322009-08-21 23:09:30 +00001065 return AddressPoint;
Mike Stump7bae1282009-08-18 21:30:21 +00001066 }
1067
1068 void GenerateVtableForVBases(const CXXRecordDecl *RD,
Mike Stumpa7ec675d2009-08-19 14:40:47 +00001069 const CXXRecordDecl *Class) {
Mike Stump7bae1282009-08-18 21:30:21 +00001070 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1071 e = RD->bases_end(); i != e; ++i) {
1072 const CXXRecordDecl *Base =
1073 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1074 if (i->isVirtual() && !IndirectPrimary.count(Base)) {
1075 // Mark it so we don't output it twice.
1076 IndirectPrimary.insert(Base);
Mike Stumpf07ede52009-08-21 01:45:00 +00001077 StartNewTable();
Mike Stumpaf0d0452009-08-20 07:22:17 +00001078 int64_t BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stump48cf0392009-08-26 01:54:35 +00001079 GenerateVtableForBase(Base, false, true, BaseOffset, true);
Mike Stump7bae1282009-08-18 21:30:21 +00001080 }
1081 if (Base->getNumVBases())
Mike Stumpa7ec675d2009-08-19 14:40:47 +00001082 GenerateVtableForVBases(Base, Class);
Mike Stumpc57b8272009-08-16 01:46:26 +00001083 }
1084 }
Mike Stump7bae1282009-08-18 21:30:21 +00001085};
Mike Stumpd6f22d82009-08-06 15:50:11 +00001086
Mike Stump48cf0392009-08-26 01:54:35 +00001087class VtableInfo {
1088public:
1089 typedef VtableBuilder::Index_t Index_t;
1090private:
1091 CodeGenModule &CGM; // Per-module state.
1092 /// Index_t - Vtable index type.
1093 typedef llvm::DenseMap<const CXXMethodDecl *, Index_t> ElTy;
1094 typedef llvm::DenseMap<const CXXRecordDecl *, ElTy *> MapTy;
1095 // FIXME: Move to Context.
1096 static MapTy IndexFor;
1097public:
1098 VtableInfo(CodeGenModule &cgm) : CGM(cgm) { }
1099 void register_index(const CXXRecordDecl *RD, const ElTy &e) {
1100 assert(IndexFor.find(RD) == IndexFor.end() || "Don't compute vtbl twice");
1101 // We own a copy of this, it will go away shortly.
1102 new ElTy (e);
1103 IndexFor[RD] = new ElTy (e);
1104 }
1105 Index_t lookup(const CXXMethodDecl *MD) {
1106 const CXXRecordDecl *RD = MD->getParent();
1107 MapTy::iterator I = IndexFor.find(RD);
1108 if (I == IndexFor.end()) {
1109 std::vector<llvm::Constant *> methods;
1110 VtableBuilder b(methods, RD, CGM);
1111 b.GenerateVtableForBase(RD, true, false, 0, false);
1112 b.GenerateVtableForVBases(RD, RD);
1113 register_index(RD, b.getIndex());
1114 I = IndexFor.find(RD);
1115 }
1116 assert(I->second->find(MD)!=I->second->end() || "Can't find vtable index");
1117 return (*I->second)[MD];
1118 }
1119};
1120
1121// FIXME: Move to Context.
1122VtableInfo::MapTy VtableInfo::IndexFor;
1123
Mike Stump7e8c9932009-07-31 18:25:34 +00001124llvm::Value *CodeGenFunction::GenerateVtable(const CXXRecordDecl *RD) {
Mike Stump7e8c9932009-07-31 18:25:34 +00001125 llvm::SmallString<256> OutName;
1126 llvm::raw_svector_ostream Out(OutName);
1127 QualType ClassTy;
Mike Stumpe7545622009-08-07 18:05:12 +00001128 ClassTy = getContext().getTagDeclType(RD);
Mike Stump7e8c9932009-07-31 18:25:34 +00001129 mangleCXXVtable(ClassTy, getContext(), Out);
Mike Stumpd0672782009-07-31 21:43:43 +00001130 llvm::GlobalVariable::LinkageTypes linktype;
1131 linktype = llvm::GlobalValue::WeakAnyLinkage;
1132 std::vector<llvm::Constant *> methods;
Mike Stumpc57b8272009-08-16 01:46:26 +00001133 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
Mike Stump00962322009-08-21 23:09:30 +00001134 int64_t Offset;
Mike Stump8b82eeb2009-08-05 22:37:18 +00001135
Mike Stump86a859e2009-08-19 18:10:47 +00001136 VtableBuilder b(methods, RD, CGM);
Mike Stump7bae1282009-08-18 21:30:21 +00001137
Mike Stumpc57b8272009-08-16 01:46:26 +00001138 // First comes the vtables for all the non-virtual bases...
Mike Stump48cf0392009-08-26 01:54:35 +00001139 Offset = b.GenerateVtableForBase(RD, true, false, 0, false);
Mike Stump42368bb2009-08-14 01:44:03 +00001140
Mike Stumpc57b8272009-08-16 01:46:26 +00001141 // then the vtables for all the virtual bases.
Mike Stumpa7ec675d2009-08-19 14:40:47 +00001142 b.GenerateVtableForVBases(RD, RD);
Mike Stumpf3371782009-08-04 21:58:42 +00001143
Mike Stumpd0672782009-07-31 21:43:43 +00001144 llvm::Constant *C;
1145 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, methods.size());
1146 C = llvm::ConstantArray::get(type, methods);
1147 llvm::Value *vtable = new llvm::GlobalVariable(CGM.getModule(), type, true,
Daniel Dunbar0433a022009-08-19 20:04:03 +00001148 linktype, C, Out.str());
Mike Stump7e8c9932009-07-31 18:25:34 +00001149 vtable = Builder.CreateBitCast(vtable, Ptr8Ty);
Mike Stump7e8c9932009-07-31 18:25:34 +00001150 vtable = Builder.CreateGEP(vtable,
Mike Stumpc57b8272009-08-16 01:46:26 +00001151 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
Mike Stump00962322009-08-21 23:09:30 +00001152 Offset*LLVMPointerWidth/8));
Mike Stump7e8c9932009-07-31 18:25:34 +00001153 return vtable;
1154}
1155
Mike Stump48cf0392009-08-26 01:54:35 +00001156// FIXME: move to Context
1157static VtableInfo *vtableinfo;
1158
1159llvm::Value *
1160CodeGenFunction::BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *&This,
1161 const llvm::Type *Ty) {
1162 // FIXME: If we know the dynamic type, we don't have to do a virtual dispatch.
1163
1164 // FIXME: move to Context
1165 if (vtableinfo == 0)
1166 vtableinfo = new VtableInfo(CGM);
1167
1168 VtableInfo::Index_t Idx = vtableinfo->lookup(MD);
1169
1170 Ty = llvm::PointerType::get(Ty, 0);
1171 Ty = llvm::PointerType::get(Ty, 0);
1172 Ty = llvm::PointerType::get(Ty, 0);
1173 llvm::Value *vtbl = Builder.CreateBitCast(This, Ty);
1174 vtbl = Builder.CreateLoad(vtbl);
1175 llvm::Value *vfn = Builder.CreateConstInBoundsGEP1_64(vtbl,
1176 Idx, "vfn");
1177 vfn = Builder.CreateLoad(vfn);
1178 return vfn;
1179}
1180
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001181/// EmitClassAggrMemberwiseCopy - This routine generates code to copy a class
1182/// array of objects from SrcValue to DestValue. Copying can be either a bitwise
1183/// copy or via a copy constructor call.
Fariborz Jahanian58a7eca2009-08-26 00:23:27 +00001184// FIXME. Consolidate this with EmitCXXAggrConstructorCall.
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001185void CodeGenFunction::EmitClassAggrMemberwiseCopy(llvm::Value *Dest,
1186 llvm::Value *Src,
1187 const ArrayType *Array,
1188 const CXXRecordDecl *BaseClassDecl,
1189 QualType Ty) {
1190 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1191 assert(CA && "VLA cannot be copied over");
1192 bool BitwiseCopy = BaseClassDecl->hasTrivialCopyConstructor();
1193
1194 // Create a temporary for the loop index and initialize it with 0.
1195 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1196 "loop.index");
1197 llvm::Value* zeroConstant =
1198 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
1199 Builder.CreateStore(zeroConstant, IndexPtr, false);
1200 // Start the loop with a block that tests the condition.
1201 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1202 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1203
1204 EmitBlock(CondBlock);
1205
1206 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1207 // Generate: if (loop-index < number-of-elements fall to the loop body,
1208 // otherwise, go to the block after the for-loop.
1209 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
1210 llvm::Value * NumElementsPtr =
1211 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1212 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1213 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
1214 "isless");
1215 // If the condition is true, execute the body.
1216 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1217
1218 EmitBlock(ForBody);
1219 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1220 // Inside the loop body, emit the constructor call on the array element.
1221 Counter = Builder.CreateLoad(IndexPtr);
1222 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1223 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1224 if (BitwiseCopy)
1225 EmitAggregateCopy(Dest, Src, Ty);
1226 else if (CXXConstructorDecl *BaseCopyCtor =
1227 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
1228 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
1229 Ctor_Complete);
1230 CallArgList CallArgs;
1231 // Push the this (Dest) ptr.
1232 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1233 BaseCopyCtor->getThisType(getContext())));
1234
1235 // Push the Src ptr.
1236 CallArgs.push_back(std::make_pair(RValue::get(Src),
1237 BaseCopyCtor->getParamDecl(0)->getType()));
1238 QualType ResultType =
1239 BaseCopyCtor->getType()->getAsFunctionType()->getResultType();
1240 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1241 Callee, CallArgs, BaseCopyCtor);
1242 }
1243 EmitBlock(ContinueBlock);
1244
1245 // Emit the increment of the loop counter.
1246 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1247 Counter = Builder.CreateLoad(IndexPtr);
1248 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1249 Builder.CreateStore(NextVal, IndexPtr, false);
1250
1251 // Finally, branch back up to the condition for the next iteration.
1252 EmitBranch(CondBlock);
1253
1254 // Emit the fall-through block.
1255 EmitBlock(AfterFor, true);
1256}
1257
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001258/// EmitClassAggrCopyAssignment - This routine generates code to assign a class
1259/// array of objects from SrcValue to DestValue. Assignment can be either a
1260/// bitwise assignment or via a copy assignment operator function call.
1261/// FIXME. This can be consolidated with EmitClassAggrMemberwiseCopy
1262void CodeGenFunction::EmitClassAggrCopyAssignment(llvm::Value *Dest,
1263 llvm::Value *Src,
1264 const ArrayType *Array,
1265 const CXXRecordDecl *BaseClassDecl,
1266 QualType Ty) {
1267 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1268 assert(CA && "VLA cannot be asssigned");
1269 bool BitwiseAssign = BaseClassDecl->hasTrivialCopyAssignment();
1270
1271 // Create a temporary for the loop index and initialize it with 0.
1272 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1273 "loop.index");
1274 llvm::Value* zeroConstant =
1275 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
1276 Builder.CreateStore(zeroConstant, IndexPtr, false);
1277 // Start the loop with a block that tests the condition.
1278 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1279 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1280
1281 EmitBlock(CondBlock);
1282
1283 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1284 // Generate: if (loop-index < number-of-elements fall to the loop body,
1285 // otherwise, go to the block after the for-loop.
1286 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
1287 llvm::Value * NumElementsPtr =
1288 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1289 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1290 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
1291 "isless");
1292 // If the condition is true, execute the body.
1293 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1294
1295 EmitBlock(ForBody);
1296 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1297 // Inside the loop body, emit the assignment operator call on array element.
1298 Counter = Builder.CreateLoad(IndexPtr);
1299 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1300 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1301 const CXXMethodDecl *MD = 0;
1302 if (BitwiseAssign)
1303 EmitAggregateCopy(Dest, Src, Ty);
1304 else {
1305 bool hasCopyAssign = BaseClassDecl->hasConstCopyAssignment(getContext(),
1306 MD);
1307 assert(hasCopyAssign && "EmitClassAggrCopyAssignment - No user assign");
1308 (void)hasCopyAssign;
1309 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
1310 const llvm::Type *LTy =
1311 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1312 FPT->isVariadic());
1313 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), LTy);
1314
1315 CallArgList CallArgs;
1316 // Push the this (Dest) ptr.
1317 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1318 MD->getThisType(getContext())));
1319
1320 // Push the Src ptr.
1321 CallArgs.push_back(std::make_pair(RValue::get(Src),
1322 MD->getParamDecl(0)->getType()));
1323 QualType ResultType =
1324 MD->getType()->getAsFunctionType()->getResultType();
1325 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1326 Callee, CallArgs, MD);
1327 }
1328 EmitBlock(ContinueBlock);
1329
1330 // Emit the increment of the loop counter.
1331 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1332 Counter = Builder.CreateLoad(IndexPtr);
1333 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1334 Builder.CreateStore(NextVal, IndexPtr, false);
1335
1336 // Finally, branch back up to the condition for the next iteration.
1337 EmitBranch(CondBlock);
1338
1339 // Emit the fall-through block.
1340 EmitBlock(AfterFor, true);
1341}
1342
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001343/// EmitClassMemberwiseCopy - This routine generates code to copy a class
1344/// object from SrcValue to DestValue. Copying can be either a bitwise copy
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001345/// or via a copy constructor call.
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001346void CodeGenFunction::EmitClassMemberwiseCopy(
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001347 llvm::Value *Dest, llvm::Value *Src,
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001348 const CXXRecordDecl *ClassDecl,
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001349 const CXXRecordDecl *BaseClassDecl, QualType Ty) {
1350 if (ClassDecl) {
1351 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
1352 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
1353 }
1354 if (BaseClassDecl->hasTrivialCopyConstructor()) {
1355 EmitAggregateCopy(Dest, Src, Ty);
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001356 return;
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001357 }
1358
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001359 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanianfbe08772009-08-08 00:59:58 +00001360 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001361 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
1362 Ctor_Complete);
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001363 CallArgList CallArgs;
1364 // Push the this (Dest) ptr.
1365 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1366 BaseCopyCtor->getThisType(getContext())));
1367
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001368 // Push the Src ptr.
1369 CallArgs.push_back(std::make_pair(RValue::get(Src),
Fariborz Jahanian0dfaec42009-08-10 17:20:45 +00001370 BaseCopyCtor->getParamDecl(0)->getType()));
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001371 QualType ResultType =
1372 BaseCopyCtor->getType()->getAsFunctionType()->getResultType();
1373 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1374 Callee, CallArgs, BaseCopyCtor);
1375 }
1376}
Fariborz Jahaniane39fab62009-08-10 18:46:38 +00001377
Fariborz Jahanian04500242009-08-12 23:34:46 +00001378/// EmitClassCopyAssignment - This routine generates code to copy assign a class
1379/// object from SrcValue to DestValue. Assignment can be either a bitwise
1380/// assignment of via an assignment operator call.
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001381// FIXME. Consolidate this with EmitClassMemberwiseCopy as they share a lot.
Fariborz Jahanian04500242009-08-12 23:34:46 +00001382void CodeGenFunction::EmitClassCopyAssignment(
1383 llvm::Value *Dest, llvm::Value *Src,
1384 const CXXRecordDecl *ClassDecl,
1385 const CXXRecordDecl *BaseClassDecl,
1386 QualType Ty) {
1387 if (ClassDecl) {
1388 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
1389 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
1390 }
1391 if (BaseClassDecl->hasTrivialCopyAssignment()) {
1392 EmitAggregateCopy(Dest, Src, Ty);
1393 return;
1394 }
1395
1396 const CXXMethodDecl *MD = 0;
Fariborz Jahanian84bd6532009-08-13 00:53:36 +00001397 bool ConstCopyAssignOp = BaseClassDecl->hasConstCopyAssignment(getContext(),
1398 MD);
1399 assert(ConstCopyAssignOp && "EmitClassCopyAssignment - missing copy assign");
1400 (void)ConstCopyAssignOp;
1401
1402 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
1403 const llvm::Type *LTy =
1404 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1405 FPT->isVariadic());
1406 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), LTy);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001407
Fariborz Jahanian84bd6532009-08-13 00:53:36 +00001408 CallArgList CallArgs;
1409 // Push the this (Dest) ptr.
1410 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1411 MD->getThisType(getContext())));
Fariborz Jahanian04500242009-08-12 23:34:46 +00001412
Fariborz Jahanian84bd6532009-08-13 00:53:36 +00001413 // Push the Src ptr.
1414 CallArgs.push_back(std::make_pair(RValue::get(Src),
1415 MD->getParamDecl(0)->getType()));
1416 QualType ResultType =
1417 MD->getType()->getAsFunctionType()->getResultType();
1418 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1419 Callee, CallArgs, MD);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001420}
1421
Fariborz Jahaniane39fab62009-08-10 18:46:38 +00001422/// SynthesizeDefaultConstructor - synthesize a default constructor
1423void
1424CodeGenFunction::SynthesizeDefaultConstructor(const CXXConstructorDecl *CD,
1425 const FunctionDecl *FD,
1426 llvm::Function *Fn,
1427 const FunctionArgList &Args) {
1428 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1429 EmitCtorPrologue(CD);
1430 FinishFunction();
1431}
1432
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001433/// SynthesizeCXXCopyConstructor - This routine implicitly defines body of a copy
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001434/// constructor, in accordance with section 12.8 (p7 and p8) of C++03
1435/// The implicitly-defined copy constructor for class X performs a memberwise
1436/// copy of its subobjects. The order of copying is the same as the order
1437/// of initialization of bases and members in a user-defined constructor
1438/// Each subobject is copied in the manner appropriate to its type:
1439/// if the subobject is of class type, the copy constructor for the class is
1440/// used;
1441/// if the subobject is an array, each element is copied, in the manner
1442/// appropriate to the element type;
1443/// if the subobject is of scalar type, the built-in assignment operator is
1444/// used.
1445/// Virtual base class subobjects shall be copied only once by the
1446/// implicitly-defined copy constructor
1447
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001448void CodeGenFunction::SynthesizeCXXCopyConstructor(const CXXConstructorDecl *CD,
1449 const FunctionDecl *FD,
1450 llvm::Function *Fn,
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001451 const FunctionArgList &Args) {
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001452 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1453 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001454 "SynthesizeCXXCopyConstructor - copy constructor has definition already");
1455 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001456
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001457 FunctionArgList::const_iterator i = Args.begin();
1458 const VarDecl *ThisArg = i->first;
1459 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1460 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1461 const VarDecl *SrcArg = (i+1)->first;
1462 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1463 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1464
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001465 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1466 Base != ClassDecl->bases_end(); ++Base) {
1467 // FIXME. copy constrution of virtual base NYI
1468 if (Base->isVirtual())
1469 continue;
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001470
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001471 CXXRecordDecl *BaseClassDecl
1472 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001473 EmitClassMemberwiseCopy(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1474 Base->getType());
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001475 }
1476
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001477 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1478 FieldEnd = ClassDecl->field_end();
1479 Field != FieldEnd; ++Field) {
1480 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001481 const ConstantArrayType *Array =
1482 getContext().getAsConstantArrayType(FieldType);
1483 if (Array)
1484 FieldType = getContext().getBaseElementType(FieldType);
1485
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001486 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1487 CXXRecordDecl *FieldClassDecl
1488 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1489 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1490 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001491 if (Array) {
1492 const llvm::Type *BasePtr = ConvertType(FieldType);
1493 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1494 llvm::Value *DestBaseAddrPtr =
1495 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1496 llvm::Value *SrcBaseAddrPtr =
1497 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1498 EmitClassAggrMemberwiseCopy(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1499 FieldClassDecl, FieldType);
1500 }
1501 else
1502 EmitClassMemberwiseCopy(LHS.getAddress(), RHS.getAddress(),
1503 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001504 continue;
1505 }
Fariborz Jahanian08d99e92009-08-10 18:34:26 +00001506 // Do a built-in assignment of scalar data members.
1507 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1508 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1509 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1510 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001511 }
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001512 FinishFunction();
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001513}
1514
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001515/// SynthesizeCXXCopyAssignment - Implicitly define copy assignment operator.
1516/// Before the implicitly-declared copy assignment operator for a class is
1517/// implicitly defined, all implicitly- declared copy assignment operators for
1518/// its direct base classes and its nonstatic data members shall have been
1519/// implicitly defined. [12.8-p12]
1520/// The implicitly-defined copy assignment operator for class X performs
1521/// memberwise assignment of its subob- jects. The direct base classes of X are
1522/// assigned first, in the order of their declaration in
1523/// the base-specifier-list, and then the immediate nonstatic data members of X
1524/// are assigned, in the order in which they were declared in the class
1525/// definition.Each subobject is assigned in the manner appropriate to its type:
Fariborz Jahanian04500242009-08-12 23:34:46 +00001526/// if the subobject is of class type, the copy assignment operator for the
1527/// class is used (as if by explicit qualification; that is, ignoring any
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001528/// possible virtual overriding functions in more derived classes);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001529///
1530/// if the subobject is an array, each element is assigned, in the manner
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001531/// appropriate to the element type;
Fariborz Jahanian04500242009-08-12 23:34:46 +00001532///
1533/// if the subobject is of scalar type, the built-in assignment operator is
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001534/// used.
1535void CodeGenFunction::SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD,
1536 const FunctionDecl *FD,
1537 llvm::Function *Fn,
1538 const FunctionArgList &Args) {
Fariborz Jahanian04500242009-08-12 23:34:46 +00001539
1540 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1541 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
1542 "SynthesizeCXXCopyAssignment - copy assignment has user declaration");
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001543 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1544
Fariborz Jahanian04500242009-08-12 23:34:46 +00001545 FunctionArgList::const_iterator i = Args.begin();
1546 const VarDecl *ThisArg = i->first;
1547 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1548 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1549 const VarDecl *SrcArg = (i+1)->first;
1550 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1551 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1552
1553 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1554 Base != ClassDecl->bases_end(); ++Base) {
1555 // FIXME. copy assignment of virtual base NYI
1556 if (Base->isVirtual())
1557 continue;
1558
1559 CXXRecordDecl *BaseClassDecl
1560 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1561 EmitClassCopyAssignment(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1562 Base->getType());
1563 }
1564
1565 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1566 FieldEnd = ClassDecl->field_end();
1567 Field != FieldEnd; ++Field) {
1568 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001569 const ConstantArrayType *Array =
1570 getContext().getAsConstantArrayType(FieldType);
1571 if (Array)
1572 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001573
1574 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1575 CXXRecordDecl *FieldClassDecl
1576 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1577 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1578 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001579 if (Array) {
1580 const llvm::Type *BasePtr = ConvertType(FieldType);
1581 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1582 llvm::Value *DestBaseAddrPtr =
1583 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1584 llvm::Value *SrcBaseAddrPtr =
1585 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1586 EmitClassAggrCopyAssignment(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1587 FieldClassDecl, FieldType);
1588 }
1589 else
1590 EmitClassCopyAssignment(LHS.getAddress(), RHS.getAddress(),
1591 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001592 continue;
1593 }
1594 // Do a built-in assignment of scalar data members.
1595 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1596 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1597 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1598 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanianc47460d2009-08-14 00:01:54 +00001599 }
1600
1601 // return *this;
1602 Builder.CreateStore(LoadOfThis, ReturnValue);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001603
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001604 FinishFunction();
1605}
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001606
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001607/// EmitCtorPrologue - This routine generates necessary code to initialize
1608/// base classes and non-static data members belonging to this constructor.
1609void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD) {
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001610 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
Mike Stump05207212009-08-06 13:41:24 +00001611 // FIXME: Add vbase initialization
Mike Stump7e8c9932009-07-31 18:25:34 +00001612 llvm::Value *LoadOfThis = 0;
Fariborz Jahanian70277012009-07-28 18:09:28 +00001613
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001614 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001615 E = CD->init_end();
1616 B != E; ++B) {
1617 CXXBaseOrMemberInitializer *Member = (*B);
1618 if (Member->isBaseInitializer()) {
Mike Stump7e8c9932009-07-31 18:25:34 +00001619 LoadOfThis = LoadCXXThis();
Fariborz Jahanian70277012009-07-28 18:09:28 +00001620 Type *BaseType = Member->getBaseClass();
1621 CXXRecordDecl *BaseClassDecl =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001622 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
Fariborz Jahanian70277012009-07-28 18:09:28 +00001623 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1624 BaseClassDecl);
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001625 EmitCXXConstructorCall(Member->getConstructor(),
1626 Ctor_Complete, V,
1627 Member->const_arg_begin(),
1628 Member->const_arg_end());
Mike Stump487ce382009-07-30 22:28:39 +00001629 } else {
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001630 // non-static data member initilaizers.
1631 FieldDecl *Field = Member->getMember();
1632 QualType FieldType = getContext().getCanonicalType((Field)->getType());
Fariborz Jahanianc7b8d9a2009-08-21 17:09:38 +00001633 const ConstantArrayType *Array =
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001634 getContext().getAsConstantArrayType(FieldType);
Fariborz Jahanianc7b8d9a2009-08-21 17:09:38 +00001635 if (Array)
1636 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian32cea8b2009-08-10 23:56:17 +00001637
Mike Stump7e8c9932009-07-31 18:25:34 +00001638 LoadOfThis = LoadCXXThis();
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001639 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001640 if (FieldType->getAs<RecordType>()) {
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +00001641 if (!Field->isAnonymousStructOrUnion()) {
Fariborz Jahanian56baceb2009-07-24 17:57:02 +00001642 assert(Member->getConstructor() &&
1643 "EmitCtorPrologue - no constructor to initialize member");
Fariborz Jahanianc7b8d9a2009-08-21 17:09:38 +00001644 if (Array) {
1645 const llvm::Type *BasePtr = ConvertType(FieldType);
1646 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1647 llvm::Value *BaseAddrPtr =
1648 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1649 EmitCXXAggrConstructorCall(Member->getConstructor(),
1650 Array, BaseAddrPtr);
1651 }
1652 else
1653 EmitCXXConstructorCall(Member->getConstructor(),
1654 Ctor_Complete, LHS.getAddress(),
1655 Member->const_arg_begin(),
1656 Member->const_arg_end());
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +00001657 continue;
1658 }
1659 else {
1660 // Initializing an anonymous union data member.
1661 FieldDecl *anonMember = Member->getAnonUnionMember();
1662 LHS = EmitLValueForField(LHS.getAddress(), anonMember, false, 0);
1663 FieldType = anonMember->getType();
1664 }
Fariborz Jahanian56baceb2009-07-24 17:57:02 +00001665 }
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001666
1667 assert(Member->getNumArgs() == 1 && "Initializer count must be 1 only");
Fariborz Jahanian56baceb2009-07-24 17:57:02 +00001668 Expr *RhsExpr = *Member->arg_begin();
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001669 llvm::Value *RHS = EmitScalarExpr(RhsExpr, true);
Fariborz Jahanian32cea8b2009-08-10 23:56:17 +00001670 EmitStoreThroughLValue(RValue::get(RHS), LHS, FieldType);
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001671 }
1672 }
Mike Stump7e8c9932009-07-31 18:25:34 +00001673
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001674 if (!CD->getNumBaseOrMemberInitializers() && !CD->isTrivial()) {
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001675 // Nontrivial default constructor with no initializer list. It may still
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001676 // have bases classes and/or contain non-static data members which require
1677 // construction.
1678 for (CXXRecordDecl::base_class_const_iterator Base =
1679 ClassDecl->bases_begin();
1680 Base != ClassDecl->bases_end(); ++Base) {
1681 // FIXME. copy assignment of virtual base NYI
1682 if (Base->isVirtual())
1683 continue;
1684
1685 CXXRecordDecl *BaseClassDecl
1686 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1687 if (BaseClassDecl->hasTrivialConstructor())
1688 continue;
1689 if (CXXConstructorDecl *BaseCX =
1690 BaseClassDecl->getDefaultConstructor(getContext())) {
1691 LoadOfThis = LoadCXXThis();
1692 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1693 BaseClassDecl);
1694 EmitCXXConstructorCall(BaseCX, Ctor_Complete, V, 0, 0);
1695 }
1696 }
1697
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001698 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1699 FieldEnd = ClassDecl->field_end();
1700 Field != FieldEnd; ++Field) {
1701 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +00001702 const ConstantArrayType *Array =
1703 getContext().getAsConstantArrayType(FieldType);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001704 if (Array)
1705 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001706 if (!FieldType->getAs<RecordType>() || Field->isAnonymousStructOrUnion())
1707 continue;
1708 const RecordType *ClassRec = FieldType->getAs<RecordType>();
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001709 CXXRecordDecl *MemberClassDecl =
1710 dyn_cast<CXXRecordDecl>(ClassRec->getDecl());
1711 if (!MemberClassDecl || MemberClassDecl->hasTrivialConstructor())
1712 continue;
1713 if (CXXConstructorDecl *MamberCX =
1714 MemberClassDecl->getDefaultConstructor(getContext())) {
1715 LoadOfThis = LoadCXXThis();
1716 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +00001717 if (Array) {
1718 const llvm::Type *BasePtr = ConvertType(FieldType);
1719 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1720 llvm::Value *BaseAddrPtr =
1721 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1722 EmitCXXAggrConstructorCall(MamberCX, Array, BaseAddrPtr);
1723 }
1724 else
1725 EmitCXXConstructorCall(MamberCX, Ctor_Complete, LHS.getAddress(),
1726 0, 0);
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001727 }
1728 }
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001729 }
1730
Mike Stump7e8c9932009-07-31 18:25:34 +00001731 // Initialize the vtable pointer
Mike Stumpeec46a72009-08-05 22:59:44 +00001732 if (ClassDecl->isDynamicClass()) {
Mike Stump7e8c9932009-07-31 18:25:34 +00001733 if (!LoadOfThis)
1734 LoadOfThis = LoadCXXThis();
1735 llvm::Value *VtableField;
1736 llvm::Type *Ptr8Ty, *PtrPtr8Ty;
Owen Anderson3f5cc0a2009-08-13 21:57:51 +00001737 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Mike Stump7e8c9932009-07-31 18:25:34 +00001738 PtrPtr8Ty = llvm::PointerType::get(Ptr8Ty, 0);
1739 VtableField = Builder.CreateBitCast(LoadOfThis, PtrPtr8Ty);
1740 llvm::Value *vtable = GenerateVtable(ClassDecl);
1741 Builder.CreateStore(vtable, VtableField);
1742 }
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001743}
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001744
1745/// EmitDtorEpilogue - Emit all code that comes at the end of class's
1746/// destructor. This is to call destructors on members and base classes
1747/// in reverse order of their construction.
1748void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD) {
1749 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(DD->getDeclContext());
1750 assert(!ClassDecl->isPolymorphic() &&
1751 "FIXME. polymorphic destruction not supported");
1752 (void)ClassDecl; // prevent warning.
1753
1754 for (CXXDestructorDecl::destr_const_iterator *B = DD->destr_begin(),
1755 *E = DD->destr_end(); B != E; ++B) {
1756 uintptr_t BaseOrMember = (*B);
1757 if (DD->isMemberToDestroy(BaseOrMember)) {
1758 FieldDecl *FD = DD->getMemberToDestroy(BaseOrMember);
1759 QualType FieldType = getContext().getCanonicalType((FD)->getType());
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001760 const ConstantArrayType *Array =
1761 getContext().getAsConstantArrayType(FieldType);
1762 if (Array)
1763 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001764 const RecordType *RT = FieldType->getAs<RecordType>();
1765 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1766 if (FieldClassDecl->hasTrivialDestructor())
1767 continue;
1768 llvm::Value *LoadOfThis = LoadCXXThis();
1769 LValue LHS = EmitLValueForField(LoadOfThis, FD, false, 0);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001770 if (Array) {
1771 const llvm::Type *BasePtr = ConvertType(FieldType);
1772 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1773 llvm::Value *BaseAddrPtr =
1774 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1775 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1776 Array, BaseAddrPtr);
1777 }
1778 else
1779 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1780 Dtor_Complete, LHS.getAddress());
Mike Stump487ce382009-07-30 22:28:39 +00001781 } else {
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001782 const RecordType *RT =
1783 DD->getAnyBaseClassToDestroy(BaseOrMember)->getAs<RecordType>();
1784 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1785 if (BaseClassDecl->hasTrivialDestructor())
1786 continue;
1787 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
1788 ClassDecl,BaseClassDecl);
1789 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1790 Dtor_Complete, V);
1791 }
1792 }
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001793 if (DD->getNumBaseOrMemberDestructions() || DD->isTrivial())
1794 return;
1795 // Case of destructor synthesis with fields and base classes
1796 // which have non-trivial destructors. They must be destructed in
1797 // reverse order of their construction.
1798 llvm::SmallVector<FieldDecl *, 16> DestructedFields;
1799
1800 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1801 FieldEnd = ClassDecl->field_end();
1802 Field != FieldEnd; ++Field) {
1803 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001804 if (getContext().getAsConstantArrayType(FieldType))
1805 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001806 if (const RecordType *RT = FieldType->getAs<RecordType>()) {
1807 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1808 if (FieldClassDecl->hasTrivialDestructor())
1809 continue;
1810 DestructedFields.push_back(*Field);
1811 }
1812 }
1813 if (!DestructedFields.empty())
1814 for (int i = DestructedFields.size() -1; i >= 0; --i) {
1815 FieldDecl *Field = DestructedFields[i];
1816 QualType FieldType = Field->getType();
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001817 const ConstantArrayType *Array =
1818 getContext().getAsConstantArrayType(FieldType);
1819 if (Array)
1820 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001821 const RecordType *RT = FieldType->getAs<RecordType>();
1822 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1823 llvm::Value *LoadOfThis = LoadCXXThis();
1824 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001825 if (Array) {
1826 const llvm::Type *BasePtr = ConvertType(FieldType);
1827 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1828 llvm::Value *BaseAddrPtr =
1829 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1830 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1831 Array, BaseAddrPtr);
1832 }
1833 else
1834 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1835 Dtor_Complete, LHS.getAddress());
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001836 }
1837
1838 llvm::SmallVector<CXXRecordDecl*, 4> DestructedBases;
1839 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1840 Base != ClassDecl->bases_end(); ++Base) {
1841 // FIXME. copy assignment of virtual base NYI
1842 if (Base->isVirtual())
1843 continue;
1844
1845 CXXRecordDecl *BaseClassDecl
1846 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1847 if (BaseClassDecl->hasTrivialDestructor())
1848 continue;
1849 DestructedBases.push_back(BaseClassDecl);
1850 }
1851 if (DestructedBases.empty())
1852 return;
1853 for (int i = DestructedBases.size() -1; i >= 0; --i) {
1854 CXXRecordDecl *BaseClassDecl = DestructedBases[i];
1855 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
1856 ClassDecl,BaseClassDecl);
1857 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1858 Dtor_Complete, V);
1859 }
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001860}
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001861
1862void CodeGenFunction::SynthesizeDefaultDestructor(const CXXDestructorDecl *CD,
1863 const FunctionDecl *FD,
1864 llvm::Function *Fn,
1865 const FunctionArgList &Args) {
1866
1867 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1868 assert(!ClassDecl->hasUserDeclaredDestructor() &&
1869 "SynthesizeDefaultDestructor - destructor has user declaration");
1870 (void) ClassDecl;
1871
1872 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1873 EmitDtorEpilogue(CD);
1874 FinishFunction();
1875}