blob: fce3288be1d5692532933687ede1492504f04fd2 [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");
377
378 // Store the blocks to use for break and continue.
379 // FIXME. Is this needed?
380 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock));
381
382 // Inside the loop body, emit the constructor call on the array element.
383 Counter = Builder.CreateLoad(IndexPtr);
384 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
385 if (const ConstantArrayType *CAT =
386 dyn_cast<ConstantArrayType>(Array->getElementType())) {
387 // Need to call this routine again.
388 EmitCXXAggrConstructorCall(D, CAT, Address);
389 }
390 else
391 EmitCXXConstructorCall(D, Ctor_Complete, Address, 0, 0);
392
393 // FIXME. Do we need this?
394 BreakContinueStack.pop_back();
395
396 EmitBlock(ContinueBlock);
397
398 // Emit the increment of the loop counter.
399 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
400 Counter = Builder.CreateLoad(IndexPtr);
401 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
402 Builder.CreateStore(NextVal, IndexPtr, false);
403
404 // Finally, branch back up to the condition for the next iteration.
405 EmitBranch(CondBlock);
406
407 // Emit the fall-through block.
408 EmitBlock(AfterFor, true);
409
410}
411
Anders Carlsson72f48292009-04-17 00:06:03 +0000412void
413CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
414 CXXCtorType Type,
415 llvm::Value *This,
416 CallExpr::const_arg_iterator ArgBeg,
417 CallExpr::const_arg_iterator ArgEnd) {
Fariborz Jahanian0fc5f252009-08-14 20:11:43 +0000418 if (D->isCopyConstructor(getContext())) {
419 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D->getDeclContext());
420 if (ClassDecl->hasTrivialCopyConstructor()) {
421 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
422 "EmitCXXConstructorCall - user declared copy constructor");
423 const Expr *E = (*ArgBeg);
424 QualType Ty = E->getType();
425 llvm::Value *Src = EmitLValue(E).getAddress();
426 EmitAggregateCopy(This, Src, Ty);
427 return;
428 }
429 }
430
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000431 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
432
433 EmitCXXMemberCall(D, Callee, This, ArgBeg, ArgEnd);
Anders Carlsson72f48292009-04-17 00:06:03 +0000434}
435
Anders Carlssond3f6b162009-05-29 21:03:38 +0000436void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *D,
437 CXXDtorType Type,
438 llvm::Value *This) {
439 llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(D, Type);
440
441 EmitCXXMemberCall(D, Callee, This, 0, 0);
442}
443
Anders Carlsson72f48292009-04-17 00:06:03 +0000444void
Anders Carlsson342aadc2009-05-03 17:47:16 +0000445CodeGenFunction::EmitCXXConstructExpr(llvm::Value *Dest,
446 const CXXConstructExpr *E) {
Anders Carlsson72f48292009-04-17 00:06:03 +0000447 assert(Dest && "Must have a destination!");
448
449 const CXXRecordDecl *RD =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000450 cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson72f48292009-04-17 00:06:03 +0000451 if (RD->hasTrivialConstructor())
452 return;
Fariborz Jahanian884036a2009-08-06 01:02:49 +0000453
454 // Code gen optimization to eliminate copy constructor and return
455 // its first argument instead.
Fariborz Jahanian325cdd82009-08-06 19:12:38 +0000456 if (E->isElidable()) {
Fariborz Jahanian884036a2009-08-06 01:02:49 +0000457 CXXConstructExpr::const_arg_iterator i = E->arg_begin();
Fariborz Jahanian325cdd82009-08-06 19:12:38 +0000458 EmitAggExpr((*i), Dest, false);
459 return;
Fariborz Jahanian884036a2009-08-06 01:02:49 +0000460 }
Anders Carlsson72f48292009-04-17 00:06:03 +0000461 // Call the constructor.
462 EmitCXXConstructorCall(E->getConstructor(), Ctor_Complete, Dest,
463 E->arg_begin(), E->arg_end());
464}
465
Anders Carlsson18e88bc2009-05-31 01:40:14 +0000466llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
Anders Carlssond5536972009-05-31 20:21:44 +0000467 if (E->isArray()) {
468 ErrorUnsupported(E, "new[] expression");
Owen Andersone0b5eff2009-07-30 23:11:26 +0000469 return llvm::UndefValue::get(ConvertType(E->getType()));
Anders Carlssond5536972009-05-31 20:21:44 +0000470 }
471
472 QualType AllocType = E->getAllocatedType();
473 FunctionDecl *NewFD = E->getOperatorNew();
474 const FunctionProtoType *NewFTy = NewFD->getType()->getAsFunctionProtoType();
475
476 CallArgList NewArgs;
477
478 // The allocation size is the first argument.
479 QualType SizeTy = getContext().getSizeType();
480 llvm::Value *AllocSize =
Owen Andersonb17ec712009-07-24 23:12:58 +0000481 llvm::ConstantInt::get(ConvertType(SizeTy),
Anders Carlssond5536972009-05-31 20:21:44 +0000482 getContext().getTypeSize(AllocType) / 8);
483
484 NewArgs.push_back(std::make_pair(RValue::get(AllocSize), SizeTy));
485
486 // Emit the rest of the arguments.
487 // FIXME: Ideally, this should just use EmitCallArgs.
488 CXXNewExpr::const_arg_iterator NewArg = E->placement_arg_begin();
489
490 // First, use the types from the function type.
491 // We start at 1 here because the first argument (the allocation size)
492 // has already been emitted.
493 for (unsigned i = 1, e = NewFTy->getNumArgs(); i != e; ++i, ++NewArg) {
494 QualType ArgType = NewFTy->getArgType(i);
495
496 assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
497 getTypePtr() ==
498 getContext().getCanonicalType(NewArg->getType()).getTypePtr() &&
499 "type mismatch in call argument!");
500
501 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
502 ArgType));
503
504 }
505
506 // Either we've emitted all the call args, or we have a call to a
507 // variadic function.
508 assert((NewArg == E->placement_arg_end() || NewFTy->isVariadic()) &&
509 "Extra arguments in non-variadic function!");
510
511 // If we still have any arguments, emit them using the type of the argument.
512 for (CXXNewExpr::const_arg_iterator NewArgEnd = E->placement_arg_end();
513 NewArg != NewArgEnd; ++NewArg) {
514 QualType ArgType = NewArg->getType();
515 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
516 ArgType));
517 }
518
519 // Emit the call to new.
520 RValue RV =
521 EmitCall(CGM.getTypes().getFunctionInfo(NewFTy->getResultType(), NewArgs),
522 CGM.GetAddrOfFunction(GlobalDecl(NewFD)),
523 NewArgs, NewFD);
524
Anders Carlsson11269042009-05-31 21:53:59 +0000525 // If an allocation function is declared with an empty exception specification
526 // it returns null to indicate failure to allocate storage. [expr.new]p13.
527 // (We don't need to check for null when there's no new initializer and
528 // we're allocating a POD type).
529 bool NullCheckResult = NewFTy->hasEmptyExceptionSpec() &&
530 !(AllocType->isPODType() && !E->hasInitializer());
Anders Carlssond5536972009-05-31 20:21:44 +0000531
Anders Carlssondbee9a52009-06-01 00:05:16 +0000532 llvm::BasicBlock *NewNull = 0;
533 llvm::BasicBlock *NewNotNull = 0;
534 llvm::BasicBlock *NewEnd = 0;
535
536 llvm::Value *NewPtr = RV.getScalarVal();
537
Anders Carlsson11269042009-05-31 21:53:59 +0000538 if (NullCheckResult) {
Anders Carlssondbee9a52009-06-01 00:05:16 +0000539 NewNull = createBasicBlock("new.null");
540 NewNotNull = createBasicBlock("new.notnull");
541 NewEnd = createBasicBlock("new.end");
542
543 llvm::Value *IsNull =
544 Builder.CreateICmpEQ(NewPtr,
Owen Andersonf37b84b2009-07-31 20:28:54 +0000545 llvm::Constant::getNullValue(NewPtr->getType()),
Anders Carlssondbee9a52009-06-01 00:05:16 +0000546 "isnull");
547
548 Builder.CreateCondBr(IsNull, NewNull, NewNotNull);
549 EmitBlock(NewNotNull);
Anders Carlsson11269042009-05-31 21:53:59 +0000550 }
551
Anders Carlssondbee9a52009-06-01 00:05:16 +0000552 NewPtr = Builder.CreateBitCast(NewPtr, ConvertType(E->getType()));
Anders Carlsson11269042009-05-31 21:53:59 +0000553
Anders Carlsson7c294782009-05-31 20:56:36 +0000554 if (AllocType->isPODType()) {
Anders Carlsson26910f62009-06-01 00:26:14 +0000555 if (E->getNumConstructorArgs() > 0) {
Anders Carlsson7c294782009-05-31 20:56:36 +0000556 assert(E->getNumConstructorArgs() == 1 &&
557 "Can only have one argument to initializer of POD type.");
558
559 const Expr *Init = E->getConstructorArg(0);
560
Anders Carlsson5f93ccf2009-05-31 21:07:58 +0000561 if (!hasAggregateLLVMType(AllocType))
Anders Carlsson7c294782009-05-31 20:56:36 +0000562 Builder.CreateStore(EmitScalarExpr(Init), NewPtr);
Anders Carlsson5f93ccf2009-05-31 21:07:58 +0000563 else if (AllocType->isAnyComplexType())
564 EmitComplexExprIntoAddr(Init, NewPtr, AllocType.isVolatileQualified());
Anders Carlssoneb39b432009-05-31 21:12:26 +0000565 else
566 EmitAggExpr(Init, NewPtr, AllocType.isVolatileQualified());
Anders Carlsson7c294782009-05-31 20:56:36 +0000567 }
Anders Carlsson11269042009-05-31 21:53:59 +0000568 } else {
569 // Call the constructor.
570 CXXConstructorDecl *Ctor = E->getConstructor();
Anders Carlsson7c294782009-05-31 20:56:36 +0000571
Anders Carlsson11269042009-05-31 21:53:59 +0000572 EmitCXXConstructorCall(Ctor, Ctor_Complete, NewPtr,
573 E->constructor_arg_begin(),
574 E->constructor_arg_end());
Anders Carlssond5536972009-05-31 20:21:44 +0000575 }
Anders Carlsson11269042009-05-31 21:53:59 +0000576
Anders Carlssondbee9a52009-06-01 00:05:16 +0000577 if (NullCheckResult) {
578 Builder.CreateBr(NewEnd);
579 EmitBlock(NewNull);
580 Builder.CreateBr(NewEnd);
581 EmitBlock(NewEnd);
582
583 llvm::PHINode *PHI = Builder.CreatePHI(NewPtr->getType());
584 PHI->reserveOperandSpace(2);
585 PHI->addIncoming(NewPtr, NewNotNull);
Owen Andersonf37b84b2009-07-31 20:28:54 +0000586 PHI->addIncoming(llvm::Constant::getNullValue(NewPtr->getType()), NewNull);
Anders Carlssondbee9a52009-06-01 00:05:16 +0000587
588 NewPtr = PHI;
589 }
590
Anders Carlsson11269042009-05-31 21:53:59 +0000591 return NewPtr;
Anders Carlsson18e88bc2009-05-31 01:40:14 +0000592}
593
Anders Carlsson133fdaf2009-08-16 21:13:42 +0000594void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
595 if (E->isArrayForm()) {
596 ErrorUnsupported(E, "delete[] expression");
597 return;
598 };
599
600 QualType DeleteTy =
601 E->getArgument()->getType()->getAs<PointerType>()->getPointeeType();
602
603 llvm::Value *Ptr = EmitScalarExpr(E->getArgument());
604
605 // Null check the pointer.
606 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
607 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
608
609 llvm::Value *IsNull =
610 Builder.CreateICmpEQ(Ptr, llvm::Constant::getNullValue(Ptr->getType()),
611 "isnull");
612
613 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
614 EmitBlock(DeleteNotNull);
615
616 // Call the destructor if necessary.
617 if (const RecordType *RT = DeleteTy->getAs<RecordType>()) {
618 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
619 if (!RD->hasTrivialDestructor()) {
620 const CXXDestructorDecl *Dtor = RD->getDestructor(getContext());
621 if (Dtor->isVirtual()) {
622 ErrorUnsupported(E, "delete expression with virtual destructor");
623 return;
624 }
625
626 EmitCXXDestructorCall(Dtor, Dtor_Complete, Ptr);
627 }
628 }
629 }
630
631 // Call delete.
632 FunctionDecl *DeleteFD = E->getOperatorDelete();
633 const FunctionProtoType *DeleteFTy =
634 DeleteFD->getType()->getAsFunctionProtoType();
635
636 CallArgList DeleteArgs;
637
638 QualType ArgTy = DeleteFTy->getArgType(0);
639 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
640 DeleteArgs.push_back(std::make_pair(RValue::get(DeletePtr), ArgTy));
641
642 // Emit the call to delete.
643 EmitCall(CGM.getTypes().getFunctionInfo(DeleteFTy->getResultType(),
644 DeleteArgs),
645 CGM.GetAddrOfFunction(GlobalDecl(DeleteFD)),
646 DeleteArgs, DeleteFD);
647
648 EmitBlock(DeleteEnd);
649}
650
Anders Carlsson4811c302009-04-17 01:58:57 +0000651static bool canGenerateCXXstructor(const CXXRecordDecl *RD,
652 ASTContext &Context) {
Anders Carlsson8496c692009-04-15 21:02:13 +0000653 // The class has base classes - we don't support that right now.
654 if (RD->getNumBases() > 0)
655 return false;
656
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000657 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
658 I != E; ++I) {
Anders Carlsson8496c692009-04-15 21:02:13 +0000659 // We don't support ctors for fields that aren't POD.
660 if (!I->getType()->isPODType())
661 return false;
662 }
663
664 return true;
665}
666
Anders Carlsson652951a2009-04-15 15:55:24 +0000667void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) {
Anders Carlsson4811c302009-04-17 01:58:57 +0000668 if (!canGenerateCXXstructor(D->getParent(), getContext())) {
Anders Carlsson8496c692009-04-15 21:02:13 +0000669 ErrorUnsupported(D, "C++ constructor", true);
670 return;
671 }
Anders Carlsson652951a2009-04-15 15:55:24 +0000672
Anders Carlsson1764af42009-05-05 04:44:02 +0000673 EmitGlobal(GlobalDecl(D, Ctor_Complete));
674 EmitGlobal(GlobalDecl(D, Ctor_Base));
Anders Carlsson652951a2009-04-15 15:55:24 +0000675}
Anders Carlsson890a9fd2009-04-16 23:57:24 +0000676
Anders Carlsson4811c302009-04-17 01:58:57 +0000677void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D,
678 CXXCtorType Type) {
679
680 llvm::Function *Fn = GetAddrOfCXXConstructor(D, Type);
681
682 CodeGenFunction(*this).GenerateCode(D, Fn);
683
684 SetFunctionDefinitionAttributes(D, Fn);
685 SetLLVMFunctionAttributesForDefinition(D, Fn);
686}
687
Anders Carlsson890a9fd2009-04-16 23:57:24 +0000688llvm::Function *
689CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
690 CXXCtorType Type) {
691 const llvm::FunctionType *FTy =
692 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false);
693
694 const char *Name = getMangledCXXCtorName(D, Type);
Chris Lattner80f39cc2009-05-12 21:21:08 +0000695 return cast<llvm::Function>(
696 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson890a9fd2009-04-16 23:57:24 +0000697}
Anders Carlsson4811c302009-04-17 01:58:57 +0000698
699const char *CodeGenModule::getMangledCXXCtorName(const CXXConstructorDecl *D,
700 CXXCtorType Type) {
701 llvm::SmallString<256> Name;
702 llvm::raw_svector_ostream Out(Name);
703 mangleCXXCtor(D, Type, Context, Out);
704
705 Name += '\0';
706 return UniqueMangledName(Name.begin(), Name.end());
707}
708
709void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) {
710 if (!canGenerateCXXstructor(D->getParent(), getContext())) {
711 ErrorUnsupported(D, "C++ destructor", true);
712 return;
713 }
714
715 EmitCXXDestructor(D, Dtor_Complete);
716 EmitCXXDestructor(D, Dtor_Base);
717}
718
719void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D,
720 CXXDtorType Type) {
721 llvm::Function *Fn = GetAddrOfCXXDestructor(D, Type);
722
723 CodeGenFunction(*this).GenerateCode(D, Fn);
724
725 SetFunctionDefinitionAttributes(D, Fn);
726 SetLLVMFunctionAttributesForDefinition(D, Fn);
727}
728
729llvm::Function *
730CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D,
731 CXXDtorType Type) {
732 const llvm::FunctionType *FTy =
733 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false);
734
735 const char *Name = getMangledCXXDtorName(D, Type);
Chris Lattner80f39cc2009-05-12 21:21:08 +0000736 return cast<llvm::Function>(
737 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson4811c302009-04-17 01:58:57 +0000738}
739
740const char *CodeGenModule::getMangledCXXDtorName(const CXXDestructorDecl *D,
741 CXXDtorType Type) {
742 llvm::SmallString<256> Name;
743 llvm::raw_svector_ostream Out(Name);
744 mangleCXXDtor(D, Type, Context, Out);
745
746 Name += '\0';
747 return UniqueMangledName(Name.begin(), Name.end());
748}
Fariborz Jahanian5400e022009-07-20 23:18:55 +0000749
Mike Stumpdca5e512009-08-18 21:49:00 +0000750llvm::Constant *CodeGenModule::GenerateRtti(const CXXRecordDecl *RD) {
Mike Stump00df7d32009-07-31 23:15:31 +0000751 llvm::Type *Ptr8Ty;
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000752 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Mike Stump69a12322009-08-04 20:06:48 +0000753 llvm::Constant *Rtti = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stump00df7d32009-07-31 23:15:31 +0000754
755 if (!getContext().getLangOptions().Rtti)
Mike Stump69a12322009-08-04 20:06:48 +0000756 return Rtti;
Mike Stump00df7d32009-07-31 23:15:31 +0000757
758 llvm::SmallString<256> OutName;
759 llvm::raw_svector_ostream Out(OutName);
760 QualType ClassTy;
Mike Stumpe7545622009-08-07 18:05:12 +0000761 ClassTy = getContext().getTagDeclType(RD);
Mike Stump00df7d32009-07-31 23:15:31 +0000762 mangleCXXRtti(ClassTy, getContext(), Out);
Mike Stump00df7d32009-07-31 23:15:31 +0000763 llvm::GlobalVariable::LinkageTypes linktype;
764 linktype = llvm::GlobalValue::WeakAnyLinkage;
765 std::vector<llvm::Constant *> info;
Mike Stump2eade572009-08-13 22:53:07 +0000766 // assert(0 && "FIXME: implement rtti descriptor");
Mike Stump00df7d32009-07-31 23:15:31 +0000767 // FIXME: descriptor
768 info.push_back(llvm::Constant::getNullValue(Ptr8Ty));
Mike Stump2eade572009-08-13 22:53:07 +0000769 // assert(0 && "FIXME: implement rtti ts");
Mike Stump00df7d32009-07-31 23:15:31 +0000770 // FIXME: TS
771 info.push_back(llvm::Constant::getNullValue(Ptr8Ty));
772
773 llvm::Constant *C;
774 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, info.size());
775 C = llvm::ConstantArray::get(type, info);
Mike Stumpdca5e512009-08-18 21:49:00 +0000776 Rtti = new llvm::GlobalVariable(getModule(), type, true, linktype, C,
Daniel Dunbar0433a022009-08-19 20:04:03 +0000777 Out.str());
Mike Stump69a12322009-08-04 20:06:48 +0000778 Rtti = llvm::ConstantExpr::getBitCast(Rtti, Ptr8Ty);
779 return Rtti;
Mike Stump00df7d32009-07-31 23:15:31 +0000780}
781
Mike Stump86a859e2009-08-19 18:10:47 +0000782class VtableBuilder {
Mike Stumpad734d12009-08-18 20:50:28 +0000783 std::vector<llvm::Constant *> &methods;
784 llvm::Type *Ptr8Ty;
Mike Stumpdca5e512009-08-18 21:49:00 +0000785 const CXXRecordDecl *Class;
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000786 const ASTRecordLayout &BLayout;
Mike Stumpa7ec675d2009-08-19 14:40:47 +0000787 llvm::SmallSet<const CXXRecordDecl *, 32> IndirectPrimary;
Mike Stumpdca5e512009-08-18 21:49:00 +0000788 llvm::Constant *rtti;
Mike Stumpad734d12009-08-18 20:50:28 +0000789 llvm::LLVMContext &VMContext;
Mike Stump1e10cf32009-08-18 21:03:28 +0000790 CodeGenModule &CGM; // Per-module state.
Mike Stumpd75d3232009-08-18 22:04:08 +0000791
792 typedef CXXRecordDecl::method_iterator method_iter;
Mike Stumpad734d12009-08-18 20:50:28 +0000793public:
Mike Stump86a859e2009-08-19 18:10:47 +0000794 VtableBuilder(std::vector<llvm::Constant *> &meth,
795 const CXXRecordDecl *c,
796 CodeGenModule &cgm)
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000797 : methods(meth), Class(c), BLayout(cgm.getContext().getASTRecordLayout(c)),
798 rtti(cgm.GenerateRtti(c)), VMContext(cgm.getModule().getContext()),
799 CGM(cgm) {
Mike Stumpad734d12009-08-18 20:50:28 +0000800 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
801 }
Mike Stumpdca5e512009-08-18 21:49:00 +0000802
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000803 llvm::Constant *GenerateVcall(const CXXMethodDecl *MD,
804 const CXXRecordDecl *RD,
805 bool VBoundary,
806 bool SecondaryVirtual) {
807 llvm::Constant *m = 0;
808
809 // FIXME: vcall: offset for virtual base for this function
810 if (SecondaryVirtual || VBoundary)
811 m = llvm::Constant::getNullValue(Ptr8Ty);
812 return m;
813 }
814
815 void GenerateVcalls(const CXXRecordDecl *RD, bool VBoundary,
816 bool SecondaryVirtual) {
Mike Stumpad734d12009-08-18 20:50:28 +0000817 llvm::Constant *m;
Mike Stump23b238e2009-08-12 23:25:18 +0000818
Mike Stumpd75d3232009-08-18 22:04:08 +0000819 for (method_iter mi = RD->method_begin(),
Mike Stumpad734d12009-08-18 20:50:28 +0000820 me = RD->method_end(); mi != me; ++mi) {
821 if (mi->isVirtual()) {
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000822 m = GenerateVcall(*mi, RD, VBoundary, SecondaryVirtual);
823 if (m)
824 methods.push_back(m);
Mike Stumpad734d12009-08-18 20:50:28 +0000825 }
Mike Stumpf640de52009-08-12 23:14:12 +0000826 }
Mike Stump23b238e2009-08-12 23:25:18 +0000827 }
Mike Stumpf640de52009-08-12 23:14:12 +0000828
Mike Stump1e10cf32009-08-18 21:03:28 +0000829 void GenerateMethods(const CXXRecordDecl *RD) {
Mike Stump1e10cf32009-08-18 21:03:28 +0000830 llvm::Constant *m;
Mike Stumpdecd7812009-08-12 23:00:59 +0000831
Mike Stumpd75d3232009-08-18 22:04:08 +0000832 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
Mike Stump1e10cf32009-08-18 21:03:28 +0000833 ++mi) {
834 if (mi->isVirtual()) {
835 m = CGM.GetAddrOfFunction(GlobalDecl(*mi));
836 m = llvm::ConstantExpr::getBitCast(m, Ptr8Ty);
837 methods.push_back(m);
838 }
Mike Stumpdecd7812009-08-12 23:00:59 +0000839 }
840 }
Mike Stump1e10cf32009-08-18 21:03:28 +0000841
Mike Stump7bae1282009-08-18 21:30:21 +0000842 void GenerateVtableForBase(const CXXRecordDecl *RD,
843 bool forPrimary,
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000844 bool VBoundary,
Mike Stump7bae1282009-08-18 21:30:21 +0000845 int64_t Offset,
Mike Stumpa7ec675d2009-08-19 14:40:47 +0000846 bool ForVirtualBase) {
Mike Stump7bae1282009-08-18 21:30:21 +0000847 llvm::Constant *m = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stumpc57b8272009-08-16 01:46:26 +0000848
Mike Stump7bae1282009-08-18 21:30:21 +0000849 if (RD && !RD->isDynamicClass())
850 return;
851
852 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
853 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
854 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
855
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000856 if (VBoundary || forPrimary || ForVirtualBase) {
857 // then comes the the vcall offsets for all our functions...
858 GenerateVcalls(RD, VBoundary, !forPrimary && ForVirtualBase);
859 }
860
Mike Stump7bae1282009-08-18 21:30:21 +0000861 // The virtual base offsets come first...
862 // FIXME: Audit, is this right?
Mike Stump4c1c8912009-08-19 02:53:08 +0000863 if (PrimaryBase == 0 || forPrimary || !PrimaryBaseWasVirtual) {
Mike Stump7bae1282009-08-18 21:30:21 +0000864 llvm::SmallSet<const CXXRecordDecl *, 32> SeenVBase;
865 std::vector<llvm::Constant *> offsets;
866 GenerateVBaseOffsets(offsets, RD, SeenVBase, Offset, Layout);
867 for (std::vector<llvm::Constant *>::reverse_iterator i = offsets.rbegin(),
868 e = offsets.rend(); i != e; ++i)
869 methods.push_back(*i);
870 }
871
Mike Stump7bae1282009-08-18 21:30:21 +0000872 bool Top = true;
873
874 // vtables are composed from the chain of primaries.
875 if (PrimaryBase) {
876 if (PrimaryBaseWasVirtual)
877 IndirectPrimary.insert(PrimaryBase);
878 Top = false;
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000879 GenerateVtableForBase(PrimaryBase, true, PrimaryBaseWasVirtual|VBoundary,
Mike Stumpa7ec675d2009-08-19 14:40:47 +0000880 Offset, PrimaryBaseWasVirtual);
Mike Stump7bae1282009-08-18 21:30:21 +0000881 }
882
883 if (Top) {
884 int64_t BaseOffset;
885 if (ForVirtualBase) {
Mike Stump7bae1282009-08-18 21:30:21 +0000886 BaseOffset = -(BLayout.getVBaseClassOffset(RD) / 8);
887 } else
888 BaseOffset = -Offset/8;
Mike Stumpc57b8272009-08-16 01:46:26 +0000889 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), BaseOffset);
890 m = llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
891 methods.push_back(m);
Mike Stump7bae1282009-08-18 21:30:21 +0000892 methods.push_back(rtti);
Mike Stumpc57b8272009-08-16 01:46:26 +0000893 }
Mike Stump2eade572009-08-13 22:53:07 +0000894
Mike Stump7bae1282009-08-18 21:30:21 +0000895 // And add the virtuals for the class to the primary vtable.
896 GenerateMethods(RD);
897
898 // and then the non-virtual bases.
899 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
900 e = RD->bases_end(); i != e; ++i) {
901 if (i->isVirtual())
902 continue;
903 const CXXRecordDecl *Base =
904 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
905 if (Base != PrimaryBase || PrimaryBaseWasVirtual) {
906 uint64_t o = Offset + Layout.getBaseClassOffset(Base);
Mike Stumpa7ec675d2009-08-19 14:40:47 +0000907 GenerateVtableForBase(Base, true, false, o, false);
Mike Stump7bae1282009-08-18 21:30:21 +0000908 }
909 }
910 }
911
912 void GenerateVtableForVBases(const CXXRecordDecl *RD,
Mike Stumpa7ec675d2009-08-19 14:40:47 +0000913 const CXXRecordDecl *Class) {
Mike Stump7bae1282009-08-18 21:30:21 +0000914 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
915 e = RD->bases_end(); i != e; ++i) {
916 const CXXRecordDecl *Base =
917 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
918 if (i->isVirtual() && !IndirectPrimary.count(Base)) {
919 // Mark it so we don't output it twice.
920 IndirectPrimary.insert(Base);
Mike Stumpa7ec675d2009-08-19 14:40:47 +0000921 GenerateVtableForBase(Base, false, true, 0, true);
Mike Stump7bae1282009-08-18 21:30:21 +0000922 }
923 if (Base->getNumVBases())
Mike Stumpa7ec675d2009-08-19 14:40:47 +0000924 GenerateVtableForVBases(Base, Class);
Mike Stumpc57b8272009-08-16 01:46:26 +0000925 }
926 }
Mike Stump7bae1282009-08-18 21:30:21 +0000927
928 void GenerateVBaseOffsets(std::vector<llvm::Constant *> &offsets,
929 const CXXRecordDecl *RD,
930 llvm::SmallSet<const CXXRecordDecl *, 32> &SeenVBase,
Mike Stump69d41a22009-08-19 14:06:50 +0000931 uint64_t Offset, const ASTRecordLayout &Layout) {
Mike Stump7bae1282009-08-18 21:30:21 +0000932 for (CXXRecordDecl::base_class_const_iterator i =RD->bases_begin(),
933 e = RD->bases_end(); i != e; ++i) {
934 const CXXRecordDecl *Base =
935 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
936 if (i->isVirtual() && !SeenVBase.count(Base)) {
937 SeenVBase.insert(Base);
Mike Stump69d41a22009-08-19 14:06:50 +0000938 int64_t BaseOffset = Offset/8 + Layout.getVBaseClassOffset(Base) / 8;
Mike Stump7bae1282009-08-18 21:30:21 +0000939 llvm::Constant *m;
940 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), BaseOffset);
941 m = llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
942 offsets.push_back(m);
943 }
Mike Stump69d41a22009-08-19 14:06:50 +0000944 GenerateVBaseOffsets(offsets, Base, SeenVBase, Offset, Layout);
Mike Stump7bae1282009-08-18 21:30:21 +0000945 }
946 }
947};
Mike Stumpd6f22d82009-08-06 15:50:11 +0000948
Mike Stump7e8c9932009-07-31 18:25:34 +0000949llvm::Value *CodeGenFunction::GenerateVtable(const CXXRecordDecl *RD) {
Mike Stump7e8c9932009-07-31 18:25:34 +0000950 llvm::SmallString<256> OutName;
951 llvm::raw_svector_ostream Out(OutName);
952 QualType ClassTy;
Mike Stumpe7545622009-08-07 18:05:12 +0000953 ClassTy = getContext().getTagDeclType(RD);
Mike Stump7e8c9932009-07-31 18:25:34 +0000954 mangleCXXVtable(ClassTy, getContext(), Out);
Mike Stumpd0672782009-07-31 21:43:43 +0000955 llvm::GlobalVariable::LinkageTypes linktype;
956 linktype = llvm::GlobalValue::WeakAnyLinkage;
957 std::vector<llvm::Constant *> methods;
Mike Stumpc57b8272009-08-16 01:46:26 +0000958 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
Mike Stump8b82eeb2009-08-05 22:37:18 +0000959 int64_t Offset = 0;
Mike Stump71e21302009-08-06 21:49:36 +0000960
961 Offset += LLVMPointerWidth;
962 Offset += LLVMPointerWidth;
Mike Stump8b82eeb2009-08-05 22:37:18 +0000963
Mike Stump86a859e2009-08-19 18:10:47 +0000964 VtableBuilder b(methods, RD, CGM);
Mike Stump7bae1282009-08-18 21:30:21 +0000965
Mike Stumpc57b8272009-08-16 01:46:26 +0000966 // First comes the vtables for all the non-virtual bases...
Mike Stumpa7ec675d2009-08-19 14:40:47 +0000967 b.GenerateVtableForBase(RD, true, false, 0, false);
Mike Stump42368bb2009-08-14 01:44:03 +0000968
Mike Stumpc57b8272009-08-16 01:46:26 +0000969 // then the vtables for all the virtual bases.
Mike Stumpa7ec675d2009-08-19 14:40:47 +0000970 b.GenerateVtableForVBases(RD, RD);
Mike Stumpf3371782009-08-04 21:58:42 +0000971
Mike Stumpd0672782009-07-31 21:43:43 +0000972 llvm::Constant *C;
973 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, methods.size());
974 C = llvm::ConstantArray::get(type, methods);
975 llvm::Value *vtable = new llvm::GlobalVariable(CGM.getModule(), type, true,
Daniel Dunbar0433a022009-08-19 20:04:03 +0000976 linktype, C, Out.str());
Mike Stump7e8c9932009-07-31 18:25:34 +0000977 vtable = Builder.CreateBitCast(vtable, Ptr8Ty);
Mike Stump7e8c9932009-07-31 18:25:34 +0000978 vtable = Builder.CreateGEP(vtable,
Mike Stumpc57b8272009-08-16 01:46:26 +0000979 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
Mike Stump8b82eeb2009-08-05 22:37:18 +0000980 Offset/8));
Mike Stump7e8c9932009-07-31 18:25:34 +0000981 return vtable;
982}
983
Fariborz Jahanianfc27d292009-08-07 23:51:33 +0000984/// EmitClassMemberwiseCopy - This routine generates code to copy a class
985/// object from SrcValue to DestValue. Copying can be either a bitwise copy
986/// of via a copy constructor call.
987void CodeGenFunction::EmitClassMemberwiseCopy(
Fariborz Jahaniancefe5922009-08-08 23:32:22 +0000988 llvm::Value *Dest, llvm::Value *Src,
Fariborz Jahanianfc27d292009-08-07 23:51:33 +0000989 const CXXRecordDecl *ClassDecl,
Fariborz Jahaniancefe5922009-08-08 23:32:22 +0000990 const CXXRecordDecl *BaseClassDecl, QualType Ty) {
991 if (ClassDecl) {
992 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
993 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
994 }
995 if (BaseClassDecl->hasTrivialCopyConstructor()) {
996 EmitAggregateCopy(Dest, Src, Ty);
Fariborz Jahanianfc27d292009-08-07 23:51:33 +0000997 return;
Fariborz Jahaniancefe5922009-08-08 23:32:22 +0000998 }
999
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001000 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanianfbe08772009-08-08 00:59:58 +00001001 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001002 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
1003 Ctor_Complete);
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001004 CallArgList CallArgs;
1005 // Push the this (Dest) ptr.
1006 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1007 BaseCopyCtor->getThisType(getContext())));
1008
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001009 // Push the Src ptr.
1010 CallArgs.push_back(std::make_pair(RValue::get(Src),
Fariborz Jahanian0dfaec42009-08-10 17:20:45 +00001011 BaseCopyCtor->getParamDecl(0)->getType()));
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001012 QualType ResultType =
1013 BaseCopyCtor->getType()->getAsFunctionType()->getResultType();
1014 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1015 Callee, CallArgs, BaseCopyCtor);
1016 }
1017}
Fariborz Jahaniane39fab62009-08-10 18:46:38 +00001018
Fariborz Jahanian04500242009-08-12 23:34:46 +00001019/// EmitClassCopyAssignment - This routine generates code to copy assign a class
1020/// object from SrcValue to DestValue. Assignment can be either a bitwise
1021/// assignment of via an assignment operator call.
1022void CodeGenFunction::EmitClassCopyAssignment(
1023 llvm::Value *Dest, llvm::Value *Src,
1024 const CXXRecordDecl *ClassDecl,
1025 const CXXRecordDecl *BaseClassDecl,
1026 QualType Ty) {
1027 if (ClassDecl) {
1028 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
1029 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
1030 }
1031 if (BaseClassDecl->hasTrivialCopyAssignment()) {
1032 EmitAggregateCopy(Dest, Src, Ty);
1033 return;
1034 }
1035
1036 const CXXMethodDecl *MD = 0;
Fariborz Jahanian84bd6532009-08-13 00:53:36 +00001037 bool ConstCopyAssignOp = BaseClassDecl->hasConstCopyAssignment(getContext(),
1038 MD);
1039 assert(ConstCopyAssignOp && "EmitClassCopyAssignment - missing copy assign");
1040 (void)ConstCopyAssignOp;
1041
1042 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
1043 const llvm::Type *LTy =
1044 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1045 FPT->isVariadic());
1046 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), LTy);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001047
Fariborz Jahanian84bd6532009-08-13 00:53:36 +00001048 CallArgList CallArgs;
1049 // Push the this (Dest) ptr.
1050 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1051 MD->getThisType(getContext())));
Fariborz Jahanian04500242009-08-12 23:34:46 +00001052
Fariborz Jahanian84bd6532009-08-13 00:53:36 +00001053 // Push the Src ptr.
1054 CallArgs.push_back(std::make_pair(RValue::get(Src),
1055 MD->getParamDecl(0)->getType()));
1056 QualType ResultType =
1057 MD->getType()->getAsFunctionType()->getResultType();
1058 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1059 Callee, CallArgs, MD);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001060}
1061
Fariborz Jahaniane39fab62009-08-10 18:46:38 +00001062/// SynthesizeDefaultConstructor - synthesize a default constructor
1063void
1064CodeGenFunction::SynthesizeDefaultConstructor(const CXXConstructorDecl *CD,
1065 const FunctionDecl *FD,
1066 llvm::Function *Fn,
1067 const FunctionArgList &Args) {
1068 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1069 EmitCtorPrologue(CD);
1070 FinishFunction();
1071}
1072
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001073/// SynthesizeCXXCopyConstructor - This routine implicitly defines body of a copy
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001074/// constructor, in accordance with section 12.8 (p7 and p8) of C++03
1075/// The implicitly-defined copy constructor for class X performs a memberwise
1076/// copy of its subobjects. The order of copying is the same as the order
1077/// of initialization of bases and members in a user-defined constructor
1078/// Each subobject is copied in the manner appropriate to its type:
1079/// if the subobject is of class type, the copy constructor for the class is
1080/// used;
1081/// if the subobject is an array, each element is copied, in the manner
1082/// appropriate to the element type;
1083/// if the subobject is of scalar type, the built-in assignment operator is
1084/// used.
1085/// Virtual base class subobjects shall be copied only once by the
1086/// implicitly-defined copy constructor
1087
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001088void CodeGenFunction::SynthesizeCXXCopyConstructor(const CXXConstructorDecl *CD,
1089 const FunctionDecl *FD,
1090 llvm::Function *Fn,
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001091 const FunctionArgList &Args) {
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001092 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1093 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001094 "SynthesizeCXXCopyConstructor - copy constructor has definition already");
1095 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001096
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001097 FunctionArgList::const_iterator i = Args.begin();
1098 const VarDecl *ThisArg = i->first;
1099 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1100 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1101 const VarDecl *SrcArg = (i+1)->first;
1102 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1103 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1104
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001105 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1106 Base != ClassDecl->bases_end(); ++Base) {
1107 // FIXME. copy constrution of virtual base NYI
1108 if (Base->isVirtual())
1109 continue;
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001110
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001111 CXXRecordDecl *BaseClassDecl
1112 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001113 EmitClassMemberwiseCopy(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1114 Base->getType());
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001115 }
1116
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001117 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1118 FieldEnd = ClassDecl->field_end();
1119 Field != FieldEnd; ++Field) {
1120 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
1121
1122 // FIXME. How about copying arrays!
1123 assert(!getContext().getAsArrayType(FieldType) &&
1124 "FIXME. Copying arrays NYI");
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +00001125
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001126 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1127 CXXRecordDecl *FieldClassDecl
1128 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1129 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1130 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001131
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001132 EmitClassMemberwiseCopy(LHS.getAddress(), RHS.getAddress(),
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001133 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001134 continue;
1135 }
Fariborz Jahanian08d99e92009-08-10 18:34:26 +00001136 // Do a built-in assignment of scalar data members.
1137 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1138 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1139 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1140 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001141 }
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001142 FinishFunction();
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001143}
1144
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001145/// SynthesizeCXXCopyAssignment - Implicitly define copy assignment operator.
1146/// Before the implicitly-declared copy assignment operator for a class is
1147/// implicitly defined, all implicitly- declared copy assignment operators for
1148/// its direct base classes and its nonstatic data members shall have been
1149/// implicitly defined. [12.8-p12]
1150/// The implicitly-defined copy assignment operator for class X performs
1151/// memberwise assignment of its subob- jects. The direct base classes of X are
1152/// assigned first, in the order of their declaration in
1153/// the base-specifier-list, and then the immediate nonstatic data members of X
1154/// are assigned, in the order in which they were declared in the class
1155/// definition.Each subobject is assigned in the manner appropriate to its type:
Fariborz Jahanian04500242009-08-12 23:34:46 +00001156/// if the subobject is of class type, the copy assignment operator for the
1157/// class is used (as if by explicit qualification; that is, ignoring any
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001158/// possible virtual overriding functions in more derived classes);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001159///
1160/// if the subobject is an array, each element is assigned, in the manner
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001161/// appropriate to the element type;
Fariborz Jahanian04500242009-08-12 23:34:46 +00001162///
1163/// if the subobject is of scalar type, the built-in assignment operator is
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001164/// used.
1165void CodeGenFunction::SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD,
1166 const FunctionDecl *FD,
1167 llvm::Function *Fn,
1168 const FunctionArgList &Args) {
Fariborz Jahanian04500242009-08-12 23:34:46 +00001169
1170 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1171 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
1172 "SynthesizeCXXCopyAssignment - copy assignment has user declaration");
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001173 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1174
Fariborz Jahanian04500242009-08-12 23:34:46 +00001175 FunctionArgList::const_iterator i = Args.begin();
1176 const VarDecl *ThisArg = i->first;
1177 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1178 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1179 const VarDecl *SrcArg = (i+1)->first;
1180 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1181 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1182
1183 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1184 Base != ClassDecl->bases_end(); ++Base) {
1185 // FIXME. copy assignment of virtual base NYI
1186 if (Base->isVirtual())
1187 continue;
1188
1189 CXXRecordDecl *BaseClassDecl
1190 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1191 EmitClassCopyAssignment(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1192 Base->getType());
1193 }
1194
1195 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1196 FieldEnd = ClassDecl->field_end();
1197 Field != FieldEnd; ++Field) {
1198 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
1199
1200 // FIXME. How about copy assignment of arrays!
1201 assert(!getContext().getAsArrayType(FieldType) &&
1202 "FIXME. Copy assignment of arrays NYI");
1203
1204 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1205 CXXRecordDecl *FieldClassDecl
1206 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1207 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1208 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1209
1210 EmitClassCopyAssignment(LHS.getAddress(), RHS.getAddress(),
1211 0 /*ClassDecl*/, FieldClassDecl, FieldType);
1212 continue;
1213 }
1214 // Do a built-in assignment of scalar data members.
1215 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1216 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1217 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1218 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanianc47460d2009-08-14 00:01:54 +00001219 }
1220
1221 // return *this;
1222 Builder.CreateStore(LoadOfThis, ReturnValue);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001223
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001224 FinishFunction();
1225}
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001226
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001227/// EmitCtorPrologue - This routine generates necessary code to initialize
1228/// base classes and non-static data members belonging to this constructor.
1229void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD) {
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001230 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
Mike Stump05207212009-08-06 13:41:24 +00001231 // FIXME: Add vbase initialization
Mike Stump7e8c9932009-07-31 18:25:34 +00001232 llvm::Value *LoadOfThis = 0;
Fariborz Jahanian70277012009-07-28 18:09:28 +00001233
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001234 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001235 E = CD->init_end();
1236 B != E; ++B) {
1237 CXXBaseOrMemberInitializer *Member = (*B);
1238 if (Member->isBaseInitializer()) {
Mike Stump7e8c9932009-07-31 18:25:34 +00001239 LoadOfThis = LoadCXXThis();
Fariborz Jahanian70277012009-07-28 18:09:28 +00001240 Type *BaseType = Member->getBaseClass();
1241 CXXRecordDecl *BaseClassDecl =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001242 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
Fariborz Jahanian70277012009-07-28 18:09:28 +00001243 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1244 BaseClassDecl);
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001245 EmitCXXConstructorCall(Member->getConstructor(),
1246 Ctor_Complete, V,
1247 Member->const_arg_begin(),
1248 Member->const_arg_end());
Mike Stump487ce382009-07-30 22:28:39 +00001249 } else {
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001250 // non-static data member initilaizers.
1251 FieldDecl *Field = Member->getMember();
1252 QualType FieldType = getContext().getCanonicalType((Field)->getType());
1253 assert(!getContext().getAsArrayType(FieldType)
1254 && "FIXME. Field arrays initialization unsupported");
Fariborz Jahanian32cea8b2009-08-10 23:56:17 +00001255
Mike Stump7e8c9932009-07-31 18:25:34 +00001256 LoadOfThis = LoadCXXThis();
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001257 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001258 if (FieldType->getAs<RecordType>()) {
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +00001259 if (!Field->isAnonymousStructOrUnion()) {
Fariborz Jahanian56baceb2009-07-24 17:57:02 +00001260 assert(Member->getConstructor() &&
1261 "EmitCtorPrologue - no constructor to initialize member");
1262 EmitCXXConstructorCall(Member->getConstructor(),
1263 Ctor_Complete, LHS.getAddress(),
1264 Member->const_arg_begin(),
1265 Member->const_arg_end());
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +00001266 continue;
1267 }
1268 else {
1269 // Initializing an anonymous union data member.
1270 FieldDecl *anonMember = Member->getAnonUnionMember();
1271 LHS = EmitLValueForField(LHS.getAddress(), anonMember, false, 0);
1272 FieldType = anonMember->getType();
1273 }
Fariborz Jahanian56baceb2009-07-24 17:57:02 +00001274 }
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001275
1276 assert(Member->getNumArgs() == 1 && "Initializer count must be 1 only");
Fariborz Jahanian56baceb2009-07-24 17:57:02 +00001277 Expr *RhsExpr = *Member->arg_begin();
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001278 llvm::Value *RHS = EmitScalarExpr(RhsExpr, true);
Fariborz Jahanian32cea8b2009-08-10 23:56:17 +00001279 EmitStoreThroughLValue(RValue::get(RHS), LHS, FieldType);
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001280 }
1281 }
Mike Stump7e8c9932009-07-31 18:25:34 +00001282
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001283 if (!CD->getNumBaseOrMemberInitializers() && !CD->isTrivial()) {
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001284 // Nontrivial default constructor with no initializer list. It may still
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001285 // have bases classes and/or contain non-static data members which require
1286 // construction.
1287 for (CXXRecordDecl::base_class_const_iterator Base =
1288 ClassDecl->bases_begin();
1289 Base != ClassDecl->bases_end(); ++Base) {
1290 // FIXME. copy assignment of virtual base NYI
1291 if (Base->isVirtual())
1292 continue;
1293
1294 CXXRecordDecl *BaseClassDecl
1295 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1296 if (BaseClassDecl->hasTrivialConstructor())
1297 continue;
1298 if (CXXConstructorDecl *BaseCX =
1299 BaseClassDecl->getDefaultConstructor(getContext())) {
1300 LoadOfThis = LoadCXXThis();
1301 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1302 BaseClassDecl);
1303 EmitCXXConstructorCall(BaseCX, Ctor_Complete, V, 0, 0);
1304 }
1305 }
1306
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001307 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1308 FieldEnd = ClassDecl->field_end();
1309 Field != FieldEnd; ++Field) {
1310 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +00001311 const ConstantArrayType *Array =
1312 getContext().getAsConstantArrayType(FieldType);
1313 if (Array) {
1314 FieldType = Array->getElementType();
1315 while (const ConstantArrayType *AT =
1316 getContext().getAsConstantArrayType(FieldType))
1317 FieldType = AT->getElementType();
1318 }
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001319 if (!FieldType->getAs<RecordType>() || Field->isAnonymousStructOrUnion())
1320 continue;
1321 const RecordType *ClassRec = FieldType->getAs<RecordType>();
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001322 CXXRecordDecl *MemberClassDecl =
1323 dyn_cast<CXXRecordDecl>(ClassRec->getDecl());
1324 if (!MemberClassDecl || MemberClassDecl->hasTrivialConstructor())
1325 continue;
1326 if (CXXConstructorDecl *MamberCX =
1327 MemberClassDecl->getDefaultConstructor(getContext())) {
1328 LoadOfThis = LoadCXXThis();
1329 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +00001330 if (Array) {
1331 const llvm::Type *BasePtr = ConvertType(FieldType);
1332 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1333 llvm::Value *BaseAddrPtr =
1334 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1335 EmitCXXAggrConstructorCall(MamberCX, Array, BaseAddrPtr);
1336 }
1337 else
1338 EmitCXXConstructorCall(MamberCX, Ctor_Complete, LHS.getAddress(),
1339 0, 0);
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001340 }
1341 }
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001342 }
1343
Mike Stump7e8c9932009-07-31 18:25:34 +00001344 // Initialize the vtable pointer
Mike Stumpeec46a72009-08-05 22:59:44 +00001345 if (ClassDecl->isDynamicClass()) {
Mike Stump7e8c9932009-07-31 18:25:34 +00001346 if (!LoadOfThis)
1347 LoadOfThis = LoadCXXThis();
1348 llvm::Value *VtableField;
1349 llvm::Type *Ptr8Ty, *PtrPtr8Ty;
Owen Anderson3f5cc0a2009-08-13 21:57:51 +00001350 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Mike Stump7e8c9932009-07-31 18:25:34 +00001351 PtrPtr8Ty = llvm::PointerType::get(Ptr8Ty, 0);
1352 VtableField = Builder.CreateBitCast(LoadOfThis, PtrPtr8Ty);
1353 llvm::Value *vtable = GenerateVtable(ClassDecl);
1354 Builder.CreateStore(vtable, VtableField);
1355 }
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001356}
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001357
1358/// EmitDtorEpilogue - Emit all code that comes at the end of class's
1359/// destructor. This is to call destructors on members and base classes
1360/// in reverse order of their construction.
1361void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD) {
1362 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(DD->getDeclContext());
1363 assert(!ClassDecl->isPolymorphic() &&
1364 "FIXME. polymorphic destruction not supported");
1365 (void)ClassDecl; // prevent warning.
1366
1367 for (CXXDestructorDecl::destr_const_iterator *B = DD->destr_begin(),
1368 *E = DD->destr_end(); B != E; ++B) {
1369 uintptr_t BaseOrMember = (*B);
1370 if (DD->isMemberToDestroy(BaseOrMember)) {
1371 FieldDecl *FD = DD->getMemberToDestroy(BaseOrMember);
1372 QualType FieldType = getContext().getCanonicalType((FD)->getType());
1373 assert(!getContext().getAsArrayType(FieldType)
1374 && "FIXME. Field arrays destruction unsupported");
1375 const RecordType *RT = FieldType->getAs<RecordType>();
1376 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1377 if (FieldClassDecl->hasTrivialDestructor())
1378 continue;
1379 llvm::Value *LoadOfThis = LoadCXXThis();
1380 LValue LHS = EmitLValueForField(LoadOfThis, FD, false, 0);
1381 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1382 Dtor_Complete, LHS.getAddress());
Mike Stump487ce382009-07-30 22:28:39 +00001383 } else {
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001384 const RecordType *RT =
1385 DD->getAnyBaseClassToDestroy(BaseOrMember)->getAs<RecordType>();
1386 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1387 if (BaseClassDecl->hasTrivialDestructor())
1388 continue;
1389 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
1390 ClassDecl,BaseClassDecl);
1391 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1392 Dtor_Complete, V);
1393 }
1394 }
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001395 if (DD->getNumBaseOrMemberDestructions() || DD->isTrivial())
1396 return;
1397 // Case of destructor synthesis with fields and base classes
1398 // which have non-trivial destructors. They must be destructed in
1399 // reverse order of their construction.
1400 llvm::SmallVector<FieldDecl *, 16> DestructedFields;
1401
1402 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1403 FieldEnd = ClassDecl->field_end();
1404 Field != FieldEnd; ++Field) {
1405 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
1406 // FIXME. Assert on arrays for now.
1407 if (const RecordType *RT = FieldType->getAs<RecordType>()) {
1408 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1409 if (FieldClassDecl->hasTrivialDestructor())
1410 continue;
1411 DestructedFields.push_back(*Field);
1412 }
1413 }
1414 if (!DestructedFields.empty())
1415 for (int i = DestructedFields.size() -1; i >= 0; --i) {
1416 FieldDecl *Field = DestructedFields[i];
1417 QualType FieldType = Field->getType();
1418 const RecordType *RT = FieldType->getAs<RecordType>();
1419 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1420 llvm::Value *LoadOfThis = LoadCXXThis();
1421 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
1422 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1423 Dtor_Complete, LHS.getAddress());
1424 }
1425
1426 llvm::SmallVector<CXXRecordDecl*, 4> DestructedBases;
1427 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1428 Base != ClassDecl->bases_end(); ++Base) {
1429 // FIXME. copy assignment of virtual base NYI
1430 if (Base->isVirtual())
1431 continue;
1432
1433 CXXRecordDecl *BaseClassDecl
1434 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1435 if (BaseClassDecl->hasTrivialDestructor())
1436 continue;
1437 DestructedBases.push_back(BaseClassDecl);
1438 }
1439 if (DestructedBases.empty())
1440 return;
1441 for (int i = DestructedBases.size() -1; i >= 0; --i) {
1442 CXXRecordDecl *BaseClassDecl = DestructedBases[i];
1443 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
1444 ClassDecl,BaseClassDecl);
1445 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1446 Dtor_Complete, V);
1447 }
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001448}
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001449
1450void CodeGenFunction::SynthesizeDefaultDestructor(const CXXDestructorDecl *CD,
1451 const FunctionDecl *FD,
1452 llvm::Function *Fn,
1453 const FunctionArgList &Args) {
1454
1455 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1456 assert(!ClassDecl->hasUserDeclaredDestructor() &&
1457 "SynthesizeDefaultDestructor - destructor has user declaration");
1458 (void) ClassDecl;
1459
1460 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1461 EmitDtorEpilogue(CD);
1462 FinishFunction();
1463}