blob: 010d89f23f616f6ec145049508d8ca0f11af26aa [file] [log] [blame]
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +00001//===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with C++ code generation.
11//
12//===----------------------------------------------------------------------===//
13
14// We might split this into multiple files if it gets too unwieldy
15
16#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
Anders Carlsson33e65e52009-04-13 18:03:33 +000018#include "Mangle.h"
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +000019#include "clang/AST/ASTContext.h"
Fariborz Jahaniana0107de2009-07-25 21:12:28 +000020#include "clang/AST/RecordLayout.h"
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +000021#include "clang/AST/Decl.h"
Anders Carlsson7a9b2982009-04-03 22:50:24 +000022#include "clang/AST/DeclCXX.h"
Anders Carlsson4715ebb2008-08-23 19:42:54 +000023#include "clang/AST/DeclObjC.h"
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +000024#include "llvm/ADT/StringExtras.h"
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +000025using namespace clang;
26using namespace CodeGen;
27
Daniel Dunbardea59212009-02-25 19:24:29 +000028void
Anders Carlssonf2a022a2009-08-08 21:45:14 +000029CodeGenFunction::EmitCXXGlobalDtorRegistration(const CXXDestructorDecl *Dtor,
30 llvm::Constant *DeclPtr) {
31 // FIXME: This is ABI dependent and we use the Itanium ABI.
32
33 const llvm::Type *Int8PtrTy =
Owen Anderson3f5cc0a2009-08-13 21:57:51 +000034 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Anders Carlssonf2a022a2009-08-08 21:45:14 +000035
36 std::vector<const llvm::Type *> Params;
37 Params.push_back(Int8PtrTy);
38
39 // Get the destructor function type
40 const llvm::Type *DtorFnTy =
Owen Anderson3f5cc0a2009-08-13 21:57:51 +000041 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Params, false);
Anders Carlssonf2a022a2009-08-08 21:45:14 +000042 DtorFnTy = llvm::PointerType::getUnqual(DtorFnTy);
43
44 Params.clear();
45 Params.push_back(DtorFnTy);
46 Params.push_back(Int8PtrTy);
47 Params.push_back(Int8PtrTy);
48
49 // Get the __cxa_atexit function type
50 // extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
51 const llvm::FunctionType *AtExitFnTy =
52 llvm::FunctionType::get(ConvertType(getContext().IntTy), Params, false);
53
54 llvm::Constant *AtExitFn = CGM.CreateRuntimeFunction(AtExitFnTy,
55 "__cxa_atexit");
56
57 llvm::Constant *Handle = CGM.CreateRuntimeVariable(Int8PtrTy,
58 "__dso_handle");
59
60 llvm::Constant *DtorFn = CGM.GetAddrOfCXXDestructor(Dtor, Dtor_Complete);
61
62 llvm::Value *Args[3] = { llvm::ConstantExpr::getBitCast(DtorFn, DtorFnTy),
63 llvm::ConstantExpr::getBitCast(DeclPtr, Int8PtrTy),
64 llvm::ConstantExpr::getBitCast(Handle, Int8PtrTy) };
65 Builder.CreateCall(AtExitFn, &Args[0], llvm::array_endof(Args));
66}
67
68void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
69 llvm::Constant *DeclPtr) {
70 assert(D.hasGlobalStorage() &&
71 "VarDecl must have global storage!");
72
73 const Expr *Init = D.getInit();
74 QualType T = D.getType();
75
76 if (T->isReferenceType()) {
Anders Carlssonf49ffa92009-08-17 18:24:57 +000077 ErrorUnsupported(Init, "global variable that binds to a reference");
Anders Carlssonf2a022a2009-08-08 21:45:14 +000078 } else if (!hasAggregateLLVMType(T)) {
79 llvm::Value *V = EmitScalarExpr(Init);
80 EmitStoreOfScalar(V, DeclPtr, T.isVolatileQualified(), T);
81 } else if (T->isAnyComplexType()) {
82 EmitComplexExprIntoAddr(Init, DeclPtr, T.isVolatileQualified());
83 } else {
84 EmitAggExpr(Init, DeclPtr, T.isVolatileQualified());
85
86 if (const RecordType *RT = T->getAs<RecordType>()) {
87 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
88 if (!RD->hasTrivialDestructor())
89 EmitCXXGlobalDtorRegistration(RD->getDestructor(getContext()), DeclPtr);
90 }
91 }
92}
93
Anders Carlssoncde4a862009-08-08 23:24:23 +000094void
95CodeGenModule::EmitCXXGlobalInitFunc() {
96 if (CXXGlobalInits.empty())
97 return;
98
Owen Anderson3f5cc0a2009-08-13 21:57:51 +000099 const llvm::FunctionType *FTy = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
Anders Carlssoncde4a862009-08-08 23:24:23 +0000100 false);
101
102 // Create our global initialization function.
103 // FIXME: Should this be tweakable by targets?
104 llvm::Function *Fn =
105 llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
106 "__cxx_global_initialization", &TheModule);
107
108 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
Benjamin Kramer3c1fe262009-08-08 23:43:26 +0000109 &CXXGlobalInits[0],
Anders Carlssoncde4a862009-08-08 23:24:23 +0000110 CXXGlobalInits.size());
111 AddGlobalCtor(Fn);
112}
113
114void CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
115 const VarDecl **Decls,
116 unsigned NumDecls) {
117 StartFunction(0, getContext().VoidTy, Fn, FunctionArgList(),
118 SourceLocation());
119
120 for (unsigned i = 0; i != NumDecls; ++i) {
121 const VarDecl *D = Decls[i];
122
123 llvm::Constant *DeclPtr = CGM.GetAddrOfGlobalVar(D);
124 EmitCXXGlobalVarDeclInit(*D, DeclPtr);
125 }
126 FinishFunction();
127}
128
Anders Carlssonf2a022a2009-08-08 21:45:14 +0000129void
130CodeGenFunction::EmitStaticCXXBlockVarDeclInit(const VarDecl &D,
131 llvm::GlobalVariable *GV) {
Daniel Dunbardea59212009-02-25 19:24:29 +0000132 // FIXME: This should use __cxa_guard_{acquire,release}?
133
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000134 assert(!getContext().getLangOptions().ThreadsafeStatics &&
135 "thread safe statics are currently not supported!");
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000136
Anders Carlsson33e65e52009-04-13 18:03:33 +0000137 llvm::SmallString<256> GuardVName;
138 llvm::raw_svector_ostream GuardVOut(GuardVName);
139 mangleGuardVariable(&D, getContext(), GuardVOut);
140
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000141 // Create the guard variable.
142 llvm::GlobalValue *GuardV =
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000143 new llvm::GlobalVariable(CGM.getModule(), llvm::Type::getInt64Ty(VMContext), false,
Daniel Dunbardea59212009-02-25 19:24:29 +0000144 GV->getLinkage(),
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000145 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext)),
Owen Anderson94148482009-07-08 19:05:04 +0000146 GuardVName.c_str());
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000147
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000148 // Load the first byte of the guard variable.
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000149 const llvm::Type *PtrTy = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000150 llvm::Value *V = Builder.CreateLoad(Builder.CreateBitCast(GuardV, PtrTy),
151 "tmp");
152
153 // Compare it against 0.
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000154 llvm::Value *nullValue = llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext));
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000155 llvm::Value *ICmp = Builder.CreateICmpEQ(V, nullValue , "tobool");
156
Daniel Dunbar72f96552008-11-11 02:29:29 +0000157 llvm::BasicBlock *InitBlock = createBasicBlock("init");
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +0000158 llvm::BasicBlock *EndBlock = createBasicBlock("init.end");
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000159
160 // If the guard variable is 0, jump to the initializer code.
161 Builder.CreateCondBr(ICmp, InitBlock, EndBlock);
162
163 EmitBlock(InitBlock);
164
Anders Carlssonf2a022a2009-08-08 21:45:14 +0000165 EmitCXXGlobalVarDeclInit(D, GV);
166
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000167 Builder.CreateStore(llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext), 1),
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000168 Builder.CreateBitCast(GuardV, PtrTy));
169
170 EmitBlock(EndBlock);
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000171}
172
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000173RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
174 llvm::Value *Callee,
175 llvm::Value *This,
176 CallExpr::const_arg_iterator ArgBeg,
177 CallExpr::const_arg_iterator ArgEnd) {
178 assert(MD->isInstance() &&
179 "Trying to emit a member call expr on a static method!");
180
181 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
182
183 CallArgList Args;
184
185 // Push the this ptr.
186 Args.push_back(std::make_pair(RValue::get(This),
187 MD->getThisType(getContext())));
188
189 // And the rest of the call args
190 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
191
192 QualType ResultType = MD->getType()->getAsFunctionType()->getResultType();
193 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args),
194 Callee, Args, MD);
195}
196
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000197RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE) {
198 const MemberExpr *ME = cast<MemberExpr>(CE->getCallee());
199 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000200
Anders Carlssonc5223142009-04-08 20:31:57 +0000201 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
Mike Stumpc37c8812009-07-30 21:47:44 +0000202
Mike Stump7e8c9932009-07-31 18:25:34 +0000203 if (MD->isVirtual()) {
Mike Stumpc37c8812009-07-30 21:47:44 +0000204 ErrorUnsupported(CE, "virtual dispatch");
205 }
206
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000207 const llvm::Type *Ty =
Anders Carlssonc5223142009-04-08 20:31:57 +0000208 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
209 FPT->isVariadic());
Chris Lattner80f39cc2009-05-12 21:21:08 +0000210 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty);
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000211
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000212 llvm::Value *This;
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000213
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000214 if (ME->isArrow())
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000215 This = EmitScalarExpr(ME->getBase());
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000216 else {
217 LValue BaseLV = EmitLValue(ME->getBase());
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000218 This = BaseLV.getAddress();
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000219 }
220
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000221 return EmitCXXMemberCall(MD, Callee, This,
222 CE->arg_begin(), CE->arg_end());
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000223}
Anders Carlsson49d4a572009-04-14 16:58:56 +0000224
Anders Carlsson85eca6f2009-05-27 04:18:27 +0000225RValue
226CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
227 const CXXMethodDecl *MD) {
228 assert(MD->isInstance() &&
229 "Trying to emit a member call expr on a static method!");
230
Fariborz Jahanian9da58e42009-08-13 21:09:41 +0000231 if (MD->isCopyAssignment()) {
232 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(MD->getDeclContext());
233 if (ClassDecl->hasTrivialCopyAssignment()) {
234 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
235 "EmitCXXOperatorMemberCallExpr - user declared copy assignment");
236 llvm::Value *This = EmitLValue(E->getArg(0)).getAddress();
237 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
238 QualType Ty = E->getType();
239 EmitAggregateCopy(This, Src, Ty);
240 return RValue::get(This);
241 }
242 }
Anders Carlsson85eca6f2009-05-27 04:18:27 +0000243
244 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
245 const llvm::Type *Ty =
246 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
247 FPT->isVariadic());
248 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty);
249
250 llvm::Value *This = EmitLValue(E->getArg(0)).getAddress();
251
252 return EmitCXXMemberCall(MD, Callee, This,
253 E->arg_begin() + 1, E->arg_end());
254}
255
Anders Carlsson49d4a572009-04-14 16:58:56 +0000256llvm::Value *CodeGenFunction::LoadCXXThis() {
257 assert(isa<CXXMethodDecl>(CurFuncDecl) &&
258 "Must be in a C++ member function decl to load 'this'");
259 assert(cast<CXXMethodDecl>(CurFuncDecl)->isInstance() &&
260 "Must be in a C++ member function decl to load 'this'");
261
262 // FIXME: What if we're inside a block?
Mike Stumpba2cb0e2009-05-16 07:57:57 +0000263 // ans: See how CodeGenFunction::LoadObjCSelf() uses
264 // CodeGenFunction::BlockForwardSelf() for how to do this.
Anders Carlsson49d4a572009-04-14 16:58:56 +0000265 return Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
266}
Anders Carlsson652951a2009-04-15 15:55:24 +0000267
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000268static bool
269GetNestedPaths(llvm::SmallVectorImpl<const CXXRecordDecl *> &NestedBasePaths,
270 const CXXRecordDecl *ClassDecl,
271 const CXXRecordDecl *BaseClassDecl) {
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000272 for (CXXRecordDecl::base_class_const_iterator i = ClassDecl->bases_begin(),
273 e = ClassDecl->bases_end(); i != e; ++i) {
274 if (i->isVirtual())
275 continue;
276 const CXXRecordDecl *Base =
Mike Stumpf3371782009-08-04 21:58:42 +0000277 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000278 if (Base == BaseClassDecl) {
279 NestedBasePaths.push_back(BaseClassDecl);
280 return true;
281 }
282 }
283 // BaseClassDecl not an immediate base of ClassDecl.
284 for (CXXRecordDecl::base_class_const_iterator i = ClassDecl->bases_begin(),
285 e = ClassDecl->bases_end(); i != e; ++i) {
286 if (i->isVirtual())
287 continue;
288 const CXXRecordDecl *Base =
289 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
290 if (GetNestedPaths(NestedBasePaths, Base, BaseClassDecl)) {
291 NestedBasePaths.push_back(Base);
292 return true;
293 }
294 }
295 return false;
296}
297
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000298llvm::Value *CodeGenFunction::AddressCXXOfBaseClass(llvm::Value *BaseValue,
Fariborz Jahanian70277012009-07-28 18:09:28 +0000299 const CXXRecordDecl *ClassDecl,
300 const CXXRecordDecl *BaseClassDecl) {
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000301 if (ClassDecl == BaseClassDecl)
302 return BaseValue;
303
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000304 llvm::Type *I8Ptr = llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000305 llvm::SmallVector<const CXXRecordDecl *, 16> NestedBasePaths;
306 GetNestedPaths(NestedBasePaths, ClassDecl, BaseClassDecl);
307 assert(NestedBasePaths.size() > 0 &&
308 "AddressCXXOfBaseClass - inheritence path failed");
309 NestedBasePaths.push_back(ClassDecl);
310 uint64_t Offset = 0;
311
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000312 // Accessing a member of the base class. Must add delata to
313 // the load of 'this'.
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000314 for (unsigned i = NestedBasePaths.size()-1; i > 0; i--) {
315 const CXXRecordDecl *DerivedClass = NestedBasePaths[i];
316 const CXXRecordDecl *BaseClass = NestedBasePaths[i-1];
317 const ASTRecordLayout &Layout =
318 getContext().getASTRecordLayout(DerivedClass);
319 Offset += Layout.getBaseClassOffset(BaseClass) / 8;
320 }
Fariborz Jahanian83a46ed2009-07-29 15:54:56 +0000321 llvm::Value *OffsetVal =
322 llvm::ConstantInt::get(
323 CGM.getTypes().ConvertType(CGM.getContext().LongTy), Offset);
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000324 BaseValue = Builder.CreateBitCast(BaseValue, I8Ptr);
325 BaseValue = Builder.CreateGEP(BaseValue, OffsetVal, "add.ptr");
326 QualType BTy =
327 getContext().getCanonicalType(
Fariborz Jahanian70277012009-07-28 18:09:28 +0000328 getContext().getTypeDeclType(const_cast<CXXRecordDecl*>(BaseClassDecl)));
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000329 const llvm::Type *BasePtr = ConvertType(BTy);
Owen Anderson7ec2d8f2009-07-29 22:16:19 +0000330 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000331 BaseValue = Builder.CreateBitCast(BaseValue, BasePtr);
332 return BaseValue;
333}
334
Anders Carlsson72f48292009-04-17 00:06:03 +0000335void
336CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
337 CXXCtorType Type,
338 llvm::Value *This,
339 CallExpr::const_arg_iterator ArgBeg,
340 CallExpr::const_arg_iterator ArgEnd) {
Fariborz Jahanian0fc5f252009-08-14 20:11:43 +0000341 if (D->isCopyConstructor(getContext())) {
342 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D->getDeclContext());
343 if (ClassDecl->hasTrivialCopyConstructor()) {
344 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
345 "EmitCXXConstructorCall - user declared copy constructor");
346 const Expr *E = (*ArgBeg);
347 QualType Ty = E->getType();
348 llvm::Value *Src = EmitLValue(E).getAddress();
349 EmitAggregateCopy(This, Src, Ty);
350 return;
351 }
352 }
353
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000354 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
355
356 EmitCXXMemberCall(D, Callee, This, ArgBeg, ArgEnd);
Anders Carlsson72f48292009-04-17 00:06:03 +0000357}
358
Anders Carlssond3f6b162009-05-29 21:03:38 +0000359void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *D,
360 CXXDtorType Type,
361 llvm::Value *This) {
362 llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(D, Type);
363
364 EmitCXXMemberCall(D, Callee, This, 0, 0);
365}
366
Anders Carlsson72f48292009-04-17 00:06:03 +0000367void
Anders Carlsson342aadc2009-05-03 17:47:16 +0000368CodeGenFunction::EmitCXXConstructExpr(llvm::Value *Dest,
369 const CXXConstructExpr *E) {
Anders Carlsson72f48292009-04-17 00:06:03 +0000370 assert(Dest && "Must have a destination!");
371
372 const CXXRecordDecl *RD =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000373 cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson72f48292009-04-17 00:06:03 +0000374 if (RD->hasTrivialConstructor())
375 return;
Fariborz Jahanian884036a2009-08-06 01:02:49 +0000376
377 // Code gen optimization to eliminate copy constructor and return
378 // its first argument instead.
Fariborz Jahanian325cdd82009-08-06 19:12:38 +0000379 if (E->isElidable()) {
Fariborz Jahanian884036a2009-08-06 01:02:49 +0000380 CXXConstructExpr::const_arg_iterator i = E->arg_begin();
Fariborz Jahanian325cdd82009-08-06 19:12:38 +0000381 EmitAggExpr((*i), Dest, false);
382 return;
Fariborz Jahanian884036a2009-08-06 01:02:49 +0000383 }
Anders Carlsson72f48292009-04-17 00:06:03 +0000384 // Call the constructor.
385 EmitCXXConstructorCall(E->getConstructor(), Ctor_Complete, Dest,
386 E->arg_begin(), E->arg_end());
387}
388
Anders Carlsson18e88bc2009-05-31 01:40:14 +0000389llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
Anders Carlssond5536972009-05-31 20:21:44 +0000390 if (E->isArray()) {
391 ErrorUnsupported(E, "new[] expression");
Owen Andersone0b5eff2009-07-30 23:11:26 +0000392 return llvm::UndefValue::get(ConvertType(E->getType()));
Anders Carlssond5536972009-05-31 20:21:44 +0000393 }
394
395 QualType AllocType = E->getAllocatedType();
396 FunctionDecl *NewFD = E->getOperatorNew();
397 const FunctionProtoType *NewFTy = NewFD->getType()->getAsFunctionProtoType();
398
399 CallArgList NewArgs;
400
401 // The allocation size is the first argument.
402 QualType SizeTy = getContext().getSizeType();
403 llvm::Value *AllocSize =
Owen Andersonb17ec712009-07-24 23:12:58 +0000404 llvm::ConstantInt::get(ConvertType(SizeTy),
Anders Carlssond5536972009-05-31 20:21:44 +0000405 getContext().getTypeSize(AllocType) / 8);
406
407 NewArgs.push_back(std::make_pair(RValue::get(AllocSize), SizeTy));
408
409 // Emit the rest of the arguments.
410 // FIXME: Ideally, this should just use EmitCallArgs.
411 CXXNewExpr::const_arg_iterator NewArg = E->placement_arg_begin();
412
413 // First, use the types from the function type.
414 // We start at 1 here because the first argument (the allocation size)
415 // has already been emitted.
416 for (unsigned i = 1, e = NewFTy->getNumArgs(); i != e; ++i, ++NewArg) {
417 QualType ArgType = NewFTy->getArgType(i);
418
419 assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
420 getTypePtr() ==
421 getContext().getCanonicalType(NewArg->getType()).getTypePtr() &&
422 "type mismatch in call argument!");
423
424 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
425 ArgType));
426
427 }
428
429 // Either we've emitted all the call args, or we have a call to a
430 // variadic function.
431 assert((NewArg == E->placement_arg_end() || NewFTy->isVariadic()) &&
432 "Extra arguments in non-variadic function!");
433
434 // If we still have any arguments, emit them using the type of the argument.
435 for (CXXNewExpr::const_arg_iterator NewArgEnd = E->placement_arg_end();
436 NewArg != NewArgEnd; ++NewArg) {
437 QualType ArgType = NewArg->getType();
438 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
439 ArgType));
440 }
441
442 // Emit the call to new.
443 RValue RV =
444 EmitCall(CGM.getTypes().getFunctionInfo(NewFTy->getResultType(), NewArgs),
445 CGM.GetAddrOfFunction(GlobalDecl(NewFD)),
446 NewArgs, NewFD);
447
Anders Carlsson11269042009-05-31 21:53:59 +0000448 // If an allocation function is declared with an empty exception specification
449 // it returns null to indicate failure to allocate storage. [expr.new]p13.
450 // (We don't need to check for null when there's no new initializer and
451 // we're allocating a POD type).
452 bool NullCheckResult = NewFTy->hasEmptyExceptionSpec() &&
453 !(AllocType->isPODType() && !E->hasInitializer());
Anders Carlssond5536972009-05-31 20:21:44 +0000454
Anders Carlssondbee9a52009-06-01 00:05:16 +0000455 llvm::BasicBlock *NewNull = 0;
456 llvm::BasicBlock *NewNotNull = 0;
457 llvm::BasicBlock *NewEnd = 0;
458
459 llvm::Value *NewPtr = RV.getScalarVal();
460
Anders Carlsson11269042009-05-31 21:53:59 +0000461 if (NullCheckResult) {
Anders Carlssondbee9a52009-06-01 00:05:16 +0000462 NewNull = createBasicBlock("new.null");
463 NewNotNull = createBasicBlock("new.notnull");
464 NewEnd = createBasicBlock("new.end");
465
466 llvm::Value *IsNull =
467 Builder.CreateICmpEQ(NewPtr,
Owen Andersonf37b84b2009-07-31 20:28:54 +0000468 llvm::Constant::getNullValue(NewPtr->getType()),
Anders Carlssondbee9a52009-06-01 00:05:16 +0000469 "isnull");
470
471 Builder.CreateCondBr(IsNull, NewNull, NewNotNull);
472 EmitBlock(NewNotNull);
Anders Carlsson11269042009-05-31 21:53:59 +0000473 }
474
Anders Carlssondbee9a52009-06-01 00:05:16 +0000475 NewPtr = Builder.CreateBitCast(NewPtr, ConvertType(E->getType()));
Anders Carlsson11269042009-05-31 21:53:59 +0000476
Anders Carlsson7c294782009-05-31 20:56:36 +0000477 if (AllocType->isPODType()) {
Anders Carlsson26910f62009-06-01 00:26:14 +0000478 if (E->getNumConstructorArgs() > 0) {
Anders Carlsson7c294782009-05-31 20:56:36 +0000479 assert(E->getNumConstructorArgs() == 1 &&
480 "Can only have one argument to initializer of POD type.");
481
482 const Expr *Init = E->getConstructorArg(0);
483
Anders Carlsson5f93ccf2009-05-31 21:07:58 +0000484 if (!hasAggregateLLVMType(AllocType))
Anders Carlsson7c294782009-05-31 20:56:36 +0000485 Builder.CreateStore(EmitScalarExpr(Init), NewPtr);
Anders Carlsson5f93ccf2009-05-31 21:07:58 +0000486 else if (AllocType->isAnyComplexType())
487 EmitComplexExprIntoAddr(Init, NewPtr, AllocType.isVolatileQualified());
Anders Carlssoneb39b432009-05-31 21:12:26 +0000488 else
489 EmitAggExpr(Init, NewPtr, AllocType.isVolatileQualified());
Anders Carlsson7c294782009-05-31 20:56:36 +0000490 }
Anders Carlsson11269042009-05-31 21:53:59 +0000491 } else {
492 // Call the constructor.
493 CXXConstructorDecl *Ctor = E->getConstructor();
Anders Carlsson7c294782009-05-31 20:56:36 +0000494
Anders Carlsson11269042009-05-31 21:53:59 +0000495 EmitCXXConstructorCall(Ctor, Ctor_Complete, NewPtr,
496 E->constructor_arg_begin(),
497 E->constructor_arg_end());
Anders Carlssond5536972009-05-31 20:21:44 +0000498 }
Anders Carlsson11269042009-05-31 21:53:59 +0000499
Anders Carlssondbee9a52009-06-01 00:05:16 +0000500 if (NullCheckResult) {
501 Builder.CreateBr(NewEnd);
502 EmitBlock(NewNull);
503 Builder.CreateBr(NewEnd);
504 EmitBlock(NewEnd);
505
506 llvm::PHINode *PHI = Builder.CreatePHI(NewPtr->getType());
507 PHI->reserveOperandSpace(2);
508 PHI->addIncoming(NewPtr, NewNotNull);
Owen Andersonf37b84b2009-07-31 20:28:54 +0000509 PHI->addIncoming(llvm::Constant::getNullValue(NewPtr->getType()), NewNull);
Anders Carlssondbee9a52009-06-01 00:05:16 +0000510
511 NewPtr = PHI;
512 }
513
Anders Carlsson11269042009-05-31 21:53:59 +0000514 return NewPtr;
Anders Carlsson18e88bc2009-05-31 01:40:14 +0000515}
516
Anders Carlsson133fdaf2009-08-16 21:13:42 +0000517void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
518 if (E->isArrayForm()) {
519 ErrorUnsupported(E, "delete[] expression");
520 return;
521 };
522
523 QualType DeleteTy =
524 E->getArgument()->getType()->getAs<PointerType>()->getPointeeType();
525
526 llvm::Value *Ptr = EmitScalarExpr(E->getArgument());
527
528 // Null check the pointer.
529 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
530 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
531
532 llvm::Value *IsNull =
533 Builder.CreateICmpEQ(Ptr, llvm::Constant::getNullValue(Ptr->getType()),
534 "isnull");
535
536 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
537 EmitBlock(DeleteNotNull);
538
539 // Call the destructor if necessary.
540 if (const RecordType *RT = DeleteTy->getAs<RecordType>()) {
541 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
542 if (!RD->hasTrivialDestructor()) {
543 const CXXDestructorDecl *Dtor = RD->getDestructor(getContext());
544 if (Dtor->isVirtual()) {
545 ErrorUnsupported(E, "delete expression with virtual destructor");
546 return;
547 }
548
549 EmitCXXDestructorCall(Dtor, Dtor_Complete, Ptr);
550 }
551 }
552 }
553
554 // Call delete.
555 FunctionDecl *DeleteFD = E->getOperatorDelete();
556 const FunctionProtoType *DeleteFTy =
557 DeleteFD->getType()->getAsFunctionProtoType();
558
559 CallArgList DeleteArgs;
560
561 QualType ArgTy = DeleteFTy->getArgType(0);
562 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
563 DeleteArgs.push_back(std::make_pair(RValue::get(DeletePtr), ArgTy));
564
565 // Emit the call to delete.
566 EmitCall(CGM.getTypes().getFunctionInfo(DeleteFTy->getResultType(),
567 DeleteArgs),
568 CGM.GetAddrOfFunction(GlobalDecl(DeleteFD)),
569 DeleteArgs, DeleteFD);
570
571 EmitBlock(DeleteEnd);
572}
573
Anders Carlsson4811c302009-04-17 01:58:57 +0000574static bool canGenerateCXXstructor(const CXXRecordDecl *RD,
575 ASTContext &Context) {
Anders Carlsson8496c692009-04-15 21:02:13 +0000576 // The class has base classes - we don't support that right now.
577 if (RD->getNumBases() > 0)
578 return false;
579
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000580 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
581 I != E; ++I) {
Anders Carlsson8496c692009-04-15 21:02:13 +0000582 // We don't support ctors for fields that aren't POD.
583 if (!I->getType()->isPODType())
584 return false;
585 }
586
587 return true;
588}
589
Anders Carlsson652951a2009-04-15 15:55:24 +0000590void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) {
Anders Carlsson4811c302009-04-17 01:58:57 +0000591 if (!canGenerateCXXstructor(D->getParent(), getContext())) {
Anders Carlsson8496c692009-04-15 21:02:13 +0000592 ErrorUnsupported(D, "C++ constructor", true);
593 return;
594 }
Anders Carlsson652951a2009-04-15 15:55:24 +0000595
Anders Carlsson1764af42009-05-05 04:44:02 +0000596 EmitGlobal(GlobalDecl(D, Ctor_Complete));
597 EmitGlobal(GlobalDecl(D, Ctor_Base));
Anders Carlsson652951a2009-04-15 15:55:24 +0000598}
Anders Carlsson890a9fd2009-04-16 23:57:24 +0000599
Anders Carlsson4811c302009-04-17 01:58:57 +0000600void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D,
601 CXXCtorType Type) {
602
603 llvm::Function *Fn = GetAddrOfCXXConstructor(D, Type);
604
605 CodeGenFunction(*this).GenerateCode(D, Fn);
606
607 SetFunctionDefinitionAttributes(D, Fn);
608 SetLLVMFunctionAttributesForDefinition(D, Fn);
609}
610
Anders Carlsson890a9fd2009-04-16 23:57:24 +0000611llvm::Function *
612CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
613 CXXCtorType Type) {
614 const llvm::FunctionType *FTy =
615 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false);
616
617 const char *Name = getMangledCXXCtorName(D, Type);
Chris Lattner80f39cc2009-05-12 21:21:08 +0000618 return cast<llvm::Function>(
619 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson890a9fd2009-04-16 23:57:24 +0000620}
Anders Carlsson4811c302009-04-17 01:58:57 +0000621
622const char *CodeGenModule::getMangledCXXCtorName(const CXXConstructorDecl *D,
623 CXXCtorType Type) {
624 llvm::SmallString<256> Name;
625 llvm::raw_svector_ostream Out(Name);
626 mangleCXXCtor(D, Type, Context, Out);
627
628 Name += '\0';
629 return UniqueMangledName(Name.begin(), Name.end());
630}
631
632void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) {
633 if (!canGenerateCXXstructor(D->getParent(), getContext())) {
634 ErrorUnsupported(D, "C++ destructor", true);
635 return;
636 }
637
638 EmitCXXDestructor(D, Dtor_Complete);
639 EmitCXXDestructor(D, Dtor_Base);
640}
641
642void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D,
643 CXXDtorType Type) {
644 llvm::Function *Fn = GetAddrOfCXXDestructor(D, Type);
645
646 CodeGenFunction(*this).GenerateCode(D, Fn);
647
648 SetFunctionDefinitionAttributes(D, Fn);
649 SetLLVMFunctionAttributesForDefinition(D, Fn);
650}
651
652llvm::Function *
653CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D,
654 CXXDtorType Type) {
655 const llvm::FunctionType *FTy =
656 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false);
657
658 const char *Name = getMangledCXXDtorName(D, Type);
Chris Lattner80f39cc2009-05-12 21:21:08 +0000659 return cast<llvm::Function>(
660 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson4811c302009-04-17 01:58:57 +0000661}
662
663const char *CodeGenModule::getMangledCXXDtorName(const CXXDestructorDecl *D,
664 CXXDtorType Type) {
665 llvm::SmallString<256> Name;
666 llvm::raw_svector_ostream Out(Name);
667 mangleCXXDtor(D, Type, Context, Out);
668
669 Name += '\0';
670 return UniqueMangledName(Name.begin(), Name.end());
671}
Fariborz Jahanian5400e022009-07-20 23:18:55 +0000672
Mike Stump00df7d32009-07-31 23:15:31 +0000673llvm::Constant *CodeGenFunction::GenerateRtti(const CXXRecordDecl *RD) {
674 llvm::Type *Ptr8Ty;
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000675 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Mike Stump69a12322009-08-04 20:06:48 +0000676 llvm::Constant *Rtti = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stump00df7d32009-07-31 23:15:31 +0000677
678 if (!getContext().getLangOptions().Rtti)
Mike Stump69a12322009-08-04 20:06:48 +0000679 return Rtti;
Mike Stump00df7d32009-07-31 23:15:31 +0000680
681 llvm::SmallString<256> OutName;
682 llvm::raw_svector_ostream Out(OutName);
683 QualType ClassTy;
Mike Stumpe7545622009-08-07 18:05:12 +0000684 ClassTy = getContext().getTagDeclType(RD);
Mike Stump00df7d32009-07-31 23:15:31 +0000685 mangleCXXRtti(ClassTy, getContext(), Out);
686 const char *Name = OutName.c_str();
687 llvm::GlobalVariable::LinkageTypes linktype;
688 linktype = llvm::GlobalValue::WeakAnyLinkage;
689 std::vector<llvm::Constant *> info;
Mike Stump2eade572009-08-13 22:53:07 +0000690 // assert(0 && "FIXME: implement rtti descriptor");
Mike Stump00df7d32009-07-31 23:15:31 +0000691 // FIXME: descriptor
692 info.push_back(llvm::Constant::getNullValue(Ptr8Ty));
Mike Stump2eade572009-08-13 22:53:07 +0000693 // assert(0 && "FIXME: implement rtti ts");
Mike Stump00df7d32009-07-31 23:15:31 +0000694 // FIXME: TS
695 info.push_back(llvm::Constant::getNullValue(Ptr8Ty));
696
697 llvm::Constant *C;
698 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, info.size());
699 C = llvm::ConstantArray::get(type, info);
Mike Stump69a12322009-08-04 20:06:48 +0000700 Rtti = new llvm::GlobalVariable(CGM.getModule(), type, true, linktype, C,
Mike Stump00df7d32009-07-31 23:15:31 +0000701 Name);
Mike Stump69a12322009-08-04 20:06:48 +0000702 Rtti = llvm::ConstantExpr::getBitCast(Rtti, Ptr8Ty);
703 return Rtti;
Mike Stump00df7d32009-07-31 23:15:31 +0000704}
705
Mike Stumpad734d12009-08-18 20:50:28 +0000706class ABIBuilder {
707 std::vector<llvm::Constant *> &methods;
708 llvm::Type *Ptr8Ty;
709 llvm::LLVMContext &VMContext;
Mike Stump1e10cf32009-08-18 21:03:28 +0000710 CodeGenModule &CGM; // Per-module state.
Mike Stumpad734d12009-08-18 20:50:28 +0000711public:
Mike Stump1e10cf32009-08-18 21:03:28 +0000712 ABIBuilder(std::vector<llvm::Constant *> &meth,
713 CodeGenModule &cgm)
714 : methods(meth), VMContext(cgm.getModule().getContext()), CGM(cgm) {
Mike Stumpad734d12009-08-18 20:50:28 +0000715 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
716 }
717 void GenerateVcalls(const CXXRecordDecl *RD) {
718 typedef CXXRecordDecl::method_iterator meth_iter;
719 llvm::Constant *m;
Mike Stump23b238e2009-08-12 23:25:18 +0000720
Mike Stumpad734d12009-08-18 20:50:28 +0000721 // FIXME: audit order
722 for (meth_iter mi = RD->method_begin(),
723 me = RD->method_end(); mi != me; ++mi) {
724 if (mi->isVirtual()) {
725 // FIXME: vcall: offset for virtual base for this function
726 m = llvm::Constant::getNullValue(Ptr8Ty);
727 methods.push_back(m);
728 }
Mike Stumpf640de52009-08-12 23:14:12 +0000729 }
Mike Stump23b238e2009-08-12 23:25:18 +0000730 }
Mike Stumpf640de52009-08-12 23:14:12 +0000731
Mike Stump1e10cf32009-08-18 21:03:28 +0000732 void GenerateMethods(const CXXRecordDecl *RD) {
733 typedef CXXRecordDecl::method_iterator meth_iter;
734 llvm::Constant *m;
Mike Stumpdecd7812009-08-12 23:00:59 +0000735
Mike Stump1e10cf32009-08-18 21:03:28 +0000736 for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
737 ++mi) {
738 if (mi->isVirtual()) {
739 m = CGM.GetAddrOfFunction(GlobalDecl(*mi));
740 m = llvm::ConstantExpr::getBitCast(m, Ptr8Ty);
741 methods.push_back(m);
742 }
Mike Stumpdecd7812009-08-12 23:00:59 +0000743 }
744 }
Mike Stump1e10cf32009-08-18 21:03:28 +0000745};
746
Mike Stumpdecd7812009-08-12 23:00:59 +0000747
Mike Stump2eade572009-08-13 22:53:07 +0000748void CodeGenFunction::GenerateVtableForVBases(const CXXRecordDecl *RD,
Mike Stumpc57b8272009-08-16 01:46:26 +0000749 const CXXRecordDecl *Class,
Mike Stump2eade572009-08-13 22:53:07 +0000750 llvm::Constant *rtti,
751 std::vector<llvm::Constant *> &methods,
752 llvm::SmallSet<const CXXRecordDecl *, 32> &IndirectPrimary) {
753 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
754 e = RD->bases_end(); i != e; ++i) {
755 const CXXRecordDecl *Base =
756 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
757 if (i->isVirtual() && !IndirectPrimary.count(Base)) {
758 // Mark it so we don't output it twice.
759 IndirectPrimary.insert(Base);
Mike Stumpc57b8272009-08-16 01:46:26 +0000760 GenerateVtableForBase(Base, true, 0, Class, rtti, methods, true,
Mike Stump2eade572009-08-13 22:53:07 +0000761 IndirectPrimary);
762 }
763 if (Base->getNumVBases())
Mike Stumpc57b8272009-08-16 01:46:26 +0000764 GenerateVtableForVBases(Base, Class, rtti, methods, IndirectPrimary);
765 }
766}
767
768void CodeGenFunction::GenerateVBaseOffsets(
769 std::vector<llvm::Constant *> &methods, const CXXRecordDecl *RD,
770 llvm::SmallSet<const CXXRecordDecl *, 32> &SeenVBase,
771 uint64_t Offset, const ASTRecordLayout &BLayout, llvm::Type *Ptr8Ty) {
772 for (CXXRecordDecl::base_class_const_iterator i =RD->bases_begin(),
773 e = RD->bases_end(); i != e; ++i) {
774 const CXXRecordDecl *Base =
775 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
776 if (i->isVirtual() && !SeenVBase.count(Base)) {
777 SeenVBase.insert(Base);
778 int64_t BaseOffset = Offset/8 + BLayout.getVBaseClassOffset(Base) / 8;
779 llvm::Constant *m;
780 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), BaseOffset);
781 m = llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
782 methods.push_back(m);
783 }
784 GenerateVBaseOffsets(methods, Base, SeenVBase, Offset, BLayout, Ptr8Ty);
Mike Stump2eade572009-08-13 22:53:07 +0000785 }
786}
787
Mike Stumpd6f22d82009-08-06 15:50:11 +0000788void CodeGenFunction::GenerateVtableForBase(const CXXRecordDecl *RD,
Mike Stumpc57b8272009-08-16 01:46:26 +0000789 bool forPrimary,
790 int64_t Offset,
Mike Stump71e21302009-08-06 21:49:36 +0000791 const CXXRecordDecl *Class,
792 llvm::Constant *rtti,
793 std::vector<llvm::Constant *> &methods,
Mike Stumpa8b58292009-08-12 17:42:21 +0000794 bool ForVirtualBase,
795 llvm::SmallSet<const CXXRecordDecl *, 32> &IndirectPrimary) {
Mike Stumpd6f22d82009-08-06 15:50:11 +0000796 llvm::Type *Ptr8Ty;
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000797 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Mike Stump71e21302009-08-06 21:49:36 +0000798 llvm::Constant *m = llvm::Constant::getNullValue(Ptr8Ty);
799
800 if (RD && !RD->isDynamicClass())
801 return;
Mike Stump96599e22009-08-06 23:48:32 +0000802
Mike Stumpc57b8272009-08-16 01:46:26 +0000803 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
804 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
805 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
Mike Stump7df1ff12009-08-11 04:03:59 +0000806
Mike Stumpc57b8272009-08-16 01:46:26 +0000807 // The virtual base offsets come first...
808 // FIXME: Audit, is this right?
809 if (forPrimary || !PrimaryBaseWasVirtual) {
810 llvm::SmallSet<const CXXRecordDecl *, 32> SeenVBase;
811 std::vector<llvm::Constant *> offsets;
812 GenerateVBaseOffsets(offsets, RD, SeenVBase, Offset, Layout, Ptr8Ty);
813 for (std::vector<llvm::Constant *>::reverse_iterator i = offsets.rbegin(),
814 e = offsets.rend(); i != e; ++i)
815 methods.push_back(*i);
Mike Stump7df1ff12009-08-11 04:03:59 +0000816 }
817
Mike Stump1e10cf32009-08-18 21:03:28 +0000818 ABIBuilder b(methods, CGM);
Mike Stumpc57b8272009-08-16 01:46:26 +0000819 if (forPrimary || ForVirtualBase) {
820 // then comes the the vcall offsets for all our functions...
Mike Stumpad734d12009-08-18 20:50:28 +0000821 b.GenerateVcalls(RD);
Mike Stump71e21302009-08-06 21:49:36 +0000822 }
Mike Stumpc57b8272009-08-16 01:46:26 +0000823
824 bool Top = true;
825
826 // vtables are composed from the chain of primaries.
827 if (PrimaryBase) {
828 if (PrimaryBaseWasVirtual)
829 IndirectPrimary.insert(PrimaryBase);
830 Top = false;
831 GenerateVtableForBase(PrimaryBase, true, Offset, Class, rtti, methods,
832 PrimaryBaseWasVirtual, IndirectPrimary);
833 }
834
Mike Stumpc57b8272009-08-16 01:46:26 +0000835 if (Top) {
836 int64_t BaseOffset;
837 if (ForVirtualBase) {
838 const ASTRecordLayout &BLayout = getContext().getASTRecordLayout(Class);
839 BaseOffset = -(BLayout.getVBaseClassOffset(RD) / 8);
840 } else
841 BaseOffset = -Offset/8;
842 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), BaseOffset);
843 m = llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
Mike Stump7df1ff12009-08-11 04:03:59 +0000844 methods.push_back(m);
845 methods.push_back(rtti);
846 }
847
Mike Stump71e21302009-08-06 21:49:36 +0000848 // And add the virtuals for the class to the primary vtable.
Mike Stump1e10cf32009-08-18 21:03:28 +0000849 b.GenerateMethods(RD);
Mike Stumpc57b8272009-08-16 01:46:26 +0000850
851 // and then the non-virtual bases.
852 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
853 e = RD->bases_end(); i != e; ++i) {
854 if (i->isVirtual())
855 continue;
856 const CXXRecordDecl *Base =
857 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
858 if (Base != PrimaryBase || PrimaryBaseWasVirtual) {
859 uint64_t o = Offset + Layout.getBaseClassOffset(Base);
860 GenerateVtableForBase(Base, true, o, Class, rtti, methods, false,
861 IndirectPrimary);
862 }
863 }
Mike Stumpd6f22d82009-08-06 15:50:11 +0000864}
865
Mike Stump7e8c9932009-07-31 18:25:34 +0000866llvm::Value *CodeGenFunction::GenerateVtable(const CXXRecordDecl *RD) {
Mike Stump7e8c9932009-07-31 18:25:34 +0000867 llvm::SmallString<256> OutName;
868 llvm::raw_svector_ostream Out(OutName);
869 QualType ClassTy;
Mike Stumpe7545622009-08-07 18:05:12 +0000870 ClassTy = getContext().getTagDeclType(RD);
Mike Stump7e8c9932009-07-31 18:25:34 +0000871 mangleCXXVtable(ClassTy, getContext(), Out);
872 const char *Name = OutName.c_str();
Mike Stumpd0672782009-07-31 21:43:43 +0000873 llvm::GlobalVariable::LinkageTypes linktype;
874 linktype = llvm::GlobalValue::WeakAnyLinkage;
875 std::vector<llvm::Constant *> methods;
Mike Stumpc57b8272009-08-16 01:46:26 +0000876 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
Mike Stump8b82eeb2009-08-05 22:37:18 +0000877 int64_t Offset = 0;
Mike Stump71e21302009-08-06 21:49:36 +0000878 llvm::Constant *rtti = GenerateRtti(RD);
879
880 Offset += LLVMPointerWidth;
881 Offset += LLVMPointerWidth;
Mike Stump8b82eeb2009-08-05 22:37:18 +0000882
Mike Stumpa8b58292009-08-12 17:42:21 +0000883 llvm::SmallSet<const CXXRecordDecl *, 32> IndirectPrimary;
Mike Stumpf3371782009-08-04 21:58:42 +0000884
Mike Stumpc57b8272009-08-16 01:46:26 +0000885 // First comes the vtables for all the non-virtual bases...
886 GenerateVtableForBase(RD, true, 0, RD, rtti, methods, false, IndirectPrimary);
Mike Stump42368bb2009-08-14 01:44:03 +0000887
Mike Stumpc57b8272009-08-16 01:46:26 +0000888 // then the vtables for all the virtual bases.
889 GenerateVtableForVBases(RD, RD, rtti, methods, IndirectPrimary);
Mike Stumpf3371782009-08-04 21:58:42 +0000890
Mike Stumpd0672782009-07-31 21:43:43 +0000891 llvm::Constant *C;
892 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, methods.size());
893 C = llvm::ConstantArray::get(type, methods);
894 llvm::Value *vtable = new llvm::GlobalVariable(CGM.getModule(), type, true,
895 linktype, C, Name);
Mike Stump7e8c9932009-07-31 18:25:34 +0000896 vtable = Builder.CreateBitCast(vtable, Ptr8Ty);
Mike Stump7e8c9932009-07-31 18:25:34 +0000897 vtable = Builder.CreateGEP(vtable,
Mike Stumpc57b8272009-08-16 01:46:26 +0000898 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
Mike Stump8b82eeb2009-08-05 22:37:18 +0000899 Offset/8));
Mike Stump7e8c9932009-07-31 18:25:34 +0000900 return vtable;
901}
902
Fariborz Jahanianfc27d292009-08-07 23:51:33 +0000903/// EmitClassMemberwiseCopy - This routine generates code to copy a class
904/// object from SrcValue to DestValue. Copying can be either a bitwise copy
905/// of via a copy constructor call.
906void CodeGenFunction::EmitClassMemberwiseCopy(
Fariborz Jahaniancefe5922009-08-08 23:32:22 +0000907 llvm::Value *Dest, llvm::Value *Src,
Fariborz Jahanianfc27d292009-08-07 23:51:33 +0000908 const CXXRecordDecl *ClassDecl,
Fariborz Jahaniancefe5922009-08-08 23:32:22 +0000909 const CXXRecordDecl *BaseClassDecl, QualType Ty) {
910 if (ClassDecl) {
911 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
912 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
913 }
914 if (BaseClassDecl->hasTrivialCopyConstructor()) {
915 EmitAggregateCopy(Dest, Src, Ty);
Fariborz Jahanianfc27d292009-08-07 23:51:33 +0000916 return;
Fariborz Jahaniancefe5922009-08-08 23:32:22 +0000917 }
918
Fariborz Jahanianfc27d292009-08-07 23:51:33 +0000919 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanianfbe08772009-08-08 00:59:58 +0000920 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
Fariborz Jahanianfc27d292009-08-07 23:51:33 +0000921 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
922 Ctor_Complete);
Fariborz Jahanianfc27d292009-08-07 23:51:33 +0000923 CallArgList CallArgs;
924 // Push the this (Dest) ptr.
925 CallArgs.push_back(std::make_pair(RValue::get(Dest),
926 BaseCopyCtor->getThisType(getContext())));
927
Fariborz Jahanianfc27d292009-08-07 23:51:33 +0000928 // Push the Src ptr.
929 CallArgs.push_back(std::make_pair(RValue::get(Src),
Fariborz Jahanian0dfaec42009-08-10 17:20:45 +0000930 BaseCopyCtor->getParamDecl(0)->getType()));
Fariborz Jahanianfc27d292009-08-07 23:51:33 +0000931 QualType ResultType =
932 BaseCopyCtor->getType()->getAsFunctionType()->getResultType();
933 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
934 Callee, CallArgs, BaseCopyCtor);
935 }
936}
Fariborz Jahaniane39fab62009-08-10 18:46:38 +0000937
Fariborz Jahanian04500242009-08-12 23:34:46 +0000938/// EmitClassCopyAssignment - This routine generates code to copy assign a class
939/// object from SrcValue to DestValue. Assignment can be either a bitwise
940/// assignment of via an assignment operator call.
941void CodeGenFunction::EmitClassCopyAssignment(
942 llvm::Value *Dest, llvm::Value *Src,
943 const CXXRecordDecl *ClassDecl,
944 const CXXRecordDecl *BaseClassDecl,
945 QualType Ty) {
946 if (ClassDecl) {
947 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
948 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
949 }
950 if (BaseClassDecl->hasTrivialCopyAssignment()) {
951 EmitAggregateCopy(Dest, Src, Ty);
952 return;
953 }
954
955 const CXXMethodDecl *MD = 0;
Fariborz Jahanian84bd6532009-08-13 00:53:36 +0000956 bool ConstCopyAssignOp = BaseClassDecl->hasConstCopyAssignment(getContext(),
957 MD);
958 assert(ConstCopyAssignOp && "EmitClassCopyAssignment - missing copy assign");
959 (void)ConstCopyAssignOp;
960
961 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
962 const llvm::Type *LTy =
963 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
964 FPT->isVariadic());
965 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), LTy);
Fariborz Jahanian04500242009-08-12 23:34:46 +0000966
Fariborz Jahanian84bd6532009-08-13 00:53:36 +0000967 CallArgList CallArgs;
968 // Push the this (Dest) ptr.
969 CallArgs.push_back(std::make_pair(RValue::get(Dest),
970 MD->getThisType(getContext())));
Fariborz Jahanian04500242009-08-12 23:34:46 +0000971
Fariborz Jahanian84bd6532009-08-13 00:53:36 +0000972 // Push the Src ptr.
973 CallArgs.push_back(std::make_pair(RValue::get(Src),
974 MD->getParamDecl(0)->getType()));
975 QualType ResultType =
976 MD->getType()->getAsFunctionType()->getResultType();
977 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
978 Callee, CallArgs, MD);
Fariborz Jahanian04500242009-08-12 23:34:46 +0000979}
980
Fariborz Jahaniane39fab62009-08-10 18:46:38 +0000981/// SynthesizeDefaultConstructor - synthesize a default constructor
982void
983CodeGenFunction::SynthesizeDefaultConstructor(const CXXConstructorDecl *CD,
984 const FunctionDecl *FD,
985 llvm::Function *Fn,
986 const FunctionArgList &Args) {
987 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
988 EmitCtorPrologue(CD);
989 FinishFunction();
990}
991
Fariborz Jahanianab840aa2009-08-08 19:31:03 +0000992/// SynthesizeCXXCopyConstructor - This routine implicitly defines body of a copy
Fariborz Jahanian5e050b82009-08-07 20:22:40 +0000993/// constructor, in accordance with section 12.8 (p7 and p8) of C++03
994/// The implicitly-defined copy constructor for class X performs a memberwise
995/// copy of its subobjects. The order of copying is the same as the order
996/// of initialization of bases and members in a user-defined constructor
997/// Each subobject is copied in the manner appropriate to its type:
998/// if the subobject is of class type, the copy constructor for the class is
999/// used;
1000/// if the subobject is an array, each element is copied, in the manner
1001/// appropriate to the element type;
1002/// if the subobject is of scalar type, the built-in assignment operator is
1003/// used.
1004/// Virtual base class subobjects shall be copied only once by the
1005/// implicitly-defined copy constructor
1006
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001007void CodeGenFunction::SynthesizeCXXCopyConstructor(const CXXConstructorDecl *CD,
1008 const FunctionDecl *FD,
1009 llvm::Function *Fn,
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001010 const FunctionArgList &Args) {
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001011 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1012 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001013 "SynthesizeCXXCopyConstructor - copy constructor has definition already");
1014 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001015
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001016 FunctionArgList::const_iterator i = Args.begin();
1017 const VarDecl *ThisArg = i->first;
1018 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1019 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1020 const VarDecl *SrcArg = (i+1)->first;
1021 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1022 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1023
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001024 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1025 Base != ClassDecl->bases_end(); ++Base) {
1026 // FIXME. copy constrution of virtual base NYI
1027 if (Base->isVirtual())
1028 continue;
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001029
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001030 CXXRecordDecl *BaseClassDecl
1031 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001032 EmitClassMemberwiseCopy(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1033 Base->getType());
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001034 }
1035
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001036 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1037 FieldEnd = ClassDecl->field_end();
1038 Field != FieldEnd; ++Field) {
1039 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
1040
1041 // FIXME. How about copying arrays!
1042 assert(!getContext().getAsArrayType(FieldType) &&
1043 "FIXME. Copying arrays NYI");
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +00001044
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001045 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1046 CXXRecordDecl *FieldClassDecl
1047 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1048 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1049 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001050
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001051 EmitClassMemberwiseCopy(LHS.getAddress(), RHS.getAddress(),
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001052 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001053 continue;
1054 }
Fariborz Jahanian08d99e92009-08-10 18:34:26 +00001055 // Do a built-in assignment of scalar data members.
1056 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1057 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1058 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1059 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001060 }
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001061 FinishFunction();
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001062}
1063
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001064/// SynthesizeCXXCopyAssignment - Implicitly define copy assignment operator.
1065/// Before the implicitly-declared copy assignment operator for a class is
1066/// implicitly defined, all implicitly- declared copy assignment operators for
1067/// its direct base classes and its nonstatic data members shall have been
1068/// implicitly defined. [12.8-p12]
1069/// The implicitly-defined copy assignment operator for class X performs
1070/// memberwise assignment of its subob- jects. The direct base classes of X are
1071/// assigned first, in the order of their declaration in
1072/// the base-specifier-list, and then the immediate nonstatic data members of X
1073/// are assigned, in the order in which they were declared in the class
1074/// definition.Each subobject is assigned in the manner appropriate to its type:
Fariborz Jahanian04500242009-08-12 23:34:46 +00001075/// if the subobject is of class type, the copy assignment operator for the
1076/// class is used (as if by explicit qualification; that is, ignoring any
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001077/// possible virtual overriding functions in more derived classes);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001078///
1079/// if the subobject is an array, each element is assigned, in the manner
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001080/// appropriate to the element type;
Fariborz Jahanian04500242009-08-12 23:34:46 +00001081///
1082/// if the subobject is of scalar type, the built-in assignment operator is
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001083/// used.
1084void CodeGenFunction::SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD,
1085 const FunctionDecl *FD,
1086 llvm::Function *Fn,
1087 const FunctionArgList &Args) {
Fariborz Jahanian04500242009-08-12 23:34:46 +00001088
1089 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1090 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
1091 "SynthesizeCXXCopyAssignment - copy assignment has user declaration");
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001092 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1093
Fariborz Jahanian04500242009-08-12 23:34:46 +00001094 FunctionArgList::const_iterator i = Args.begin();
1095 const VarDecl *ThisArg = i->first;
1096 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1097 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1098 const VarDecl *SrcArg = (i+1)->first;
1099 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1100 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1101
1102 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1103 Base != ClassDecl->bases_end(); ++Base) {
1104 // FIXME. copy assignment of virtual base NYI
1105 if (Base->isVirtual())
1106 continue;
1107
1108 CXXRecordDecl *BaseClassDecl
1109 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1110 EmitClassCopyAssignment(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1111 Base->getType());
1112 }
1113
1114 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1115 FieldEnd = ClassDecl->field_end();
1116 Field != FieldEnd; ++Field) {
1117 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
1118
1119 // FIXME. How about copy assignment of arrays!
1120 assert(!getContext().getAsArrayType(FieldType) &&
1121 "FIXME. Copy assignment of arrays NYI");
1122
1123 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1124 CXXRecordDecl *FieldClassDecl
1125 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1126 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1127 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1128
1129 EmitClassCopyAssignment(LHS.getAddress(), RHS.getAddress(),
1130 0 /*ClassDecl*/, FieldClassDecl, FieldType);
1131 continue;
1132 }
1133 // Do a built-in assignment of scalar data members.
1134 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1135 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1136 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1137 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanianc47460d2009-08-14 00:01:54 +00001138 }
1139
1140 // return *this;
1141 Builder.CreateStore(LoadOfThis, ReturnValue);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001142
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001143 FinishFunction();
1144}
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001145
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001146/// EmitCtorPrologue - This routine generates necessary code to initialize
1147/// base classes and non-static data members belonging to this constructor.
1148void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD) {
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001149 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
Mike Stump05207212009-08-06 13:41:24 +00001150 // FIXME: Add vbase initialization
Mike Stump7e8c9932009-07-31 18:25:34 +00001151 llvm::Value *LoadOfThis = 0;
Fariborz Jahanian70277012009-07-28 18:09:28 +00001152
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001153 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001154 E = CD->init_end();
1155 B != E; ++B) {
1156 CXXBaseOrMemberInitializer *Member = (*B);
1157 if (Member->isBaseInitializer()) {
Mike Stump7e8c9932009-07-31 18:25:34 +00001158 LoadOfThis = LoadCXXThis();
Fariborz Jahanian70277012009-07-28 18:09:28 +00001159 Type *BaseType = Member->getBaseClass();
1160 CXXRecordDecl *BaseClassDecl =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001161 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
Fariborz Jahanian70277012009-07-28 18:09:28 +00001162 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1163 BaseClassDecl);
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001164 EmitCXXConstructorCall(Member->getConstructor(),
1165 Ctor_Complete, V,
1166 Member->const_arg_begin(),
1167 Member->const_arg_end());
Mike Stump487ce382009-07-30 22:28:39 +00001168 } else {
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001169 // non-static data member initilaizers.
1170 FieldDecl *Field = Member->getMember();
1171 QualType FieldType = getContext().getCanonicalType((Field)->getType());
1172 assert(!getContext().getAsArrayType(FieldType)
1173 && "FIXME. Field arrays initialization unsupported");
Fariborz Jahanian32cea8b2009-08-10 23:56:17 +00001174
Mike Stump7e8c9932009-07-31 18:25:34 +00001175 LoadOfThis = LoadCXXThis();
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001176 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001177 if (FieldType->getAs<RecordType>()) {
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +00001178 if (!Field->isAnonymousStructOrUnion()) {
Fariborz Jahanian56baceb2009-07-24 17:57:02 +00001179 assert(Member->getConstructor() &&
1180 "EmitCtorPrologue - no constructor to initialize member");
1181 EmitCXXConstructorCall(Member->getConstructor(),
1182 Ctor_Complete, LHS.getAddress(),
1183 Member->const_arg_begin(),
1184 Member->const_arg_end());
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +00001185 continue;
1186 }
1187 else {
1188 // Initializing an anonymous union data member.
1189 FieldDecl *anonMember = Member->getAnonUnionMember();
1190 LHS = EmitLValueForField(LHS.getAddress(), anonMember, false, 0);
1191 FieldType = anonMember->getType();
1192 }
Fariborz Jahanian56baceb2009-07-24 17:57:02 +00001193 }
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001194
1195 assert(Member->getNumArgs() == 1 && "Initializer count must be 1 only");
Fariborz Jahanian56baceb2009-07-24 17:57:02 +00001196 Expr *RhsExpr = *Member->arg_begin();
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001197 llvm::Value *RHS = EmitScalarExpr(RhsExpr, true);
Fariborz Jahanian32cea8b2009-08-10 23:56:17 +00001198 EmitStoreThroughLValue(RValue::get(RHS), LHS, FieldType);
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001199 }
1200 }
Mike Stump7e8c9932009-07-31 18:25:34 +00001201
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001202 if (!CD->getNumBaseOrMemberInitializers() && !CD->isTrivial()) {
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001203 // Nontrivial default constructor with no initializer list. It may still
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001204 // have bases classes and/or contain non-static data members which require
1205 // construction.
1206 for (CXXRecordDecl::base_class_const_iterator Base =
1207 ClassDecl->bases_begin();
1208 Base != ClassDecl->bases_end(); ++Base) {
1209 // FIXME. copy assignment of virtual base NYI
1210 if (Base->isVirtual())
1211 continue;
1212
1213 CXXRecordDecl *BaseClassDecl
1214 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1215 if (BaseClassDecl->hasTrivialConstructor())
1216 continue;
1217 if (CXXConstructorDecl *BaseCX =
1218 BaseClassDecl->getDefaultConstructor(getContext())) {
1219 LoadOfThis = LoadCXXThis();
1220 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1221 BaseClassDecl);
1222 EmitCXXConstructorCall(BaseCX, Ctor_Complete, V, 0, 0);
1223 }
1224 }
1225
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001226 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1227 FieldEnd = ClassDecl->field_end();
1228 Field != FieldEnd; ++Field) {
1229 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
1230 if (!FieldType->getAs<RecordType>() || Field->isAnonymousStructOrUnion())
1231 continue;
1232 const RecordType *ClassRec = FieldType->getAs<RecordType>();
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001233 CXXRecordDecl *MemberClassDecl =
1234 dyn_cast<CXXRecordDecl>(ClassRec->getDecl());
1235 if (!MemberClassDecl || MemberClassDecl->hasTrivialConstructor())
1236 continue;
1237 if (CXXConstructorDecl *MamberCX =
1238 MemberClassDecl->getDefaultConstructor(getContext())) {
1239 LoadOfThis = LoadCXXThis();
1240 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1241 EmitCXXConstructorCall(MamberCX, Ctor_Complete, LHS.getAddress(), 0, 0);
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001242 }
1243 }
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001244 }
1245
Mike Stump7e8c9932009-07-31 18:25:34 +00001246 // Initialize the vtable pointer
Mike Stumpeec46a72009-08-05 22:59:44 +00001247 if (ClassDecl->isDynamicClass()) {
Mike Stump7e8c9932009-07-31 18:25:34 +00001248 if (!LoadOfThis)
1249 LoadOfThis = LoadCXXThis();
1250 llvm::Value *VtableField;
1251 llvm::Type *Ptr8Ty, *PtrPtr8Ty;
Owen Anderson3f5cc0a2009-08-13 21:57:51 +00001252 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Mike Stump7e8c9932009-07-31 18:25:34 +00001253 PtrPtr8Ty = llvm::PointerType::get(Ptr8Ty, 0);
1254 VtableField = Builder.CreateBitCast(LoadOfThis, PtrPtr8Ty);
1255 llvm::Value *vtable = GenerateVtable(ClassDecl);
1256 Builder.CreateStore(vtable, VtableField);
1257 }
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001258}
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001259
1260/// EmitDtorEpilogue - Emit all code that comes at the end of class's
1261/// destructor. This is to call destructors on members and base classes
1262/// in reverse order of their construction.
1263void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD) {
1264 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(DD->getDeclContext());
1265 assert(!ClassDecl->isPolymorphic() &&
1266 "FIXME. polymorphic destruction not supported");
1267 (void)ClassDecl; // prevent warning.
1268
1269 for (CXXDestructorDecl::destr_const_iterator *B = DD->destr_begin(),
1270 *E = DD->destr_end(); B != E; ++B) {
1271 uintptr_t BaseOrMember = (*B);
1272 if (DD->isMemberToDestroy(BaseOrMember)) {
1273 FieldDecl *FD = DD->getMemberToDestroy(BaseOrMember);
1274 QualType FieldType = getContext().getCanonicalType((FD)->getType());
1275 assert(!getContext().getAsArrayType(FieldType)
1276 && "FIXME. Field arrays destruction unsupported");
1277 const RecordType *RT = FieldType->getAs<RecordType>();
1278 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1279 if (FieldClassDecl->hasTrivialDestructor())
1280 continue;
1281 llvm::Value *LoadOfThis = LoadCXXThis();
1282 LValue LHS = EmitLValueForField(LoadOfThis, FD, false, 0);
1283 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1284 Dtor_Complete, LHS.getAddress());
Mike Stump487ce382009-07-30 22:28:39 +00001285 } else {
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001286 const RecordType *RT =
1287 DD->getAnyBaseClassToDestroy(BaseOrMember)->getAs<RecordType>();
1288 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1289 if (BaseClassDecl->hasTrivialDestructor())
1290 continue;
1291 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
1292 ClassDecl,BaseClassDecl);
1293 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1294 Dtor_Complete, V);
1295 }
1296 }
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001297 if (DD->getNumBaseOrMemberDestructions() || DD->isTrivial())
1298 return;
1299 // Case of destructor synthesis with fields and base classes
1300 // which have non-trivial destructors. They must be destructed in
1301 // reverse order of their construction.
1302 llvm::SmallVector<FieldDecl *, 16> DestructedFields;
1303
1304 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1305 FieldEnd = ClassDecl->field_end();
1306 Field != FieldEnd; ++Field) {
1307 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
1308 // FIXME. Assert on arrays for now.
1309 if (const RecordType *RT = FieldType->getAs<RecordType>()) {
1310 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1311 if (FieldClassDecl->hasTrivialDestructor())
1312 continue;
1313 DestructedFields.push_back(*Field);
1314 }
1315 }
1316 if (!DestructedFields.empty())
1317 for (int i = DestructedFields.size() -1; i >= 0; --i) {
1318 FieldDecl *Field = DestructedFields[i];
1319 QualType FieldType = Field->getType();
1320 const RecordType *RT = FieldType->getAs<RecordType>();
1321 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1322 llvm::Value *LoadOfThis = LoadCXXThis();
1323 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
1324 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1325 Dtor_Complete, LHS.getAddress());
1326 }
1327
1328 llvm::SmallVector<CXXRecordDecl*, 4> DestructedBases;
1329 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1330 Base != ClassDecl->bases_end(); ++Base) {
1331 // FIXME. copy assignment of virtual base NYI
1332 if (Base->isVirtual())
1333 continue;
1334
1335 CXXRecordDecl *BaseClassDecl
1336 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1337 if (BaseClassDecl->hasTrivialDestructor())
1338 continue;
1339 DestructedBases.push_back(BaseClassDecl);
1340 }
1341 if (DestructedBases.empty())
1342 return;
1343 for (int i = DestructedBases.size() -1; i >= 0; --i) {
1344 CXXRecordDecl *BaseClassDecl = DestructedBases[i];
1345 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
1346 ClassDecl,BaseClassDecl);
1347 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1348 Dtor_Complete, V);
1349 }
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001350}
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001351
1352void CodeGenFunction::SynthesizeDefaultDestructor(const CXXDestructorDecl *CD,
1353 const FunctionDecl *FD,
1354 llvm::Function *Fn,
1355 const FunctionArgList &Args) {
1356
1357 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1358 assert(!ClassDecl->hasUserDeclaredDestructor() &&
1359 "SynthesizeDefaultDestructor - destructor has user declaration");
1360 (void) ClassDecl;
1361
1362 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1363 EmitDtorEpilogue(CD);
1364 FinishFunction();
1365}