blob: b564a0850154d376773b06c33ecbfa709f485532 [file] [log] [blame]
Anders Carlssone1b29ef2008-08-22 16:00:37 +00001//===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with C++ code generation.
11//
12//===----------------------------------------------------------------------===//
13
14// We might split this into multiple files if it gets too unwieldy
15
16#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
Anders Carlsson283a0622009-04-13 18:03:33 +000018#include "Mangle.h"
Anders Carlssone1b29ef2008-08-22 16:00:37 +000019#include "clang/AST/ASTContext.h"
Fariborz Jahanian742cd1b2009-07-25 21:12:28 +000020#include "clang/AST/RecordLayout.h"
Anders Carlssone1b29ef2008-08-22 16:00:37 +000021#include "clang/AST/Decl.h"
Anders Carlsson774e7c62009-04-03 22:50:24 +000022#include "clang/AST/DeclCXX.h"
Anders Carlsson86e96442008-08-23 19:42:54 +000023#include "clang/AST/DeclObjC.h"
Anders Carlssone1b29ef2008-08-22 16:00:37 +000024#include "llvm/ADT/StringExtras.h"
Anders Carlssone1b29ef2008-08-22 16:00:37 +000025using namespace clang;
26using namespace CodeGen;
27
Daniel Dunbar0096acf2009-02-25 19:24:29 +000028void
Anders Carlsson3b2e16b2009-08-08 21:45:14 +000029CodeGenFunction::EmitCXXGlobalDtorRegistration(const CXXDestructorDecl *Dtor,
30 llvm::Constant *DeclPtr) {
31 // FIXME: This is ABI dependent and we use the Itanium ABI.
32
33 const llvm::Type *Int8PtrTy =
Owen Anderson0032b272009-08-13 21:57:51 +000034 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Anders Carlsson3b2e16b2009-08-08 21:45:14 +000035
36 std::vector<const llvm::Type *> Params;
37 Params.push_back(Int8PtrTy);
38
39 // Get the destructor function type
40 const llvm::Type *DtorFnTy =
Owen Anderson0032b272009-08-13 21:57:51 +000041 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Params, false);
Anders Carlsson3b2e16b2009-08-08 21:45:14 +000042 DtorFnTy = llvm::PointerType::getUnqual(DtorFnTy);
43
44 Params.clear();
45 Params.push_back(DtorFnTy);
46 Params.push_back(Int8PtrTy);
47 Params.push_back(Int8PtrTy);
48
49 // Get the __cxa_atexit function type
50 // extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
51 const llvm::FunctionType *AtExitFnTy =
52 llvm::FunctionType::get(ConvertType(getContext().IntTy), Params, false);
53
54 llvm::Constant *AtExitFn = CGM.CreateRuntimeFunction(AtExitFnTy,
55 "__cxa_atexit");
56
57 llvm::Constant *Handle = CGM.CreateRuntimeVariable(Int8PtrTy,
58 "__dso_handle");
59
60 llvm::Constant *DtorFn = CGM.GetAddrOfCXXDestructor(Dtor, Dtor_Complete);
61
62 llvm::Value *Args[3] = { llvm::ConstantExpr::getBitCast(DtorFn, DtorFnTy),
63 llvm::ConstantExpr::getBitCast(DeclPtr, Int8PtrTy),
64 llvm::ConstantExpr::getBitCast(Handle, Int8PtrTy) };
65 Builder.CreateCall(AtExitFn, &Args[0], llvm::array_endof(Args));
66}
67
68void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
69 llvm::Constant *DeclPtr) {
70 assert(D.hasGlobalStorage() &&
71 "VarDecl must have global storage!");
72
73 const Expr *Init = D.getInit();
74 QualType T = D.getType();
75
76 if (T->isReferenceType()) {
Anders Carlsson622f9dc2009-08-17 18:24:57 +000077 ErrorUnsupported(Init, "global variable that binds to a reference");
Anders Carlsson3b2e16b2009-08-08 21:45:14 +000078 } else if (!hasAggregateLLVMType(T)) {
79 llvm::Value *V = EmitScalarExpr(Init);
80 EmitStoreOfScalar(V, DeclPtr, T.isVolatileQualified(), T);
81 } else if (T->isAnyComplexType()) {
82 EmitComplexExprIntoAddr(Init, DeclPtr, T.isVolatileQualified());
83 } else {
84 EmitAggExpr(Init, DeclPtr, T.isVolatileQualified());
85
86 if (const RecordType *RT = T->getAs<RecordType>()) {
87 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
88 if (!RD->hasTrivialDestructor())
89 EmitCXXGlobalDtorRegistration(RD->getDestructor(getContext()), DeclPtr);
90 }
91 }
92}
93
Anders Carlsson89ed31d2009-08-08 23:24:23 +000094void
95CodeGenModule::EmitCXXGlobalInitFunc() {
96 if (CXXGlobalInits.empty())
97 return;
98
Owen Anderson0032b272009-08-13 21:57:51 +000099 const llvm::FunctionType *FTy = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
Anders Carlsson89ed31d2009-08-08 23:24:23 +0000100 false);
101
102 // Create our global initialization function.
103 // FIXME: Should this be tweakable by targets?
104 llvm::Function *Fn =
105 llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
106 "__cxx_global_initialization", &TheModule);
107
108 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
Benjamin Kramer10c40ee2009-08-08 23:43:26 +0000109 &CXXGlobalInits[0],
Anders Carlsson89ed31d2009-08-08 23:24:23 +0000110 CXXGlobalInits.size());
111 AddGlobalCtor(Fn);
112}
113
114void CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
115 const VarDecl **Decls,
116 unsigned NumDecls) {
117 StartFunction(0, getContext().VoidTy, Fn, FunctionArgList(),
118 SourceLocation());
119
120 for (unsigned i = 0; i != NumDecls; ++i) {
121 const VarDecl *D = Decls[i];
122
123 llvm::Constant *DeclPtr = CGM.GetAddrOfGlobalVar(D);
124 EmitCXXGlobalVarDeclInit(*D, DeclPtr);
125 }
126 FinishFunction();
127}
128
Anders Carlsson3b2e16b2009-08-08 21:45:14 +0000129void
130CodeGenFunction::EmitStaticCXXBlockVarDeclInit(const VarDecl &D,
131 llvm::GlobalVariable *GV) {
Daniel Dunbar0096acf2009-02-25 19:24:29 +0000132 // FIXME: This should use __cxa_guard_{acquire,release}?
133
Anders Carlssone1b29ef2008-08-22 16:00:37 +0000134 assert(!getContext().getLangOptions().ThreadsafeStatics &&
135 "thread safe statics are currently not supported!");
Anders Carlssone1b29ef2008-08-22 16:00:37 +0000136
Anders Carlsson283a0622009-04-13 18:03:33 +0000137 llvm::SmallString<256> GuardVName;
138 llvm::raw_svector_ostream GuardVOut(GuardVName);
139 mangleGuardVariable(&D, getContext(), GuardVOut);
140
Anders Carlssone1b29ef2008-08-22 16:00:37 +0000141 // Create the guard variable.
142 llvm::GlobalValue *GuardV =
Owen Anderson0032b272009-08-13 21:57:51 +0000143 new llvm::GlobalVariable(CGM.getModule(), llvm::Type::getInt64Ty(VMContext), false,
Daniel Dunbar0096acf2009-02-25 19:24:29 +0000144 GV->getLinkage(),
Owen Anderson0032b272009-08-13 21:57:51 +0000145 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext)),
Daniel Dunbar77659342009-08-19 20:04:03 +0000146 GuardVName.str());
Anders Carlssone1b29ef2008-08-22 16:00:37 +0000147
Anders Carlssone1b29ef2008-08-22 16:00:37 +0000148 // Load the first byte of the guard variable.
Owen Anderson0032b272009-08-13 21:57:51 +0000149 const llvm::Type *PtrTy = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Anders Carlssone1b29ef2008-08-22 16:00:37 +0000150 llvm::Value *V = Builder.CreateLoad(Builder.CreateBitCast(GuardV, PtrTy),
151 "tmp");
152
153 // Compare it against 0.
Owen Anderson0032b272009-08-13 21:57:51 +0000154 llvm::Value *nullValue = llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext));
Anders Carlssone1b29ef2008-08-22 16:00:37 +0000155 llvm::Value *ICmp = Builder.CreateICmpEQ(V, nullValue , "tobool");
156
Daniel Dunbar55e87422008-11-11 02:29:29 +0000157 llvm::BasicBlock *InitBlock = createBasicBlock("init");
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000158 llvm::BasicBlock *EndBlock = createBasicBlock("init.end");
Anders Carlssone1b29ef2008-08-22 16:00:37 +0000159
160 // If the guard variable is 0, jump to the initializer code.
161 Builder.CreateCondBr(ICmp, InitBlock, EndBlock);
162
163 EmitBlock(InitBlock);
164
Anders Carlsson3b2e16b2009-08-08 21:45:14 +0000165 EmitCXXGlobalVarDeclInit(D, GV);
166
Owen Anderson0032b272009-08-13 21:57:51 +0000167 Builder.CreateStore(llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext), 1),
Anders Carlssone1b29ef2008-08-22 16:00:37 +0000168 Builder.CreateBitCast(GuardV, PtrTy));
169
170 EmitBlock(EndBlock);
Anders Carlssone1b29ef2008-08-22 16:00:37 +0000171}
172
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000173RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
174 llvm::Value *Callee,
175 llvm::Value *This,
176 CallExpr::const_arg_iterator ArgBeg,
177 CallExpr::const_arg_iterator ArgEnd) {
178 assert(MD->isInstance() &&
179 "Trying to emit a member call expr on a static method!");
180
181 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
182
183 CallArgList Args;
184
185 // Push the this ptr.
186 Args.push_back(std::make_pair(RValue::get(This),
187 MD->getThisType(getContext())));
188
189 // And the rest of the call args
190 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
191
192 QualType ResultType = MD->getType()->getAsFunctionType()->getResultType();
193 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args),
194 Callee, Args, MD);
195}
196
Anders Carlsson774e7c62009-04-03 22:50:24 +0000197RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE) {
198 const MemberExpr *ME = cast<MemberExpr>(CE->getCallee());
199 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000200
Anders Carlssone9918d22009-04-08 20:31:57 +0000201 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
Mike Stump7116da12009-07-30 21:47:44 +0000202
Mike Stumpf1216772009-07-31 18:25:34 +0000203 if (MD->isVirtual()) {
Mike Stump7116da12009-07-30 21:47:44 +0000204 ErrorUnsupported(CE, "virtual dispatch");
205 }
206
Anders Carlsson774e7c62009-04-03 22:50:24 +0000207 const llvm::Type *Ty =
Anders Carlssone9918d22009-04-08 20:31:57 +0000208 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
209 FPT->isVariadic());
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000210 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty);
Anders Carlsson774e7c62009-04-03 22:50:24 +0000211
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000212 llvm::Value *This;
Anders Carlsson774e7c62009-04-03 22:50:24 +0000213
Anders Carlsson774e7c62009-04-03 22:50:24 +0000214 if (ME->isArrow())
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000215 This = EmitScalarExpr(ME->getBase());
Anders Carlsson774e7c62009-04-03 22:50:24 +0000216 else {
217 LValue BaseLV = EmitLValue(ME->getBase());
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000218 This = BaseLV.getAddress();
Anders Carlsson774e7c62009-04-03 22:50:24 +0000219 }
220
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000221 return EmitCXXMemberCall(MD, Callee, This,
222 CE->arg_begin(), CE->arg_end());
Anders Carlsson774e7c62009-04-03 22:50:24 +0000223}
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000224
Anders Carlsson0f294632009-05-27 04:18:27 +0000225RValue
226CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
227 const CXXMethodDecl *MD) {
228 assert(MD->isInstance() &&
229 "Trying to emit a member call expr on a static method!");
230
Fariborz Jahanianad258832009-08-13 21:09:41 +0000231 if (MD->isCopyAssignment()) {
232 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(MD->getDeclContext());
233 if (ClassDecl->hasTrivialCopyAssignment()) {
234 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
235 "EmitCXXOperatorMemberCallExpr - user declared copy assignment");
236 llvm::Value *This = EmitLValue(E->getArg(0)).getAddress();
237 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
238 QualType Ty = E->getType();
239 EmitAggregateCopy(This, Src, Ty);
240 return RValue::get(This);
241 }
242 }
Anders Carlsson0f294632009-05-27 04:18:27 +0000243
244 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
245 const llvm::Type *Ty =
246 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
247 FPT->isVariadic());
248 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty);
249
250 llvm::Value *This = EmitLValue(E->getArg(0)).getAddress();
251
252 return EmitCXXMemberCall(MD, Callee, This,
253 E->arg_begin() + 1, E->arg_end());
254}
255
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000256llvm::Value *CodeGenFunction::LoadCXXThis() {
257 assert(isa<CXXMethodDecl>(CurFuncDecl) &&
258 "Must be in a C++ member function decl to load 'this'");
259 assert(cast<CXXMethodDecl>(CurFuncDecl)->isInstance() &&
260 "Must be in a C++ member function decl to load 'this'");
261
262 // FIXME: What if we're inside a block?
Mike Stumpf5408fe2009-05-16 07:57:57 +0000263 // ans: See how CodeGenFunction::LoadObjCSelf() uses
264 // CodeGenFunction::BlockForwardSelf() for how to do this.
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000265 return Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
266}
Anders Carlsson95d4e5d2009-04-15 15:55:24 +0000267
Fariborz Jahanianc238a792009-07-30 00:10:25 +0000268static bool
269GetNestedPaths(llvm::SmallVectorImpl<const CXXRecordDecl *> &NestedBasePaths,
270 const CXXRecordDecl *ClassDecl,
271 const CXXRecordDecl *BaseClassDecl) {
Fariborz Jahanianc238a792009-07-30 00:10:25 +0000272 for (CXXRecordDecl::base_class_const_iterator i = ClassDecl->bases_begin(),
273 e = ClassDecl->bases_end(); i != e; ++i) {
274 if (i->isVirtual())
275 continue;
276 const CXXRecordDecl *Base =
Mike Stump104ffaa2009-08-04 21:58:42 +0000277 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanianc238a792009-07-30 00:10:25 +0000278 if (Base == BaseClassDecl) {
279 NestedBasePaths.push_back(BaseClassDecl);
280 return true;
281 }
282 }
283 // BaseClassDecl not an immediate base of ClassDecl.
284 for (CXXRecordDecl::base_class_const_iterator i = ClassDecl->bases_begin(),
285 e = ClassDecl->bases_end(); i != e; ++i) {
286 if (i->isVirtual())
287 continue;
288 const CXXRecordDecl *Base =
289 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
290 if (GetNestedPaths(NestedBasePaths, Base, BaseClassDecl)) {
291 NestedBasePaths.push_back(Base);
292 return true;
293 }
294 }
295 return false;
296}
297
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000298llvm::Value *CodeGenFunction::AddressCXXOfBaseClass(llvm::Value *BaseValue,
Fariborz Jahanian6d0bdaa2009-07-28 18:09:28 +0000299 const CXXRecordDecl *ClassDecl,
300 const CXXRecordDecl *BaseClassDecl) {
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000301 if (ClassDecl == BaseClassDecl)
302 return BaseValue;
303
Owen Anderson0032b272009-08-13 21:57:51 +0000304 llvm::Type *I8Ptr = llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Fariborz Jahanianc238a792009-07-30 00:10:25 +0000305 llvm::SmallVector<const CXXRecordDecl *, 16> NestedBasePaths;
306 GetNestedPaths(NestedBasePaths, ClassDecl, BaseClassDecl);
307 assert(NestedBasePaths.size() > 0 &&
308 "AddressCXXOfBaseClass - inheritence path failed");
309 NestedBasePaths.push_back(ClassDecl);
310 uint64_t Offset = 0;
311
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000312 // Accessing a member of the base class. Must add delata to
313 // the load of 'this'.
Fariborz Jahanianc238a792009-07-30 00:10:25 +0000314 for (unsigned i = NestedBasePaths.size()-1; i > 0; i--) {
315 const CXXRecordDecl *DerivedClass = NestedBasePaths[i];
316 const CXXRecordDecl *BaseClass = NestedBasePaths[i-1];
317 const ASTRecordLayout &Layout =
318 getContext().getASTRecordLayout(DerivedClass);
319 Offset += Layout.getBaseClassOffset(BaseClass) / 8;
320 }
Fariborz Jahanian5a8503b2009-07-29 15:54:56 +0000321 llvm::Value *OffsetVal =
322 llvm::ConstantInt::get(
323 CGM.getTypes().ConvertType(CGM.getContext().LongTy), Offset);
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000324 BaseValue = Builder.CreateBitCast(BaseValue, I8Ptr);
325 BaseValue = Builder.CreateGEP(BaseValue, OffsetVal, "add.ptr");
326 QualType BTy =
327 getContext().getCanonicalType(
Fariborz Jahanian6d0bdaa2009-07-28 18:09:28 +0000328 getContext().getTypeDeclType(const_cast<CXXRecordDecl*>(BaseClassDecl)));
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000329 const llvm::Type *BasePtr = ConvertType(BTy);
Owen Anderson96e0fc72009-07-29 22:16:19 +0000330 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000331 BaseValue = Builder.CreateBitCast(BaseValue, BasePtr);
332 return BaseValue;
333}
334
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000335/// EmitCXXAggrConstructorCall - This routine essentially creates a (nested)
336/// for-loop to call the default constructor on individual members of the
337/// array. 'Array' is the array type, 'This' is llvm pointer of the start
338/// of the array and 'D' is the default costructor Decl for elements of the
339/// array. It is assumed that all relevant checks have been made by the
340/// caller.
341void
342CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
343 const ArrayType *Array,
344 llvm::Value *This) {
345 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
346 assert(CA && "Do we support VLA for construction ?");
347
348 // Create a temporary for the loop index and initialize it with 0.
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 Jahanian288dcaf2009-08-19 20:55:16 +0000377 // Inside the loop body, emit the constructor call on the array element.
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000378 if (const ConstantArrayType *CAT =
379 dyn_cast<ConstantArrayType>(Array->getElementType())) {
380 // Need to call this routine again.
Fariborz Jahanian6147a902009-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);
387 // Address = This + delta*Counter
388 llvm::Value *DeltaPtr =
389 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), delta);
390 Counter = Builder.CreateLoad(IndexPtr);
391 DeltaPtr = Builder.CreateMul(Counter, DeltaPtr, "mul");
392 llvm::Value *Address =
393 Builder.CreateInBoundsGEP(This, DeltaPtr, "arrayidx");
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000394 EmitCXXAggrConstructorCall(D, CAT, Address);
395 }
Fariborz Jahanian6147a902009-08-20 00:15:15 +0000396 else {
397 Counter = Builder.CreateLoad(IndexPtr);
398 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000399 EmitCXXConstructorCall(D, Ctor_Complete, Address, 0, 0);
Fariborz Jahanian6147a902009-08-20 00:15:15 +0000400 }
401
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000402 EmitBlock(ContinueBlock);
403
404 // Emit the increment of the loop counter.
405 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
406 Counter = Builder.CreateLoad(IndexPtr);
407 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
408 Builder.CreateStore(NextVal, IndexPtr, false);
409
410 // Finally, branch back up to the condition for the next iteration.
411 EmitBranch(CondBlock);
412
413 // Emit the fall-through block.
414 EmitBlock(AfterFor, true);
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +0000415}
416
Anders Carlssonb14095a2009-04-17 00:06:03 +0000417void
418CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
419 CXXCtorType Type,
420 llvm::Value *This,
421 CallExpr::const_arg_iterator ArgBeg,
422 CallExpr::const_arg_iterator ArgEnd) {
Fariborz Jahanian343a3cf2009-08-14 20:11:43 +0000423 if (D->isCopyConstructor(getContext())) {
424 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D->getDeclContext());
425 if (ClassDecl->hasTrivialCopyConstructor()) {
426 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
427 "EmitCXXConstructorCall - user declared copy constructor");
428 const Expr *E = (*ArgBeg);
429 QualType Ty = E->getType();
430 llvm::Value *Src = EmitLValue(E).getAddress();
431 EmitAggregateCopy(This, Src, Ty);
432 return;
433 }
434 }
435
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000436 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
437
438 EmitCXXMemberCall(D, Callee, This, ArgBeg, ArgEnd);
Anders Carlssonb14095a2009-04-17 00:06:03 +0000439}
440
Anders Carlsson7267c162009-05-29 21:03:38 +0000441void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *D,
442 CXXDtorType Type,
443 llvm::Value *This) {
444 llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(D, Type);
445
446 EmitCXXMemberCall(D, Callee, This, 0, 0);
447}
448
Anders Carlssonb14095a2009-04-17 00:06:03 +0000449void
Anders Carlsson31ccf372009-05-03 17:47:16 +0000450CodeGenFunction::EmitCXXConstructExpr(llvm::Value *Dest,
451 const CXXConstructExpr *E) {
Anders Carlssonb14095a2009-04-17 00:06:03 +0000452 assert(Dest && "Must have a destination!");
453
454 const CXXRecordDecl *RD =
Ted Kremenek6217b802009-07-29 21:53:49 +0000455 cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
Anders Carlssonb14095a2009-04-17 00:06:03 +0000456 if (RD->hasTrivialConstructor())
457 return;
Fariborz Jahanian6904cbb2009-08-06 01:02:49 +0000458
459 // Code gen optimization to eliminate copy constructor and return
460 // its first argument instead.
Fariborz Jahanian1cf9ff82009-08-06 19:12:38 +0000461 if (E->isElidable()) {
Fariborz Jahanian6904cbb2009-08-06 01:02:49 +0000462 CXXConstructExpr::const_arg_iterator i = E->arg_begin();
Fariborz Jahanian1cf9ff82009-08-06 19:12:38 +0000463 EmitAggExpr((*i), Dest, false);
464 return;
Fariborz Jahanian6904cbb2009-08-06 01:02:49 +0000465 }
Anders Carlssonb14095a2009-04-17 00:06:03 +0000466 // Call the constructor.
467 EmitCXXConstructorCall(E->getConstructor(), Ctor_Complete, Dest,
468 E->arg_begin(), E->arg_end());
469}
470
Anders Carlssona00703d2009-05-31 01:40:14 +0000471llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
Anders Carlssoned4e3672009-05-31 20:21:44 +0000472 if (E->isArray()) {
473 ErrorUnsupported(E, "new[] expression");
Owen Anderson03e20502009-07-30 23:11:26 +0000474 return llvm::UndefValue::get(ConvertType(E->getType()));
Anders Carlssoned4e3672009-05-31 20:21:44 +0000475 }
476
477 QualType AllocType = E->getAllocatedType();
478 FunctionDecl *NewFD = E->getOperatorNew();
479 const FunctionProtoType *NewFTy = NewFD->getType()->getAsFunctionProtoType();
480
481 CallArgList NewArgs;
482
483 // The allocation size is the first argument.
484 QualType SizeTy = getContext().getSizeType();
485 llvm::Value *AllocSize =
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000486 llvm::ConstantInt::get(ConvertType(SizeTy),
Anders Carlssoned4e3672009-05-31 20:21:44 +0000487 getContext().getTypeSize(AllocType) / 8);
488
489 NewArgs.push_back(std::make_pair(RValue::get(AllocSize), SizeTy));
490
491 // Emit the rest of the arguments.
492 // FIXME: Ideally, this should just use EmitCallArgs.
493 CXXNewExpr::const_arg_iterator NewArg = E->placement_arg_begin();
494
495 // First, use the types from the function type.
496 // We start at 1 here because the first argument (the allocation size)
497 // has already been emitted.
498 for (unsigned i = 1, e = NewFTy->getNumArgs(); i != e; ++i, ++NewArg) {
499 QualType ArgType = NewFTy->getArgType(i);
500
501 assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
502 getTypePtr() ==
503 getContext().getCanonicalType(NewArg->getType()).getTypePtr() &&
504 "type mismatch in call argument!");
505
506 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
507 ArgType));
508
509 }
510
511 // Either we've emitted all the call args, or we have a call to a
512 // variadic function.
513 assert((NewArg == E->placement_arg_end() || NewFTy->isVariadic()) &&
514 "Extra arguments in non-variadic function!");
515
516 // If we still have any arguments, emit them using the type of the argument.
517 for (CXXNewExpr::const_arg_iterator NewArgEnd = E->placement_arg_end();
518 NewArg != NewArgEnd; ++NewArg) {
519 QualType ArgType = NewArg->getType();
520 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
521 ArgType));
522 }
523
524 // Emit the call to new.
525 RValue RV =
526 EmitCall(CGM.getTypes().getFunctionInfo(NewFTy->getResultType(), NewArgs),
527 CGM.GetAddrOfFunction(GlobalDecl(NewFD)),
528 NewArgs, NewFD);
529
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000530 // If an allocation function is declared with an empty exception specification
531 // it returns null to indicate failure to allocate storage. [expr.new]p13.
532 // (We don't need to check for null when there's no new initializer and
533 // we're allocating a POD type).
534 bool NullCheckResult = NewFTy->hasEmptyExceptionSpec() &&
535 !(AllocType->isPODType() && !E->hasInitializer());
Anders Carlssoned4e3672009-05-31 20:21:44 +0000536
Anders Carlssonf1108532009-06-01 00:05:16 +0000537 llvm::BasicBlock *NewNull = 0;
538 llvm::BasicBlock *NewNotNull = 0;
539 llvm::BasicBlock *NewEnd = 0;
540
541 llvm::Value *NewPtr = RV.getScalarVal();
542
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000543 if (NullCheckResult) {
Anders Carlssonf1108532009-06-01 00:05:16 +0000544 NewNull = createBasicBlock("new.null");
545 NewNotNull = createBasicBlock("new.notnull");
546 NewEnd = createBasicBlock("new.end");
547
548 llvm::Value *IsNull =
549 Builder.CreateICmpEQ(NewPtr,
Owen Andersonc9c88b42009-07-31 20:28:54 +0000550 llvm::Constant::getNullValue(NewPtr->getType()),
Anders Carlssonf1108532009-06-01 00:05:16 +0000551 "isnull");
552
553 Builder.CreateCondBr(IsNull, NewNull, NewNotNull);
554 EmitBlock(NewNotNull);
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000555 }
556
Anders Carlssonf1108532009-06-01 00:05:16 +0000557 NewPtr = Builder.CreateBitCast(NewPtr, ConvertType(E->getType()));
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000558
Anders Carlsson6d0ffad2009-05-31 20:56:36 +0000559 if (AllocType->isPODType()) {
Anders Carlsson215bd202009-06-01 00:26:14 +0000560 if (E->getNumConstructorArgs() > 0) {
Anders Carlsson6d0ffad2009-05-31 20:56:36 +0000561 assert(E->getNumConstructorArgs() == 1 &&
562 "Can only have one argument to initializer of POD type.");
563
564 const Expr *Init = E->getConstructorArg(0);
565
Anders Carlsson3923e952009-05-31 21:07:58 +0000566 if (!hasAggregateLLVMType(AllocType))
Anders Carlsson6d0ffad2009-05-31 20:56:36 +0000567 Builder.CreateStore(EmitScalarExpr(Init), NewPtr);
Anders Carlsson3923e952009-05-31 21:07:58 +0000568 else if (AllocType->isAnyComplexType())
569 EmitComplexExprIntoAddr(Init, NewPtr, AllocType.isVolatileQualified());
Anders Carlsson627a3e52009-05-31 21:12:26 +0000570 else
571 EmitAggExpr(Init, NewPtr, AllocType.isVolatileQualified());
Anders Carlsson6d0ffad2009-05-31 20:56:36 +0000572 }
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000573 } else {
574 // Call the constructor.
575 CXXConstructorDecl *Ctor = E->getConstructor();
Anders Carlsson6d0ffad2009-05-31 20:56:36 +0000576
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000577 EmitCXXConstructorCall(Ctor, Ctor_Complete, NewPtr,
578 E->constructor_arg_begin(),
579 E->constructor_arg_end());
Anders Carlssoned4e3672009-05-31 20:21:44 +0000580 }
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000581
Anders Carlssonf1108532009-06-01 00:05:16 +0000582 if (NullCheckResult) {
583 Builder.CreateBr(NewEnd);
584 EmitBlock(NewNull);
585 Builder.CreateBr(NewEnd);
586 EmitBlock(NewEnd);
587
588 llvm::PHINode *PHI = Builder.CreatePHI(NewPtr->getType());
589 PHI->reserveOperandSpace(2);
590 PHI->addIncoming(NewPtr, NewNotNull);
Owen Andersonc9c88b42009-07-31 20:28:54 +0000591 PHI->addIncoming(llvm::Constant::getNullValue(NewPtr->getType()), NewNull);
Anders Carlssonf1108532009-06-01 00:05:16 +0000592
593 NewPtr = PHI;
594 }
595
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000596 return NewPtr;
Anders Carlssona00703d2009-05-31 01:40:14 +0000597}
598
Anders Carlsson60e282c2009-08-16 21:13:42 +0000599void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
600 if (E->isArrayForm()) {
601 ErrorUnsupported(E, "delete[] expression");
602 return;
603 };
604
605 QualType DeleteTy =
606 E->getArgument()->getType()->getAs<PointerType>()->getPointeeType();
607
608 llvm::Value *Ptr = EmitScalarExpr(E->getArgument());
609
610 // Null check the pointer.
611 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
612 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
613
614 llvm::Value *IsNull =
615 Builder.CreateICmpEQ(Ptr, llvm::Constant::getNullValue(Ptr->getType()),
616 "isnull");
617
618 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
619 EmitBlock(DeleteNotNull);
620
621 // Call the destructor if necessary.
622 if (const RecordType *RT = DeleteTy->getAs<RecordType>()) {
623 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
624 if (!RD->hasTrivialDestructor()) {
625 const CXXDestructorDecl *Dtor = RD->getDestructor(getContext());
626 if (Dtor->isVirtual()) {
627 ErrorUnsupported(E, "delete expression with virtual destructor");
628 return;
629 }
630
631 EmitCXXDestructorCall(Dtor, Dtor_Complete, Ptr);
632 }
633 }
634 }
635
636 // Call delete.
637 FunctionDecl *DeleteFD = E->getOperatorDelete();
638 const FunctionProtoType *DeleteFTy =
639 DeleteFD->getType()->getAsFunctionProtoType();
640
641 CallArgList DeleteArgs;
642
643 QualType ArgTy = DeleteFTy->getArgType(0);
644 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
645 DeleteArgs.push_back(std::make_pair(RValue::get(DeletePtr), ArgTy));
646
647 // Emit the call to delete.
648 EmitCall(CGM.getTypes().getFunctionInfo(DeleteFTy->getResultType(),
649 DeleteArgs),
650 CGM.GetAddrOfFunction(GlobalDecl(DeleteFD)),
651 DeleteArgs, DeleteFD);
652
653 EmitBlock(DeleteEnd);
654}
655
Anders Carlsson27ae5362009-04-17 01:58:57 +0000656static bool canGenerateCXXstructor(const CXXRecordDecl *RD,
657 ASTContext &Context) {
Anders Carlsson59d8e0f2009-04-15 21:02:13 +0000658 // The class has base classes - we don't support that right now.
659 if (RD->getNumBases() > 0)
660 return false;
661
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000662 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
663 I != E; ++I) {
Anders Carlsson59d8e0f2009-04-15 21:02:13 +0000664 // We don't support ctors for fields that aren't POD.
665 if (!I->getType()->isPODType())
666 return false;
667 }
668
669 return true;
670}
671
Anders Carlsson95d4e5d2009-04-15 15:55:24 +0000672void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) {
Anders Carlsson27ae5362009-04-17 01:58:57 +0000673 if (!canGenerateCXXstructor(D->getParent(), getContext())) {
Anders Carlsson59d8e0f2009-04-15 21:02:13 +0000674 ErrorUnsupported(D, "C++ constructor", true);
675 return;
676 }
Anders Carlsson95d4e5d2009-04-15 15:55:24 +0000677
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000678 EmitGlobal(GlobalDecl(D, Ctor_Complete));
679 EmitGlobal(GlobalDecl(D, Ctor_Base));
Anders Carlsson95d4e5d2009-04-15 15:55:24 +0000680}
Anders Carlsson363c1842009-04-16 23:57:24 +0000681
Anders Carlsson27ae5362009-04-17 01:58:57 +0000682void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D,
683 CXXCtorType Type) {
684
685 llvm::Function *Fn = GetAddrOfCXXConstructor(D, Type);
686
687 CodeGenFunction(*this).GenerateCode(D, Fn);
688
689 SetFunctionDefinitionAttributes(D, Fn);
690 SetLLVMFunctionAttributesForDefinition(D, Fn);
691}
692
Anders Carlsson363c1842009-04-16 23:57:24 +0000693llvm::Function *
694CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
695 CXXCtorType Type) {
696 const llvm::FunctionType *FTy =
697 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false);
698
699 const char *Name = getMangledCXXCtorName(D, Type);
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000700 return cast<llvm::Function>(
701 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson363c1842009-04-16 23:57:24 +0000702}
Anders Carlsson27ae5362009-04-17 01:58:57 +0000703
704const char *CodeGenModule::getMangledCXXCtorName(const CXXConstructorDecl *D,
705 CXXCtorType Type) {
706 llvm::SmallString<256> Name;
707 llvm::raw_svector_ostream Out(Name);
708 mangleCXXCtor(D, Type, Context, Out);
709
710 Name += '\0';
711 return UniqueMangledName(Name.begin(), Name.end());
712}
713
714void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) {
715 if (!canGenerateCXXstructor(D->getParent(), getContext())) {
716 ErrorUnsupported(D, "C++ destructor", true);
717 return;
718 }
719
720 EmitCXXDestructor(D, Dtor_Complete);
721 EmitCXXDestructor(D, Dtor_Base);
722}
723
724void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D,
725 CXXDtorType Type) {
726 llvm::Function *Fn = GetAddrOfCXXDestructor(D, Type);
727
728 CodeGenFunction(*this).GenerateCode(D, Fn);
729
730 SetFunctionDefinitionAttributes(D, Fn);
731 SetLLVMFunctionAttributesForDefinition(D, Fn);
732}
733
734llvm::Function *
735CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D,
736 CXXDtorType Type) {
737 const llvm::FunctionType *FTy =
738 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false);
739
740 const char *Name = getMangledCXXDtorName(D, Type);
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000741 return cast<llvm::Function>(
742 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson27ae5362009-04-17 01:58:57 +0000743}
744
745const char *CodeGenModule::getMangledCXXDtorName(const CXXDestructorDecl *D,
746 CXXDtorType Type) {
747 llvm::SmallString<256> Name;
748 llvm::raw_svector_ostream Out(Name);
749 mangleCXXDtor(D, Type, Context, Out);
750
751 Name += '\0';
752 return UniqueMangledName(Name.begin(), Name.end());
753}
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +0000754
Mike Stump32f37012009-08-18 21:49:00 +0000755llvm::Constant *CodeGenModule::GenerateRtti(const CXXRecordDecl *RD) {
Mike Stump738f8c22009-07-31 23:15:31 +0000756 llvm::Type *Ptr8Ty;
Owen Anderson0032b272009-08-13 21:57:51 +0000757 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Mike Stumpcb1b5d32009-08-04 20:06:48 +0000758 llvm::Constant *Rtti = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stump738f8c22009-07-31 23:15:31 +0000759
760 if (!getContext().getLangOptions().Rtti)
Mike Stumpcb1b5d32009-08-04 20:06:48 +0000761 return Rtti;
Mike Stump738f8c22009-07-31 23:15:31 +0000762
763 llvm::SmallString<256> OutName;
764 llvm::raw_svector_ostream Out(OutName);
765 QualType ClassTy;
Mike Stumpe607ed02009-08-07 18:05:12 +0000766 ClassTy = getContext().getTagDeclType(RD);
Mike Stump738f8c22009-07-31 23:15:31 +0000767 mangleCXXRtti(ClassTy, getContext(), Out);
Mike Stump738f8c22009-07-31 23:15:31 +0000768 llvm::GlobalVariable::LinkageTypes linktype;
769 linktype = llvm::GlobalValue::WeakAnyLinkage;
770 std::vector<llvm::Constant *> info;
Mike Stump4ef98092009-08-13 22:53:07 +0000771 // assert(0 && "FIXME: implement rtti descriptor");
Mike Stump738f8c22009-07-31 23:15:31 +0000772 // FIXME: descriptor
773 info.push_back(llvm::Constant::getNullValue(Ptr8Ty));
Mike Stump4ef98092009-08-13 22:53:07 +0000774 // assert(0 && "FIXME: implement rtti ts");
Mike Stump738f8c22009-07-31 23:15:31 +0000775 // FIXME: TS
776 info.push_back(llvm::Constant::getNullValue(Ptr8Ty));
777
778 llvm::Constant *C;
779 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, info.size());
780 C = llvm::ConstantArray::get(type, info);
Mike Stump32f37012009-08-18 21:49:00 +0000781 Rtti = new llvm::GlobalVariable(getModule(), type, true, linktype, C,
Daniel Dunbar77659342009-08-19 20:04:03 +0000782 Out.str());
Mike Stumpcb1b5d32009-08-04 20:06:48 +0000783 Rtti = llvm::ConstantExpr::getBitCast(Rtti, Ptr8Ty);
784 return Rtti;
Mike Stump738f8c22009-07-31 23:15:31 +0000785}
786
Mike Stumpeb7e9c32009-08-19 18:10:47 +0000787class VtableBuilder {
Mike Stump7c435fa2009-08-18 20:50:28 +0000788 std::vector<llvm::Constant *> &methods;
789 llvm::Type *Ptr8Ty;
Mike Stump32f37012009-08-18 21:49:00 +0000790 const CXXRecordDecl *Class;
Mike Stumpb46c92d2009-08-19 02:06:38 +0000791 const ASTRecordLayout &BLayout;
Mike Stumpee560f32009-08-19 14:40:47 +0000792 llvm::SmallSet<const CXXRecordDecl *, 32> IndirectPrimary;
Mike Stump32f37012009-08-18 21:49:00 +0000793 llvm::Constant *rtti;
Mike Stump7c435fa2009-08-18 20:50:28 +0000794 llvm::LLVMContext &VMContext;
Mike Stump65defe32009-08-18 21:03:28 +0000795 CodeGenModule &CGM; // Per-module state.
Mike Stump552b2752009-08-18 22:04:08 +0000796
797 typedef CXXRecordDecl::method_iterator method_iter;
Mike Stump7c435fa2009-08-18 20:50:28 +0000798public:
Mike Stumpeb7e9c32009-08-19 18:10:47 +0000799 VtableBuilder(std::vector<llvm::Constant *> &meth,
800 const CXXRecordDecl *c,
801 CodeGenModule &cgm)
Mike Stumpb46c92d2009-08-19 02:06:38 +0000802 : methods(meth), Class(c), BLayout(cgm.getContext().getASTRecordLayout(c)),
803 rtti(cgm.GenerateRtti(c)), VMContext(cgm.getModule().getContext()),
804 CGM(cgm) {
Mike Stump7c435fa2009-08-18 20:50:28 +0000805 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
806 }
Mike Stump32f37012009-08-18 21:49:00 +0000807
Mike Stumpb46c92d2009-08-19 02:06:38 +0000808 llvm::Constant *GenerateVcall(const CXXMethodDecl *MD,
809 const CXXRecordDecl *RD,
810 bool VBoundary,
811 bool SecondaryVirtual) {
812 llvm::Constant *m = 0;
813
814 // FIXME: vcall: offset for virtual base for this function
815 if (SecondaryVirtual || VBoundary)
816 m = llvm::Constant::getNullValue(Ptr8Ty);
817 return m;
818 }
819
820 void GenerateVcalls(const CXXRecordDecl *RD, bool VBoundary,
821 bool SecondaryVirtual) {
Mike Stump7c435fa2009-08-18 20:50:28 +0000822 llvm::Constant *m;
Mike Stump80a0e322009-08-12 23:25:18 +0000823
Mike Stump552b2752009-08-18 22:04:08 +0000824 for (method_iter mi = RD->method_begin(),
Mike Stump7c435fa2009-08-18 20:50:28 +0000825 me = RD->method_end(); mi != me; ++mi) {
826 if (mi->isVirtual()) {
Mike Stumpb46c92d2009-08-19 02:06:38 +0000827 m = GenerateVcall(*mi, RD, VBoundary, SecondaryVirtual);
828 if (m)
829 methods.push_back(m);
Mike Stump7c435fa2009-08-18 20:50:28 +0000830 }
Mike Stump4c3aedd2009-08-12 23:14:12 +0000831 }
Mike Stump80a0e322009-08-12 23:25:18 +0000832 }
Mike Stump4c3aedd2009-08-12 23:14:12 +0000833
Mike Stump65defe32009-08-18 21:03:28 +0000834 void GenerateMethods(const CXXRecordDecl *RD) {
Mike Stump65defe32009-08-18 21:03:28 +0000835 llvm::Constant *m;
Mike Stumpbc16aea2009-08-12 23:00:59 +0000836
Mike Stump552b2752009-08-18 22:04:08 +0000837 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
Mike Stump65defe32009-08-18 21:03:28 +0000838 ++mi) {
839 if (mi->isVirtual()) {
840 m = CGM.GetAddrOfFunction(GlobalDecl(*mi));
841 m = llvm::ConstantExpr::getBitCast(m, Ptr8Ty);
842 methods.push_back(m);
843 }
Mike Stumpbc16aea2009-08-12 23:00:59 +0000844 }
845 }
Mike Stump65defe32009-08-18 21:03:28 +0000846
Mike Stump109b13d2009-08-18 21:30:21 +0000847 void GenerateVtableForBase(const CXXRecordDecl *RD,
848 bool forPrimary,
Mike Stumpb46c92d2009-08-19 02:06:38 +0000849 bool VBoundary,
Mike Stump109b13d2009-08-18 21:30:21 +0000850 int64_t Offset,
Mike Stumpee560f32009-08-19 14:40:47 +0000851 bool ForVirtualBase) {
Mike Stump109b13d2009-08-18 21:30:21 +0000852 llvm::Constant *m = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stump276b9f12009-08-16 01:46:26 +0000853
Mike Stump109b13d2009-08-18 21:30:21 +0000854 if (RD && !RD->isDynamicClass())
855 return;
856
857 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
858 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
859 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
860
Mike Stumpb46c92d2009-08-19 02:06:38 +0000861 if (VBoundary || forPrimary || ForVirtualBase) {
862 // then comes the the vcall offsets for all our functions...
863 GenerateVcalls(RD, VBoundary, !forPrimary && ForVirtualBase);
864 }
865
Mike Stump109b13d2009-08-18 21:30:21 +0000866 // The virtual base offsets come first...
867 // FIXME: Audit, is this right?
Mike Stump09765ec2009-08-19 02:53:08 +0000868 if (PrimaryBase == 0 || forPrimary || !PrimaryBaseWasVirtual) {
Mike Stump109b13d2009-08-18 21:30:21 +0000869 llvm::SmallSet<const CXXRecordDecl *, 32> SeenVBase;
870 std::vector<llvm::Constant *> offsets;
871 GenerateVBaseOffsets(offsets, RD, SeenVBase, Offset, Layout);
872 for (std::vector<llvm::Constant *>::reverse_iterator i = offsets.rbegin(),
873 e = offsets.rend(); i != e; ++i)
874 methods.push_back(*i);
875 }
876
Mike Stump109b13d2009-08-18 21:30:21 +0000877 bool Top = true;
878
879 // vtables are composed from the chain of primaries.
880 if (PrimaryBase) {
881 if (PrimaryBaseWasVirtual)
882 IndirectPrimary.insert(PrimaryBase);
883 Top = false;
Mike Stumpb46c92d2009-08-19 02:06:38 +0000884 GenerateVtableForBase(PrimaryBase, true, PrimaryBaseWasVirtual|VBoundary,
Mike Stumpee560f32009-08-19 14:40:47 +0000885 Offset, PrimaryBaseWasVirtual);
Mike Stump109b13d2009-08-18 21:30:21 +0000886 }
887
888 if (Top) {
889 int64_t BaseOffset;
890 if (ForVirtualBase) {
Mike Stump109b13d2009-08-18 21:30:21 +0000891 BaseOffset = -(BLayout.getVBaseClassOffset(RD) / 8);
892 } else
893 BaseOffset = -Offset/8;
Mike Stump276b9f12009-08-16 01:46:26 +0000894 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), BaseOffset);
895 m = llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
896 methods.push_back(m);
Mike Stump109b13d2009-08-18 21:30:21 +0000897 methods.push_back(rtti);
Mike Stump276b9f12009-08-16 01:46:26 +0000898 }
Mike Stump4ef98092009-08-13 22:53:07 +0000899
Mike Stump109b13d2009-08-18 21:30:21 +0000900 // And add the virtuals for the class to the primary vtable.
901 GenerateMethods(RD);
902
903 // and then the non-virtual bases.
904 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
905 e = RD->bases_end(); i != e; ++i) {
906 if (i->isVirtual())
907 continue;
908 const CXXRecordDecl *Base =
909 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
910 if (Base != PrimaryBase || PrimaryBaseWasVirtual) {
911 uint64_t o = Offset + Layout.getBaseClassOffset(Base);
Mike Stumpee560f32009-08-19 14:40:47 +0000912 GenerateVtableForBase(Base, true, false, o, false);
Mike Stump109b13d2009-08-18 21:30:21 +0000913 }
914 }
915 }
916
917 void GenerateVtableForVBases(const CXXRecordDecl *RD,
Mike Stumpee560f32009-08-19 14:40:47 +0000918 const CXXRecordDecl *Class) {
Mike Stump109b13d2009-08-18 21:30:21 +0000919 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
920 e = RD->bases_end(); i != e; ++i) {
921 const CXXRecordDecl *Base =
922 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
923 if (i->isVirtual() && !IndirectPrimary.count(Base)) {
924 // Mark it so we don't output it twice.
925 IndirectPrimary.insert(Base);
Mike Stumpee560f32009-08-19 14:40:47 +0000926 GenerateVtableForBase(Base, false, true, 0, true);
Mike Stump109b13d2009-08-18 21:30:21 +0000927 }
928 if (Base->getNumVBases())
Mike Stumpee560f32009-08-19 14:40:47 +0000929 GenerateVtableForVBases(Base, Class);
Mike Stump276b9f12009-08-16 01:46:26 +0000930 }
931 }
Mike Stump109b13d2009-08-18 21:30:21 +0000932
933 void GenerateVBaseOffsets(std::vector<llvm::Constant *> &offsets,
934 const CXXRecordDecl *RD,
935 llvm::SmallSet<const CXXRecordDecl *, 32> &SeenVBase,
Mike Stumpcc2a0122009-08-19 14:06:50 +0000936 uint64_t Offset, const ASTRecordLayout &Layout) {
Mike Stump109b13d2009-08-18 21:30:21 +0000937 for (CXXRecordDecl::base_class_const_iterator i =RD->bases_begin(),
938 e = RD->bases_end(); i != e; ++i) {
939 const CXXRecordDecl *Base =
940 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
941 if (i->isVirtual() && !SeenVBase.count(Base)) {
942 SeenVBase.insert(Base);
Mike Stumpcc2a0122009-08-19 14:06:50 +0000943 int64_t BaseOffset = Offset/8 + Layout.getVBaseClassOffset(Base) / 8;
Mike Stump109b13d2009-08-18 21:30:21 +0000944 llvm::Constant *m;
945 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), BaseOffset);
946 m = llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
947 offsets.push_back(m);
948 }
Mike Stumpcc2a0122009-08-19 14:06:50 +0000949 GenerateVBaseOffsets(offsets, Base, SeenVBase, Offset, Layout);
Mike Stump109b13d2009-08-18 21:30:21 +0000950 }
951 }
952};
Mike Stump8a12b562009-08-06 15:50:11 +0000953
Mike Stumpf1216772009-07-31 18:25:34 +0000954llvm::Value *CodeGenFunction::GenerateVtable(const CXXRecordDecl *RD) {
Mike Stumpf1216772009-07-31 18:25:34 +0000955 llvm::SmallString<256> OutName;
956 llvm::raw_svector_ostream Out(OutName);
957 QualType ClassTy;
Mike Stumpe607ed02009-08-07 18:05:12 +0000958 ClassTy = getContext().getTagDeclType(RD);
Mike Stumpf1216772009-07-31 18:25:34 +0000959 mangleCXXVtable(ClassTy, getContext(), Out);
Mike Stump82b56962009-07-31 21:43:43 +0000960 llvm::GlobalVariable::LinkageTypes linktype;
961 linktype = llvm::GlobalValue::WeakAnyLinkage;
962 std::vector<llvm::Constant *> methods;
Mike Stump276b9f12009-08-16 01:46:26 +0000963 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
Mike Stump6f376332009-08-05 22:37:18 +0000964 int64_t Offset = 0;
Mike Stumpe1be2b12009-08-06 21:49:36 +0000965
966 Offset += LLVMPointerWidth;
967 Offset += LLVMPointerWidth;
Mike Stump6f376332009-08-05 22:37:18 +0000968
Mike Stumpeb7e9c32009-08-19 18:10:47 +0000969 VtableBuilder b(methods, RD, CGM);
Mike Stump109b13d2009-08-18 21:30:21 +0000970
Mike Stump276b9f12009-08-16 01:46:26 +0000971 // First comes the vtables for all the non-virtual bases...
Mike Stumpee560f32009-08-19 14:40:47 +0000972 b.GenerateVtableForBase(RD, true, false, 0, false);
Mike Stump21538912009-08-14 01:44:03 +0000973
Mike Stump276b9f12009-08-16 01:46:26 +0000974 // then the vtables for all the virtual bases.
Mike Stumpee560f32009-08-19 14:40:47 +0000975 b.GenerateVtableForVBases(RD, RD);
Mike Stump104ffaa2009-08-04 21:58:42 +0000976
Mike Stump82b56962009-07-31 21:43:43 +0000977 llvm::Constant *C;
978 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, methods.size());
979 C = llvm::ConstantArray::get(type, methods);
980 llvm::Value *vtable = new llvm::GlobalVariable(CGM.getModule(), type, true,
Daniel Dunbar77659342009-08-19 20:04:03 +0000981 linktype, C, Out.str());
Mike Stumpf1216772009-07-31 18:25:34 +0000982 vtable = Builder.CreateBitCast(vtable, Ptr8Ty);
Mike Stumpf1216772009-07-31 18:25:34 +0000983 vtable = Builder.CreateGEP(vtable,
Mike Stump276b9f12009-08-16 01:46:26 +0000984 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
Mike Stump6f376332009-08-05 22:37:18 +0000985 Offset/8));
Mike Stumpf1216772009-07-31 18:25:34 +0000986 return vtable;
987}
988
Fariborz Jahanianca283612009-08-07 23:51:33 +0000989/// EmitClassMemberwiseCopy - This routine generates code to copy a class
990/// object from SrcValue to DestValue. Copying can be either a bitwise copy
991/// of via a copy constructor call.
992void CodeGenFunction::EmitClassMemberwiseCopy(
Fariborz Jahanian942f4f32009-08-08 23:32:22 +0000993 llvm::Value *Dest, llvm::Value *Src,
Fariborz Jahanianca283612009-08-07 23:51:33 +0000994 const CXXRecordDecl *ClassDecl,
Fariborz Jahanian942f4f32009-08-08 23:32:22 +0000995 const CXXRecordDecl *BaseClassDecl, QualType Ty) {
996 if (ClassDecl) {
997 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
998 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
999 }
1000 if (BaseClassDecl->hasTrivialCopyConstructor()) {
1001 EmitAggregateCopy(Dest, Src, Ty);
Fariborz Jahanianca283612009-08-07 23:51:33 +00001002 return;
Fariborz Jahanian942f4f32009-08-08 23:32:22 +00001003 }
1004
Fariborz Jahanianca283612009-08-07 23:51:33 +00001005 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian80e4b9e2009-08-08 00:59:58 +00001006 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
Fariborz Jahanianca283612009-08-07 23:51:33 +00001007 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
1008 Ctor_Complete);
Fariborz Jahanianca283612009-08-07 23:51:33 +00001009 CallArgList CallArgs;
1010 // Push the this (Dest) ptr.
1011 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1012 BaseCopyCtor->getThisType(getContext())));
1013
Fariborz Jahanianca283612009-08-07 23:51:33 +00001014 // Push the Src ptr.
1015 CallArgs.push_back(std::make_pair(RValue::get(Src),
Fariborz Jahanian370c8842009-08-10 17:20:45 +00001016 BaseCopyCtor->getParamDecl(0)->getType()));
Fariborz Jahanianca283612009-08-07 23:51:33 +00001017 QualType ResultType =
1018 BaseCopyCtor->getType()->getAsFunctionType()->getResultType();
1019 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1020 Callee, CallArgs, BaseCopyCtor);
1021 }
1022}
Fariborz Jahanian06f598a2009-08-10 18:46:38 +00001023
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001024/// EmitClassCopyAssignment - This routine generates code to copy assign a class
1025/// object from SrcValue to DestValue. Assignment can be either a bitwise
1026/// assignment of via an assignment operator call.
1027void CodeGenFunction::EmitClassCopyAssignment(
1028 llvm::Value *Dest, llvm::Value *Src,
1029 const CXXRecordDecl *ClassDecl,
1030 const CXXRecordDecl *BaseClassDecl,
1031 QualType Ty) {
1032 if (ClassDecl) {
1033 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
1034 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
1035 }
1036 if (BaseClassDecl->hasTrivialCopyAssignment()) {
1037 EmitAggregateCopy(Dest, Src, Ty);
1038 return;
1039 }
1040
1041 const CXXMethodDecl *MD = 0;
Fariborz Jahaniane82c3e22009-08-13 00:53:36 +00001042 bool ConstCopyAssignOp = BaseClassDecl->hasConstCopyAssignment(getContext(),
1043 MD);
1044 assert(ConstCopyAssignOp && "EmitClassCopyAssignment - missing copy assign");
1045 (void)ConstCopyAssignOp;
1046
1047 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
1048 const llvm::Type *LTy =
1049 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1050 FPT->isVariadic());
1051 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), LTy);
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001052
Fariborz Jahaniane82c3e22009-08-13 00:53:36 +00001053 CallArgList CallArgs;
1054 // Push the this (Dest) ptr.
1055 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1056 MD->getThisType(getContext())));
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001057
Fariborz Jahaniane82c3e22009-08-13 00:53:36 +00001058 // Push the Src ptr.
1059 CallArgs.push_back(std::make_pair(RValue::get(Src),
1060 MD->getParamDecl(0)->getType()));
1061 QualType ResultType =
1062 MD->getType()->getAsFunctionType()->getResultType();
1063 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1064 Callee, CallArgs, MD);
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001065}
1066
Fariborz Jahanian06f598a2009-08-10 18:46:38 +00001067/// SynthesizeDefaultConstructor - synthesize a default constructor
1068void
1069CodeGenFunction::SynthesizeDefaultConstructor(const CXXConstructorDecl *CD,
1070 const FunctionDecl *FD,
1071 llvm::Function *Fn,
1072 const FunctionArgList &Args) {
1073 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1074 EmitCtorPrologue(CD);
1075 FinishFunction();
1076}
1077
Fariborz Jahanian8c241a22009-08-08 19:31:03 +00001078/// SynthesizeCXXCopyConstructor - This routine implicitly defines body of a copy
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001079/// constructor, in accordance with section 12.8 (p7 and p8) of C++03
1080/// The implicitly-defined copy constructor for class X performs a memberwise
1081/// copy of its subobjects. The order of copying is the same as the order
1082/// of initialization of bases and members in a user-defined constructor
1083/// Each subobject is copied in the manner appropriate to its type:
1084/// if the subobject is of class type, the copy constructor for the class is
1085/// used;
1086/// if the subobject is an array, each element is copied, in the manner
1087/// appropriate to the element type;
1088/// if the subobject is of scalar type, the built-in assignment operator is
1089/// used.
1090/// Virtual base class subobjects shall be copied only once by the
1091/// implicitly-defined copy constructor
1092
Fariborz Jahanian8c241a22009-08-08 19:31:03 +00001093void CodeGenFunction::SynthesizeCXXCopyConstructor(const CXXConstructorDecl *CD,
1094 const FunctionDecl *FD,
1095 llvm::Function *Fn,
Fariborz Jahanianca283612009-08-07 23:51:33 +00001096 const FunctionArgList &Args) {
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001097 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1098 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
Fariborz Jahanian8c241a22009-08-08 19:31:03 +00001099 "SynthesizeCXXCopyConstructor - copy constructor has definition already");
1100 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001101
Fariborz Jahanian1e4edd52009-08-08 00:15:41 +00001102 FunctionArgList::const_iterator i = Args.begin();
1103 const VarDecl *ThisArg = i->first;
1104 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1105 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1106 const VarDecl *SrcArg = (i+1)->first;
1107 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1108 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1109
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001110 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1111 Base != ClassDecl->bases_end(); ++Base) {
1112 // FIXME. copy constrution of virtual base NYI
1113 if (Base->isVirtual())
1114 continue;
Fariborz Jahanianca283612009-08-07 23:51:33 +00001115
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001116 CXXRecordDecl *BaseClassDecl
1117 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian942f4f32009-08-08 23:32:22 +00001118 EmitClassMemberwiseCopy(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1119 Base->getType());
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001120 }
1121
Fariborz Jahanian1e4edd52009-08-08 00:15:41 +00001122 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1123 FieldEnd = ClassDecl->field_end();
1124 Field != FieldEnd; ++Field) {
1125 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
1126
1127 // FIXME. How about copying arrays!
1128 assert(!getContext().getAsArrayType(FieldType) &&
1129 "FIXME. Copying arrays NYI");
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001130
Fariborz Jahanian1e4edd52009-08-08 00:15:41 +00001131 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1132 CXXRecordDecl *FieldClassDecl
1133 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1134 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1135 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Fariborz Jahanian942f4f32009-08-08 23:32:22 +00001136
Fariborz Jahanian1e4edd52009-08-08 00:15:41 +00001137 EmitClassMemberwiseCopy(LHS.getAddress(), RHS.getAddress(),
Fariborz Jahanian942f4f32009-08-08 23:32:22 +00001138 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanian1e4edd52009-08-08 00:15:41 +00001139 continue;
1140 }
Fariborz Jahanianf05fe652009-08-10 18:34:26 +00001141 // Do a built-in assignment of scalar data members.
1142 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1143 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1144 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1145 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanian1e4edd52009-08-08 00:15:41 +00001146 }
Fariborz Jahanian8c241a22009-08-08 19:31:03 +00001147 FinishFunction();
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001148}
1149
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001150/// SynthesizeCXXCopyAssignment - Implicitly define copy assignment operator.
1151/// Before the implicitly-declared copy assignment operator for a class is
1152/// implicitly defined, all implicitly- declared copy assignment operators for
1153/// its direct base classes and its nonstatic data members shall have been
1154/// implicitly defined. [12.8-p12]
1155/// The implicitly-defined copy assignment operator for class X performs
1156/// memberwise assignment of its subob- jects. The direct base classes of X are
1157/// assigned first, in the order of their declaration in
1158/// the base-specifier-list, and then the immediate nonstatic data members of X
1159/// are assigned, in the order in which they were declared in the class
1160/// definition.Each subobject is assigned in the manner appropriate to its type:
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001161/// if the subobject is of class type, the copy assignment operator for the
1162/// class is used (as if by explicit qualification; that is, ignoring any
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001163/// possible virtual overriding functions in more derived classes);
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001164///
1165/// if the subobject is an array, each element is assigned, in the manner
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001166/// appropriate to the element type;
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001167///
1168/// if the subobject is of scalar type, the built-in assignment operator is
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001169/// used.
1170void CodeGenFunction::SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD,
1171 const FunctionDecl *FD,
1172 llvm::Function *Fn,
1173 const FunctionArgList &Args) {
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001174
1175 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1176 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
1177 "SynthesizeCXXCopyAssignment - copy assignment has user declaration");
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001178 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1179
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001180 FunctionArgList::const_iterator i = Args.begin();
1181 const VarDecl *ThisArg = i->first;
1182 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1183 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1184 const VarDecl *SrcArg = (i+1)->first;
1185 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1186 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1187
1188 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1189 Base != ClassDecl->bases_end(); ++Base) {
1190 // FIXME. copy assignment of virtual base NYI
1191 if (Base->isVirtual())
1192 continue;
1193
1194 CXXRecordDecl *BaseClassDecl
1195 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1196 EmitClassCopyAssignment(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1197 Base->getType());
1198 }
1199
1200 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1201 FieldEnd = ClassDecl->field_end();
1202 Field != FieldEnd; ++Field) {
1203 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
1204
1205 // FIXME. How about copy assignment of arrays!
1206 assert(!getContext().getAsArrayType(FieldType) &&
1207 "FIXME. Copy assignment of arrays NYI");
1208
1209 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1210 CXXRecordDecl *FieldClassDecl
1211 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1212 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1213 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1214
1215 EmitClassCopyAssignment(LHS.getAddress(), RHS.getAddress(),
1216 0 /*ClassDecl*/, FieldClassDecl, FieldType);
1217 continue;
1218 }
1219 // Do a built-in assignment of scalar data members.
1220 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1221 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1222 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1223 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanian183d7182009-08-14 00:01:54 +00001224 }
1225
1226 // return *this;
1227 Builder.CreateStore(LoadOfThis, ReturnValue);
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001228
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001229 FinishFunction();
1230}
Fariborz Jahanian97a93752009-08-07 20:22:40 +00001231
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001232/// EmitCtorPrologue - This routine generates necessary code to initialize
1233/// base classes and non-static data members belonging to this constructor.
1234void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD) {
Fariborz Jahanian742cd1b2009-07-25 21:12:28 +00001235 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
Mike Stumpeb19fa92009-08-06 13:41:24 +00001236 // FIXME: Add vbase initialization
Mike Stumpf1216772009-07-31 18:25:34 +00001237 llvm::Value *LoadOfThis = 0;
Fariborz Jahanian6d0bdaa2009-07-28 18:09:28 +00001238
Fariborz Jahanian742cd1b2009-07-25 21:12:28 +00001239 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001240 E = CD->init_end();
1241 B != E; ++B) {
1242 CXXBaseOrMemberInitializer *Member = (*B);
1243 if (Member->isBaseInitializer()) {
Mike Stumpf1216772009-07-31 18:25:34 +00001244 LoadOfThis = LoadCXXThis();
Fariborz Jahanian6d0bdaa2009-07-28 18:09:28 +00001245 Type *BaseType = Member->getBaseClass();
1246 CXXRecordDecl *BaseClassDecl =
Ted Kremenek6217b802009-07-29 21:53:49 +00001247 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
Fariborz Jahanian6d0bdaa2009-07-28 18:09:28 +00001248 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1249 BaseClassDecl);
Fariborz Jahanian742cd1b2009-07-25 21:12:28 +00001250 EmitCXXConstructorCall(Member->getConstructor(),
1251 Ctor_Complete, V,
1252 Member->const_arg_begin(),
1253 Member->const_arg_end());
Mike Stumpb3589f42009-07-30 22:28:39 +00001254 } else {
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001255 // non-static data member initilaizers.
1256 FieldDecl *Field = Member->getMember();
1257 QualType FieldType = getContext().getCanonicalType((Field)->getType());
1258 assert(!getContext().getAsArrayType(FieldType)
1259 && "FIXME. Field arrays initialization unsupported");
Fariborz Jahanian8c64e002009-08-10 23:56:17 +00001260
Mike Stumpf1216772009-07-31 18:25:34 +00001261 LoadOfThis = LoadCXXThis();
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001262 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
Ted Kremenek6217b802009-07-29 21:53:49 +00001263 if (FieldType->getAs<RecordType>()) {
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001264 if (!Field->isAnonymousStructOrUnion()) {
Fariborz Jahanian50b8eea2009-07-24 17:57:02 +00001265 assert(Member->getConstructor() &&
1266 "EmitCtorPrologue - no constructor to initialize member");
1267 EmitCXXConstructorCall(Member->getConstructor(),
1268 Ctor_Complete, LHS.getAddress(),
1269 Member->const_arg_begin(),
1270 Member->const_arg_end());
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001271 continue;
1272 }
1273 else {
1274 // Initializing an anonymous union data member.
1275 FieldDecl *anonMember = Member->getAnonUnionMember();
1276 LHS = EmitLValueForField(LHS.getAddress(), anonMember, false, 0);
1277 FieldType = anonMember->getType();
1278 }
Fariborz Jahanian50b8eea2009-07-24 17:57:02 +00001279 }
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001280
1281 assert(Member->getNumArgs() == 1 && "Initializer count must be 1 only");
Fariborz Jahanian50b8eea2009-07-24 17:57:02 +00001282 Expr *RhsExpr = *Member->arg_begin();
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001283 llvm::Value *RHS = EmitScalarExpr(RhsExpr, true);
Fariborz Jahanian8c64e002009-08-10 23:56:17 +00001284 EmitStoreThroughLValue(RValue::get(RHS), LHS, FieldType);
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001285 }
1286 }
Mike Stumpf1216772009-07-31 18:25:34 +00001287
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001288 if (!CD->getNumBaseOrMemberInitializers() && !CD->isTrivial()) {
Fariborz Jahanian1d9b5ef2009-08-15 18:55:17 +00001289 // Nontrivial default constructor with no initializer list. It may still
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001290 // have bases classes and/or contain non-static data members which require
1291 // construction.
1292 for (CXXRecordDecl::base_class_const_iterator Base =
1293 ClassDecl->bases_begin();
1294 Base != ClassDecl->bases_end(); ++Base) {
1295 // FIXME. copy assignment of virtual base NYI
1296 if (Base->isVirtual())
1297 continue;
1298
1299 CXXRecordDecl *BaseClassDecl
1300 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1301 if (BaseClassDecl->hasTrivialConstructor())
1302 continue;
1303 if (CXXConstructorDecl *BaseCX =
1304 BaseClassDecl->getDefaultConstructor(getContext())) {
1305 LoadOfThis = LoadCXXThis();
1306 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1307 BaseClassDecl);
1308 EmitCXXConstructorCall(BaseCX, Ctor_Complete, V, 0, 0);
1309 }
1310 }
1311
Fariborz Jahanian1d9b5ef2009-08-15 18:55:17 +00001312 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1313 FieldEnd = ClassDecl->field_end();
1314 Field != FieldEnd; ++Field) {
1315 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +00001316 const ConstantArrayType *Array =
1317 getContext().getAsConstantArrayType(FieldType);
1318 if (Array) {
1319 FieldType = Array->getElementType();
1320 while (const ConstantArrayType *AT =
1321 getContext().getAsConstantArrayType(FieldType))
1322 FieldType = AT->getElementType();
1323 }
Fariborz Jahanian1d9b5ef2009-08-15 18:55:17 +00001324 if (!FieldType->getAs<RecordType>() || Field->isAnonymousStructOrUnion())
1325 continue;
1326 const RecordType *ClassRec = FieldType->getAs<RecordType>();
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001327 CXXRecordDecl *MemberClassDecl =
1328 dyn_cast<CXXRecordDecl>(ClassRec->getDecl());
1329 if (!MemberClassDecl || MemberClassDecl->hasTrivialConstructor())
1330 continue;
1331 if (CXXConstructorDecl *MamberCX =
1332 MemberClassDecl->getDefaultConstructor(getContext())) {
1333 LoadOfThis = LoadCXXThis();
1334 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
Fariborz Jahanian288dcaf2009-08-19 20:55:16 +00001335 if (Array) {
1336 const llvm::Type *BasePtr = ConvertType(FieldType);
1337 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1338 llvm::Value *BaseAddrPtr =
1339 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1340 EmitCXXAggrConstructorCall(MamberCX, Array, BaseAddrPtr);
1341 }
1342 else
1343 EmitCXXConstructorCall(MamberCX, Ctor_Complete, LHS.getAddress(),
1344 0, 0);
Fariborz Jahanian1d9b5ef2009-08-15 18:55:17 +00001345 }
1346 }
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001347 }
1348
Mike Stumpf1216772009-07-31 18:25:34 +00001349 // Initialize the vtable pointer
Mike Stumpb502d832009-08-05 22:59:44 +00001350 if (ClassDecl->isDynamicClass()) {
Mike Stumpf1216772009-07-31 18:25:34 +00001351 if (!LoadOfThis)
1352 LoadOfThis = LoadCXXThis();
1353 llvm::Value *VtableField;
1354 llvm::Type *Ptr8Ty, *PtrPtr8Ty;
Owen Anderson0032b272009-08-13 21:57:51 +00001355 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Mike Stumpf1216772009-07-31 18:25:34 +00001356 PtrPtr8Ty = llvm::PointerType::get(Ptr8Ty, 0);
1357 VtableField = Builder.CreateBitCast(LoadOfThis, PtrPtr8Ty);
1358 llvm::Value *vtable = GenerateVtable(ClassDecl);
1359 Builder.CreateStore(vtable, VtableField);
1360 }
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +00001361}
Fariborz Jahanian426cc382009-07-30 17:49:11 +00001362
1363/// EmitDtorEpilogue - Emit all code that comes at the end of class's
1364/// destructor. This is to call destructors on members and base classes
1365/// in reverse order of their construction.
1366void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD) {
1367 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(DD->getDeclContext());
1368 assert(!ClassDecl->isPolymorphic() &&
1369 "FIXME. polymorphic destruction not supported");
1370 (void)ClassDecl; // prevent warning.
1371
1372 for (CXXDestructorDecl::destr_const_iterator *B = DD->destr_begin(),
1373 *E = DD->destr_end(); B != E; ++B) {
1374 uintptr_t BaseOrMember = (*B);
1375 if (DD->isMemberToDestroy(BaseOrMember)) {
1376 FieldDecl *FD = DD->getMemberToDestroy(BaseOrMember);
1377 QualType FieldType = getContext().getCanonicalType((FD)->getType());
1378 assert(!getContext().getAsArrayType(FieldType)
1379 && "FIXME. Field arrays destruction unsupported");
1380 const RecordType *RT = FieldType->getAs<RecordType>();
1381 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1382 if (FieldClassDecl->hasTrivialDestructor())
1383 continue;
1384 llvm::Value *LoadOfThis = LoadCXXThis();
1385 LValue LHS = EmitLValueForField(LoadOfThis, FD, false, 0);
1386 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1387 Dtor_Complete, LHS.getAddress());
Mike Stumpb3589f42009-07-30 22:28:39 +00001388 } else {
Fariborz Jahanian426cc382009-07-30 17:49:11 +00001389 const RecordType *RT =
1390 DD->getAnyBaseClassToDestroy(BaseOrMember)->getAs<RecordType>();
1391 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1392 if (BaseClassDecl->hasTrivialDestructor())
1393 continue;
1394 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
1395 ClassDecl,BaseClassDecl);
1396 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1397 Dtor_Complete, V);
1398 }
1399 }
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001400 if (DD->getNumBaseOrMemberDestructions() || DD->isTrivial())
1401 return;
1402 // Case of destructor synthesis with fields and base classes
1403 // which have non-trivial destructors. They must be destructed in
1404 // reverse order of their construction.
1405 llvm::SmallVector<FieldDecl *, 16> DestructedFields;
1406
1407 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1408 FieldEnd = ClassDecl->field_end();
1409 Field != FieldEnd; ++Field) {
1410 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
1411 // FIXME. Assert on arrays for now.
1412 if (const RecordType *RT = FieldType->getAs<RecordType>()) {
1413 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1414 if (FieldClassDecl->hasTrivialDestructor())
1415 continue;
1416 DestructedFields.push_back(*Field);
1417 }
1418 }
1419 if (!DestructedFields.empty())
1420 for (int i = DestructedFields.size() -1; i >= 0; --i) {
1421 FieldDecl *Field = DestructedFields[i];
1422 QualType FieldType = Field->getType();
1423 const RecordType *RT = FieldType->getAs<RecordType>();
1424 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1425 llvm::Value *LoadOfThis = LoadCXXThis();
1426 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
1427 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1428 Dtor_Complete, LHS.getAddress());
1429 }
1430
1431 llvm::SmallVector<CXXRecordDecl*, 4> DestructedBases;
1432 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1433 Base != ClassDecl->bases_end(); ++Base) {
1434 // FIXME. copy assignment of virtual base NYI
1435 if (Base->isVirtual())
1436 continue;
1437
1438 CXXRecordDecl *BaseClassDecl
1439 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1440 if (BaseClassDecl->hasTrivialDestructor())
1441 continue;
1442 DestructedBases.push_back(BaseClassDecl);
1443 }
1444 if (DestructedBases.empty())
1445 return;
1446 for (int i = DestructedBases.size() -1; i >= 0; --i) {
1447 CXXRecordDecl *BaseClassDecl = DestructedBases[i];
1448 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
1449 ClassDecl,BaseClassDecl);
1450 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1451 Dtor_Complete, V);
1452 }
Fariborz Jahanian426cc382009-07-30 17:49:11 +00001453}
Fariborz Jahanian0880bac2009-08-17 19:04:50 +00001454
1455void CodeGenFunction::SynthesizeDefaultDestructor(const CXXDestructorDecl *CD,
1456 const FunctionDecl *FD,
1457 llvm::Function *Fn,
1458 const FunctionArgList &Args) {
1459
1460 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1461 assert(!ClassDecl->hasUserDeclaredDestructor() &&
1462 "SynthesizeDefaultDestructor - destructor has user declaration");
1463 (void) ClassDecl;
1464
1465 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1466 EmitDtorEpilogue(CD);
1467 FinishFunction();
1468}