blob: 04dbe9760a2cf0e0eca438bb9ceb2c8f7e562035 [file] [log] [blame]
Anders Carlssone1b29ef2008-08-22 16:00:37 +00001//===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with C++ code generation.
11//
12//===----------------------------------------------------------------------===//
13
14// We might split this into multiple files if it gets too unwieldy
15
16#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
Anders Carlsson283a0622009-04-13 18:03:33 +000018#include "Mangle.h"
Anders Carlssone1b29ef2008-08-22 16:00:37 +000019#include "clang/AST/ASTContext.h"
Fariborz Jahanian742cd1b2009-07-25 21:12:28 +000020#include "clang/AST/RecordLayout.h"
Anders Carlssone1b29ef2008-08-22 16:00:37 +000021#include "clang/AST/Decl.h"
Anders Carlsson774e7c62009-04-03 22:50:24 +000022#include "clang/AST/DeclCXX.h"
Anders Carlsson86e96442008-08-23 19:42:54 +000023#include "clang/AST/DeclObjC.h"
Anders Carlssone1b29ef2008-08-22 16:00:37 +000024#include "llvm/ADT/StringExtras.h"
Anders Carlssone1b29ef2008-08-22 16:00:37 +000025using namespace clang;
26using namespace CodeGen;
27
Daniel Dunbar0096acf2009-02-25 19:24:29 +000028void
Anders Carlsson3b2e16b2009-08-08 21:45:14 +000029CodeGenFunction::EmitCXXGlobalDtorRegistration(const CXXDestructorDecl *Dtor,
30 llvm::Constant *DeclPtr) {
31 // FIXME: This is ABI dependent and we use the Itanium ABI.
32
33 const llvm::Type *Int8PtrTy =
Owen Anderson0032b272009-08-13 21:57:51 +000034 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Anders Carlsson3b2e16b2009-08-08 21:45:14 +000035
36 std::vector<const llvm::Type *> Params;
37 Params.push_back(Int8PtrTy);
38
39 // Get the destructor function type
40 const llvm::Type *DtorFnTy =
Owen Anderson0032b272009-08-13 21:57:51 +000041 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Params, false);
Anders Carlsson3b2e16b2009-08-08 21:45:14 +000042 DtorFnTy = llvm::PointerType::getUnqual(DtorFnTy);
43
44 Params.clear();
45 Params.push_back(DtorFnTy);
46 Params.push_back(Int8PtrTy);
47 Params.push_back(Int8PtrTy);
48
49 // Get the __cxa_atexit function type
50 // extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
51 const llvm::FunctionType *AtExitFnTy =
52 llvm::FunctionType::get(ConvertType(getContext().IntTy), Params, false);
53
54 llvm::Constant *AtExitFn = CGM.CreateRuntimeFunction(AtExitFnTy,
55 "__cxa_atexit");
56
57 llvm::Constant *Handle = CGM.CreateRuntimeVariable(Int8PtrTy,
58 "__dso_handle");
59
60 llvm::Constant *DtorFn = CGM.GetAddrOfCXXDestructor(Dtor, Dtor_Complete);
61
62 llvm::Value *Args[3] = { llvm::ConstantExpr::getBitCast(DtorFn, DtorFnTy),
63 llvm::ConstantExpr::getBitCast(DeclPtr, Int8PtrTy),
64 llvm::ConstantExpr::getBitCast(Handle, Int8PtrTy) };
65 Builder.CreateCall(AtExitFn, &Args[0], llvm::array_endof(Args));
66}
67
68void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
69 llvm::Constant *DeclPtr) {
70 assert(D.hasGlobalStorage() &&
71 "VarDecl must have global storage!");
72
73 const Expr *Init = D.getInit();
74 QualType T = D.getType();
75
76 if (T->isReferenceType()) {
Anders Carlsson622f9dc2009-08-17 18:24:57 +000077 ErrorUnsupported(Init, "global variable that binds to a reference");
Anders Carlsson3b2e16b2009-08-08 21:45:14 +000078 } else if (!hasAggregateLLVMType(T)) {
79 llvm::Value *V = EmitScalarExpr(Init);
80 EmitStoreOfScalar(V, DeclPtr, T.isVolatileQualified(), T);
81 } else if (T->isAnyComplexType()) {
82 EmitComplexExprIntoAddr(Init, DeclPtr, T.isVolatileQualified());
83 } else {
84 EmitAggExpr(Init, DeclPtr, T.isVolatileQualified());
85
86 if (const RecordType *RT = T->getAs<RecordType>()) {
87 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
88 if (!RD->hasTrivialDestructor())
89 EmitCXXGlobalDtorRegistration(RD->getDestructor(getContext()), DeclPtr);
90 }
91 }
92}
93
Anders Carlsson89ed31d2009-08-08 23:24:23 +000094void
95CodeGenModule::EmitCXXGlobalInitFunc() {
96 if (CXXGlobalInits.empty())
97 return;
98
Owen Anderson0032b272009-08-13 21:57:51 +000099 const llvm::FunctionType *FTy = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
Anders Carlsson89ed31d2009-08-08 23:24:23 +0000100 false);
101
102 // Create our global initialization function.
103 // FIXME: Should this be tweakable by targets?
104 llvm::Function *Fn =
105 llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
106 "__cxx_global_initialization", &TheModule);
107
108 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
Benjamin Kramer10c40ee2009-08-08 23:43:26 +0000109 &CXXGlobalInits[0],
Anders Carlsson89ed31d2009-08-08 23:24:23 +0000110 CXXGlobalInits.size());
111 AddGlobalCtor(Fn);
112}
113
114void CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
115 const VarDecl **Decls,
116 unsigned NumDecls) {
117 StartFunction(0, getContext().VoidTy, Fn, FunctionArgList(),
118 SourceLocation());
119
120 for (unsigned i = 0; i != NumDecls; ++i) {
121 const VarDecl *D = Decls[i];
122
123 llvm::Constant *DeclPtr = CGM.GetAddrOfGlobalVar(D);
124 EmitCXXGlobalVarDeclInit(*D, DeclPtr);
125 }
126 FinishFunction();
127}
128
Anders Carlsson3b2e16b2009-08-08 21:45:14 +0000129void
130CodeGenFunction::EmitStaticCXXBlockVarDeclInit(const VarDecl &D,
131 llvm::GlobalVariable *GV) {
Daniel Dunbar0096acf2009-02-25 19:24:29 +0000132 // FIXME: This should use __cxa_guard_{acquire,release}?
133
Anders Carlssone1b29ef2008-08-22 16:00:37 +0000134 assert(!getContext().getLangOptions().ThreadsafeStatics &&
135 "thread safe statics are currently not supported!");
Anders Carlssone1b29ef2008-08-22 16:00:37 +0000136
Anders Carlsson283a0622009-04-13 18:03:33 +0000137 llvm::SmallString<256> GuardVName;
138 llvm::raw_svector_ostream GuardVOut(GuardVName);
139 mangleGuardVariable(&D, getContext(), GuardVOut);
140
Anders Carlssone1b29ef2008-08-22 16:00:37 +0000141 // Create the guard variable.
142 llvm::GlobalValue *GuardV =
Owen Anderson0032b272009-08-13 21:57:51 +0000143 new llvm::GlobalVariable(CGM.getModule(), llvm::Type::getInt64Ty(VMContext), false,
Daniel Dunbar0096acf2009-02-25 19:24:29 +0000144 GV->getLinkage(),
Owen Anderson0032b272009-08-13 21:57:51 +0000145 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext)),
Daniel Dunbar77659342009-08-19 20:04:03 +0000146 GuardVName.str());
Anders Carlssone1b29ef2008-08-22 16:00:37 +0000147
Anders Carlssone1b29ef2008-08-22 16:00:37 +0000148 // Load the first byte of the guard variable.
Owen Anderson0032b272009-08-13 21:57:51 +0000149 const llvm::Type *PtrTy = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Anders Carlssone1b29ef2008-08-22 16:00:37 +0000150 llvm::Value *V = Builder.CreateLoad(Builder.CreateBitCast(GuardV, PtrTy),
151 "tmp");
152
153 // Compare it against 0.
Owen Anderson0032b272009-08-13 21:57:51 +0000154 llvm::Value *nullValue = llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext));
Anders Carlssone1b29ef2008-08-22 16:00:37 +0000155 llvm::Value *ICmp = Builder.CreateICmpEQ(V, nullValue , "tobool");
156
Daniel Dunbar55e87422008-11-11 02:29:29 +0000157 llvm::BasicBlock *InitBlock = createBasicBlock("init");
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000158 llvm::BasicBlock *EndBlock = createBasicBlock("init.end");
Anders Carlssone1b29ef2008-08-22 16:00:37 +0000159
160 // If the guard variable is 0, jump to the initializer code.
161 Builder.CreateCondBr(ICmp, InitBlock, EndBlock);
162
163 EmitBlock(InitBlock);
164
Anders Carlsson3b2e16b2009-08-08 21:45:14 +0000165 EmitCXXGlobalVarDeclInit(D, GV);
166
Owen Anderson0032b272009-08-13 21:57:51 +0000167 Builder.CreateStore(llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext), 1),
Anders Carlssone1b29ef2008-08-22 16:00:37 +0000168 Builder.CreateBitCast(GuardV, PtrTy));
169
170 EmitBlock(EndBlock);
Anders Carlssone1b29ef2008-08-22 16:00:37 +0000171}
172
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000173RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
174 llvm::Value *Callee,
175 llvm::Value *This,
176 CallExpr::const_arg_iterator ArgBeg,
177 CallExpr::const_arg_iterator ArgEnd) {
178 assert(MD->isInstance() &&
179 "Trying to emit a member call expr on a static method!");
180
181 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
182
183 CallArgList Args;
184
185 // Push the this ptr.
186 Args.push_back(std::make_pair(RValue::get(This),
187 MD->getThisType(getContext())));
188
189 // And the rest of the call args
190 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
191
192 QualType ResultType = MD->getType()->getAsFunctionType()->getResultType();
193 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args),
194 Callee, Args, MD);
195}
196
Anders Carlsson774e7c62009-04-03 22:50:24 +0000197RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE) {
198 const MemberExpr *ME = cast<MemberExpr>(CE->getCallee());
199 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000200
Anders Carlssone9918d22009-04-08 20:31:57 +0000201 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
Mike Stump7116da12009-07-30 21:47:44 +0000202
Anders Carlsson774e7c62009-04-03 22:50:24 +0000203 const llvm::Type *Ty =
Anders Carlssone9918d22009-04-08 20:31:57 +0000204 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
205 FPT->isVariadic());
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000206 llvm::Value *This;
Anders Carlsson774e7c62009-04-03 22:50:24 +0000207
Anders Carlsson774e7c62009-04-03 22:50:24 +0000208 if (ME->isArrow())
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000209 This = EmitScalarExpr(ME->getBase());
Anders Carlsson774e7c62009-04-03 22:50:24 +0000210 else {
211 LValue BaseLV = EmitLValue(ME->getBase());
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000212 This = BaseLV.getAddress();
Anders Carlsson774e7c62009-04-03 22:50:24 +0000213 }
Mike Stumpf0070db2009-08-26 20:46:33 +0000214
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +0000215 // C++ [class.virtual]p12:
216 // Explicit qualification with the scope operator (5.1) suppresses the
217 // virtual call mechanism.
Mike Stumpf0070db2009-08-26 20:46:33 +0000218 llvm::Value *Callee;
Mike Stump63bb7c22009-08-26 23:38:08 +0000219 if (MD->isVirtual() && !isa<CXXQualifiedMemberExpr>(ME)) {
Mike Stumpf0070db2009-08-26 20:46:33 +0000220 Callee = BuildVirtualCall(MD, This, Ty);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +0000221 } else
Mike Stumpf0070db2009-08-26 20:46:33 +0000222 Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty);
Anders Carlsson774e7c62009-04-03 22:50:24 +0000223
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000224 return EmitCXXMemberCall(MD, Callee, This,
225 CE->arg_begin(), CE->arg_end());
Anders Carlsson774e7c62009-04-03 22:50:24 +0000226}
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000227
Anders Carlsson0f294632009-05-27 04:18:27 +0000228RValue
229CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
230 const CXXMethodDecl *MD) {
231 assert(MD->isInstance() &&
232 "Trying to emit a member call expr on a static method!");
233
Fariborz Jahanianad258832009-08-13 21:09:41 +0000234 if (MD->isCopyAssignment()) {
235 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(MD->getDeclContext());
236 if (ClassDecl->hasTrivialCopyAssignment()) {
237 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
238 "EmitCXXOperatorMemberCallExpr - user declared copy assignment");
239 llvm::Value *This = EmitLValue(E->getArg(0)).getAddress();
240 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
241 QualType Ty = E->getType();
242 EmitAggregateCopy(This, Src, Ty);
243 return RValue::get(This);
244 }
245 }
Anders Carlsson0f294632009-05-27 04:18:27 +0000246
247 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
248 const llvm::Type *Ty =
249 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
250 FPT->isVariadic());
251 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty);
252
253 llvm::Value *This = EmitLValue(E->getArg(0)).getAddress();
254
255 return EmitCXXMemberCall(MD, Callee, This,
256 E->arg_begin() + 1, E->arg_end());
257}
258
Fariborz Jahanian64e690e2009-08-26 23:31:30 +0000259RValue
260CodeGenFunction::EmitCXXFunctionalCastExpr(const CXXFunctionalCastExpr *E) {
261 assert((E->getCastKind() == CastExpr::CK_UserDefinedConversion) &&
262 "EmitCXXFunctionalCastExpr - called with wrong cast");
263
264 CXXMethodDecl *MD = E->getTypeConversionMethod();
Fariborz Jahanian4fc7ab32009-08-28 15:11:24 +0000265 assert(MD && "EmitCXXFunctionalCastExpr - null conversion method");
266 assert(isa<CXXConversionDecl>(MD) && "EmitCXXFunctionalCastExpr - not"
267 " method decl");
Fariborz Jahanian64e690e2009-08-26 23:31:30 +0000268 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
Fariborz Jahanian64e690e2009-08-26 23:31:30 +0000269
Fariborz Jahanian4fc7ab32009-08-28 15:11:24 +0000270 const llvm::Type *Ty =
271 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
272 FPT->isVariadic());
273 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty);
274 llvm::Value *This = EmitLValue(E->getSubExpr()).getAddress();
275 RValue RV = EmitCXXMemberCall(MD, Callee, This, 0, 0);
276 if (RV.isAggregate())
277 RV = RValue::get(RV.getAggregateAddr());
278 return RV;
Fariborz Jahanian64e690e2009-08-26 23:31:30 +0000279}
280
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000281llvm::Value *CodeGenFunction::LoadCXXThis() {
282 assert(isa<CXXMethodDecl>(CurFuncDecl) &&
283 "Must be in a C++ member function decl to load 'this'");
284 assert(cast<CXXMethodDecl>(CurFuncDecl)->isInstance() &&
285 "Must be in a C++ member function decl to load 'this'");
286
287 // FIXME: What if we're inside a block?
Mike Stumpf5408fe2009-05-16 07:57:57 +0000288 // ans: See how CodeGenFunction::LoadObjCSelf() uses
289 // CodeGenFunction::BlockForwardSelf() for how to do this.
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000290 return Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
291}
Anders Carlsson95d4e5d2009-04-15 15:55:24 +0000292
Fariborz Jahanianc238a792009-07-30 00:10:25 +0000293static bool
294GetNestedPaths(llvm::SmallVectorImpl<const CXXRecordDecl *> &NestedBasePaths,
295 const CXXRecordDecl *ClassDecl,
296 const CXXRecordDecl *BaseClassDecl) {
Fariborz Jahanianc238a792009-07-30 00:10:25 +0000297 for (CXXRecordDecl::base_class_const_iterator i = ClassDecl->bases_begin(),
298 e = ClassDecl->bases_end(); i != e; ++i) {
299 if (i->isVirtual())
300 continue;
301 const CXXRecordDecl *Base =
Mike Stump104ffaa2009-08-04 21:58:42 +0000302 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanianc238a792009-07-30 00:10:25 +0000303 if (Base == BaseClassDecl) {
304 NestedBasePaths.push_back(BaseClassDecl);
305 return true;
306 }
307 }
308 // BaseClassDecl not an immediate base of ClassDecl.
309 for (CXXRecordDecl::base_class_const_iterator i = ClassDecl->bases_begin(),
310 e = ClassDecl->bases_end(); i != e; ++i) {
311 if (i->isVirtual())
312 continue;
313 const CXXRecordDecl *Base =
314 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
315 if (GetNestedPaths(NestedBasePaths, Base, BaseClassDecl)) {
316 NestedBasePaths.push_back(Base);
317 return true;
318 }
319 }
320 return false;
321}
322
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000323llvm::Value *CodeGenFunction::AddressCXXOfBaseClass(llvm::Value *BaseValue,
Fariborz Jahanian6d0bdaa2009-07-28 18:09:28 +0000324 const CXXRecordDecl *ClassDecl,
325 const CXXRecordDecl *BaseClassDecl) {
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000326 if (ClassDecl == BaseClassDecl)
327 return BaseValue;
328
Owen Anderson0032b272009-08-13 21:57:51 +0000329 llvm::Type *I8Ptr = llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Fariborz Jahanianc238a792009-07-30 00:10:25 +0000330 llvm::SmallVector<const CXXRecordDecl *, 16> NestedBasePaths;
331 GetNestedPaths(NestedBasePaths, ClassDecl, BaseClassDecl);
332 assert(NestedBasePaths.size() > 0 &&
333 "AddressCXXOfBaseClass - inheritence path failed");
334 NestedBasePaths.push_back(ClassDecl);
335 uint64_t Offset = 0;
336
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000337 // Accessing a member of the base class. Must add delata to
338 // the load of 'this'.
Fariborz Jahanianc238a792009-07-30 00:10:25 +0000339 for (unsigned i = NestedBasePaths.size()-1; i > 0; i--) {
340 const CXXRecordDecl *DerivedClass = NestedBasePaths[i];
341 const CXXRecordDecl *BaseClass = NestedBasePaths[i-1];
342 const ASTRecordLayout &Layout =
343 getContext().getASTRecordLayout(DerivedClass);
344 Offset += Layout.getBaseClassOffset(BaseClass) / 8;
345 }
Fariborz Jahanian5a8503b2009-07-29 15:54:56 +0000346 llvm::Value *OffsetVal =
347 llvm::ConstantInt::get(
348 CGM.getTypes().ConvertType(CGM.getContext().LongTy), Offset);
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000349 BaseValue = Builder.CreateBitCast(BaseValue, I8Ptr);
350 BaseValue = Builder.CreateGEP(BaseValue, OffsetVal, "add.ptr");
351 QualType BTy =
352 getContext().getCanonicalType(
Fariborz Jahanian6d0bdaa2009-07-28 18:09:28 +0000353 getContext().getTypeDeclType(const_cast<CXXRecordDecl*>(BaseClassDecl)));
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000354 const llvm::Type *BasePtr = ConvertType(BTy);
Owen Anderson96e0fc72009-07-29 22:16:19 +0000355 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000356 BaseValue = Builder.CreateBitCast(BaseValue, BasePtr);
357 return BaseValue;
358}
359
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000360/// EmitCXXAggrConstructorCall - This routine essentially creates a (nested)
361/// for-loop to call the default constructor on individual members of the
362/// array. 'Array' is the array type, 'This' is llvm pointer of the start
363/// of the array and 'D' is the default costructor Decl for elements of the
364/// array. It is assumed that all relevant checks have been made by the
365/// caller.
366void
367CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
368 const ArrayType *Array,
369 llvm::Value *This) {
370 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
371 assert(CA && "Do we support VLA for construction ?");
372
373 // Create a temporary for the loop index and initialize it with 0.
Fariborz Jahanian0de78992009-08-21 16:31:06 +0000374 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000375 "loop.index");
376 llvm::Value* zeroConstant =
Fariborz Jahanian0de78992009-08-21 16:31:06 +0000377 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000378 Builder.CreateStore(zeroConstant, IndexPtr, false);
379
380 // Start the loop with a block that tests the condition.
381 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
382 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
383
384 EmitBlock(CondBlock);
385
386 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
387
388 // Generate: if (loop-index < number-of-elements fall to the loop body,
389 // otherwise, go to the block after the for-loop.
Fariborz Jahanian4f68d532009-08-26 00:23:27 +0000390 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000391 llvm::Value * NumElementsPtr =
Fariborz Jahanian4f68d532009-08-26 00:23:27 +0000392 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000393 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
394 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
395 "isless");
396 // If the condition is true, execute the body.
397 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
398
399 EmitBlock(ForBody);
400
401 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000402 // Inside the loop body, emit the constructor call on the array element.
Fariborz Jahanian995d2812009-08-20 01:01:06 +0000403 Counter = Builder.CreateLoad(IndexPtr);
Fariborz Jahanian4f68d532009-08-26 00:23:27 +0000404 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
405 EmitCXXConstructorCall(D, Ctor_Complete, Address, 0, 0);
Fariborz Jahanian6147a902009-08-20 00:15:15 +0000406
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000407 EmitBlock(ContinueBlock);
408
409 // Emit the increment of the loop counter.
410 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
411 Counter = Builder.CreateLoad(IndexPtr);
412 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
413 Builder.CreateStore(NextVal, IndexPtr, false);
414
415 // Finally, branch back up to the condition for the next iteration.
416 EmitBranch(CondBlock);
417
418 // Emit the fall-through block.
419 EmitBlock(AfterFor, true);
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000420}
421
Fariborz Jahanian1c536bf2009-08-20 23:02:58 +0000422/// EmitCXXAggrDestructorCall - calls the default destructor on array
423/// elements in reverse order of construction.
Anders Carlssonb14095a2009-04-17 00:06:03 +0000424void
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +0000425CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
426 const ArrayType *Array,
427 llvm::Value *This) {
Fariborz Jahanian1c536bf2009-08-20 23:02:58 +0000428 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
429 assert(CA && "Do we support VLA for destruction ?");
430 llvm::Value *One = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
431 1);
Fariborz Jahanian0de78992009-08-21 16:31:06 +0000432 uint64_t ElementCount = getContext().getConstantArrayElementCount(CA);
Fariborz Jahanian1c536bf2009-08-20 23:02:58 +0000433 // Create a temporary for the loop index and initialize it with count of
434 // array elements.
435 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
436 "loop.index");
437 // Index = ElementCount;
438 llvm::Value* UpperCount =
439 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), ElementCount);
440 Builder.CreateStore(UpperCount, IndexPtr, false);
441
442 // Start the loop with a block that tests the condition.
443 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
444 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
445
446 EmitBlock(CondBlock);
447
448 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
449
450 // Generate: if (loop-index != 0 fall to the loop body,
451 // otherwise, go to the block after the for-loop.
452 llvm::Value* zeroConstant =
453 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
454 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
455 llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant,
456 "isne");
457 // If the condition is true, execute the body.
458 Builder.CreateCondBr(IsNE, ForBody, AfterFor);
459
460 EmitBlock(ForBody);
461
462 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
463 // Inside the loop body, emit the constructor call on the array element.
464 Counter = Builder.CreateLoad(IndexPtr);
465 Counter = Builder.CreateSub(Counter, One);
466 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
467 EmitCXXDestructorCall(D, Dtor_Complete, Address);
468
469 EmitBlock(ContinueBlock);
470
471 // Emit the decrement of the loop counter.
472 Counter = Builder.CreateLoad(IndexPtr);
473 Counter = Builder.CreateSub(Counter, One, "dec");
474 Builder.CreateStore(Counter, IndexPtr, false);
475
476 // Finally, branch back up to the condition for the next iteration.
477 EmitBranch(CondBlock);
478
479 // Emit the fall-through block.
480 EmitBlock(AfterFor, true);
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +0000481}
482
483void
Anders Carlssonb14095a2009-04-17 00:06:03 +0000484CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
485 CXXCtorType Type,
486 llvm::Value *This,
487 CallExpr::const_arg_iterator ArgBeg,
488 CallExpr::const_arg_iterator ArgEnd) {
Fariborz Jahanian343a3cf2009-08-14 20:11:43 +0000489 if (D->isCopyConstructor(getContext())) {
490 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D->getDeclContext());
491 if (ClassDecl->hasTrivialCopyConstructor()) {
492 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
493 "EmitCXXConstructorCall - user declared copy constructor");
494 const Expr *E = (*ArgBeg);
495 QualType Ty = E->getType();
496 llvm::Value *Src = EmitLValue(E).getAddress();
497 EmitAggregateCopy(This, Src, Ty);
498 return;
499 }
500 }
501
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000502 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
503
504 EmitCXXMemberCall(D, Callee, This, ArgBeg, ArgEnd);
Anders Carlssonb14095a2009-04-17 00:06:03 +0000505}
506
Anders Carlsson7267c162009-05-29 21:03:38 +0000507void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *D,
508 CXXDtorType Type,
509 llvm::Value *This) {
510 llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(D, Type);
511
512 EmitCXXMemberCall(D, Callee, This, 0, 0);
513}
514
Anders Carlssonb14095a2009-04-17 00:06:03 +0000515void
Anders Carlsson31ccf372009-05-03 17:47:16 +0000516CodeGenFunction::EmitCXXConstructExpr(llvm::Value *Dest,
517 const CXXConstructExpr *E) {
Anders Carlssonb14095a2009-04-17 00:06:03 +0000518 assert(Dest && "Must have a destination!");
519
520 const CXXRecordDecl *RD =
Ted Kremenek6217b802009-07-29 21:53:49 +0000521 cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
Anders Carlssonb14095a2009-04-17 00:06:03 +0000522 if (RD->hasTrivialConstructor())
523 return;
Fariborz Jahanian6904cbb2009-08-06 01:02:49 +0000524
525 // Code gen optimization to eliminate copy constructor and return
526 // its first argument instead.
Anders Carlsson92f58222009-08-22 22:30:33 +0000527 if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
Fariborz Jahanian6904cbb2009-08-06 01:02:49 +0000528 CXXConstructExpr::const_arg_iterator i = E->arg_begin();
Fariborz Jahanian1cf9ff82009-08-06 19:12:38 +0000529 EmitAggExpr((*i), Dest, false);
530 return;
Fariborz Jahanian6904cbb2009-08-06 01:02:49 +0000531 }
Anders Carlssonb14095a2009-04-17 00:06:03 +0000532 // Call the constructor.
533 EmitCXXConstructorCall(E->getConstructor(), Ctor_Complete, Dest,
534 E->arg_begin(), E->arg_end());
535}
536
Anders Carlssona00703d2009-05-31 01:40:14 +0000537llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
Anders Carlssoned4e3672009-05-31 20:21:44 +0000538 if (E->isArray()) {
539 ErrorUnsupported(E, "new[] expression");
Owen Anderson03e20502009-07-30 23:11:26 +0000540 return llvm::UndefValue::get(ConvertType(E->getType()));
Anders Carlssoned4e3672009-05-31 20:21:44 +0000541 }
542
543 QualType AllocType = E->getAllocatedType();
544 FunctionDecl *NewFD = E->getOperatorNew();
545 const FunctionProtoType *NewFTy = NewFD->getType()->getAsFunctionProtoType();
546
547 CallArgList NewArgs;
548
549 // The allocation size is the first argument.
550 QualType SizeTy = getContext().getSizeType();
551 llvm::Value *AllocSize =
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000552 llvm::ConstantInt::get(ConvertType(SizeTy),
Anders Carlssoned4e3672009-05-31 20:21:44 +0000553 getContext().getTypeSize(AllocType) / 8);
554
555 NewArgs.push_back(std::make_pair(RValue::get(AllocSize), SizeTy));
556
557 // Emit the rest of the arguments.
558 // FIXME: Ideally, this should just use EmitCallArgs.
559 CXXNewExpr::const_arg_iterator NewArg = E->placement_arg_begin();
560
561 // First, use the types from the function type.
562 // We start at 1 here because the first argument (the allocation size)
563 // has already been emitted.
564 for (unsigned i = 1, e = NewFTy->getNumArgs(); i != e; ++i, ++NewArg) {
565 QualType ArgType = NewFTy->getArgType(i);
566
567 assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
568 getTypePtr() ==
569 getContext().getCanonicalType(NewArg->getType()).getTypePtr() &&
570 "type mismatch in call argument!");
571
572 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
573 ArgType));
574
575 }
576
577 // Either we've emitted all the call args, or we have a call to a
578 // variadic function.
579 assert((NewArg == E->placement_arg_end() || NewFTy->isVariadic()) &&
580 "Extra arguments in non-variadic function!");
581
582 // If we still have any arguments, emit them using the type of the argument.
583 for (CXXNewExpr::const_arg_iterator NewArgEnd = E->placement_arg_end();
584 NewArg != NewArgEnd; ++NewArg) {
585 QualType ArgType = NewArg->getType();
586 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
587 ArgType));
588 }
589
590 // Emit the call to new.
591 RValue RV =
592 EmitCall(CGM.getTypes().getFunctionInfo(NewFTy->getResultType(), NewArgs),
593 CGM.GetAddrOfFunction(GlobalDecl(NewFD)),
594 NewArgs, NewFD);
595
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000596 // If an allocation function is declared with an empty exception specification
597 // it returns null to indicate failure to allocate storage. [expr.new]p13.
598 // (We don't need to check for null when there's no new initializer and
599 // we're allocating a POD type).
600 bool NullCheckResult = NewFTy->hasEmptyExceptionSpec() &&
601 !(AllocType->isPODType() && !E->hasInitializer());
Anders Carlssoned4e3672009-05-31 20:21:44 +0000602
Anders Carlssonf1108532009-06-01 00:05:16 +0000603 llvm::BasicBlock *NewNull = 0;
604 llvm::BasicBlock *NewNotNull = 0;
605 llvm::BasicBlock *NewEnd = 0;
606
607 llvm::Value *NewPtr = RV.getScalarVal();
608
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000609 if (NullCheckResult) {
Anders Carlssonf1108532009-06-01 00:05:16 +0000610 NewNull = createBasicBlock("new.null");
611 NewNotNull = createBasicBlock("new.notnull");
612 NewEnd = createBasicBlock("new.end");
613
614 llvm::Value *IsNull =
615 Builder.CreateICmpEQ(NewPtr,
Owen Andersonc9c88b42009-07-31 20:28:54 +0000616 llvm::Constant::getNullValue(NewPtr->getType()),
Anders Carlssonf1108532009-06-01 00:05:16 +0000617 "isnull");
618
619 Builder.CreateCondBr(IsNull, NewNull, NewNotNull);
620 EmitBlock(NewNotNull);
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000621 }
622
Anders Carlssonf1108532009-06-01 00:05:16 +0000623 NewPtr = Builder.CreateBitCast(NewPtr, ConvertType(E->getType()));
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000624
Anders Carlsson6d0ffad2009-05-31 20:56:36 +0000625 if (AllocType->isPODType()) {
Anders Carlsson215bd202009-06-01 00:26:14 +0000626 if (E->getNumConstructorArgs() > 0) {
Anders Carlsson6d0ffad2009-05-31 20:56:36 +0000627 assert(E->getNumConstructorArgs() == 1 &&
628 "Can only have one argument to initializer of POD type.");
629
630 const Expr *Init = E->getConstructorArg(0);
631
Anders Carlsson3923e952009-05-31 21:07:58 +0000632 if (!hasAggregateLLVMType(AllocType))
Anders Carlsson6d0ffad2009-05-31 20:56:36 +0000633 Builder.CreateStore(EmitScalarExpr(Init), NewPtr);
Anders Carlsson3923e952009-05-31 21:07:58 +0000634 else if (AllocType->isAnyComplexType())
635 EmitComplexExprIntoAddr(Init, NewPtr, AllocType.isVolatileQualified());
Anders Carlsson627a3e52009-05-31 21:12:26 +0000636 else
637 EmitAggExpr(Init, NewPtr, AllocType.isVolatileQualified());
Anders Carlsson6d0ffad2009-05-31 20:56:36 +0000638 }
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000639 } else {
640 // Call the constructor.
641 CXXConstructorDecl *Ctor = E->getConstructor();
Anders Carlsson6d0ffad2009-05-31 20:56:36 +0000642
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000643 EmitCXXConstructorCall(Ctor, Ctor_Complete, NewPtr,
644 E->constructor_arg_begin(),
645 E->constructor_arg_end());
Anders Carlssoned4e3672009-05-31 20:21:44 +0000646 }
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000647
Anders Carlssonf1108532009-06-01 00:05:16 +0000648 if (NullCheckResult) {
649 Builder.CreateBr(NewEnd);
650 EmitBlock(NewNull);
651 Builder.CreateBr(NewEnd);
652 EmitBlock(NewEnd);
653
654 llvm::PHINode *PHI = Builder.CreatePHI(NewPtr->getType());
655 PHI->reserveOperandSpace(2);
656 PHI->addIncoming(NewPtr, NewNotNull);
Owen Andersonc9c88b42009-07-31 20:28:54 +0000657 PHI->addIncoming(llvm::Constant::getNullValue(NewPtr->getType()), NewNull);
Anders Carlssonf1108532009-06-01 00:05:16 +0000658
659 NewPtr = PHI;
660 }
661
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000662 return NewPtr;
Anders Carlssona00703d2009-05-31 01:40:14 +0000663}
664
Anders Carlsson60e282c2009-08-16 21:13:42 +0000665void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
666 if (E->isArrayForm()) {
667 ErrorUnsupported(E, "delete[] expression");
668 return;
669 };
670
671 QualType DeleteTy =
672 E->getArgument()->getType()->getAs<PointerType>()->getPointeeType();
673
674 llvm::Value *Ptr = EmitScalarExpr(E->getArgument());
675
676 // Null check the pointer.
677 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
678 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
679
680 llvm::Value *IsNull =
681 Builder.CreateICmpEQ(Ptr, llvm::Constant::getNullValue(Ptr->getType()),
682 "isnull");
683
684 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
685 EmitBlock(DeleteNotNull);
686
687 // Call the destructor if necessary.
688 if (const RecordType *RT = DeleteTy->getAs<RecordType>()) {
689 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
690 if (!RD->hasTrivialDestructor()) {
691 const CXXDestructorDecl *Dtor = RD->getDestructor(getContext());
692 if (Dtor->isVirtual()) {
693 ErrorUnsupported(E, "delete expression with virtual destructor");
694 return;
695 }
696
697 EmitCXXDestructorCall(Dtor, Dtor_Complete, Ptr);
698 }
699 }
700 }
701
702 // Call delete.
703 FunctionDecl *DeleteFD = E->getOperatorDelete();
704 const FunctionProtoType *DeleteFTy =
705 DeleteFD->getType()->getAsFunctionProtoType();
706
707 CallArgList DeleteArgs;
708
709 QualType ArgTy = DeleteFTy->getArgType(0);
710 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
711 DeleteArgs.push_back(std::make_pair(RValue::get(DeletePtr), ArgTy));
712
713 // Emit the call to delete.
714 EmitCall(CGM.getTypes().getFunctionInfo(DeleteFTy->getResultType(),
715 DeleteArgs),
716 CGM.GetAddrOfFunction(GlobalDecl(DeleteFD)),
717 DeleteArgs, DeleteFD);
718
719 EmitBlock(DeleteEnd);
720}
721
Anders Carlsson27ae5362009-04-17 01:58:57 +0000722static bool canGenerateCXXstructor(const CXXRecordDecl *RD,
723 ASTContext &Context) {
Anders Carlsson59d8e0f2009-04-15 21:02:13 +0000724 // The class has base classes - we don't support that right now.
725 if (RD->getNumBases() > 0)
726 return false;
727
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000728 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
729 I != E; ++I) {
Anders Carlsson59d8e0f2009-04-15 21:02:13 +0000730 // We don't support ctors for fields that aren't POD.
731 if (!I->getType()->isPODType())
732 return false;
733 }
734
735 return true;
736}
737
Anders Carlsson95d4e5d2009-04-15 15:55:24 +0000738void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) {
Anders Carlsson27ae5362009-04-17 01:58:57 +0000739 if (!canGenerateCXXstructor(D->getParent(), getContext())) {
Anders Carlsson59d8e0f2009-04-15 21:02:13 +0000740 ErrorUnsupported(D, "C++ constructor", true);
741 return;
742 }
Anders Carlsson95d4e5d2009-04-15 15:55:24 +0000743
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000744 EmitGlobal(GlobalDecl(D, Ctor_Complete));
745 EmitGlobal(GlobalDecl(D, Ctor_Base));
Anders Carlsson95d4e5d2009-04-15 15:55:24 +0000746}
Anders Carlsson363c1842009-04-16 23:57:24 +0000747
Anders Carlsson27ae5362009-04-17 01:58:57 +0000748void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D,
749 CXXCtorType Type) {
750
751 llvm::Function *Fn = GetAddrOfCXXConstructor(D, Type);
752
753 CodeGenFunction(*this).GenerateCode(D, Fn);
754
755 SetFunctionDefinitionAttributes(D, Fn);
756 SetLLVMFunctionAttributesForDefinition(D, Fn);
757}
758
Anders Carlsson363c1842009-04-16 23:57:24 +0000759llvm::Function *
760CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
761 CXXCtorType Type) {
762 const llvm::FunctionType *FTy =
763 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false);
764
765 const char *Name = getMangledCXXCtorName(D, Type);
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000766 return cast<llvm::Function>(
767 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson363c1842009-04-16 23:57:24 +0000768}
Anders Carlsson27ae5362009-04-17 01:58:57 +0000769
770const char *CodeGenModule::getMangledCXXCtorName(const CXXConstructorDecl *D,
771 CXXCtorType Type) {
772 llvm::SmallString<256> Name;
773 llvm::raw_svector_ostream Out(Name);
774 mangleCXXCtor(D, Type, Context, Out);
775
776 Name += '\0';
777 return UniqueMangledName(Name.begin(), Name.end());
778}
779
780void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) {
781 if (!canGenerateCXXstructor(D->getParent(), getContext())) {
782 ErrorUnsupported(D, "C++ destructor", true);
783 return;
784 }
785
786 EmitCXXDestructor(D, Dtor_Complete);
787 EmitCXXDestructor(D, Dtor_Base);
788}
789
790void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D,
791 CXXDtorType Type) {
792 llvm::Function *Fn = GetAddrOfCXXDestructor(D, Type);
793
794 CodeGenFunction(*this).GenerateCode(D, Fn);
795
796 SetFunctionDefinitionAttributes(D, Fn);
797 SetLLVMFunctionAttributesForDefinition(D, Fn);
798}
799
800llvm::Function *
801CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D,
802 CXXDtorType Type) {
803 const llvm::FunctionType *FTy =
804 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false);
805
806 const char *Name = getMangledCXXDtorName(D, Type);
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000807 return cast<llvm::Function>(
808 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson27ae5362009-04-17 01:58:57 +0000809}
810
811const char *CodeGenModule::getMangledCXXDtorName(const CXXDestructorDecl *D,
812 CXXDtorType Type) {
813 llvm::SmallString<256> Name;
814 llvm::raw_svector_ostream Out(Name);
815 mangleCXXDtor(D, Type, Context, Out);
816
817 Name += '\0';
818 return UniqueMangledName(Name.begin(), Name.end());
819}
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +0000820
Mike Stump32f37012009-08-18 21:49:00 +0000821llvm::Constant *CodeGenModule::GenerateRtti(const CXXRecordDecl *RD) {
Mike Stump738f8c22009-07-31 23:15:31 +0000822 llvm::Type *Ptr8Ty;
Owen Anderson0032b272009-08-13 21:57:51 +0000823 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Mike Stumpcb1b5d32009-08-04 20:06:48 +0000824 llvm::Constant *Rtti = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stump738f8c22009-07-31 23:15:31 +0000825
826 if (!getContext().getLangOptions().Rtti)
Mike Stumpcb1b5d32009-08-04 20:06:48 +0000827 return Rtti;
Mike Stump738f8c22009-07-31 23:15:31 +0000828
829 llvm::SmallString<256> OutName;
830 llvm::raw_svector_ostream Out(OutName);
831 QualType ClassTy;
Mike Stumpe607ed02009-08-07 18:05:12 +0000832 ClassTy = getContext().getTagDeclType(RD);
Mike Stump738f8c22009-07-31 23:15:31 +0000833 mangleCXXRtti(ClassTy, getContext(), Out);
Mike Stump738f8c22009-07-31 23:15:31 +0000834 llvm::GlobalVariable::LinkageTypes linktype;
835 linktype = llvm::GlobalValue::WeakAnyLinkage;
836 std::vector<llvm::Constant *> info;
Mike Stump4ef98092009-08-13 22:53:07 +0000837 // assert(0 && "FIXME: implement rtti descriptor");
Mike Stump738f8c22009-07-31 23:15:31 +0000838 // FIXME: descriptor
839 info.push_back(llvm::Constant::getNullValue(Ptr8Ty));
Mike Stump4ef98092009-08-13 22:53:07 +0000840 // assert(0 && "FIXME: implement rtti ts");
Mike Stump738f8c22009-07-31 23:15:31 +0000841 // FIXME: TS
842 info.push_back(llvm::Constant::getNullValue(Ptr8Ty));
843
844 llvm::Constant *C;
845 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, info.size());
846 C = llvm::ConstantArray::get(type, info);
Mike Stump32f37012009-08-18 21:49:00 +0000847 Rtti = new llvm::GlobalVariable(getModule(), type, true, linktype, C,
Daniel Dunbar77659342009-08-19 20:04:03 +0000848 Out.str());
Mike Stumpcb1b5d32009-08-04 20:06:48 +0000849 Rtti = llvm::ConstantExpr::getBitCast(Rtti, Ptr8Ty);
850 return Rtti;
Mike Stump738f8c22009-07-31 23:15:31 +0000851}
852
Mike Stumpeb7e9c32009-08-19 18:10:47 +0000853class VtableBuilder {
Mike Stumpf0070db2009-08-26 20:46:33 +0000854public:
855 /// Index_t - Vtable index type.
856 typedef uint64_t Index_t;
857private:
Mike Stump7c435fa2009-08-18 20:50:28 +0000858 std::vector<llvm::Constant *> &methods;
859 llvm::Type *Ptr8Ty;
Mike Stumpb9871a22009-08-21 01:45:00 +0000860 /// Class - The most derived class that this vtable is being built for.
Mike Stump32f37012009-08-18 21:49:00 +0000861 const CXXRecordDecl *Class;
Mike Stumpb9871a22009-08-21 01:45:00 +0000862 /// BLayout - Layout for the most derived class that this vtable is being
863 /// built for.
Mike Stumpb46c92d2009-08-19 02:06:38 +0000864 const ASTRecordLayout &BLayout;
Mike Stumpee560f32009-08-19 14:40:47 +0000865 llvm::SmallSet<const CXXRecordDecl *, 32> IndirectPrimary;
Mike Stump7fa0d932009-08-20 02:11:48 +0000866 llvm::SmallSet<const CXXRecordDecl *, 32> SeenVBase;
Mike Stump32f37012009-08-18 21:49:00 +0000867 llvm::Constant *rtti;
Mike Stump7c435fa2009-08-18 20:50:28 +0000868 llvm::LLVMContext &VMContext;
Mike Stump65defe32009-08-18 21:03:28 +0000869 CodeGenModule &CGM; // Per-module state.
Mike Stumpb9871a22009-08-21 01:45:00 +0000870 /// Index - Maps a method decl into a vtable index. Useful for virtual
871 /// dispatch codegen.
Mike Stumpf0070db2009-08-26 20:46:33 +0000872 llvm::DenseMap<const CXXMethodDecl *, Index_t> Index;
Mike Stump552b2752009-08-18 22:04:08 +0000873 typedef CXXRecordDecl::method_iterator method_iter;
Mike Stump7c435fa2009-08-18 20:50:28 +0000874public:
Mike Stumpeb7e9c32009-08-19 18:10:47 +0000875 VtableBuilder(std::vector<llvm::Constant *> &meth,
876 const CXXRecordDecl *c,
877 CodeGenModule &cgm)
Mike Stumpb46c92d2009-08-19 02:06:38 +0000878 : methods(meth), Class(c), BLayout(cgm.getContext().getASTRecordLayout(c)),
879 rtti(cgm.GenerateRtti(c)), VMContext(cgm.getModule().getContext()),
880 CGM(cgm) {
Mike Stump7c435fa2009-08-18 20:50:28 +0000881 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
882 }
Mike Stump32f37012009-08-18 21:49:00 +0000883
Mike Stumpf0070db2009-08-26 20:46:33 +0000884 llvm::DenseMap<const CXXMethodDecl *, Index_t> &getIndex() { return Index; }
Mike Stumpb46c92d2009-08-19 02:06:38 +0000885 llvm::Constant *GenerateVcall(const CXXMethodDecl *MD,
886 const CXXRecordDecl *RD,
887 bool VBoundary,
888 bool SecondaryVirtual) {
Mike Stump263b3522009-08-21 23:09:30 +0000889 typedef CXXMethodDecl::method_iterator meth_iter;
890 // No vcall for methods that don't override in primary vtables.
Mike Stumpb46c92d2009-08-19 02:06:38 +0000891 llvm::Constant *m = 0;
892
Mike Stumpb46c92d2009-08-19 02:06:38 +0000893 if (SecondaryVirtual || VBoundary)
894 m = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stump263b3522009-08-21 23:09:30 +0000895
896 int64_t Offset = 0;
897 int64_t BaseOffset = 0;
898 for (meth_iter mi = MD->begin_overridden_methods(),
899 me = MD->end_overridden_methods();
900 mi != me; ++mi) {
901 const CXXRecordDecl *DefBase = (*mi)->getParent();
902 // FIXME: vcall: offset for virtual base for this function
903 // m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), 900);
904 // m = llvm::Constant::getNullValue(Ptr8Ty);
905 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
906 e = RD->bases_end(); i != e; ++i) {
907 const CXXRecordDecl *Base =
908 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
909 if (DefBase == Base) {
910 if (!i->isVirtual())
911 break;
912
913 // FIXME: drop the 700-, just for debugging
914 BaseOffset = 700- -(BLayout.getVBaseClassOffset(Base) / 8);
915 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
916 BaseOffset);
917 m = llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
918 break;
919 } else {
920 // FIXME: more searching.
921 (void)Offset;
922 }
923 }
924 }
925
Mike Stumpb46c92d2009-08-19 02:06:38 +0000926 return m;
927 }
928
929 void GenerateVcalls(const CXXRecordDecl *RD, bool VBoundary,
930 bool SecondaryVirtual) {
Mike Stump7c435fa2009-08-18 20:50:28 +0000931 llvm::Constant *m;
Mike Stump80a0e322009-08-12 23:25:18 +0000932
Mike Stump552b2752009-08-18 22:04:08 +0000933 for (method_iter mi = RD->method_begin(),
Mike Stump7c435fa2009-08-18 20:50:28 +0000934 me = RD->method_end(); mi != me; ++mi) {
935 if (mi->isVirtual()) {
Mike Stumpb46c92d2009-08-19 02:06:38 +0000936 m = GenerateVcall(*mi, RD, VBoundary, SecondaryVirtual);
937 if (m)
938 methods.push_back(m);
Mike Stump7c435fa2009-08-18 20:50:28 +0000939 }
Mike Stump4c3aedd2009-08-12 23:14:12 +0000940 }
Mike Stump80a0e322009-08-12 23:25:18 +0000941 }
Mike Stump4c3aedd2009-08-12 23:14:12 +0000942
Mike Stump7fa0d932009-08-20 02:11:48 +0000943 void GenerateVBaseOffsets(std::vector<llvm::Constant *> &offsets,
Mike Stumpb9837442009-08-20 07:22:17 +0000944 const CXXRecordDecl *RD, uint64_t Offset) {
Mike Stump7fa0d932009-08-20 02:11:48 +0000945 for (CXXRecordDecl::base_class_const_iterator i =RD->bases_begin(),
946 e = RD->bases_end(); i != e; ++i) {
947 const CXXRecordDecl *Base =
948 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
949 if (i->isVirtual() && !SeenVBase.count(Base)) {
950 SeenVBase.insert(Base);
Mike Stumpb9837442009-08-20 07:22:17 +0000951 int64_t BaseOffset = -(Offset/8) + BLayout.getVBaseClassOffset(Base)/8;
Mike Stump7fa0d932009-08-20 02:11:48 +0000952 llvm::Constant *m;
Mike Stumpb9837442009-08-20 07:22:17 +0000953 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),BaseOffset);
Mike Stump7fa0d932009-08-20 02:11:48 +0000954 m = llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
955 offsets.push_back(m);
956 }
Mike Stumpb9837442009-08-20 07:22:17 +0000957 GenerateVBaseOffsets(offsets, Base, Offset);
Mike Stump7fa0d932009-08-20 02:11:48 +0000958 }
959 }
960
Mike Stumpb9871a22009-08-21 01:45:00 +0000961 void StartNewTable() {
962 SeenVBase.clear();
963 }
Mike Stumpbc16aea2009-08-12 23:00:59 +0000964
Mike Stumpf0070db2009-08-26 20:46:33 +0000965 void AddMethod(const CXXMethodDecl *MD, Index_t AddressPoint) {
Mike Stumpb9871a22009-08-21 01:45:00 +0000966 typedef CXXMethodDecl::method_iterator meth_iter;
967
968 llvm::Constant *m;
969 m = CGM.GetAddrOfFunction(GlobalDecl(MD), Ptr8Ty);
970 m = llvm::ConstantExpr::getBitCast(m, Ptr8Ty);
971
972 // FIXME: Don't like the nested loops. For very large inheritance
973 // heirarchies we could have a table on the side with the final overridder
974 // and just replace each instance of an overridden method once. Would be
975 // nice to measure the cost/benefit on real code.
976
977 // If we can find a previously allocated slot for this, reuse it.
978 for (meth_iter mi = MD->begin_overridden_methods(),
979 e = MD->end_overridden_methods();
980 mi != e; ++mi) {
981 const CXXMethodDecl *OMD = *mi;
982 llvm::Constant *om;
983 om = CGM.GetAddrOfFunction(GlobalDecl(OMD), Ptr8Ty);
984 om = llvm::ConstantExpr::getBitCast(om, Ptr8Ty);
985
Mike Stumpf0070db2009-08-26 20:46:33 +0000986 for (Index_t i = AddressPoint, e = methods.size();
987 i != e; ++i) {
Mike Stumpb9871a22009-08-21 01:45:00 +0000988 // FIXME: begin_overridden_methods might be too lax, covariance */
989 if (methods[i] == om) {
990 methods[i] = m;
Mike Stumpf0070db2009-08-26 20:46:33 +0000991 Index[MD] = i - AddressPoint;
Mike Stumpb9871a22009-08-21 01:45:00 +0000992 return;
993 }
Mike Stump65defe32009-08-18 21:03:28 +0000994 }
Mike Stumpbc16aea2009-08-12 23:00:59 +0000995 }
Mike Stumpb9871a22009-08-21 01:45:00 +0000996
997 // else allocate a new slot.
Mike Stumpf0070db2009-08-26 20:46:33 +0000998 Index[MD] = methods.size() - AddressPoint;
Mike Stumpb9871a22009-08-21 01:45:00 +0000999 methods.push_back(m);
1000 }
1001
Mike Stumpf0070db2009-08-26 20:46:33 +00001002 void GenerateMethods(const CXXRecordDecl *RD, Index_t AddressPoint) {
Mike Stumpb9871a22009-08-21 01:45:00 +00001003 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
1004 ++mi)
1005 if (mi->isVirtual())
Mike Stumpf0070db2009-08-26 20:46:33 +00001006 AddMethod(*mi, AddressPoint);
Mike Stumpbc16aea2009-08-12 23:00:59 +00001007 }
Mike Stump65defe32009-08-18 21:03:28 +00001008
Mike Stump263b3522009-08-21 23:09:30 +00001009 int64_t GenerateVtableForBase(const CXXRecordDecl *RD,
1010 bool forPrimary,
1011 bool VBoundary,
1012 int64_t Offset,
Mike Stumpf0070db2009-08-26 20:46:33 +00001013 bool ForVirtualBase) {
Mike Stump109b13d2009-08-18 21:30:21 +00001014 llvm::Constant *m = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stump263b3522009-08-21 23:09:30 +00001015 int64_t AddressPoint=0;
Mike Stump276b9f12009-08-16 01:46:26 +00001016
Mike Stump109b13d2009-08-18 21:30:21 +00001017 if (RD && !RD->isDynamicClass())
Mike Stump263b3522009-08-21 23:09:30 +00001018 return 0;
Mike Stump109b13d2009-08-18 21:30:21 +00001019
1020 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1021 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1022 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
1023
Mike Stumpb46c92d2009-08-19 02:06:38 +00001024 if (VBoundary || forPrimary || ForVirtualBase) {
1025 // then comes the the vcall offsets for all our functions...
1026 GenerateVcalls(RD, VBoundary, !forPrimary && ForVirtualBase);
1027 }
1028
Mike Stump109b13d2009-08-18 21:30:21 +00001029 // The virtual base offsets come first...
1030 // FIXME: Audit, is this right?
Mike Stump09765ec2009-08-19 02:53:08 +00001031 if (PrimaryBase == 0 || forPrimary || !PrimaryBaseWasVirtual) {
Mike Stump109b13d2009-08-18 21:30:21 +00001032 std::vector<llvm::Constant *> offsets;
Mike Stumpb9837442009-08-20 07:22:17 +00001033 GenerateVBaseOffsets(offsets, RD, Offset);
Mike Stump109b13d2009-08-18 21:30:21 +00001034 for (std::vector<llvm::Constant *>::reverse_iterator i = offsets.rbegin(),
1035 e = offsets.rend(); i != e; ++i)
1036 methods.push_back(*i);
1037 }
1038
Mike Stump109b13d2009-08-18 21:30:21 +00001039 bool Top = true;
1040
1041 // vtables are composed from the chain of primaries.
1042 if (PrimaryBase) {
1043 if (PrimaryBaseWasVirtual)
1044 IndirectPrimary.insert(PrimaryBase);
1045 Top = false;
Mike Stumpf0070db2009-08-26 20:46:33 +00001046 AddressPoint = GenerateVtableForBase(PrimaryBase, true,
1047 PrimaryBaseWasVirtual|VBoundary,
1048 Offset, PrimaryBaseWasVirtual);
Mike Stump109b13d2009-08-18 21:30:21 +00001049 }
1050
1051 if (Top) {
1052 int64_t BaseOffset;
1053 if (ForVirtualBase) {
Mike Stump109b13d2009-08-18 21:30:21 +00001054 BaseOffset = -(BLayout.getVBaseClassOffset(RD) / 8);
1055 } else
1056 BaseOffset = -Offset/8;
Mike Stump276b9f12009-08-16 01:46:26 +00001057 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), BaseOffset);
1058 m = llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
1059 methods.push_back(m);
Mike Stump109b13d2009-08-18 21:30:21 +00001060 methods.push_back(rtti);
Mike Stump263b3522009-08-21 23:09:30 +00001061 AddressPoint = methods.size();
Mike Stump276b9f12009-08-16 01:46:26 +00001062 }
Mike Stump4ef98092009-08-13 22:53:07 +00001063
Mike Stump109b13d2009-08-18 21:30:21 +00001064 // And add the virtuals for the class to the primary vtable.
Mike Stumpf0070db2009-08-26 20:46:33 +00001065 GenerateMethods(RD, AddressPoint);
Mike Stump109b13d2009-08-18 21:30:21 +00001066
1067 // and then the non-virtual bases.
1068 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1069 e = RD->bases_end(); i != e; ++i) {
1070 if (i->isVirtual())
1071 continue;
1072 const CXXRecordDecl *Base =
1073 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1074 if (Base != PrimaryBase || PrimaryBaseWasVirtual) {
1075 uint64_t o = Offset + Layout.getBaseClassOffset(Base);
Mike Stumpb9871a22009-08-21 01:45:00 +00001076 StartNewTable();
Mike Stumpf0070db2009-08-26 20:46:33 +00001077 GenerateVtableForBase(Base, true, false, o, false);
Mike Stump109b13d2009-08-18 21:30:21 +00001078 }
1079 }
Mike Stump263b3522009-08-21 23:09:30 +00001080 return AddressPoint;
Mike Stump109b13d2009-08-18 21:30:21 +00001081 }
1082
1083 void GenerateVtableForVBases(const CXXRecordDecl *RD,
Mike Stumpee560f32009-08-19 14:40:47 +00001084 const CXXRecordDecl *Class) {
Mike Stump109b13d2009-08-18 21:30:21 +00001085 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1086 e = RD->bases_end(); i != e; ++i) {
1087 const CXXRecordDecl *Base =
1088 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1089 if (i->isVirtual() && !IndirectPrimary.count(Base)) {
1090 // Mark it so we don't output it twice.
1091 IndirectPrimary.insert(Base);
Mike Stumpb9871a22009-08-21 01:45:00 +00001092 StartNewTable();
Mike Stumpb9837442009-08-20 07:22:17 +00001093 int64_t BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stumpf0070db2009-08-26 20:46:33 +00001094 GenerateVtableForBase(Base, false, true, BaseOffset, true);
Mike Stump109b13d2009-08-18 21:30:21 +00001095 }
1096 if (Base->getNumVBases())
Mike Stumpee560f32009-08-19 14:40:47 +00001097 GenerateVtableForVBases(Base, Class);
Mike Stump276b9f12009-08-16 01:46:26 +00001098 }
1099 }
Mike Stump109b13d2009-08-18 21:30:21 +00001100};
Mike Stump8a12b562009-08-06 15:50:11 +00001101
Mike Stumpf0070db2009-08-26 20:46:33 +00001102class VtableInfo {
1103public:
1104 typedef VtableBuilder::Index_t Index_t;
1105private:
1106 CodeGenModule &CGM; // Per-module state.
1107 /// Index_t - Vtable index type.
1108 typedef llvm::DenseMap<const CXXMethodDecl *, Index_t> ElTy;
1109 typedef llvm::DenseMap<const CXXRecordDecl *, ElTy *> MapTy;
1110 // FIXME: Move to Context.
1111 static MapTy IndexFor;
1112public:
1113 VtableInfo(CodeGenModule &cgm) : CGM(cgm) { }
1114 void register_index(const CXXRecordDecl *RD, const ElTy &e) {
1115 assert(IndexFor.find(RD) == IndexFor.end() && "Don't compute vtbl twice");
1116 // We own a copy of this, it will go away shortly.
1117 new ElTy (e);
1118 IndexFor[RD] = new ElTy (e);
1119 }
1120 Index_t lookup(const CXXMethodDecl *MD) {
1121 const CXXRecordDecl *RD = MD->getParent();
1122 MapTy::iterator I = IndexFor.find(RD);
1123 if (I == IndexFor.end()) {
1124 std::vector<llvm::Constant *> methods;
1125 VtableBuilder b(methods, RD, CGM);
1126 b.GenerateVtableForBase(RD, true, false, 0, false);
1127 b.GenerateVtableForVBases(RD, RD);
1128 register_index(RD, b.getIndex());
1129 I = IndexFor.find(RD);
1130 }
1131 assert(I->second->find(MD)!=I->second->end() && "Can't find vtable index");
1132 return (*I->second)[MD];
1133 }
1134};
1135
1136// FIXME: Move to Context.
1137VtableInfo::MapTy VtableInfo::IndexFor;
1138
Mike Stumpf1216772009-07-31 18:25:34 +00001139llvm::Value *CodeGenFunction::GenerateVtable(const CXXRecordDecl *RD) {
Mike Stumpf1216772009-07-31 18:25:34 +00001140 llvm::SmallString<256> OutName;
1141 llvm::raw_svector_ostream Out(OutName);
1142 QualType ClassTy;
Mike Stumpe607ed02009-08-07 18:05:12 +00001143 ClassTy = getContext().getTagDeclType(RD);
Mike Stumpf1216772009-07-31 18:25:34 +00001144 mangleCXXVtable(ClassTy, getContext(), Out);
Mike Stump82b56962009-07-31 21:43:43 +00001145 llvm::GlobalVariable::LinkageTypes linktype;
1146 linktype = llvm::GlobalValue::WeakAnyLinkage;
1147 std::vector<llvm::Constant *> methods;
Mike Stump276b9f12009-08-16 01:46:26 +00001148 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
Mike Stump263b3522009-08-21 23:09:30 +00001149 int64_t Offset;
Mike Stump6f376332009-08-05 22:37:18 +00001150
Mike Stumpeb7e9c32009-08-19 18:10:47 +00001151 VtableBuilder b(methods, RD, CGM);
Mike Stump109b13d2009-08-18 21:30:21 +00001152
Mike Stump276b9f12009-08-16 01:46:26 +00001153 // First comes the vtables for all the non-virtual bases...
Mike Stumpf0070db2009-08-26 20:46:33 +00001154 Offset = b.GenerateVtableForBase(RD, true, false, 0, false);
Mike Stump21538912009-08-14 01:44:03 +00001155
Mike Stump276b9f12009-08-16 01:46:26 +00001156 // then the vtables for all the virtual bases.
Mike Stumpee560f32009-08-19 14:40:47 +00001157 b.GenerateVtableForVBases(RD, RD);
Mike Stump104ffaa2009-08-04 21:58:42 +00001158
Mike Stump82b56962009-07-31 21:43:43 +00001159 llvm::Constant *C;
1160 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, methods.size());
1161 C = llvm::ConstantArray::get(type, methods);
1162 llvm::Value *vtable = new llvm::GlobalVariable(CGM.getModule(), type, true,
Daniel Dunbar77659342009-08-19 20:04:03 +00001163 linktype, C, Out.str());
Mike Stumpf1216772009-07-31 18:25:34 +00001164 vtable = Builder.CreateBitCast(vtable, Ptr8Ty);
Mike Stumpf1216772009-07-31 18:25:34 +00001165 vtable = Builder.CreateGEP(vtable,
Mike Stump276b9f12009-08-16 01:46:26 +00001166 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
Mike Stump263b3522009-08-21 23:09:30 +00001167 Offset*LLVMPointerWidth/8));
Mike Stumpf1216772009-07-31 18:25:34 +00001168 return vtable;
1169}
1170
Mike Stumpf0070db2009-08-26 20:46:33 +00001171// FIXME: move to Context
1172static VtableInfo *vtableinfo;
1173
1174llvm::Value *
1175CodeGenFunction::BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *&This,
1176 const llvm::Type *Ty) {
1177 // FIXME: If we know the dynamic type, we don't have to do a virtual dispatch.
1178
1179 // FIXME: move to Context
1180 if (vtableinfo == 0)
1181 vtableinfo = new VtableInfo(CGM);
1182
1183 VtableInfo::Index_t Idx = vtableinfo->lookup(MD);
1184
1185 Ty = llvm::PointerType::get(Ty, 0);
1186 Ty = llvm::PointerType::get(Ty, 0);
1187 Ty = llvm::PointerType::get(Ty, 0);
1188 llvm::Value *vtbl = Builder.CreateBitCast(This, Ty);
1189 vtbl = Builder.CreateLoad(vtbl);
1190 llvm::Value *vfn = Builder.CreateConstInBoundsGEP1_64(vtbl,
1191 Idx, "vfn");
1192 vfn = Builder.CreateLoad(vfn);
1193 return vfn;
1194}
1195
Fariborz Jahanianeb0b6d52009-08-21 18:30:26 +00001196/// EmitClassAggrMemberwiseCopy - This routine generates code to copy a class
1197/// array of objects from SrcValue to DestValue. Copying can be either a bitwise
1198/// copy or via a copy constructor call.
Fariborz Jahanian4f68d532009-08-26 00:23:27 +00001199// FIXME. Consolidate this with EmitCXXAggrConstructorCall.
Fariborz Jahanianeb0b6d52009-08-21 18:30:26 +00001200void CodeGenFunction::EmitClassAggrMemberwiseCopy(llvm::Value *Dest,
1201 llvm::Value *Src,
1202 const ArrayType *Array,
1203 const CXXRecordDecl *BaseClassDecl,
1204 QualType Ty) {
1205 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1206 assert(CA && "VLA cannot be copied over");
1207 bool BitwiseCopy = BaseClassDecl->hasTrivialCopyConstructor();
1208
1209 // Create a temporary for the loop index and initialize it with 0.
1210 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1211 "loop.index");
1212 llvm::Value* zeroConstant =
1213 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
1214 Builder.CreateStore(zeroConstant, IndexPtr, false);
1215 // Start the loop with a block that tests the condition.
1216 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1217 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1218
1219 EmitBlock(CondBlock);
1220
1221 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1222 // Generate: if (loop-index < number-of-elements fall to the loop body,
1223 // otherwise, go to the block after the for-loop.
1224 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
1225 llvm::Value * NumElementsPtr =
1226 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1227 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1228 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
1229 "isless");
1230 // If the condition is true, execute the body.
1231 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1232
1233 EmitBlock(ForBody);
1234 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1235 // Inside the loop body, emit the constructor call on the array element.
1236 Counter = Builder.CreateLoad(IndexPtr);
1237 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1238 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1239 if (BitwiseCopy)
1240 EmitAggregateCopy(Dest, Src, Ty);
1241 else if (CXXConstructorDecl *BaseCopyCtor =
1242 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
1243 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
1244 Ctor_Complete);
1245 CallArgList CallArgs;
1246 // Push the this (Dest) ptr.
1247 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1248 BaseCopyCtor->getThisType(getContext())));
1249
1250 // Push the Src ptr.
1251 CallArgs.push_back(std::make_pair(RValue::get(Src),
1252 BaseCopyCtor->getParamDecl(0)->getType()));
1253 QualType ResultType =
1254 BaseCopyCtor->getType()->getAsFunctionType()->getResultType();
1255 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1256 Callee, CallArgs, BaseCopyCtor);
1257 }
1258 EmitBlock(ContinueBlock);
1259
1260 // Emit the increment of the loop counter.
1261 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1262 Counter = Builder.CreateLoad(IndexPtr);
1263 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1264 Builder.CreateStore(NextVal, IndexPtr, false);
1265
1266 // Finally, branch back up to the condition for the next iteration.
1267 EmitBranch(CondBlock);
1268
1269 // Emit the fall-through block.
1270 EmitBlock(AfterFor, true);
1271}
1272
Fariborz Jahanianc28bbc22009-08-21 22:34:55 +00001273/// EmitClassAggrCopyAssignment - This routine generates code to assign a class
1274/// array of objects from SrcValue to DestValue. Assignment can be either a
1275/// bitwise assignment or via a copy assignment operator function call.
1276/// FIXME. This can be consolidated with EmitClassAggrMemberwiseCopy
1277void CodeGenFunction::EmitClassAggrCopyAssignment(llvm::Value *Dest,
1278 llvm::Value *Src,
1279 const ArrayType *Array,
1280 const CXXRecordDecl *BaseClassDecl,
1281 QualType Ty) {
1282 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1283 assert(CA && "VLA cannot be asssigned");
1284 bool BitwiseAssign = BaseClassDecl->hasTrivialCopyAssignment();
1285
1286 // Create a temporary for the loop index and initialize it with 0.
1287 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1288 "loop.index");
1289 llvm::Value* zeroConstant =
1290 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
1291 Builder.CreateStore(zeroConstant, IndexPtr, false);
1292 // Start the loop with a block that tests the condition.
1293 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1294 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1295
1296 EmitBlock(CondBlock);
1297
1298 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1299 // Generate: if (loop-index < number-of-elements fall to the loop body,
1300 // otherwise, go to the block after the for-loop.
1301 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
1302 llvm::Value * NumElementsPtr =
1303 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1304 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1305 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
1306 "isless");
1307 // If the condition is true, execute the body.
1308 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1309
1310 EmitBlock(ForBody);
1311 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1312 // Inside the loop body, emit the assignment operator call on array element.
1313 Counter = Builder.CreateLoad(IndexPtr);
1314 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1315 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1316 const CXXMethodDecl *MD = 0;
1317 if (BitwiseAssign)
1318 EmitAggregateCopy(Dest, Src, Ty);
1319 else {
1320 bool hasCopyAssign = BaseClassDecl->hasConstCopyAssignment(getContext(),
1321 MD);
1322 assert(hasCopyAssign && "EmitClassAggrCopyAssignment - No user assign");
1323 (void)hasCopyAssign;
1324 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
1325 const llvm::Type *LTy =
1326 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1327 FPT->isVariadic());
1328 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), LTy);
1329
1330 CallArgList CallArgs;
1331 // Push the this (Dest) ptr.
1332 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1333 MD->getThisType(getContext())));
1334
1335 // Push the Src ptr.
1336 CallArgs.push_back(std::make_pair(RValue::get(Src),
1337 MD->getParamDecl(0)->getType()));
1338 QualType ResultType =
1339 MD->getType()->getAsFunctionType()->getResultType();
1340 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1341 Callee, CallArgs, MD);
1342 }
1343 EmitBlock(ContinueBlock);
1344
1345 // Emit the increment of the loop counter.
1346 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1347 Counter = Builder.CreateLoad(IndexPtr);
1348 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1349 Builder.CreateStore(NextVal, IndexPtr, false);
1350
1351 // Finally, branch back up to the condition for the next iteration.
1352 EmitBranch(CondBlock);
1353
1354 // Emit the fall-through block.
1355 EmitBlock(AfterFor, true);
1356}
1357
Fariborz Jahanianca283612009-08-07 23:51:33 +00001358/// EmitClassMemberwiseCopy - This routine generates code to copy a class
1359/// object from SrcValue to DestValue. Copying can be either a bitwise copy
Fariborz Jahanianeb0b6d52009-08-21 18:30:26 +00001360/// or via a copy constructor call.
Fariborz Jahanianca283612009-08-07 23:51:33 +00001361void CodeGenFunction::EmitClassMemberwiseCopy(
Fariborz Jahanian942f4f32009-08-08 23:32:22 +00001362 llvm::Value *Dest, llvm::Value *Src,
Fariborz Jahanianca283612009-08-07 23:51:33 +00001363 const CXXRecordDecl *ClassDecl,
Fariborz Jahanian942f4f32009-08-08 23:32:22 +00001364 const CXXRecordDecl *BaseClassDecl, QualType Ty) {
1365 if (ClassDecl) {
1366 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
1367 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
1368 }
1369 if (BaseClassDecl->hasTrivialCopyConstructor()) {
1370 EmitAggregateCopy(Dest, Src, Ty);
Fariborz Jahanianca283612009-08-07 23:51:33 +00001371 return;
Fariborz Jahanian942f4f32009-08-08 23:32:22 +00001372 }
1373
Fariborz Jahanianca283612009-08-07 23:51:33 +00001374 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian80e4b9e2009-08-08 00:59:58 +00001375 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
Fariborz Jahanianca283612009-08-07 23:51:33 +00001376 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
1377 Ctor_Complete);
Fariborz Jahanianca283612009-08-07 23:51:33 +00001378 CallArgList CallArgs;
1379 // Push the this (Dest) ptr.
1380 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1381 BaseCopyCtor->getThisType(getContext())));
1382
Fariborz Jahanianca283612009-08-07 23:51:33 +00001383 // Push the Src ptr.
1384 CallArgs.push_back(std::make_pair(RValue::get(Src),
Fariborz Jahanian370c8842009-08-10 17:20:45 +00001385 BaseCopyCtor->getParamDecl(0)->getType()));
Fariborz Jahanianca283612009-08-07 23:51:33 +00001386 QualType ResultType =
1387 BaseCopyCtor->getType()->getAsFunctionType()->getResultType();
1388 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1389 Callee, CallArgs, BaseCopyCtor);
1390 }
1391}
Fariborz Jahanian06f598a2009-08-10 18:46:38 +00001392
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001393/// EmitClassCopyAssignment - This routine generates code to copy assign a class
1394/// object from SrcValue to DestValue. Assignment can be either a bitwise
1395/// assignment of via an assignment operator call.
Fariborz Jahanianc28bbc22009-08-21 22:34:55 +00001396// FIXME. Consolidate this with EmitClassMemberwiseCopy as they share a lot.
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001397void CodeGenFunction::EmitClassCopyAssignment(
1398 llvm::Value *Dest, llvm::Value *Src,
1399 const CXXRecordDecl *ClassDecl,
1400 const CXXRecordDecl *BaseClassDecl,
1401 QualType Ty) {
1402 if (ClassDecl) {
1403 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
1404 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
1405 }
1406 if (BaseClassDecl->hasTrivialCopyAssignment()) {
1407 EmitAggregateCopy(Dest, Src, Ty);
1408 return;
1409 }
1410
1411 const CXXMethodDecl *MD = 0;
Fariborz Jahaniane82c3e22009-08-13 00:53:36 +00001412 bool ConstCopyAssignOp = BaseClassDecl->hasConstCopyAssignment(getContext(),
1413 MD);
1414 assert(ConstCopyAssignOp && "EmitClassCopyAssignment - missing copy assign");
1415 (void)ConstCopyAssignOp;
1416
1417 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
1418 const llvm::Type *LTy =
1419 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1420 FPT->isVariadic());
1421 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), LTy);
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001422
Fariborz Jahaniane82c3e22009-08-13 00:53:36 +00001423 CallArgList CallArgs;
1424 // Push the this (Dest) ptr.
1425 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1426 MD->getThisType(getContext())));
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001427
Fariborz Jahaniane82c3e22009-08-13 00:53:36 +00001428 // Push the Src ptr.
1429 CallArgs.push_back(std::make_pair(RValue::get(Src),
1430 MD->getParamDecl(0)->getType()));
1431 QualType ResultType =
1432 MD->getType()->getAsFunctionType()->getResultType();
1433 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1434 Callee, CallArgs, MD);
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001435}
1436
Fariborz Jahanian06f598a2009-08-10 18:46:38 +00001437/// SynthesizeDefaultConstructor - synthesize a default constructor
1438void
1439CodeGenFunction::SynthesizeDefaultConstructor(const CXXConstructorDecl *CD,
1440 const FunctionDecl *FD,
1441 llvm::Function *Fn,
1442 const FunctionArgList &Args) {
1443 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1444 EmitCtorPrologue(CD);
1445 FinishFunction();
1446}
1447
Fariborz Jahanian8c241a22009-08-08 19:31:03 +00001448/// SynthesizeCXXCopyConstructor - This routine implicitly defines body of a copy
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001449/// constructor, in accordance with section 12.8 (p7 and p8) of C++03
1450/// The implicitly-defined copy constructor for class X performs a memberwise
1451/// copy of its subobjects. The order of copying is the same as the order
1452/// of initialization of bases and members in a user-defined constructor
1453/// Each subobject is copied in the manner appropriate to its type:
1454/// if the subobject is of class type, the copy constructor for the class is
1455/// used;
1456/// if the subobject is an array, each element is copied, in the manner
1457/// appropriate to the element type;
1458/// if the subobject is of scalar type, the built-in assignment operator is
1459/// used.
1460/// Virtual base class subobjects shall be copied only once by the
1461/// implicitly-defined copy constructor
1462
Fariborz Jahanian8c241a22009-08-08 19:31:03 +00001463void CodeGenFunction::SynthesizeCXXCopyConstructor(const CXXConstructorDecl *CD,
1464 const FunctionDecl *FD,
1465 llvm::Function *Fn,
Fariborz Jahanianca283612009-08-07 23:51:33 +00001466 const FunctionArgList &Args) {
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001467 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1468 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
Fariborz Jahanian8c241a22009-08-08 19:31:03 +00001469 "SynthesizeCXXCopyConstructor - copy constructor has definition already");
1470 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001471
Fariborz Jahanian1e4edd52009-08-08 00:15:41 +00001472 FunctionArgList::const_iterator i = Args.begin();
1473 const VarDecl *ThisArg = i->first;
1474 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1475 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1476 const VarDecl *SrcArg = (i+1)->first;
1477 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1478 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1479
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001480 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1481 Base != ClassDecl->bases_end(); ++Base) {
1482 // FIXME. copy constrution of virtual base NYI
1483 if (Base->isVirtual())
1484 continue;
Fariborz Jahanianca283612009-08-07 23:51:33 +00001485
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001486 CXXRecordDecl *BaseClassDecl
1487 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian942f4f32009-08-08 23:32:22 +00001488 EmitClassMemberwiseCopy(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1489 Base->getType());
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001490 }
1491
Fariborz Jahanian1e4edd52009-08-08 00:15:41 +00001492 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1493 FieldEnd = ClassDecl->field_end();
1494 Field != FieldEnd; ++Field) {
1495 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanianeb0b6d52009-08-21 18:30:26 +00001496 const ConstantArrayType *Array =
1497 getContext().getAsConstantArrayType(FieldType);
1498 if (Array)
1499 FieldType = getContext().getBaseElementType(FieldType);
1500
Fariborz Jahanian1e4edd52009-08-08 00:15:41 +00001501 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1502 CXXRecordDecl *FieldClassDecl
1503 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1504 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1505 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Fariborz Jahanianeb0b6d52009-08-21 18:30:26 +00001506 if (Array) {
1507 const llvm::Type *BasePtr = ConvertType(FieldType);
1508 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1509 llvm::Value *DestBaseAddrPtr =
1510 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1511 llvm::Value *SrcBaseAddrPtr =
1512 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1513 EmitClassAggrMemberwiseCopy(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1514 FieldClassDecl, FieldType);
1515 }
1516 else
1517 EmitClassMemberwiseCopy(LHS.getAddress(), RHS.getAddress(),
1518 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanian1e4edd52009-08-08 00:15:41 +00001519 continue;
1520 }
Fariborz Jahanianf05fe652009-08-10 18:34:26 +00001521 // Do a built-in assignment of scalar data members.
1522 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1523 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1524 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1525 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanian1e4edd52009-08-08 00:15:41 +00001526 }
Fariborz Jahanian8c241a22009-08-08 19:31:03 +00001527 FinishFunction();
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001528}
1529
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001530/// SynthesizeCXXCopyAssignment - Implicitly define copy assignment operator.
1531/// Before the implicitly-declared copy assignment operator for a class is
1532/// implicitly defined, all implicitly- declared copy assignment operators for
1533/// its direct base classes and its nonstatic data members shall have been
1534/// implicitly defined. [12.8-p12]
1535/// The implicitly-defined copy assignment operator for class X performs
1536/// memberwise assignment of its subob- jects. The direct base classes of X are
1537/// assigned first, in the order of their declaration in
1538/// the base-specifier-list, and then the immediate nonstatic data members of X
1539/// are assigned, in the order in which they were declared in the class
1540/// definition.Each subobject is assigned in the manner appropriate to its type:
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001541/// if the subobject is of class type, the copy assignment operator for the
1542/// class is used (as if by explicit qualification; that is, ignoring any
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001543/// possible virtual overriding functions in more derived classes);
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001544///
1545/// if the subobject is an array, each element is assigned, in the manner
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001546/// appropriate to the element type;
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001547///
1548/// if the subobject is of scalar type, the built-in assignment operator is
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001549/// used.
1550void CodeGenFunction::SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD,
1551 const FunctionDecl *FD,
1552 llvm::Function *Fn,
1553 const FunctionArgList &Args) {
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001554
1555 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1556 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
1557 "SynthesizeCXXCopyAssignment - copy assignment has user declaration");
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001558 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1559
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001560 FunctionArgList::const_iterator i = Args.begin();
1561 const VarDecl *ThisArg = i->first;
1562 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1563 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1564 const VarDecl *SrcArg = (i+1)->first;
1565 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1566 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1567
1568 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1569 Base != ClassDecl->bases_end(); ++Base) {
1570 // FIXME. copy assignment of virtual base NYI
1571 if (Base->isVirtual())
1572 continue;
1573
1574 CXXRecordDecl *BaseClassDecl
1575 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1576 EmitClassCopyAssignment(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1577 Base->getType());
1578 }
1579
1580 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1581 FieldEnd = ClassDecl->field_end();
1582 Field != FieldEnd; ++Field) {
1583 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanianc28bbc22009-08-21 22:34:55 +00001584 const ConstantArrayType *Array =
1585 getContext().getAsConstantArrayType(FieldType);
1586 if (Array)
1587 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001588
1589 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1590 CXXRecordDecl *FieldClassDecl
1591 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1592 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1593 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Fariborz Jahanianc28bbc22009-08-21 22:34:55 +00001594 if (Array) {
1595 const llvm::Type *BasePtr = ConvertType(FieldType);
1596 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1597 llvm::Value *DestBaseAddrPtr =
1598 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1599 llvm::Value *SrcBaseAddrPtr =
1600 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1601 EmitClassAggrCopyAssignment(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1602 FieldClassDecl, FieldType);
1603 }
1604 else
1605 EmitClassCopyAssignment(LHS.getAddress(), RHS.getAddress(),
1606 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001607 continue;
1608 }
1609 // Do a built-in assignment of scalar data members.
1610 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1611 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1612 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1613 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanian183d7182009-08-14 00:01:54 +00001614 }
1615
1616 // return *this;
1617 Builder.CreateStore(LoadOfThis, ReturnValue);
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001618
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001619 FinishFunction();
1620}
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001621
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001622/// EmitCtorPrologue - This routine generates necessary code to initialize
1623/// base classes and non-static data members belonging to this constructor.
1624void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD) {
Fariborz Jahanian742cd1b2009-07-25 21:12:28 +00001625 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
Mike Stumpeb19fa92009-08-06 13:41:24 +00001626 // FIXME: Add vbase initialization
Mike Stumpf1216772009-07-31 18:25:34 +00001627 llvm::Value *LoadOfThis = 0;
Fariborz Jahanian6d0bdaa2009-07-28 18:09:28 +00001628
Fariborz Jahanian742cd1b2009-07-25 21:12:28 +00001629 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001630 E = CD->init_end();
1631 B != E; ++B) {
1632 CXXBaseOrMemberInitializer *Member = (*B);
1633 if (Member->isBaseInitializer()) {
Mike Stumpf1216772009-07-31 18:25:34 +00001634 LoadOfThis = LoadCXXThis();
Fariborz Jahanian6d0bdaa2009-07-28 18:09:28 +00001635 Type *BaseType = Member->getBaseClass();
1636 CXXRecordDecl *BaseClassDecl =
Ted Kremenek6217b802009-07-29 21:53:49 +00001637 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
Fariborz Jahanian6d0bdaa2009-07-28 18:09:28 +00001638 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1639 BaseClassDecl);
Fariborz Jahanian742cd1b2009-07-25 21:12:28 +00001640 EmitCXXConstructorCall(Member->getConstructor(),
1641 Ctor_Complete, V,
1642 Member->const_arg_begin(),
1643 Member->const_arg_end());
Mike Stumpb3589f42009-07-30 22:28:39 +00001644 } else {
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001645 // non-static data member initilaizers.
1646 FieldDecl *Field = Member->getMember();
1647 QualType FieldType = getContext().getCanonicalType((Field)->getType());
Fariborz Jahanian64a54ad2009-08-21 17:09:38 +00001648 const ConstantArrayType *Array =
Fariborz Jahanianeb0b6d52009-08-21 18:30:26 +00001649 getContext().getAsConstantArrayType(FieldType);
Fariborz Jahanian64a54ad2009-08-21 17:09:38 +00001650 if (Array)
1651 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian8c64e002009-08-10 23:56:17 +00001652
Mike Stumpf1216772009-07-31 18:25:34 +00001653 LoadOfThis = LoadCXXThis();
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001654 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
Ted Kremenek6217b802009-07-29 21:53:49 +00001655 if (FieldType->getAs<RecordType>()) {
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001656 if (!Field->isAnonymousStructOrUnion()) {
Fariborz Jahanian50b8eea2009-07-24 17:57:02 +00001657 assert(Member->getConstructor() &&
1658 "EmitCtorPrologue - no constructor to initialize member");
Fariborz Jahanian64a54ad2009-08-21 17:09:38 +00001659 if (Array) {
1660 const llvm::Type *BasePtr = ConvertType(FieldType);
1661 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1662 llvm::Value *BaseAddrPtr =
1663 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1664 EmitCXXAggrConstructorCall(Member->getConstructor(),
1665 Array, BaseAddrPtr);
1666 }
1667 else
1668 EmitCXXConstructorCall(Member->getConstructor(),
1669 Ctor_Complete, LHS.getAddress(),
1670 Member->const_arg_begin(),
1671 Member->const_arg_end());
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001672 continue;
1673 }
1674 else {
1675 // Initializing an anonymous union data member.
1676 FieldDecl *anonMember = Member->getAnonUnionMember();
1677 LHS = EmitLValueForField(LHS.getAddress(), anonMember, false, 0);
1678 FieldType = anonMember->getType();
1679 }
Fariborz Jahanian50b8eea2009-07-24 17:57:02 +00001680 }
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001681
1682 assert(Member->getNumArgs() == 1 && "Initializer count must be 1 only");
Fariborz Jahanian50b8eea2009-07-24 17:57:02 +00001683 Expr *RhsExpr = *Member->arg_begin();
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001684 llvm::Value *RHS = EmitScalarExpr(RhsExpr, true);
Fariborz Jahanian8c64e002009-08-10 23:56:17 +00001685 EmitStoreThroughLValue(RValue::get(RHS), LHS, FieldType);
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001686 }
1687 }
Mike Stumpf1216772009-07-31 18:25:34 +00001688
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001689 if (!CD->getNumBaseOrMemberInitializers() && !CD->isTrivial()) {
Fariborz Jahanian1d9b5ef2009-08-15 18:55:17 +00001690 // Nontrivial default constructor with no initializer list. It may still
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001691 // have bases classes and/or contain non-static data members which require
1692 // construction.
1693 for (CXXRecordDecl::base_class_const_iterator Base =
1694 ClassDecl->bases_begin();
1695 Base != ClassDecl->bases_end(); ++Base) {
1696 // FIXME. copy assignment of virtual base NYI
1697 if (Base->isVirtual())
1698 continue;
1699
1700 CXXRecordDecl *BaseClassDecl
1701 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1702 if (BaseClassDecl->hasTrivialConstructor())
1703 continue;
1704 if (CXXConstructorDecl *BaseCX =
1705 BaseClassDecl->getDefaultConstructor(getContext())) {
1706 LoadOfThis = LoadCXXThis();
1707 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1708 BaseClassDecl);
1709 EmitCXXConstructorCall(BaseCX, Ctor_Complete, V, 0, 0);
1710 }
1711 }
1712
Fariborz Jahanian1d9b5ef2009-08-15 18:55:17 +00001713 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1714 FieldEnd = ClassDecl->field_end();
1715 Field != FieldEnd; ++Field) {
1716 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +00001717 const ConstantArrayType *Array =
1718 getContext().getAsConstantArrayType(FieldType);
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +00001719 if (Array)
1720 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian1d9b5ef2009-08-15 18:55:17 +00001721 if (!FieldType->getAs<RecordType>() || Field->isAnonymousStructOrUnion())
1722 continue;
1723 const RecordType *ClassRec = FieldType->getAs<RecordType>();
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001724 CXXRecordDecl *MemberClassDecl =
1725 dyn_cast<CXXRecordDecl>(ClassRec->getDecl());
1726 if (!MemberClassDecl || MemberClassDecl->hasTrivialConstructor())
1727 continue;
1728 if (CXXConstructorDecl *MamberCX =
1729 MemberClassDecl->getDefaultConstructor(getContext())) {
1730 LoadOfThis = LoadCXXThis();
1731 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +00001732 if (Array) {
1733 const llvm::Type *BasePtr = ConvertType(FieldType);
1734 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1735 llvm::Value *BaseAddrPtr =
1736 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1737 EmitCXXAggrConstructorCall(MamberCX, Array, BaseAddrPtr);
1738 }
1739 else
1740 EmitCXXConstructorCall(MamberCX, Ctor_Complete, LHS.getAddress(),
1741 0, 0);
Fariborz Jahanian1d9b5ef2009-08-15 18:55:17 +00001742 }
1743 }
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001744 }
1745
Mike Stumpf1216772009-07-31 18:25:34 +00001746 // Initialize the vtable pointer
Mike Stumpb502d832009-08-05 22:59:44 +00001747 if (ClassDecl->isDynamicClass()) {
Mike Stumpf1216772009-07-31 18:25:34 +00001748 if (!LoadOfThis)
1749 LoadOfThis = LoadCXXThis();
1750 llvm::Value *VtableField;
1751 llvm::Type *Ptr8Ty, *PtrPtr8Ty;
Owen Anderson0032b272009-08-13 21:57:51 +00001752 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Mike Stumpf1216772009-07-31 18:25:34 +00001753 PtrPtr8Ty = llvm::PointerType::get(Ptr8Ty, 0);
1754 VtableField = Builder.CreateBitCast(LoadOfThis, PtrPtr8Ty);
1755 llvm::Value *vtable = GenerateVtable(ClassDecl);
1756 Builder.CreateStore(vtable, VtableField);
1757 }
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001758}
Fariborz Jahanian426cc382009-07-30 17:49:11 +00001759
1760/// EmitDtorEpilogue - Emit all code that comes at the end of class's
1761/// destructor. This is to call destructors on members and base classes
1762/// in reverse order of their construction.
1763void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD) {
1764 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(DD->getDeclContext());
1765 assert(!ClassDecl->isPolymorphic() &&
1766 "FIXME. polymorphic destruction not supported");
1767 (void)ClassDecl; // prevent warning.
1768
1769 for (CXXDestructorDecl::destr_const_iterator *B = DD->destr_begin(),
1770 *E = DD->destr_end(); B != E; ++B) {
1771 uintptr_t BaseOrMember = (*B);
1772 if (DD->isMemberToDestroy(BaseOrMember)) {
1773 FieldDecl *FD = DD->getMemberToDestroy(BaseOrMember);
1774 QualType FieldType = getContext().getCanonicalType((FD)->getType());
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +00001775 const ConstantArrayType *Array =
1776 getContext().getAsConstantArrayType(FieldType);
1777 if (Array)
1778 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian426cc382009-07-30 17:49:11 +00001779 const RecordType *RT = FieldType->getAs<RecordType>();
1780 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1781 if (FieldClassDecl->hasTrivialDestructor())
1782 continue;
1783 llvm::Value *LoadOfThis = LoadCXXThis();
1784 LValue LHS = EmitLValueForField(LoadOfThis, FD, false, 0);
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +00001785 if (Array) {
1786 const llvm::Type *BasePtr = ConvertType(FieldType);
1787 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1788 llvm::Value *BaseAddrPtr =
1789 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1790 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1791 Array, BaseAddrPtr);
1792 }
1793 else
1794 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1795 Dtor_Complete, LHS.getAddress());
Mike Stumpb3589f42009-07-30 22:28:39 +00001796 } else {
Fariborz Jahanian426cc382009-07-30 17:49:11 +00001797 const RecordType *RT =
1798 DD->getAnyBaseClassToDestroy(BaseOrMember)->getAs<RecordType>();
1799 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1800 if (BaseClassDecl->hasTrivialDestructor())
1801 continue;
1802 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
1803 ClassDecl,BaseClassDecl);
1804 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1805 Dtor_Complete, V);
1806 }
1807 }
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001808 if (DD->getNumBaseOrMemberDestructions() || DD->isTrivial())
1809 return;
1810 // Case of destructor synthesis with fields and base classes
1811 // which have non-trivial destructors. They must be destructed in
1812 // reverse order of their construction.
1813 llvm::SmallVector<FieldDecl *, 16> DestructedFields;
1814
1815 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1816 FieldEnd = ClassDecl->field_end();
1817 Field != FieldEnd; ++Field) {
1818 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +00001819 if (getContext().getAsConstantArrayType(FieldType))
1820 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001821 if (const RecordType *RT = FieldType->getAs<RecordType>()) {
1822 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1823 if (FieldClassDecl->hasTrivialDestructor())
1824 continue;
1825 DestructedFields.push_back(*Field);
1826 }
1827 }
1828 if (!DestructedFields.empty())
1829 for (int i = DestructedFields.size() -1; i >= 0; --i) {
1830 FieldDecl *Field = DestructedFields[i];
1831 QualType FieldType = Field->getType();
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +00001832 const ConstantArrayType *Array =
1833 getContext().getAsConstantArrayType(FieldType);
1834 if (Array)
1835 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001836 const RecordType *RT = FieldType->getAs<RecordType>();
1837 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1838 llvm::Value *LoadOfThis = LoadCXXThis();
1839 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
Fariborz Jahanianf800f6c2009-08-20 20:54:15 +00001840 if (Array) {
1841 const llvm::Type *BasePtr = ConvertType(FieldType);
1842 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1843 llvm::Value *BaseAddrPtr =
1844 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1845 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1846 Array, BaseAddrPtr);
1847 }
1848 else
1849 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1850 Dtor_Complete, LHS.getAddress());
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001851 }
1852
1853 llvm::SmallVector<CXXRecordDecl*, 4> DestructedBases;
1854 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1855 Base != ClassDecl->bases_end(); ++Base) {
1856 // FIXME. copy assignment of virtual base NYI
1857 if (Base->isVirtual())
1858 continue;
1859
1860 CXXRecordDecl *BaseClassDecl
1861 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1862 if (BaseClassDecl->hasTrivialDestructor())
1863 continue;
1864 DestructedBases.push_back(BaseClassDecl);
1865 }
1866 if (DestructedBases.empty())
1867 return;
1868 for (int i = DestructedBases.size() -1; i >= 0; --i) {
1869 CXXRecordDecl *BaseClassDecl = DestructedBases[i];
1870 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
1871 ClassDecl,BaseClassDecl);
1872 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1873 Dtor_Complete, V);
1874 }
Fariborz Jahanian426cc382009-07-30 17:49:11 +00001875}
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001876
1877void CodeGenFunction::SynthesizeDefaultDestructor(const CXXDestructorDecl *CD,
1878 const FunctionDecl *FD,
1879 llvm::Function *Fn,
1880 const FunctionArgList &Args) {
1881
1882 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1883 assert(!ClassDecl->hasUserDeclaredDestructor() &&
1884 "SynthesizeDefaultDestructor - destructor has user declaration");
1885 (void) ClassDecl;
1886
1887 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1888 EmitDtorEpilogue(CD);
1889 FinishFunction();
1890}