blob: 72aa9fc090e6aac0c42cabcf78dbaf10f6f0f555 [file] [log] [blame]
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +00001//===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with C++ code generation.
11//
12//===----------------------------------------------------------------------===//
13
14// We might split this into multiple files if it gets too unwieldy
15
16#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
Anders Carlsson33e65e52009-04-13 18:03:33 +000018#include "Mangle.h"
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +000019#include "clang/AST/ASTContext.h"
Fariborz Jahaniana0107de2009-07-25 21:12:28 +000020#include "clang/AST/RecordLayout.h"
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +000021#include "clang/AST/Decl.h"
Anders Carlsson7a9b2982009-04-03 22:50:24 +000022#include "clang/AST/DeclCXX.h"
Anders Carlsson4715ebb2008-08-23 19:42:54 +000023#include "clang/AST/DeclObjC.h"
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +000024#include "llvm/ADT/StringExtras.h"
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +000025using namespace clang;
26using namespace CodeGen;
27
Daniel Dunbardea59212009-02-25 19:24:29 +000028void
Anders Carlssonf2a022a2009-08-08 21:45:14 +000029CodeGenFunction::EmitCXXGlobalDtorRegistration(const CXXDestructorDecl *Dtor,
30 llvm::Constant *DeclPtr) {
31 // FIXME: This is ABI dependent and we use the Itanium ABI.
32
33 const llvm::Type *Int8PtrTy =
Owen Anderson3f5cc0a2009-08-13 21:57:51 +000034 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Anders Carlssonf2a022a2009-08-08 21:45:14 +000035
36 std::vector<const llvm::Type *> Params;
37 Params.push_back(Int8PtrTy);
38
39 // Get the destructor function type
40 const llvm::Type *DtorFnTy =
Owen Anderson3f5cc0a2009-08-13 21:57:51 +000041 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Params, false);
Anders Carlssonf2a022a2009-08-08 21:45:14 +000042 DtorFnTy = llvm::PointerType::getUnqual(DtorFnTy);
43
44 Params.clear();
45 Params.push_back(DtorFnTy);
46 Params.push_back(Int8PtrTy);
47 Params.push_back(Int8PtrTy);
48
49 // Get the __cxa_atexit function type
50 // extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
51 const llvm::FunctionType *AtExitFnTy =
52 llvm::FunctionType::get(ConvertType(getContext().IntTy), Params, false);
53
54 llvm::Constant *AtExitFn = CGM.CreateRuntimeFunction(AtExitFnTy,
55 "__cxa_atexit");
56
57 llvm::Constant *Handle = CGM.CreateRuntimeVariable(Int8PtrTy,
58 "__dso_handle");
59
60 llvm::Constant *DtorFn = CGM.GetAddrOfCXXDestructor(Dtor, Dtor_Complete);
61
62 llvm::Value *Args[3] = { llvm::ConstantExpr::getBitCast(DtorFn, DtorFnTy),
63 llvm::ConstantExpr::getBitCast(DeclPtr, Int8PtrTy),
64 llvm::ConstantExpr::getBitCast(Handle, Int8PtrTy) };
65 Builder.CreateCall(AtExitFn, &Args[0], llvm::array_endof(Args));
66}
67
68void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
69 llvm::Constant *DeclPtr) {
70 assert(D.hasGlobalStorage() &&
71 "VarDecl must have global storage!");
72
73 const Expr *Init = D.getInit();
74 QualType T = D.getType();
75
76 if (T->isReferenceType()) {
Anders Carlssonf49ffa92009-08-17 18:24:57 +000077 ErrorUnsupported(Init, "global variable that binds to a reference");
Anders Carlssonf2a022a2009-08-08 21:45:14 +000078 } else if (!hasAggregateLLVMType(T)) {
79 llvm::Value *V = EmitScalarExpr(Init);
80 EmitStoreOfScalar(V, DeclPtr, T.isVolatileQualified(), T);
81 } else if (T->isAnyComplexType()) {
82 EmitComplexExprIntoAddr(Init, DeclPtr, T.isVolatileQualified());
83 } else {
84 EmitAggExpr(Init, DeclPtr, T.isVolatileQualified());
85
86 if (const RecordType *RT = T->getAs<RecordType>()) {
87 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
88 if (!RD->hasTrivialDestructor())
89 EmitCXXGlobalDtorRegistration(RD->getDestructor(getContext()), DeclPtr);
90 }
91 }
92}
93
Anders Carlssoncde4a862009-08-08 23:24:23 +000094void
95CodeGenModule::EmitCXXGlobalInitFunc() {
96 if (CXXGlobalInits.empty())
97 return;
98
Owen Anderson3f5cc0a2009-08-13 21:57:51 +000099 const llvm::FunctionType *FTy = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
Anders Carlssoncde4a862009-08-08 23:24:23 +0000100 false);
101
102 // Create our global initialization function.
103 // FIXME: Should this be tweakable by targets?
104 llvm::Function *Fn =
105 llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
106 "__cxx_global_initialization", &TheModule);
107
108 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
Benjamin Kramer3c1fe262009-08-08 23:43:26 +0000109 &CXXGlobalInits[0],
Anders Carlssoncde4a862009-08-08 23:24:23 +0000110 CXXGlobalInits.size());
111 AddGlobalCtor(Fn);
112}
113
114void CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
115 const VarDecl **Decls,
116 unsigned NumDecls) {
117 StartFunction(0, getContext().VoidTy, Fn, FunctionArgList(),
118 SourceLocation());
119
120 for (unsigned i = 0; i != NumDecls; ++i) {
121 const VarDecl *D = Decls[i];
122
123 llvm::Constant *DeclPtr = CGM.GetAddrOfGlobalVar(D);
124 EmitCXXGlobalVarDeclInit(*D, DeclPtr);
125 }
126 FinishFunction();
127}
128
Anders Carlssonf2a022a2009-08-08 21:45:14 +0000129void
130CodeGenFunction::EmitStaticCXXBlockVarDeclInit(const VarDecl &D,
131 llvm::GlobalVariable *GV) {
Daniel Dunbardea59212009-02-25 19:24:29 +0000132 // FIXME: This should use __cxa_guard_{acquire,release}?
133
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000134 assert(!getContext().getLangOptions().ThreadsafeStatics &&
135 "thread safe statics are currently not supported!");
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000136
Anders Carlsson33e65e52009-04-13 18:03:33 +0000137 llvm::SmallString<256> GuardVName;
138 llvm::raw_svector_ostream GuardVOut(GuardVName);
139 mangleGuardVariable(&D, getContext(), GuardVOut);
140
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000141 // Create the guard variable.
142 llvm::GlobalValue *GuardV =
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000143 new llvm::GlobalVariable(CGM.getModule(), llvm::Type::getInt64Ty(VMContext), false,
Daniel Dunbardea59212009-02-25 19:24:29 +0000144 GV->getLinkage(),
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000145 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext)),
Daniel Dunbar0433a022009-08-19 20:04:03 +0000146 GuardVName.str());
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000147
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000148 // Load the first byte of the guard variable.
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000149 const llvm::Type *PtrTy = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000150 llvm::Value *V = Builder.CreateLoad(Builder.CreateBitCast(GuardV, PtrTy),
151 "tmp");
152
153 // Compare it against 0.
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000154 llvm::Value *nullValue = llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext));
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000155 llvm::Value *ICmp = Builder.CreateICmpEQ(V, nullValue , "tobool");
156
Daniel Dunbar72f96552008-11-11 02:29:29 +0000157 llvm::BasicBlock *InitBlock = createBasicBlock("init");
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +0000158 llvm::BasicBlock *EndBlock = createBasicBlock("init.end");
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000159
160 // If the guard variable is 0, jump to the initializer code.
161 Builder.CreateCondBr(ICmp, InitBlock, EndBlock);
162
163 EmitBlock(InitBlock);
164
Anders Carlssonf2a022a2009-08-08 21:45:14 +0000165 EmitCXXGlobalVarDeclInit(D, GV);
166
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000167 Builder.CreateStore(llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext), 1),
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000168 Builder.CreateBitCast(GuardV, PtrTy));
169
170 EmitBlock(EndBlock);
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000171}
172
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000173RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
174 llvm::Value *Callee,
175 llvm::Value *This,
176 CallExpr::const_arg_iterator ArgBeg,
177 CallExpr::const_arg_iterator ArgEnd) {
178 assert(MD->isInstance() &&
179 "Trying to emit a member call expr on a static method!");
180
181 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
182
183 CallArgList Args;
184
185 // Push the this ptr.
186 Args.push_back(std::make_pair(RValue::get(This),
187 MD->getThisType(getContext())));
188
189 // And the rest of the call args
190 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
191
192 QualType ResultType = MD->getType()->getAsFunctionType()->getResultType();
193 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args),
194 Callee, Args, MD);
195}
196
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000197RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE) {
198 const MemberExpr *ME = cast<MemberExpr>(CE->getCallee());
199 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000200
Anders Carlssonc5223142009-04-08 20:31:57 +0000201 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
Mike Stumpc37c8812009-07-30 21:47:44 +0000202
Mike Stump7e8c9932009-07-31 18:25:34 +0000203 if (MD->isVirtual()) {
Mike Stumpc37c8812009-07-30 21:47:44 +0000204 ErrorUnsupported(CE, "virtual dispatch");
205 }
206
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000207 const llvm::Type *Ty =
Anders Carlssonc5223142009-04-08 20:31:57 +0000208 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
209 FPT->isVariadic());
Chris Lattner80f39cc2009-05-12 21:21:08 +0000210 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty);
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000211
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000212 llvm::Value *This;
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000213
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000214 if (ME->isArrow())
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000215 This = EmitScalarExpr(ME->getBase());
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000216 else {
217 LValue BaseLV = EmitLValue(ME->getBase());
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000218 This = BaseLV.getAddress();
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000219 }
220
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000221 return EmitCXXMemberCall(MD, Callee, This,
222 CE->arg_begin(), CE->arg_end());
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000223}
Anders Carlsson49d4a572009-04-14 16:58:56 +0000224
Anders Carlsson85eca6f2009-05-27 04:18:27 +0000225RValue
226CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
227 const CXXMethodDecl *MD) {
228 assert(MD->isInstance() &&
229 "Trying to emit a member call expr on a static method!");
230
Fariborz Jahanian9da58e42009-08-13 21:09:41 +0000231 if (MD->isCopyAssignment()) {
232 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(MD->getDeclContext());
233 if (ClassDecl->hasTrivialCopyAssignment()) {
234 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
235 "EmitCXXOperatorMemberCallExpr - user declared copy assignment");
236 llvm::Value *This = EmitLValue(E->getArg(0)).getAddress();
237 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
238 QualType Ty = E->getType();
239 EmitAggregateCopy(This, Src, Ty);
240 return RValue::get(This);
241 }
242 }
Anders Carlsson85eca6f2009-05-27 04:18:27 +0000243
244 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
245 const llvm::Type *Ty =
246 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
247 FPT->isVariadic());
248 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty);
249
250 llvm::Value *This = EmitLValue(E->getArg(0)).getAddress();
251
252 return EmitCXXMemberCall(MD, Callee, This,
253 E->arg_begin() + 1, E->arg_end());
254}
255
Anders Carlsson49d4a572009-04-14 16:58:56 +0000256llvm::Value *CodeGenFunction::LoadCXXThis() {
257 assert(isa<CXXMethodDecl>(CurFuncDecl) &&
258 "Must be in a C++ member function decl to load 'this'");
259 assert(cast<CXXMethodDecl>(CurFuncDecl)->isInstance() &&
260 "Must be in a C++ member function decl to load 'this'");
261
262 // FIXME: What if we're inside a block?
Mike Stumpba2cb0e2009-05-16 07:57:57 +0000263 // ans: See how CodeGenFunction::LoadObjCSelf() uses
264 // CodeGenFunction::BlockForwardSelf() for how to do this.
Anders Carlsson49d4a572009-04-14 16:58:56 +0000265 return Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
266}
Anders Carlsson652951a2009-04-15 15:55:24 +0000267
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000268static bool
269GetNestedPaths(llvm::SmallVectorImpl<const CXXRecordDecl *> &NestedBasePaths,
270 const CXXRecordDecl *ClassDecl,
271 const CXXRecordDecl *BaseClassDecl) {
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000272 for (CXXRecordDecl::base_class_const_iterator i = ClassDecl->bases_begin(),
273 e = ClassDecl->bases_end(); i != e; ++i) {
274 if (i->isVirtual())
275 continue;
276 const CXXRecordDecl *Base =
Mike Stumpf3371782009-08-04 21:58:42 +0000277 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000278 if (Base == BaseClassDecl) {
279 NestedBasePaths.push_back(BaseClassDecl);
280 return true;
281 }
282 }
283 // BaseClassDecl not an immediate base of ClassDecl.
284 for (CXXRecordDecl::base_class_const_iterator i = ClassDecl->bases_begin(),
285 e = ClassDecl->bases_end(); i != e; ++i) {
286 if (i->isVirtual())
287 continue;
288 const CXXRecordDecl *Base =
289 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
290 if (GetNestedPaths(NestedBasePaths, Base, BaseClassDecl)) {
291 NestedBasePaths.push_back(Base);
292 return true;
293 }
294 }
295 return false;
296}
297
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000298llvm::Value *CodeGenFunction::AddressCXXOfBaseClass(llvm::Value *BaseValue,
Fariborz Jahanian70277012009-07-28 18:09:28 +0000299 const CXXRecordDecl *ClassDecl,
300 const CXXRecordDecl *BaseClassDecl) {
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000301 if (ClassDecl == BaseClassDecl)
302 return BaseValue;
303
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000304 llvm::Type *I8Ptr = llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000305 llvm::SmallVector<const CXXRecordDecl *, 16> NestedBasePaths;
306 GetNestedPaths(NestedBasePaths, ClassDecl, BaseClassDecl);
307 assert(NestedBasePaths.size() > 0 &&
308 "AddressCXXOfBaseClass - inheritence path failed");
309 NestedBasePaths.push_back(ClassDecl);
310 uint64_t Offset = 0;
311
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000312 // Accessing a member of the base class. Must add delata to
313 // the load of 'this'.
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000314 for (unsigned i = NestedBasePaths.size()-1; i > 0; i--) {
315 const CXXRecordDecl *DerivedClass = NestedBasePaths[i];
316 const CXXRecordDecl *BaseClass = NestedBasePaths[i-1];
317 const ASTRecordLayout &Layout =
318 getContext().getASTRecordLayout(DerivedClass);
319 Offset += Layout.getBaseClassOffset(BaseClass) / 8;
320 }
Fariborz Jahanian83a46ed2009-07-29 15:54:56 +0000321 llvm::Value *OffsetVal =
322 llvm::ConstantInt::get(
323 CGM.getTypes().ConvertType(CGM.getContext().LongTy), Offset);
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000324 BaseValue = Builder.CreateBitCast(BaseValue, I8Ptr);
325 BaseValue = Builder.CreateGEP(BaseValue, OffsetVal, "add.ptr");
326 QualType BTy =
327 getContext().getCanonicalType(
Fariborz Jahanian70277012009-07-28 18:09:28 +0000328 getContext().getTypeDeclType(const_cast<CXXRecordDecl*>(BaseClassDecl)));
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000329 const llvm::Type *BasePtr = ConvertType(BTy);
Owen Anderson7ec2d8f2009-07-29 22:16:19 +0000330 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000331 BaseValue = Builder.CreateBitCast(BaseValue, BasePtr);
332 return BaseValue;
333}
334
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000335/// EmitCXXAggrConstructorCall - This routine essentially creates a (nested)
336/// for-loop to call the default constructor on individual members of the
337/// array. 'Array' is the array type, 'This' is llvm pointer of the start
338/// of the array and 'D' is the default costructor Decl for elements of the
339/// array. It is assumed that all relevant checks have been made by the
340/// caller.
341void
342CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
343 const ArrayType *Array,
344 llvm::Value *This) {
345 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
346 assert(CA && "Do we support VLA for construction ?");
347
348 // Create a temporary for the loop index and initialize it with 0.
349 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt32Ty(VMContext),
350 "loop.index");
351 llvm::Value* zeroConstant =
352 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
353 Builder.CreateStore(zeroConstant, IndexPtr, false);
354
355 // Start the loop with a block that tests the condition.
356 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
357 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
358
359 EmitBlock(CondBlock);
360
361 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
362
363 // Generate: if (loop-index < number-of-elements fall to the loop body,
364 // otherwise, go to the block after the for-loop.
365 uint64_t NumElements = CA->getSize().getZExtValue();
366 llvm::Value * NumElementsPtr =
367 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), NumElements);
368 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
369 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
370 "isless");
371 // If the condition is true, execute the body.
372 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
373
374 EmitBlock(ForBody);
375
376 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000377 // Inside the loop body, emit the constructor call on the array element.
Fariborz Jahaniana0ab7352009-08-20 01:01:06 +0000378 Counter = Builder.CreateLoad(IndexPtr);
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000379 if (const ConstantArrayType *CAT =
380 dyn_cast<ConstantArrayType>(Array->getElementType())) {
Fariborz Jahanianf36f8d22009-08-20 00:15:15 +0000381 uint32_t delta = 1;
382 const ConstantArrayType *CAW = CAT;
383 do {
384 delta *= CAW->getSize().getZExtValue();
385 CAW = dyn_cast<ConstantArrayType>(CAW->getElementType());
386 } while (CAW);
Fariborz Jahaniana0ab7352009-08-20 01:01:06 +0000387 // Address = This + delta*Counter for current loop iteration.
Fariborz Jahanianf36f8d22009-08-20 00:15:15 +0000388 llvm::Value *DeltaPtr =
389 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), delta);
Fariborz Jahanianf36f8d22009-08-20 00:15:15 +0000390 DeltaPtr = Builder.CreateMul(Counter, DeltaPtr, "mul");
391 llvm::Value *Address =
392 Builder.CreateInBoundsGEP(This, DeltaPtr, "arrayidx");
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000393 EmitCXXAggrConstructorCall(D, CAT, Address);
394 }
Fariborz Jahanianf36f8d22009-08-20 00:15:15 +0000395 else {
Fariborz Jahanianf36f8d22009-08-20 00:15:15 +0000396 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000397 EmitCXXConstructorCall(D, Ctor_Complete, Address, 0, 0);
Fariborz Jahanianf36f8d22009-08-20 00:15:15 +0000398 }
399
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000400 EmitBlock(ContinueBlock);
401
402 // Emit the increment of the loop counter.
403 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
404 Counter = Builder.CreateLoad(IndexPtr);
405 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
406 Builder.CreateStore(NextVal, IndexPtr, false);
407
408 // Finally, branch back up to the condition for the next iteration.
409 EmitBranch(CondBlock);
410
411 // Emit the fall-through block.
412 EmitBlock(AfterFor, true);
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000413}
414
Anders Carlsson72f48292009-04-17 00:06:03 +0000415void
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +0000416CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
417 const ArrayType *Array,
418 llvm::Value *This) {
419}
420
421void
Anders Carlsson72f48292009-04-17 00:06:03 +0000422CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
423 CXXCtorType Type,
424 llvm::Value *This,
425 CallExpr::const_arg_iterator ArgBeg,
426 CallExpr::const_arg_iterator ArgEnd) {
Fariborz Jahanian0fc5f252009-08-14 20:11:43 +0000427 if (D->isCopyConstructor(getContext())) {
428 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D->getDeclContext());
429 if (ClassDecl->hasTrivialCopyConstructor()) {
430 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
431 "EmitCXXConstructorCall - user declared copy constructor");
432 const Expr *E = (*ArgBeg);
433 QualType Ty = E->getType();
434 llvm::Value *Src = EmitLValue(E).getAddress();
435 EmitAggregateCopy(This, Src, Ty);
436 return;
437 }
438 }
439
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000440 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
441
442 EmitCXXMemberCall(D, Callee, This, ArgBeg, ArgEnd);
Anders Carlsson72f48292009-04-17 00:06:03 +0000443}
444
Anders Carlssond3f6b162009-05-29 21:03:38 +0000445void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *D,
446 CXXDtorType Type,
447 llvm::Value *This) {
448 llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(D, Type);
449
450 EmitCXXMemberCall(D, Callee, This, 0, 0);
451}
452
Anders Carlsson72f48292009-04-17 00:06:03 +0000453void
Anders Carlsson342aadc2009-05-03 17:47:16 +0000454CodeGenFunction::EmitCXXConstructExpr(llvm::Value *Dest,
455 const CXXConstructExpr *E) {
Anders Carlsson72f48292009-04-17 00:06:03 +0000456 assert(Dest && "Must have a destination!");
457
458 const CXXRecordDecl *RD =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000459 cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson72f48292009-04-17 00:06:03 +0000460 if (RD->hasTrivialConstructor())
461 return;
Fariborz Jahanian884036a2009-08-06 01:02:49 +0000462
463 // Code gen optimization to eliminate copy constructor and return
464 // its first argument instead.
Fariborz Jahanian325cdd82009-08-06 19:12:38 +0000465 if (E->isElidable()) {
Fariborz Jahanian884036a2009-08-06 01:02:49 +0000466 CXXConstructExpr::const_arg_iterator i = E->arg_begin();
Fariborz Jahanian325cdd82009-08-06 19:12:38 +0000467 EmitAggExpr((*i), Dest, false);
468 return;
Fariborz Jahanian884036a2009-08-06 01:02:49 +0000469 }
Anders Carlsson72f48292009-04-17 00:06:03 +0000470 // Call the constructor.
471 EmitCXXConstructorCall(E->getConstructor(), Ctor_Complete, Dest,
472 E->arg_begin(), E->arg_end());
473}
474
Anders Carlsson18e88bc2009-05-31 01:40:14 +0000475llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
Anders Carlssond5536972009-05-31 20:21:44 +0000476 if (E->isArray()) {
477 ErrorUnsupported(E, "new[] expression");
Owen Andersone0b5eff2009-07-30 23:11:26 +0000478 return llvm::UndefValue::get(ConvertType(E->getType()));
Anders Carlssond5536972009-05-31 20:21:44 +0000479 }
480
481 QualType AllocType = E->getAllocatedType();
482 FunctionDecl *NewFD = E->getOperatorNew();
483 const FunctionProtoType *NewFTy = NewFD->getType()->getAsFunctionProtoType();
484
485 CallArgList NewArgs;
486
487 // The allocation size is the first argument.
488 QualType SizeTy = getContext().getSizeType();
489 llvm::Value *AllocSize =
Owen Andersonb17ec712009-07-24 23:12:58 +0000490 llvm::ConstantInt::get(ConvertType(SizeTy),
Anders Carlssond5536972009-05-31 20:21:44 +0000491 getContext().getTypeSize(AllocType) / 8);
492
493 NewArgs.push_back(std::make_pair(RValue::get(AllocSize), SizeTy));
494
495 // Emit the rest of the arguments.
496 // FIXME: Ideally, this should just use EmitCallArgs.
497 CXXNewExpr::const_arg_iterator NewArg = E->placement_arg_begin();
498
499 // First, use the types from the function type.
500 // We start at 1 here because the first argument (the allocation size)
501 // has already been emitted.
502 for (unsigned i = 1, e = NewFTy->getNumArgs(); i != e; ++i, ++NewArg) {
503 QualType ArgType = NewFTy->getArgType(i);
504
505 assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
506 getTypePtr() ==
507 getContext().getCanonicalType(NewArg->getType()).getTypePtr() &&
508 "type mismatch in call argument!");
509
510 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
511 ArgType));
512
513 }
514
515 // Either we've emitted all the call args, or we have a call to a
516 // variadic function.
517 assert((NewArg == E->placement_arg_end() || NewFTy->isVariadic()) &&
518 "Extra arguments in non-variadic function!");
519
520 // If we still have any arguments, emit them using the type of the argument.
521 for (CXXNewExpr::const_arg_iterator NewArgEnd = E->placement_arg_end();
522 NewArg != NewArgEnd; ++NewArg) {
523 QualType ArgType = NewArg->getType();
524 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
525 ArgType));
526 }
527
528 // Emit the call to new.
529 RValue RV =
530 EmitCall(CGM.getTypes().getFunctionInfo(NewFTy->getResultType(), NewArgs),
531 CGM.GetAddrOfFunction(GlobalDecl(NewFD)),
532 NewArgs, NewFD);
533
Anders Carlsson11269042009-05-31 21:53:59 +0000534 // If an allocation function is declared with an empty exception specification
535 // it returns null to indicate failure to allocate storage. [expr.new]p13.
536 // (We don't need to check for null when there's no new initializer and
537 // we're allocating a POD type).
538 bool NullCheckResult = NewFTy->hasEmptyExceptionSpec() &&
539 !(AllocType->isPODType() && !E->hasInitializer());
Anders Carlssond5536972009-05-31 20:21:44 +0000540
Anders Carlssondbee9a52009-06-01 00:05:16 +0000541 llvm::BasicBlock *NewNull = 0;
542 llvm::BasicBlock *NewNotNull = 0;
543 llvm::BasicBlock *NewEnd = 0;
544
545 llvm::Value *NewPtr = RV.getScalarVal();
546
Anders Carlsson11269042009-05-31 21:53:59 +0000547 if (NullCheckResult) {
Anders Carlssondbee9a52009-06-01 00:05:16 +0000548 NewNull = createBasicBlock("new.null");
549 NewNotNull = createBasicBlock("new.notnull");
550 NewEnd = createBasicBlock("new.end");
551
552 llvm::Value *IsNull =
553 Builder.CreateICmpEQ(NewPtr,
Owen Andersonf37b84b2009-07-31 20:28:54 +0000554 llvm::Constant::getNullValue(NewPtr->getType()),
Anders Carlssondbee9a52009-06-01 00:05:16 +0000555 "isnull");
556
557 Builder.CreateCondBr(IsNull, NewNull, NewNotNull);
558 EmitBlock(NewNotNull);
Anders Carlsson11269042009-05-31 21:53:59 +0000559 }
560
Anders Carlssondbee9a52009-06-01 00:05:16 +0000561 NewPtr = Builder.CreateBitCast(NewPtr, ConvertType(E->getType()));
Anders Carlsson11269042009-05-31 21:53:59 +0000562
Anders Carlsson7c294782009-05-31 20:56:36 +0000563 if (AllocType->isPODType()) {
Anders Carlsson26910f62009-06-01 00:26:14 +0000564 if (E->getNumConstructorArgs() > 0) {
Anders Carlsson7c294782009-05-31 20:56:36 +0000565 assert(E->getNumConstructorArgs() == 1 &&
566 "Can only have one argument to initializer of POD type.");
567
568 const Expr *Init = E->getConstructorArg(0);
569
Anders Carlsson5f93ccf2009-05-31 21:07:58 +0000570 if (!hasAggregateLLVMType(AllocType))
Anders Carlsson7c294782009-05-31 20:56:36 +0000571 Builder.CreateStore(EmitScalarExpr(Init), NewPtr);
Anders Carlsson5f93ccf2009-05-31 21:07:58 +0000572 else if (AllocType->isAnyComplexType())
573 EmitComplexExprIntoAddr(Init, NewPtr, AllocType.isVolatileQualified());
Anders Carlssoneb39b432009-05-31 21:12:26 +0000574 else
575 EmitAggExpr(Init, NewPtr, AllocType.isVolatileQualified());
Anders Carlsson7c294782009-05-31 20:56:36 +0000576 }
Anders Carlsson11269042009-05-31 21:53:59 +0000577 } else {
578 // Call the constructor.
579 CXXConstructorDecl *Ctor = E->getConstructor();
Anders Carlsson7c294782009-05-31 20:56:36 +0000580
Anders Carlsson11269042009-05-31 21:53:59 +0000581 EmitCXXConstructorCall(Ctor, Ctor_Complete, NewPtr,
582 E->constructor_arg_begin(),
583 E->constructor_arg_end());
Anders Carlssond5536972009-05-31 20:21:44 +0000584 }
Anders Carlsson11269042009-05-31 21:53:59 +0000585
Anders Carlssondbee9a52009-06-01 00:05:16 +0000586 if (NullCheckResult) {
587 Builder.CreateBr(NewEnd);
588 EmitBlock(NewNull);
589 Builder.CreateBr(NewEnd);
590 EmitBlock(NewEnd);
591
592 llvm::PHINode *PHI = Builder.CreatePHI(NewPtr->getType());
593 PHI->reserveOperandSpace(2);
594 PHI->addIncoming(NewPtr, NewNotNull);
Owen Andersonf37b84b2009-07-31 20:28:54 +0000595 PHI->addIncoming(llvm::Constant::getNullValue(NewPtr->getType()), NewNull);
Anders Carlssondbee9a52009-06-01 00:05:16 +0000596
597 NewPtr = PHI;
598 }
599
Anders Carlsson11269042009-05-31 21:53:59 +0000600 return NewPtr;
Anders Carlsson18e88bc2009-05-31 01:40:14 +0000601}
602
Anders Carlsson133fdaf2009-08-16 21:13:42 +0000603void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
604 if (E->isArrayForm()) {
605 ErrorUnsupported(E, "delete[] expression");
606 return;
607 };
608
609 QualType DeleteTy =
610 E->getArgument()->getType()->getAs<PointerType>()->getPointeeType();
611
612 llvm::Value *Ptr = EmitScalarExpr(E->getArgument());
613
614 // Null check the pointer.
615 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
616 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
617
618 llvm::Value *IsNull =
619 Builder.CreateICmpEQ(Ptr, llvm::Constant::getNullValue(Ptr->getType()),
620 "isnull");
621
622 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
623 EmitBlock(DeleteNotNull);
624
625 // Call the destructor if necessary.
626 if (const RecordType *RT = DeleteTy->getAs<RecordType>()) {
627 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
628 if (!RD->hasTrivialDestructor()) {
629 const CXXDestructorDecl *Dtor = RD->getDestructor(getContext());
630 if (Dtor->isVirtual()) {
631 ErrorUnsupported(E, "delete expression with virtual destructor");
632 return;
633 }
634
635 EmitCXXDestructorCall(Dtor, Dtor_Complete, Ptr);
636 }
637 }
638 }
639
640 // Call delete.
641 FunctionDecl *DeleteFD = E->getOperatorDelete();
642 const FunctionProtoType *DeleteFTy =
643 DeleteFD->getType()->getAsFunctionProtoType();
644
645 CallArgList DeleteArgs;
646
647 QualType ArgTy = DeleteFTy->getArgType(0);
648 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
649 DeleteArgs.push_back(std::make_pair(RValue::get(DeletePtr), ArgTy));
650
651 // Emit the call to delete.
652 EmitCall(CGM.getTypes().getFunctionInfo(DeleteFTy->getResultType(),
653 DeleteArgs),
654 CGM.GetAddrOfFunction(GlobalDecl(DeleteFD)),
655 DeleteArgs, DeleteFD);
656
657 EmitBlock(DeleteEnd);
658}
659
Anders Carlsson4811c302009-04-17 01:58:57 +0000660static bool canGenerateCXXstructor(const CXXRecordDecl *RD,
661 ASTContext &Context) {
Anders Carlsson8496c692009-04-15 21:02:13 +0000662 // The class has base classes - we don't support that right now.
663 if (RD->getNumBases() > 0)
664 return false;
665
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000666 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
667 I != E; ++I) {
Anders Carlsson8496c692009-04-15 21:02:13 +0000668 // We don't support ctors for fields that aren't POD.
669 if (!I->getType()->isPODType())
670 return false;
671 }
672
673 return true;
674}
675
Anders Carlsson652951a2009-04-15 15:55:24 +0000676void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) {
Anders Carlsson4811c302009-04-17 01:58:57 +0000677 if (!canGenerateCXXstructor(D->getParent(), getContext())) {
Anders Carlsson8496c692009-04-15 21:02:13 +0000678 ErrorUnsupported(D, "C++ constructor", true);
679 return;
680 }
Anders Carlsson652951a2009-04-15 15:55:24 +0000681
Anders Carlsson1764af42009-05-05 04:44:02 +0000682 EmitGlobal(GlobalDecl(D, Ctor_Complete));
683 EmitGlobal(GlobalDecl(D, Ctor_Base));
Anders Carlsson652951a2009-04-15 15:55:24 +0000684}
Anders Carlsson890a9fd2009-04-16 23:57:24 +0000685
Anders Carlsson4811c302009-04-17 01:58:57 +0000686void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D,
687 CXXCtorType Type) {
688
689 llvm::Function *Fn = GetAddrOfCXXConstructor(D, Type);
690
691 CodeGenFunction(*this).GenerateCode(D, Fn);
692
693 SetFunctionDefinitionAttributes(D, Fn);
694 SetLLVMFunctionAttributesForDefinition(D, Fn);
695}
696
Anders Carlsson890a9fd2009-04-16 23:57:24 +0000697llvm::Function *
698CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
699 CXXCtorType Type) {
700 const llvm::FunctionType *FTy =
701 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false);
702
703 const char *Name = getMangledCXXCtorName(D, Type);
Chris Lattner80f39cc2009-05-12 21:21:08 +0000704 return cast<llvm::Function>(
705 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson890a9fd2009-04-16 23:57:24 +0000706}
Anders Carlsson4811c302009-04-17 01:58:57 +0000707
708const char *CodeGenModule::getMangledCXXCtorName(const CXXConstructorDecl *D,
709 CXXCtorType Type) {
710 llvm::SmallString<256> Name;
711 llvm::raw_svector_ostream Out(Name);
712 mangleCXXCtor(D, Type, Context, Out);
713
714 Name += '\0';
715 return UniqueMangledName(Name.begin(), Name.end());
716}
717
718void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) {
719 if (!canGenerateCXXstructor(D->getParent(), getContext())) {
720 ErrorUnsupported(D, "C++ destructor", true);
721 return;
722 }
723
724 EmitCXXDestructor(D, Dtor_Complete);
725 EmitCXXDestructor(D, Dtor_Base);
726}
727
728void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D,
729 CXXDtorType Type) {
730 llvm::Function *Fn = GetAddrOfCXXDestructor(D, Type);
731
732 CodeGenFunction(*this).GenerateCode(D, Fn);
733
734 SetFunctionDefinitionAttributes(D, Fn);
735 SetLLVMFunctionAttributesForDefinition(D, Fn);
736}
737
738llvm::Function *
739CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D,
740 CXXDtorType Type) {
741 const llvm::FunctionType *FTy =
742 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false);
743
744 const char *Name = getMangledCXXDtorName(D, Type);
Chris Lattner80f39cc2009-05-12 21:21:08 +0000745 return cast<llvm::Function>(
746 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson4811c302009-04-17 01:58:57 +0000747}
748
749const char *CodeGenModule::getMangledCXXDtorName(const CXXDestructorDecl *D,
750 CXXDtorType Type) {
751 llvm::SmallString<256> Name;
752 llvm::raw_svector_ostream Out(Name);
753 mangleCXXDtor(D, Type, Context, Out);
754
755 Name += '\0';
756 return UniqueMangledName(Name.begin(), Name.end());
757}
Fariborz Jahanian5400e022009-07-20 23:18:55 +0000758
Mike Stumpdca5e512009-08-18 21:49:00 +0000759llvm::Constant *CodeGenModule::GenerateRtti(const CXXRecordDecl *RD) {
Mike Stump00df7d32009-07-31 23:15:31 +0000760 llvm::Type *Ptr8Ty;
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000761 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Mike Stump69a12322009-08-04 20:06:48 +0000762 llvm::Constant *Rtti = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stump00df7d32009-07-31 23:15:31 +0000763
764 if (!getContext().getLangOptions().Rtti)
Mike Stump69a12322009-08-04 20:06:48 +0000765 return Rtti;
Mike Stump00df7d32009-07-31 23:15:31 +0000766
767 llvm::SmallString<256> OutName;
768 llvm::raw_svector_ostream Out(OutName);
769 QualType ClassTy;
Mike Stumpe7545622009-08-07 18:05:12 +0000770 ClassTy = getContext().getTagDeclType(RD);
Mike Stump00df7d32009-07-31 23:15:31 +0000771 mangleCXXRtti(ClassTy, getContext(), Out);
Mike Stump00df7d32009-07-31 23:15:31 +0000772 llvm::GlobalVariable::LinkageTypes linktype;
773 linktype = llvm::GlobalValue::WeakAnyLinkage;
774 std::vector<llvm::Constant *> info;
Mike Stump2eade572009-08-13 22:53:07 +0000775 // assert(0 && "FIXME: implement rtti descriptor");
Mike Stump00df7d32009-07-31 23:15:31 +0000776 // FIXME: descriptor
777 info.push_back(llvm::Constant::getNullValue(Ptr8Ty));
Mike Stump2eade572009-08-13 22:53:07 +0000778 // assert(0 && "FIXME: implement rtti ts");
Mike Stump00df7d32009-07-31 23:15:31 +0000779 // FIXME: TS
780 info.push_back(llvm::Constant::getNullValue(Ptr8Ty));
781
782 llvm::Constant *C;
783 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, info.size());
784 C = llvm::ConstantArray::get(type, info);
Mike Stumpdca5e512009-08-18 21:49:00 +0000785 Rtti = new llvm::GlobalVariable(getModule(), type, true, linktype, C,
Daniel Dunbar0433a022009-08-19 20:04:03 +0000786 Out.str());
Mike Stump69a12322009-08-04 20:06:48 +0000787 Rtti = llvm::ConstantExpr::getBitCast(Rtti, Ptr8Ty);
788 return Rtti;
Mike Stump00df7d32009-07-31 23:15:31 +0000789}
790
Mike Stump86a859e2009-08-19 18:10:47 +0000791class VtableBuilder {
Mike Stumpad734d12009-08-18 20:50:28 +0000792 std::vector<llvm::Constant *> &methods;
793 llvm::Type *Ptr8Ty;
Mike Stumpdca5e512009-08-18 21:49:00 +0000794 const CXXRecordDecl *Class;
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000795 const ASTRecordLayout &BLayout;
Mike Stumpa7ec675d2009-08-19 14:40:47 +0000796 llvm::SmallSet<const CXXRecordDecl *, 32> IndirectPrimary;
Mike Stump2b9ba612009-08-20 02:11:48 +0000797 llvm::SmallSet<const CXXRecordDecl *, 32> SeenVBase;
Mike Stumpdca5e512009-08-18 21:49:00 +0000798 llvm::Constant *rtti;
Mike Stumpad734d12009-08-18 20:50:28 +0000799 llvm::LLVMContext &VMContext;
Mike Stump1e10cf32009-08-18 21:03:28 +0000800 CodeGenModule &CGM; // Per-module state.
Mike Stumpd75d3232009-08-18 22:04:08 +0000801
802 typedef CXXRecordDecl::method_iterator method_iter;
Mike Stumpad734d12009-08-18 20:50:28 +0000803public:
Mike Stump86a859e2009-08-19 18:10:47 +0000804 VtableBuilder(std::vector<llvm::Constant *> &meth,
805 const CXXRecordDecl *c,
806 CodeGenModule &cgm)
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000807 : methods(meth), Class(c), BLayout(cgm.getContext().getASTRecordLayout(c)),
808 rtti(cgm.GenerateRtti(c)), VMContext(cgm.getModule().getContext()),
809 CGM(cgm) {
Mike Stumpad734d12009-08-18 20:50:28 +0000810 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
811 }
Mike Stumpdca5e512009-08-18 21:49:00 +0000812
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000813 llvm::Constant *GenerateVcall(const CXXMethodDecl *MD,
814 const CXXRecordDecl *RD,
815 bool VBoundary,
816 bool SecondaryVirtual) {
817 llvm::Constant *m = 0;
818
819 // FIXME: vcall: offset for virtual base for this function
820 if (SecondaryVirtual || VBoundary)
821 m = llvm::Constant::getNullValue(Ptr8Ty);
822 return m;
823 }
824
825 void GenerateVcalls(const CXXRecordDecl *RD, bool VBoundary,
826 bool SecondaryVirtual) {
Mike Stumpad734d12009-08-18 20:50:28 +0000827 llvm::Constant *m;
Mike Stump23b238e2009-08-12 23:25:18 +0000828
Mike Stumpd75d3232009-08-18 22:04:08 +0000829 for (method_iter mi = RD->method_begin(),
Mike Stumpad734d12009-08-18 20:50:28 +0000830 me = RD->method_end(); mi != me; ++mi) {
831 if (mi->isVirtual()) {
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000832 m = GenerateVcall(*mi, RD, VBoundary, SecondaryVirtual);
833 if (m)
834 methods.push_back(m);
Mike Stumpad734d12009-08-18 20:50:28 +0000835 }
Mike Stumpf640de52009-08-12 23:14:12 +0000836 }
Mike Stump23b238e2009-08-12 23:25:18 +0000837 }
Mike Stumpf640de52009-08-12 23:14:12 +0000838
Mike Stump2b9ba612009-08-20 02:11:48 +0000839 void GenerateVBaseOffsets(std::vector<llvm::Constant *> &offsets,
Mike Stumpaf0d0452009-08-20 07:22:17 +0000840 const CXXRecordDecl *RD, uint64_t Offset) {
Mike Stump2b9ba612009-08-20 02:11:48 +0000841 for (CXXRecordDecl::base_class_const_iterator i =RD->bases_begin(),
842 e = RD->bases_end(); i != e; ++i) {
843 const CXXRecordDecl *Base =
844 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
845 if (i->isVirtual() && !SeenVBase.count(Base)) {
846 SeenVBase.insert(Base);
Mike Stumpaf0d0452009-08-20 07:22:17 +0000847 int64_t BaseOffset = -(Offset/8) + BLayout.getVBaseClassOffset(Base)/8;
Mike Stump2b9ba612009-08-20 02:11:48 +0000848 llvm::Constant *m;
Mike Stumpaf0d0452009-08-20 07:22:17 +0000849 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),BaseOffset);
Mike Stump2b9ba612009-08-20 02:11:48 +0000850 m = llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
851 offsets.push_back(m);
852 }
Mike Stumpaf0d0452009-08-20 07:22:17 +0000853 GenerateVBaseOffsets(offsets, Base, Offset);
Mike Stump2b9ba612009-08-20 02:11:48 +0000854 }
855 }
856
Mike Stump1e10cf32009-08-18 21:03:28 +0000857 void GenerateMethods(const CXXRecordDecl *RD) {
Mike Stump1e10cf32009-08-18 21:03:28 +0000858 llvm::Constant *m;
Mike Stumpdecd7812009-08-12 23:00:59 +0000859
Mike Stumpd75d3232009-08-18 22:04:08 +0000860 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
Mike Stump1e10cf32009-08-18 21:03:28 +0000861 ++mi) {
862 if (mi->isVirtual()) {
863 m = CGM.GetAddrOfFunction(GlobalDecl(*mi));
864 m = llvm::ConstantExpr::getBitCast(m, Ptr8Ty);
865 methods.push_back(m);
866 }
Mike Stumpdecd7812009-08-12 23:00:59 +0000867 }
868 }
Mike Stump1e10cf32009-08-18 21:03:28 +0000869
Mike Stump7bae1282009-08-18 21:30:21 +0000870 void GenerateVtableForBase(const CXXRecordDecl *RD,
871 bool forPrimary,
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000872 bool VBoundary,
Mike Stump7bae1282009-08-18 21:30:21 +0000873 int64_t Offset,
Mike Stumpa7ec675d2009-08-19 14:40:47 +0000874 bool ForVirtualBase) {
Mike Stump7bae1282009-08-18 21:30:21 +0000875 llvm::Constant *m = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stumpc57b8272009-08-16 01:46:26 +0000876
Mike Stump7bae1282009-08-18 21:30:21 +0000877 if (RD && !RD->isDynamicClass())
878 return;
879
880 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
881 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
882 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
883
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000884 if (VBoundary || forPrimary || ForVirtualBase) {
885 // then comes the the vcall offsets for all our functions...
886 GenerateVcalls(RD, VBoundary, !forPrimary && ForVirtualBase);
887 }
888
Mike Stump7bae1282009-08-18 21:30:21 +0000889 // The virtual base offsets come first...
890 // FIXME: Audit, is this right?
Mike Stump4c1c8912009-08-19 02:53:08 +0000891 if (PrimaryBase == 0 || forPrimary || !PrimaryBaseWasVirtual) {
Mike Stump7bae1282009-08-18 21:30:21 +0000892 std::vector<llvm::Constant *> offsets;
Mike Stumpaf0d0452009-08-20 07:22:17 +0000893 GenerateVBaseOffsets(offsets, RD, Offset);
Mike Stump7bae1282009-08-18 21:30:21 +0000894 for (std::vector<llvm::Constant *>::reverse_iterator i = offsets.rbegin(),
895 e = offsets.rend(); i != e; ++i)
896 methods.push_back(*i);
897 }
898
Mike Stump7bae1282009-08-18 21:30:21 +0000899 bool Top = true;
900
901 // vtables are composed from the chain of primaries.
902 if (PrimaryBase) {
903 if (PrimaryBaseWasVirtual)
904 IndirectPrimary.insert(PrimaryBase);
905 Top = false;
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000906 GenerateVtableForBase(PrimaryBase, true, PrimaryBaseWasVirtual|VBoundary,
Mike Stumpa7ec675d2009-08-19 14:40:47 +0000907 Offset, PrimaryBaseWasVirtual);
Mike Stump7bae1282009-08-18 21:30:21 +0000908 }
909
910 if (Top) {
911 int64_t BaseOffset;
912 if (ForVirtualBase) {
Mike Stump7bae1282009-08-18 21:30:21 +0000913 BaseOffset = -(BLayout.getVBaseClassOffset(RD) / 8);
914 } else
915 BaseOffset = -Offset/8;
Mike Stumpc57b8272009-08-16 01:46:26 +0000916 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), BaseOffset);
917 m = llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
918 methods.push_back(m);
Mike Stump7bae1282009-08-18 21:30:21 +0000919 methods.push_back(rtti);
Mike Stumpc57b8272009-08-16 01:46:26 +0000920 }
Mike Stump2eade572009-08-13 22:53:07 +0000921
Mike Stump7bae1282009-08-18 21:30:21 +0000922 // And add the virtuals for the class to the primary vtable.
923 GenerateMethods(RD);
924
925 // and then the non-virtual bases.
926 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
927 e = RD->bases_end(); i != e; ++i) {
928 if (i->isVirtual())
929 continue;
930 const CXXRecordDecl *Base =
931 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
932 if (Base != PrimaryBase || PrimaryBaseWasVirtual) {
933 uint64_t o = Offset + Layout.getBaseClassOffset(Base);
Mike Stump2b9ba612009-08-20 02:11:48 +0000934 SeenVBase.clear();
Mike Stumpa7ec675d2009-08-19 14:40:47 +0000935 GenerateVtableForBase(Base, true, false, o, false);
Mike Stump7bae1282009-08-18 21:30:21 +0000936 }
937 }
938 }
939
940 void GenerateVtableForVBases(const CXXRecordDecl *RD,
Mike Stumpa7ec675d2009-08-19 14:40:47 +0000941 const CXXRecordDecl *Class) {
Mike Stump7bae1282009-08-18 21:30:21 +0000942 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
943 e = RD->bases_end(); i != e; ++i) {
944 const CXXRecordDecl *Base =
945 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
946 if (i->isVirtual() && !IndirectPrimary.count(Base)) {
947 // Mark it so we don't output it twice.
948 IndirectPrimary.insert(Base);
Mike Stump2b9ba612009-08-20 02:11:48 +0000949 SeenVBase.clear();
Mike Stumpaf0d0452009-08-20 07:22:17 +0000950 int64_t BaseOffset = BLayout.getVBaseClassOffset(Base);
951 GenerateVtableForBase(Base, false, true, BaseOffset, true);
Mike Stump7bae1282009-08-18 21:30:21 +0000952 }
953 if (Base->getNumVBases())
Mike Stumpa7ec675d2009-08-19 14:40:47 +0000954 GenerateVtableForVBases(Base, Class);
Mike Stumpc57b8272009-08-16 01:46:26 +0000955 }
956 }
Mike Stump7bae1282009-08-18 21:30:21 +0000957};
Mike Stumpd6f22d82009-08-06 15:50:11 +0000958
Mike Stump7e8c9932009-07-31 18:25:34 +0000959llvm::Value *CodeGenFunction::GenerateVtable(const CXXRecordDecl *RD) {
Mike Stump7e8c9932009-07-31 18:25:34 +0000960 llvm::SmallString<256> OutName;
961 llvm::raw_svector_ostream Out(OutName);
962 QualType ClassTy;
Mike Stumpe7545622009-08-07 18:05:12 +0000963 ClassTy = getContext().getTagDeclType(RD);
Mike Stump7e8c9932009-07-31 18:25:34 +0000964 mangleCXXVtable(ClassTy, getContext(), Out);
Mike Stumpd0672782009-07-31 21:43:43 +0000965 llvm::GlobalVariable::LinkageTypes linktype;
966 linktype = llvm::GlobalValue::WeakAnyLinkage;
967 std::vector<llvm::Constant *> methods;
Mike Stumpc57b8272009-08-16 01:46:26 +0000968 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
Mike Stump8b82eeb2009-08-05 22:37:18 +0000969 int64_t Offset = 0;
Mike Stump71e21302009-08-06 21:49:36 +0000970
971 Offset += LLVMPointerWidth;
972 Offset += LLVMPointerWidth;
Mike Stump8b82eeb2009-08-05 22:37:18 +0000973
Mike Stump86a859e2009-08-19 18:10:47 +0000974 VtableBuilder b(methods, RD, CGM);
Mike Stump7bae1282009-08-18 21:30:21 +0000975
Mike Stumpc57b8272009-08-16 01:46:26 +0000976 // First comes the vtables for all the non-virtual bases...
Mike Stumpa7ec675d2009-08-19 14:40:47 +0000977 b.GenerateVtableForBase(RD, true, false, 0, false);
Mike Stump42368bb2009-08-14 01:44:03 +0000978
Mike Stumpc57b8272009-08-16 01:46:26 +0000979 // then the vtables for all the virtual bases.
Mike Stumpa7ec675d2009-08-19 14:40:47 +0000980 b.GenerateVtableForVBases(RD, RD);
Mike Stumpf3371782009-08-04 21:58:42 +0000981
Mike Stumpd0672782009-07-31 21:43:43 +0000982 llvm::Constant *C;
983 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, methods.size());
984 C = llvm::ConstantArray::get(type, methods);
985 llvm::Value *vtable = new llvm::GlobalVariable(CGM.getModule(), type, true,
Daniel Dunbar0433a022009-08-19 20:04:03 +0000986 linktype, C, Out.str());
Mike Stump7e8c9932009-07-31 18:25:34 +0000987 vtable = Builder.CreateBitCast(vtable, Ptr8Ty);
Mike Stump7e8c9932009-07-31 18:25:34 +0000988 vtable = Builder.CreateGEP(vtable,
Mike Stumpc57b8272009-08-16 01:46:26 +0000989 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
Mike Stump8b82eeb2009-08-05 22:37:18 +0000990 Offset/8));
Mike Stump7e8c9932009-07-31 18:25:34 +0000991 return vtable;
992}
993
Fariborz Jahanianfc27d292009-08-07 23:51:33 +0000994/// EmitClassMemberwiseCopy - This routine generates code to copy a class
995/// object from SrcValue to DestValue. Copying can be either a bitwise copy
996/// of via a copy constructor call.
997void CodeGenFunction::EmitClassMemberwiseCopy(
Fariborz Jahaniancefe5922009-08-08 23:32:22 +0000998 llvm::Value *Dest, llvm::Value *Src,
Fariborz Jahanianfc27d292009-08-07 23:51:33 +0000999 const CXXRecordDecl *ClassDecl,
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001000 const CXXRecordDecl *BaseClassDecl, QualType Ty) {
1001 if (ClassDecl) {
1002 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
1003 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
1004 }
1005 if (BaseClassDecl->hasTrivialCopyConstructor()) {
1006 EmitAggregateCopy(Dest, Src, Ty);
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001007 return;
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001008 }
1009
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001010 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanianfbe08772009-08-08 00:59:58 +00001011 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001012 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
1013 Ctor_Complete);
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001014 CallArgList CallArgs;
1015 // Push the this (Dest) ptr.
1016 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1017 BaseCopyCtor->getThisType(getContext())));
1018
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001019 // Push the Src ptr.
1020 CallArgs.push_back(std::make_pair(RValue::get(Src),
Fariborz Jahanian0dfaec42009-08-10 17:20:45 +00001021 BaseCopyCtor->getParamDecl(0)->getType()));
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001022 QualType ResultType =
1023 BaseCopyCtor->getType()->getAsFunctionType()->getResultType();
1024 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1025 Callee, CallArgs, BaseCopyCtor);
1026 }
1027}
Fariborz Jahaniane39fab62009-08-10 18:46:38 +00001028
Fariborz Jahanian04500242009-08-12 23:34:46 +00001029/// EmitClassCopyAssignment - This routine generates code to copy assign a class
1030/// object from SrcValue to DestValue. Assignment can be either a bitwise
1031/// assignment of via an assignment operator call.
1032void CodeGenFunction::EmitClassCopyAssignment(
1033 llvm::Value *Dest, llvm::Value *Src,
1034 const CXXRecordDecl *ClassDecl,
1035 const CXXRecordDecl *BaseClassDecl,
1036 QualType Ty) {
1037 if (ClassDecl) {
1038 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
1039 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
1040 }
1041 if (BaseClassDecl->hasTrivialCopyAssignment()) {
1042 EmitAggregateCopy(Dest, Src, Ty);
1043 return;
1044 }
1045
1046 const CXXMethodDecl *MD = 0;
Fariborz Jahanian84bd6532009-08-13 00:53:36 +00001047 bool ConstCopyAssignOp = BaseClassDecl->hasConstCopyAssignment(getContext(),
1048 MD);
1049 assert(ConstCopyAssignOp && "EmitClassCopyAssignment - missing copy assign");
1050 (void)ConstCopyAssignOp;
1051
1052 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
1053 const llvm::Type *LTy =
1054 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1055 FPT->isVariadic());
1056 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), LTy);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001057
Fariborz Jahanian84bd6532009-08-13 00:53:36 +00001058 CallArgList CallArgs;
1059 // Push the this (Dest) ptr.
1060 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1061 MD->getThisType(getContext())));
Fariborz Jahanian04500242009-08-12 23:34:46 +00001062
Fariborz Jahanian84bd6532009-08-13 00:53:36 +00001063 // Push the Src ptr.
1064 CallArgs.push_back(std::make_pair(RValue::get(Src),
1065 MD->getParamDecl(0)->getType()));
1066 QualType ResultType =
1067 MD->getType()->getAsFunctionType()->getResultType();
1068 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1069 Callee, CallArgs, MD);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001070}
1071
Fariborz Jahaniane39fab62009-08-10 18:46:38 +00001072/// SynthesizeDefaultConstructor - synthesize a default constructor
1073void
1074CodeGenFunction::SynthesizeDefaultConstructor(const CXXConstructorDecl *CD,
1075 const FunctionDecl *FD,
1076 llvm::Function *Fn,
1077 const FunctionArgList &Args) {
1078 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1079 EmitCtorPrologue(CD);
1080 FinishFunction();
1081}
1082
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001083/// SynthesizeCXXCopyConstructor - This routine implicitly defines body of a copy
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001084/// constructor, in accordance with section 12.8 (p7 and p8) of C++03
1085/// The implicitly-defined copy constructor for class X performs a memberwise
1086/// copy of its subobjects. The order of copying is the same as the order
1087/// of initialization of bases and members in a user-defined constructor
1088/// Each subobject is copied in the manner appropriate to its type:
1089/// if the subobject is of class type, the copy constructor for the class is
1090/// used;
1091/// if the subobject is an array, each element is copied, in the manner
1092/// appropriate to the element type;
1093/// if the subobject is of scalar type, the built-in assignment operator is
1094/// used.
1095/// Virtual base class subobjects shall be copied only once by the
1096/// implicitly-defined copy constructor
1097
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001098void CodeGenFunction::SynthesizeCXXCopyConstructor(const CXXConstructorDecl *CD,
1099 const FunctionDecl *FD,
1100 llvm::Function *Fn,
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001101 const FunctionArgList &Args) {
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001102 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1103 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001104 "SynthesizeCXXCopyConstructor - copy constructor has definition already");
1105 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001106
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001107 FunctionArgList::const_iterator i = Args.begin();
1108 const VarDecl *ThisArg = i->first;
1109 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1110 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1111 const VarDecl *SrcArg = (i+1)->first;
1112 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1113 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1114
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001115 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1116 Base != ClassDecl->bases_end(); ++Base) {
1117 // FIXME. copy constrution of virtual base NYI
1118 if (Base->isVirtual())
1119 continue;
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001120
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001121 CXXRecordDecl *BaseClassDecl
1122 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001123 EmitClassMemberwiseCopy(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1124 Base->getType());
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001125 }
1126
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001127 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1128 FieldEnd = ClassDecl->field_end();
1129 Field != FieldEnd; ++Field) {
1130 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
1131
1132 // FIXME. How about copying arrays!
1133 assert(!getContext().getAsArrayType(FieldType) &&
1134 "FIXME. Copying arrays NYI");
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +00001135
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001136 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1137 CXXRecordDecl *FieldClassDecl
1138 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1139 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1140 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001141
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001142 EmitClassMemberwiseCopy(LHS.getAddress(), RHS.getAddress(),
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001143 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001144 continue;
1145 }
Fariborz Jahanian08d99e92009-08-10 18:34:26 +00001146 // Do a built-in assignment of scalar data members.
1147 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1148 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1149 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1150 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001151 }
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001152 FinishFunction();
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001153}
1154
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001155/// SynthesizeCXXCopyAssignment - Implicitly define copy assignment operator.
1156/// Before the implicitly-declared copy assignment operator for a class is
1157/// implicitly defined, all implicitly- declared copy assignment operators for
1158/// its direct base classes and its nonstatic data members shall have been
1159/// implicitly defined. [12.8-p12]
1160/// The implicitly-defined copy assignment operator for class X performs
1161/// memberwise assignment of its subob- jects. The direct base classes of X are
1162/// assigned first, in the order of their declaration in
1163/// the base-specifier-list, and then the immediate nonstatic data members of X
1164/// are assigned, in the order in which they were declared in the class
1165/// definition.Each subobject is assigned in the manner appropriate to its type:
Fariborz Jahanian04500242009-08-12 23:34:46 +00001166/// if the subobject is of class type, the copy assignment operator for the
1167/// class is used (as if by explicit qualification; that is, ignoring any
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001168/// possible virtual overriding functions in more derived classes);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001169///
1170/// if the subobject is an array, each element is assigned, in the manner
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001171/// appropriate to the element type;
Fariborz Jahanian04500242009-08-12 23:34:46 +00001172///
1173/// if the subobject is of scalar type, the built-in assignment operator is
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001174/// used.
1175void CodeGenFunction::SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD,
1176 const FunctionDecl *FD,
1177 llvm::Function *Fn,
1178 const FunctionArgList &Args) {
Fariborz Jahanian04500242009-08-12 23:34:46 +00001179
1180 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1181 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
1182 "SynthesizeCXXCopyAssignment - copy assignment has user declaration");
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001183 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1184
Fariborz Jahanian04500242009-08-12 23:34:46 +00001185 FunctionArgList::const_iterator i = Args.begin();
1186 const VarDecl *ThisArg = i->first;
1187 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1188 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1189 const VarDecl *SrcArg = (i+1)->first;
1190 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1191 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1192
1193 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1194 Base != ClassDecl->bases_end(); ++Base) {
1195 // FIXME. copy assignment of virtual base NYI
1196 if (Base->isVirtual())
1197 continue;
1198
1199 CXXRecordDecl *BaseClassDecl
1200 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1201 EmitClassCopyAssignment(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1202 Base->getType());
1203 }
1204
1205 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1206 FieldEnd = ClassDecl->field_end();
1207 Field != FieldEnd; ++Field) {
1208 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
1209
1210 // FIXME. How about copy assignment of arrays!
1211 assert(!getContext().getAsArrayType(FieldType) &&
1212 "FIXME. Copy assignment of arrays NYI");
1213
1214 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1215 CXXRecordDecl *FieldClassDecl
1216 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1217 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1218 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1219
1220 EmitClassCopyAssignment(LHS.getAddress(), RHS.getAddress(),
1221 0 /*ClassDecl*/, FieldClassDecl, FieldType);
1222 continue;
1223 }
1224 // Do a built-in assignment of scalar data members.
1225 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1226 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1227 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1228 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanianc47460d2009-08-14 00:01:54 +00001229 }
1230
1231 // return *this;
1232 Builder.CreateStore(LoadOfThis, ReturnValue);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001233
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001234 FinishFunction();
1235}
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001236
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001237/// EmitCtorPrologue - This routine generates necessary code to initialize
1238/// base classes and non-static data members belonging to this constructor.
1239void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD) {
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001240 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
Mike Stump05207212009-08-06 13:41:24 +00001241 // FIXME: Add vbase initialization
Mike Stump7e8c9932009-07-31 18:25:34 +00001242 llvm::Value *LoadOfThis = 0;
Fariborz Jahanian70277012009-07-28 18:09:28 +00001243
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001244 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001245 E = CD->init_end();
1246 B != E; ++B) {
1247 CXXBaseOrMemberInitializer *Member = (*B);
1248 if (Member->isBaseInitializer()) {
Mike Stump7e8c9932009-07-31 18:25:34 +00001249 LoadOfThis = LoadCXXThis();
Fariborz Jahanian70277012009-07-28 18:09:28 +00001250 Type *BaseType = Member->getBaseClass();
1251 CXXRecordDecl *BaseClassDecl =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001252 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
Fariborz Jahanian70277012009-07-28 18:09:28 +00001253 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1254 BaseClassDecl);
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001255 EmitCXXConstructorCall(Member->getConstructor(),
1256 Ctor_Complete, V,
1257 Member->const_arg_begin(),
1258 Member->const_arg_end());
Mike Stump487ce382009-07-30 22:28:39 +00001259 } else {
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001260 // non-static data member initilaizers.
1261 FieldDecl *Field = Member->getMember();
1262 QualType FieldType = getContext().getCanonicalType((Field)->getType());
1263 assert(!getContext().getAsArrayType(FieldType)
1264 && "FIXME. Field arrays initialization unsupported");
Fariborz Jahanian32cea8b2009-08-10 23:56:17 +00001265
Mike Stump7e8c9932009-07-31 18:25:34 +00001266 LoadOfThis = LoadCXXThis();
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001267 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001268 if (FieldType->getAs<RecordType>()) {
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +00001269 if (!Field->isAnonymousStructOrUnion()) {
Fariborz Jahanian56baceb2009-07-24 17:57:02 +00001270 assert(Member->getConstructor() &&
1271 "EmitCtorPrologue - no constructor to initialize member");
1272 EmitCXXConstructorCall(Member->getConstructor(),
1273 Ctor_Complete, LHS.getAddress(),
1274 Member->const_arg_begin(),
1275 Member->const_arg_end());
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +00001276 continue;
1277 }
1278 else {
1279 // Initializing an anonymous union data member.
1280 FieldDecl *anonMember = Member->getAnonUnionMember();
1281 LHS = EmitLValueForField(LHS.getAddress(), anonMember, false, 0);
1282 FieldType = anonMember->getType();
1283 }
Fariborz Jahanian56baceb2009-07-24 17:57:02 +00001284 }
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001285
1286 assert(Member->getNumArgs() == 1 && "Initializer count must be 1 only");
Fariborz Jahanian56baceb2009-07-24 17:57:02 +00001287 Expr *RhsExpr = *Member->arg_begin();
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001288 llvm::Value *RHS = EmitScalarExpr(RhsExpr, true);
Fariborz Jahanian32cea8b2009-08-10 23:56:17 +00001289 EmitStoreThroughLValue(RValue::get(RHS), LHS, FieldType);
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001290 }
1291 }
Mike Stump7e8c9932009-07-31 18:25:34 +00001292
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001293 if (!CD->getNumBaseOrMemberInitializers() && !CD->isTrivial()) {
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001294 // Nontrivial default constructor with no initializer list. It may still
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001295 // have bases classes and/or contain non-static data members which require
1296 // construction.
1297 for (CXXRecordDecl::base_class_const_iterator Base =
1298 ClassDecl->bases_begin();
1299 Base != ClassDecl->bases_end(); ++Base) {
1300 // FIXME. copy assignment of virtual base NYI
1301 if (Base->isVirtual())
1302 continue;
1303
1304 CXXRecordDecl *BaseClassDecl
1305 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1306 if (BaseClassDecl->hasTrivialConstructor())
1307 continue;
1308 if (CXXConstructorDecl *BaseCX =
1309 BaseClassDecl->getDefaultConstructor(getContext())) {
1310 LoadOfThis = LoadCXXThis();
1311 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1312 BaseClassDecl);
1313 EmitCXXConstructorCall(BaseCX, Ctor_Complete, V, 0, 0);
1314 }
1315 }
1316
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001317 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1318 FieldEnd = ClassDecl->field_end();
1319 Field != FieldEnd; ++Field) {
1320 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +00001321 const ConstantArrayType *Array =
1322 getContext().getAsConstantArrayType(FieldType);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001323 if (Array)
1324 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001325 if (!FieldType->getAs<RecordType>() || Field->isAnonymousStructOrUnion())
1326 continue;
1327 const RecordType *ClassRec = FieldType->getAs<RecordType>();
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001328 CXXRecordDecl *MemberClassDecl =
1329 dyn_cast<CXXRecordDecl>(ClassRec->getDecl());
1330 if (!MemberClassDecl || MemberClassDecl->hasTrivialConstructor())
1331 continue;
1332 if (CXXConstructorDecl *MamberCX =
1333 MemberClassDecl->getDefaultConstructor(getContext())) {
1334 LoadOfThis = LoadCXXThis();
1335 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +00001336 if (Array) {
1337 const llvm::Type *BasePtr = ConvertType(FieldType);
1338 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1339 llvm::Value *BaseAddrPtr =
1340 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1341 EmitCXXAggrConstructorCall(MamberCX, Array, BaseAddrPtr);
1342 }
1343 else
1344 EmitCXXConstructorCall(MamberCX, Ctor_Complete, LHS.getAddress(),
1345 0, 0);
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001346 }
1347 }
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001348 }
1349
Mike Stump7e8c9932009-07-31 18:25:34 +00001350 // Initialize the vtable pointer
Mike Stumpeec46a72009-08-05 22:59:44 +00001351 if (ClassDecl->isDynamicClass()) {
Mike Stump7e8c9932009-07-31 18:25:34 +00001352 if (!LoadOfThis)
1353 LoadOfThis = LoadCXXThis();
1354 llvm::Value *VtableField;
1355 llvm::Type *Ptr8Ty, *PtrPtr8Ty;
Owen Anderson3f5cc0a2009-08-13 21:57:51 +00001356 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Mike Stump7e8c9932009-07-31 18:25:34 +00001357 PtrPtr8Ty = llvm::PointerType::get(Ptr8Ty, 0);
1358 VtableField = Builder.CreateBitCast(LoadOfThis, PtrPtr8Ty);
1359 llvm::Value *vtable = GenerateVtable(ClassDecl);
1360 Builder.CreateStore(vtable, VtableField);
1361 }
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001362}
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001363
1364/// EmitDtorEpilogue - Emit all code that comes at the end of class's
1365/// destructor. This is to call destructors on members and base classes
1366/// in reverse order of their construction.
1367void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD) {
1368 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(DD->getDeclContext());
1369 assert(!ClassDecl->isPolymorphic() &&
1370 "FIXME. polymorphic destruction not supported");
1371 (void)ClassDecl; // prevent warning.
1372
1373 for (CXXDestructorDecl::destr_const_iterator *B = DD->destr_begin(),
1374 *E = DD->destr_end(); B != E; ++B) {
1375 uintptr_t BaseOrMember = (*B);
1376 if (DD->isMemberToDestroy(BaseOrMember)) {
1377 FieldDecl *FD = DD->getMemberToDestroy(BaseOrMember);
1378 QualType FieldType = getContext().getCanonicalType((FD)->getType());
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001379 const ConstantArrayType *Array =
1380 getContext().getAsConstantArrayType(FieldType);
1381 if (Array)
1382 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001383 const RecordType *RT = FieldType->getAs<RecordType>();
1384 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1385 if (FieldClassDecl->hasTrivialDestructor())
1386 continue;
1387 llvm::Value *LoadOfThis = LoadCXXThis();
1388 LValue LHS = EmitLValueForField(LoadOfThis, FD, false, 0);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001389 if (Array) {
1390 const llvm::Type *BasePtr = ConvertType(FieldType);
1391 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1392 llvm::Value *BaseAddrPtr =
1393 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1394 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1395 Array, BaseAddrPtr);
1396 }
1397 else
1398 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1399 Dtor_Complete, LHS.getAddress());
Mike Stump487ce382009-07-30 22:28:39 +00001400 } else {
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001401 const RecordType *RT =
1402 DD->getAnyBaseClassToDestroy(BaseOrMember)->getAs<RecordType>();
1403 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1404 if (BaseClassDecl->hasTrivialDestructor())
1405 continue;
1406 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
1407 ClassDecl,BaseClassDecl);
1408 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1409 Dtor_Complete, V);
1410 }
1411 }
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001412 if (DD->getNumBaseOrMemberDestructions() || DD->isTrivial())
1413 return;
1414 // Case of destructor synthesis with fields and base classes
1415 // which have non-trivial destructors. They must be destructed in
1416 // reverse order of their construction.
1417 llvm::SmallVector<FieldDecl *, 16> DestructedFields;
1418
1419 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1420 FieldEnd = ClassDecl->field_end();
1421 Field != FieldEnd; ++Field) {
1422 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001423 if (getContext().getAsConstantArrayType(FieldType))
1424 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001425 if (const RecordType *RT = FieldType->getAs<RecordType>()) {
1426 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1427 if (FieldClassDecl->hasTrivialDestructor())
1428 continue;
1429 DestructedFields.push_back(*Field);
1430 }
1431 }
1432 if (!DestructedFields.empty())
1433 for (int i = DestructedFields.size() -1; i >= 0; --i) {
1434 FieldDecl *Field = DestructedFields[i];
1435 QualType FieldType = Field->getType();
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001436 const ConstantArrayType *Array =
1437 getContext().getAsConstantArrayType(FieldType);
1438 if (Array)
1439 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001440 const RecordType *RT = FieldType->getAs<RecordType>();
1441 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1442 llvm::Value *LoadOfThis = LoadCXXThis();
1443 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001444 if (Array) {
1445 const llvm::Type *BasePtr = ConvertType(FieldType);
1446 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1447 llvm::Value *BaseAddrPtr =
1448 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1449 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1450 Array, BaseAddrPtr);
1451 }
1452 else
1453 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1454 Dtor_Complete, LHS.getAddress());
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001455 }
1456
1457 llvm::SmallVector<CXXRecordDecl*, 4> DestructedBases;
1458 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1459 Base != ClassDecl->bases_end(); ++Base) {
1460 // FIXME. copy assignment of virtual base NYI
1461 if (Base->isVirtual())
1462 continue;
1463
1464 CXXRecordDecl *BaseClassDecl
1465 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1466 if (BaseClassDecl->hasTrivialDestructor())
1467 continue;
1468 DestructedBases.push_back(BaseClassDecl);
1469 }
1470 if (DestructedBases.empty())
1471 return;
1472 for (int i = DestructedBases.size() -1; i >= 0; --i) {
1473 CXXRecordDecl *BaseClassDecl = DestructedBases[i];
1474 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
1475 ClassDecl,BaseClassDecl);
1476 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1477 Dtor_Complete, V);
1478 }
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001479}
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001480
1481void CodeGenFunction::SynthesizeDefaultDestructor(const CXXDestructorDecl *CD,
1482 const FunctionDecl *FD,
1483 llvm::Function *Fn,
1484 const FunctionArgList &Args) {
1485
1486 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1487 assert(!ClassDecl->hasUserDeclaredDestructor() &&
1488 "SynthesizeDefaultDestructor - destructor has user declaration");
1489 (void) ClassDecl;
1490
1491 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1492 EmitDtorEpilogue(CD);
1493 FinishFunction();
1494}