blob: 680d7357b9a434c2a112e4214ab756e349a4998c [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
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000203 const llvm::Type *Ty =
Anders Carlssonc5223142009-04-08 20:31:57 +0000204 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
205 FPT->isVariadic());
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000206 llvm::Value *This;
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000207
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000208 if (ME->isArrow())
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000209 This = EmitScalarExpr(ME->getBase());
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000210 else {
211 LValue BaseLV = EmitLValue(ME->getBase());
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000212 This = BaseLV.getAddress();
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000213 }
Mike Stumpf7d47a52009-08-26 20:46:33 +0000214
Douglas Gregore399ad42009-08-26 22:36:53 +0000215 // C++ [class.virtual]p12:
216 // Explicit qualification with the scope operator (5.1) suppresses the
217 // virtual call mechanism.
Mike Stumpf7d47a52009-08-26 20:46:33 +0000218 llvm::Value *Callee;
Douglas Gregore399ad42009-08-26 22:36:53 +0000219 if (MD->isVirtual() && !isa<CXXQualifiedMemberExpr>(CE)) {
Mike Stumpf7d47a52009-08-26 20:46:33 +0000220 Callee = BuildVirtualCall(MD, This, Ty);
Douglas Gregore399ad42009-08-26 22:36:53 +0000221 } else
Mike Stumpf7d47a52009-08-26 20:46:33 +0000222 Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty);
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000223
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000224 return EmitCXXMemberCall(MD, Callee, This,
225 CE->arg_begin(), CE->arg_end());
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000226}
Anders Carlsson49d4a572009-04-14 16:58:56 +0000227
Anders Carlsson85eca6f2009-05-27 04:18:27 +0000228RValue
229CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
230 const CXXMethodDecl *MD) {
231 assert(MD->isInstance() &&
232 "Trying to emit a member call expr on a static method!");
233
Fariborz Jahanian9da58e42009-08-13 21:09:41 +0000234 if (MD->isCopyAssignment()) {
235 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(MD->getDeclContext());
236 if (ClassDecl->hasTrivialCopyAssignment()) {
237 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
238 "EmitCXXOperatorMemberCallExpr - user declared copy assignment");
239 llvm::Value *This = EmitLValue(E->getArg(0)).getAddress();
240 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
241 QualType Ty = E->getType();
242 EmitAggregateCopy(This, Src, Ty);
243 return RValue::get(This);
244 }
245 }
Anders Carlsson85eca6f2009-05-27 04:18:27 +0000246
247 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
248 const llvm::Type *Ty =
249 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
250 FPT->isVariadic());
251 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty);
252
253 llvm::Value *This = EmitLValue(E->getArg(0)).getAddress();
254
255 return EmitCXXMemberCall(MD, Callee, This,
256 E->arg_begin() + 1, E->arg_end());
257}
258
Anders Carlsson49d4a572009-04-14 16:58:56 +0000259llvm::Value *CodeGenFunction::LoadCXXThis() {
260 assert(isa<CXXMethodDecl>(CurFuncDecl) &&
261 "Must be in a C++ member function decl to load 'this'");
262 assert(cast<CXXMethodDecl>(CurFuncDecl)->isInstance() &&
263 "Must be in a C++ member function decl to load 'this'");
264
265 // FIXME: What if we're inside a block?
Mike Stumpba2cb0e2009-05-16 07:57:57 +0000266 // ans: See how CodeGenFunction::LoadObjCSelf() uses
267 // CodeGenFunction::BlockForwardSelf() for how to do this.
Anders Carlsson49d4a572009-04-14 16:58:56 +0000268 return Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
269}
Anders Carlsson652951a2009-04-15 15:55:24 +0000270
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000271static bool
272GetNestedPaths(llvm::SmallVectorImpl<const CXXRecordDecl *> &NestedBasePaths,
273 const CXXRecordDecl *ClassDecl,
274 const CXXRecordDecl *BaseClassDecl) {
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000275 for (CXXRecordDecl::base_class_const_iterator i = ClassDecl->bases_begin(),
276 e = ClassDecl->bases_end(); i != e; ++i) {
277 if (i->isVirtual())
278 continue;
279 const CXXRecordDecl *Base =
Mike Stumpf3371782009-08-04 21:58:42 +0000280 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000281 if (Base == BaseClassDecl) {
282 NestedBasePaths.push_back(BaseClassDecl);
283 return true;
284 }
285 }
286 // BaseClassDecl not an immediate base of ClassDecl.
287 for (CXXRecordDecl::base_class_const_iterator i = ClassDecl->bases_begin(),
288 e = ClassDecl->bases_end(); i != e; ++i) {
289 if (i->isVirtual())
290 continue;
291 const CXXRecordDecl *Base =
292 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
293 if (GetNestedPaths(NestedBasePaths, Base, BaseClassDecl)) {
294 NestedBasePaths.push_back(Base);
295 return true;
296 }
297 }
298 return false;
299}
300
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000301llvm::Value *CodeGenFunction::AddressCXXOfBaseClass(llvm::Value *BaseValue,
Fariborz Jahanian70277012009-07-28 18:09:28 +0000302 const CXXRecordDecl *ClassDecl,
303 const CXXRecordDecl *BaseClassDecl) {
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000304 if (ClassDecl == BaseClassDecl)
305 return BaseValue;
306
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000307 llvm::Type *I8Ptr = llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000308 llvm::SmallVector<const CXXRecordDecl *, 16> NestedBasePaths;
309 GetNestedPaths(NestedBasePaths, ClassDecl, BaseClassDecl);
310 assert(NestedBasePaths.size() > 0 &&
311 "AddressCXXOfBaseClass - inheritence path failed");
312 NestedBasePaths.push_back(ClassDecl);
313 uint64_t Offset = 0;
314
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000315 // Accessing a member of the base class. Must add delata to
316 // the load of 'this'.
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000317 for (unsigned i = NestedBasePaths.size()-1; i > 0; i--) {
318 const CXXRecordDecl *DerivedClass = NestedBasePaths[i];
319 const CXXRecordDecl *BaseClass = NestedBasePaths[i-1];
320 const ASTRecordLayout &Layout =
321 getContext().getASTRecordLayout(DerivedClass);
322 Offset += Layout.getBaseClassOffset(BaseClass) / 8;
323 }
Fariborz Jahanian83a46ed2009-07-29 15:54:56 +0000324 llvm::Value *OffsetVal =
325 llvm::ConstantInt::get(
326 CGM.getTypes().ConvertType(CGM.getContext().LongTy), Offset);
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000327 BaseValue = Builder.CreateBitCast(BaseValue, I8Ptr);
328 BaseValue = Builder.CreateGEP(BaseValue, OffsetVal, "add.ptr");
329 QualType BTy =
330 getContext().getCanonicalType(
Fariborz Jahanian70277012009-07-28 18:09:28 +0000331 getContext().getTypeDeclType(const_cast<CXXRecordDecl*>(BaseClassDecl)));
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000332 const llvm::Type *BasePtr = ConvertType(BTy);
Owen Anderson7ec2d8f2009-07-29 22:16:19 +0000333 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000334 BaseValue = Builder.CreateBitCast(BaseValue, BasePtr);
335 return BaseValue;
336}
337
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000338/// EmitCXXAggrConstructorCall - This routine essentially creates a (nested)
339/// for-loop to call the default constructor on individual members of the
340/// array. 'Array' is the array type, 'This' is llvm pointer of the start
341/// of the array and 'D' is the default costructor Decl for elements of the
342/// array. It is assumed that all relevant checks have been made by the
343/// caller.
344void
345CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
346 const ArrayType *Array,
347 llvm::Value *This) {
348 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
349 assert(CA && "Do we support VLA for construction ?");
350
351 // Create a temporary for the loop index and initialize it with 0.
Fariborz Jahaniandae3e752009-08-21 16:31:06 +0000352 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000353 "loop.index");
354 llvm::Value* zeroConstant =
Fariborz Jahaniandae3e752009-08-21 16:31:06 +0000355 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000356 Builder.CreateStore(zeroConstant, IndexPtr, false);
357
358 // Start the loop with a block that tests the condition.
359 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
360 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
361
362 EmitBlock(CondBlock);
363
364 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
365
366 // Generate: if (loop-index < number-of-elements fall to the loop body,
367 // otherwise, go to the block after the for-loop.
Fariborz Jahanian58a7eca2009-08-26 00:23:27 +0000368 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000369 llvm::Value * NumElementsPtr =
Fariborz Jahanian58a7eca2009-08-26 00:23:27 +0000370 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000371 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
372 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
373 "isless");
374 // If the condition is true, execute the body.
375 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
376
377 EmitBlock(ForBody);
378
379 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000380 // Inside the loop body, emit the constructor call on the array element.
Fariborz Jahaniana0ab7352009-08-20 01:01:06 +0000381 Counter = Builder.CreateLoad(IndexPtr);
Fariborz Jahanian58a7eca2009-08-26 00:23:27 +0000382 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
383 EmitCXXConstructorCall(D, Ctor_Complete, Address, 0, 0);
Fariborz Jahanianf36f8d22009-08-20 00:15:15 +0000384
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000385 EmitBlock(ContinueBlock);
386
387 // Emit the increment of the loop counter.
388 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
389 Counter = Builder.CreateLoad(IndexPtr);
390 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
391 Builder.CreateStore(NextVal, IndexPtr, false);
392
393 // Finally, branch back up to the condition for the next iteration.
394 EmitBranch(CondBlock);
395
396 // Emit the fall-through block.
397 EmitBlock(AfterFor, true);
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000398}
399
Fariborz Jahanian25879ce2009-08-20 23:02:58 +0000400/// EmitCXXAggrDestructorCall - calls the default destructor on array
401/// elements in reverse order of construction.
Anders Carlsson72f48292009-04-17 00:06:03 +0000402void
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +0000403CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
404 const ArrayType *Array,
405 llvm::Value *This) {
Fariborz Jahanian25879ce2009-08-20 23:02:58 +0000406 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
407 assert(CA && "Do we support VLA for destruction ?");
408 llvm::Value *One = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
409 1);
Fariborz Jahaniandae3e752009-08-21 16:31:06 +0000410 uint64_t ElementCount = getContext().getConstantArrayElementCount(CA);
Fariborz Jahanian25879ce2009-08-20 23:02:58 +0000411 // Create a temporary for the loop index and initialize it with count of
412 // array elements.
413 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
414 "loop.index");
415 // Index = ElementCount;
416 llvm::Value* UpperCount =
417 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), ElementCount);
418 Builder.CreateStore(UpperCount, IndexPtr, false);
419
420 // Start the loop with a block that tests the condition.
421 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
422 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
423
424 EmitBlock(CondBlock);
425
426 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
427
428 // Generate: if (loop-index != 0 fall to the loop body,
429 // otherwise, go to the block after the for-loop.
430 llvm::Value* zeroConstant =
431 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
432 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
433 llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant,
434 "isne");
435 // If the condition is true, execute the body.
436 Builder.CreateCondBr(IsNE, ForBody, AfterFor);
437
438 EmitBlock(ForBody);
439
440 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
441 // Inside the loop body, emit the constructor call on the array element.
442 Counter = Builder.CreateLoad(IndexPtr);
443 Counter = Builder.CreateSub(Counter, One);
444 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
445 EmitCXXDestructorCall(D, Dtor_Complete, Address);
446
447 EmitBlock(ContinueBlock);
448
449 // Emit the decrement of the loop counter.
450 Counter = Builder.CreateLoad(IndexPtr);
451 Counter = Builder.CreateSub(Counter, One, "dec");
452 Builder.CreateStore(Counter, IndexPtr, false);
453
454 // Finally, branch back up to the condition for the next iteration.
455 EmitBranch(CondBlock);
456
457 // Emit the fall-through block.
458 EmitBlock(AfterFor, true);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +0000459}
460
461void
Anders Carlsson72f48292009-04-17 00:06:03 +0000462CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
463 CXXCtorType Type,
464 llvm::Value *This,
465 CallExpr::const_arg_iterator ArgBeg,
466 CallExpr::const_arg_iterator ArgEnd) {
Fariborz Jahanian0fc5f252009-08-14 20:11:43 +0000467 if (D->isCopyConstructor(getContext())) {
468 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D->getDeclContext());
469 if (ClassDecl->hasTrivialCopyConstructor()) {
470 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
471 "EmitCXXConstructorCall - user declared copy constructor");
472 const Expr *E = (*ArgBeg);
473 QualType Ty = E->getType();
474 llvm::Value *Src = EmitLValue(E).getAddress();
475 EmitAggregateCopy(This, Src, Ty);
476 return;
477 }
478 }
479
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000480 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
481
482 EmitCXXMemberCall(D, Callee, This, ArgBeg, ArgEnd);
Anders Carlsson72f48292009-04-17 00:06:03 +0000483}
484
Anders Carlssond3f6b162009-05-29 21:03:38 +0000485void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *D,
486 CXXDtorType Type,
487 llvm::Value *This) {
488 llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(D, Type);
489
490 EmitCXXMemberCall(D, Callee, This, 0, 0);
491}
492
Anders Carlsson72f48292009-04-17 00:06:03 +0000493void
Anders Carlsson342aadc2009-05-03 17:47:16 +0000494CodeGenFunction::EmitCXXConstructExpr(llvm::Value *Dest,
495 const CXXConstructExpr *E) {
Anders Carlsson72f48292009-04-17 00:06:03 +0000496 assert(Dest && "Must have a destination!");
497
498 const CXXRecordDecl *RD =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000499 cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson72f48292009-04-17 00:06:03 +0000500 if (RD->hasTrivialConstructor())
501 return;
Fariborz Jahanian884036a2009-08-06 01:02:49 +0000502
503 // Code gen optimization to eliminate copy constructor and return
504 // its first argument instead.
Anders Carlsson9a0c2a52009-08-22 22:30:33 +0000505 if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
Fariborz Jahanian884036a2009-08-06 01:02:49 +0000506 CXXConstructExpr::const_arg_iterator i = E->arg_begin();
Fariborz Jahanian325cdd82009-08-06 19:12:38 +0000507 EmitAggExpr((*i), Dest, false);
508 return;
Fariborz Jahanian884036a2009-08-06 01:02:49 +0000509 }
Anders Carlsson72f48292009-04-17 00:06:03 +0000510 // Call the constructor.
511 EmitCXXConstructorCall(E->getConstructor(), Ctor_Complete, Dest,
512 E->arg_begin(), E->arg_end());
513}
514
Anders Carlsson18e88bc2009-05-31 01:40:14 +0000515llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
Anders Carlssond5536972009-05-31 20:21:44 +0000516 if (E->isArray()) {
517 ErrorUnsupported(E, "new[] expression");
Owen Andersone0b5eff2009-07-30 23:11:26 +0000518 return llvm::UndefValue::get(ConvertType(E->getType()));
Anders Carlssond5536972009-05-31 20:21:44 +0000519 }
520
521 QualType AllocType = E->getAllocatedType();
522 FunctionDecl *NewFD = E->getOperatorNew();
523 const FunctionProtoType *NewFTy = NewFD->getType()->getAsFunctionProtoType();
524
525 CallArgList NewArgs;
526
527 // The allocation size is the first argument.
528 QualType SizeTy = getContext().getSizeType();
529 llvm::Value *AllocSize =
Owen Andersonb17ec712009-07-24 23:12:58 +0000530 llvm::ConstantInt::get(ConvertType(SizeTy),
Anders Carlssond5536972009-05-31 20:21:44 +0000531 getContext().getTypeSize(AllocType) / 8);
532
533 NewArgs.push_back(std::make_pair(RValue::get(AllocSize), SizeTy));
534
535 // Emit the rest of the arguments.
536 // FIXME: Ideally, this should just use EmitCallArgs.
537 CXXNewExpr::const_arg_iterator NewArg = E->placement_arg_begin();
538
539 // First, use the types from the function type.
540 // We start at 1 here because the first argument (the allocation size)
541 // has already been emitted.
542 for (unsigned i = 1, e = NewFTy->getNumArgs(); i != e; ++i, ++NewArg) {
543 QualType ArgType = NewFTy->getArgType(i);
544
545 assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
546 getTypePtr() ==
547 getContext().getCanonicalType(NewArg->getType()).getTypePtr() &&
548 "type mismatch in call argument!");
549
550 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
551 ArgType));
552
553 }
554
555 // Either we've emitted all the call args, or we have a call to a
556 // variadic function.
557 assert((NewArg == E->placement_arg_end() || NewFTy->isVariadic()) &&
558 "Extra arguments in non-variadic function!");
559
560 // If we still have any arguments, emit them using the type of the argument.
561 for (CXXNewExpr::const_arg_iterator NewArgEnd = E->placement_arg_end();
562 NewArg != NewArgEnd; ++NewArg) {
563 QualType ArgType = NewArg->getType();
564 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
565 ArgType));
566 }
567
568 // Emit the call to new.
569 RValue RV =
570 EmitCall(CGM.getTypes().getFunctionInfo(NewFTy->getResultType(), NewArgs),
571 CGM.GetAddrOfFunction(GlobalDecl(NewFD)),
572 NewArgs, NewFD);
573
Anders Carlsson11269042009-05-31 21:53:59 +0000574 // If an allocation function is declared with an empty exception specification
575 // it returns null to indicate failure to allocate storage. [expr.new]p13.
576 // (We don't need to check for null when there's no new initializer and
577 // we're allocating a POD type).
578 bool NullCheckResult = NewFTy->hasEmptyExceptionSpec() &&
579 !(AllocType->isPODType() && !E->hasInitializer());
Anders Carlssond5536972009-05-31 20:21:44 +0000580
Anders Carlssondbee9a52009-06-01 00:05:16 +0000581 llvm::BasicBlock *NewNull = 0;
582 llvm::BasicBlock *NewNotNull = 0;
583 llvm::BasicBlock *NewEnd = 0;
584
585 llvm::Value *NewPtr = RV.getScalarVal();
586
Anders Carlsson11269042009-05-31 21:53:59 +0000587 if (NullCheckResult) {
Anders Carlssondbee9a52009-06-01 00:05:16 +0000588 NewNull = createBasicBlock("new.null");
589 NewNotNull = createBasicBlock("new.notnull");
590 NewEnd = createBasicBlock("new.end");
591
592 llvm::Value *IsNull =
593 Builder.CreateICmpEQ(NewPtr,
Owen Andersonf37b84b2009-07-31 20:28:54 +0000594 llvm::Constant::getNullValue(NewPtr->getType()),
Anders Carlssondbee9a52009-06-01 00:05:16 +0000595 "isnull");
596
597 Builder.CreateCondBr(IsNull, NewNull, NewNotNull);
598 EmitBlock(NewNotNull);
Anders Carlsson11269042009-05-31 21:53:59 +0000599 }
600
Anders Carlssondbee9a52009-06-01 00:05:16 +0000601 NewPtr = Builder.CreateBitCast(NewPtr, ConvertType(E->getType()));
Anders Carlsson11269042009-05-31 21:53:59 +0000602
Anders Carlsson7c294782009-05-31 20:56:36 +0000603 if (AllocType->isPODType()) {
Anders Carlsson26910f62009-06-01 00:26:14 +0000604 if (E->getNumConstructorArgs() > 0) {
Anders Carlsson7c294782009-05-31 20:56:36 +0000605 assert(E->getNumConstructorArgs() == 1 &&
606 "Can only have one argument to initializer of POD type.");
607
608 const Expr *Init = E->getConstructorArg(0);
609
Anders Carlsson5f93ccf2009-05-31 21:07:58 +0000610 if (!hasAggregateLLVMType(AllocType))
Anders Carlsson7c294782009-05-31 20:56:36 +0000611 Builder.CreateStore(EmitScalarExpr(Init), NewPtr);
Anders Carlsson5f93ccf2009-05-31 21:07:58 +0000612 else if (AllocType->isAnyComplexType())
613 EmitComplexExprIntoAddr(Init, NewPtr, AllocType.isVolatileQualified());
Anders Carlssoneb39b432009-05-31 21:12:26 +0000614 else
615 EmitAggExpr(Init, NewPtr, AllocType.isVolatileQualified());
Anders Carlsson7c294782009-05-31 20:56:36 +0000616 }
Anders Carlsson11269042009-05-31 21:53:59 +0000617 } else {
618 // Call the constructor.
619 CXXConstructorDecl *Ctor = E->getConstructor();
Anders Carlsson7c294782009-05-31 20:56:36 +0000620
Anders Carlsson11269042009-05-31 21:53:59 +0000621 EmitCXXConstructorCall(Ctor, Ctor_Complete, NewPtr,
622 E->constructor_arg_begin(),
623 E->constructor_arg_end());
Anders Carlssond5536972009-05-31 20:21:44 +0000624 }
Anders Carlsson11269042009-05-31 21:53:59 +0000625
Anders Carlssondbee9a52009-06-01 00:05:16 +0000626 if (NullCheckResult) {
627 Builder.CreateBr(NewEnd);
628 EmitBlock(NewNull);
629 Builder.CreateBr(NewEnd);
630 EmitBlock(NewEnd);
631
632 llvm::PHINode *PHI = Builder.CreatePHI(NewPtr->getType());
633 PHI->reserveOperandSpace(2);
634 PHI->addIncoming(NewPtr, NewNotNull);
Owen Andersonf37b84b2009-07-31 20:28:54 +0000635 PHI->addIncoming(llvm::Constant::getNullValue(NewPtr->getType()), NewNull);
Anders Carlssondbee9a52009-06-01 00:05:16 +0000636
637 NewPtr = PHI;
638 }
639
Anders Carlsson11269042009-05-31 21:53:59 +0000640 return NewPtr;
Anders Carlsson18e88bc2009-05-31 01:40:14 +0000641}
642
Anders Carlsson133fdaf2009-08-16 21:13:42 +0000643void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
644 if (E->isArrayForm()) {
645 ErrorUnsupported(E, "delete[] expression");
646 return;
647 };
648
649 QualType DeleteTy =
650 E->getArgument()->getType()->getAs<PointerType>()->getPointeeType();
651
652 llvm::Value *Ptr = EmitScalarExpr(E->getArgument());
653
654 // Null check the pointer.
655 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
656 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
657
658 llvm::Value *IsNull =
659 Builder.CreateICmpEQ(Ptr, llvm::Constant::getNullValue(Ptr->getType()),
660 "isnull");
661
662 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
663 EmitBlock(DeleteNotNull);
664
665 // Call the destructor if necessary.
666 if (const RecordType *RT = DeleteTy->getAs<RecordType>()) {
667 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
668 if (!RD->hasTrivialDestructor()) {
669 const CXXDestructorDecl *Dtor = RD->getDestructor(getContext());
670 if (Dtor->isVirtual()) {
671 ErrorUnsupported(E, "delete expression with virtual destructor");
672 return;
673 }
674
675 EmitCXXDestructorCall(Dtor, Dtor_Complete, Ptr);
676 }
677 }
678 }
679
680 // Call delete.
681 FunctionDecl *DeleteFD = E->getOperatorDelete();
682 const FunctionProtoType *DeleteFTy =
683 DeleteFD->getType()->getAsFunctionProtoType();
684
685 CallArgList DeleteArgs;
686
687 QualType ArgTy = DeleteFTy->getArgType(0);
688 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
689 DeleteArgs.push_back(std::make_pair(RValue::get(DeletePtr), ArgTy));
690
691 // Emit the call to delete.
692 EmitCall(CGM.getTypes().getFunctionInfo(DeleteFTy->getResultType(),
693 DeleteArgs),
694 CGM.GetAddrOfFunction(GlobalDecl(DeleteFD)),
695 DeleteArgs, DeleteFD);
696
697 EmitBlock(DeleteEnd);
698}
699
Anders Carlsson4811c302009-04-17 01:58:57 +0000700static bool canGenerateCXXstructor(const CXXRecordDecl *RD,
701 ASTContext &Context) {
Anders Carlsson8496c692009-04-15 21:02:13 +0000702 // The class has base classes - we don't support that right now.
703 if (RD->getNumBases() > 0)
704 return false;
705
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000706 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
707 I != E; ++I) {
Anders Carlsson8496c692009-04-15 21:02:13 +0000708 // We don't support ctors for fields that aren't POD.
709 if (!I->getType()->isPODType())
710 return false;
711 }
712
713 return true;
714}
715
Anders Carlsson652951a2009-04-15 15:55:24 +0000716void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) {
Anders Carlsson4811c302009-04-17 01:58:57 +0000717 if (!canGenerateCXXstructor(D->getParent(), getContext())) {
Anders Carlsson8496c692009-04-15 21:02:13 +0000718 ErrorUnsupported(D, "C++ constructor", true);
719 return;
720 }
Anders Carlsson652951a2009-04-15 15:55:24 +0000721
Anders Carlsson1764af42009-05-05 04:44:02 +0000722 EmitGlobal(GlobalDecl(D, Ctor_Complete));
723 EmitGlobal(GlobalDecl(D, Ctor_Base));
Anders Carlsson652951a2009-04-15 15:55:24 +0000724}
Anders Carlsson890a9fd2009-04-16 23:57:24 +0000725
Anders Carlsson4811c302009-04-17 01:58:57 +0000726void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D,
727 CXXCtorType Type) {
728
729 llvm::Function *Fn = GetAddrOfCXXConstructor(D, Type);
730
731 CodeGenFunction(*this).GenerateCode(D, Fn);
732
733 SetFunctionDefinitionAttributes(D, Fn);
734 SetLLVMFunctionAttributesForDefinition(D, Fn);
735}
736
Anders Carlsson890a9fd2009-04-16 23:57:24 +0000737llvm::Function *
738CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
739 CXXCtorType Type) {
740 const llvm::FunctionType *FTy =
741 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false);
742
743 const char *Name = getMangledCXXCtorName(D, Type);
Chris Lattner80f39cc2009-05-12 21:21:08 +0000744 return cast<llvm::Function>(
745 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson890a9fd2009-04-16 23:57:24 +0000746}
Anders Carlsson4811c302009-04-17 01:58:57 +0000747
748const char *CodeGenModule::getMangledCXXCtorName(const CXXConstructorDecl *D,
749 CXXCtorType Type) {
750 llvm::SmallString<256> Name;
751 llvm::raw_svector_ostream Out(Name);
752 mangleCXXCtor(D, Type, Context, Out);
753
754 Name += '\0';
755 return UniqueMangledName(Name.begin(), Name.end());
756}
757
758void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) {
759 if (!canGenerateCXXstructor(D->getParent(), getContext())) {
760 ErrorUnsupported(D, "C++ destructor", true);
761 return;
762 }
763
764 EmitCXXDestructor(D, Dtor_Complete);
765 EmitCXXDestructor(D, Dtor_Base);
766}
767
768void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D,
769 CXXDtorType Type) {
770 llvm::Function *Fn = GetAddrOfCXXDestructor(D, Type);
771
772 CodeGenFunction(*this).GenerateCode(D, Fn);
773
774 SetFunctionDefinitionAttributes(D, Fn);
775 SetLLVMFunctionAttributesForDefinition(D, Fn);
776}
777
778llvm::Function *
779CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D,
780 CXXDtorType Type) {
781 const llvm::FunctionType *FTy =
782 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false);
783
784 const char *Name = getMangledCXXDtorName(D, Type);
Chris Lattner80f39cc2009-05-12 21:21:08 +0000785 return cast<llvm::Function>(
786 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson4811c302009-04-17 01:58:57 +0000787}
788
789const char *CodeGenModule::getMangledCXXDtorName(const CXXDestructorDecl *D,
790 CXXDtorType Type) {
791 llvm::SmallString<256> Name;
792 llvm::raw_svector_ostream Out(Name);
793 mangleCXXDtor(D, Type, Context, Out);
794
795 Name += '\0';
796 return UniqueMangledName(Name.begin(), Name.end());
797}
Fariborz Jahanian5400e022009-07-20 23:18:55 +0000798
Mike Stumpdca5e512009-08-18 21:49:00 +0000799llvm::Constant *CodeGenModule::GenerateRtti(const CXXRecordDecl *RD) {
Mike Stump00df7d32009-07-31 23:15:31 +0000800 llvm::Type *Ptr8Ty;
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000801 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Mike Stump69a12322009-08-04 20:06:48 +0000802 llvm::Constant *Rtti = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stump00df7d32009-07-31 23:15:31 +0000803
804 if (!getContext().getLangOptions().Rtti)
Mike Stump69a12322009-08-04 20:06:48 +0000805 return Rtti;
Mike Stump00df7d32009-07-31 23:15:31 +0000806
807 llvm::SmallString<256> OutName;
808 llvm::raw_svector_ostream Out(OutName);
809 QualType ClassTy;
Mike Stumpe7545622009-08-07 18:05:12 +0000810 ClassTy = getContext().getTagDeclType(RD);
Mike Stump00df7d32009-07-31 23:15:31 +0000811 mangleCXXRtti(ClassTy, getContext(), Out);
Mike Stump00df7d32009-07-31 23:15:31 +0000812 llvm::GlobalVariable::LinkageTypes linktype;
813 linktype = llvm::GlobalValue::WeakAnyLinkage;
814 std::vector<llvm::Constant *> info;
Mike Stump2eade572009-08-13 22:53:07 +0000815 // assert(0 && "FIXME: implement rtti descriptor");
Mike Stump00df7d32009-07-31 23:15:31 +0000816 // FIXME: descriptor
817 info.push_back(llvm::Constant::getNullValue(Ptr8Ty));
Mike Stump2eade572009-08-13 22:53:07 +0000818 // assert(0 && "FIXME: implement rtti ts");
Mike Stump00df7d32009-07-31 23:15:31 +0000819 // FIXME: TS
820 info.push_back(llvm::Constant::getNullValue(Ptr8Ty));
821
822 llvm::Constant *C;
823 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, info.size());
824 C = llvm::ConstantArray::get(type, info);
Mike Stumpdca5e512009-08-18 21:49:00 +0000825 Rtti = new llvm::GlobalVariable(getModule(), type, true, linktype, C,
Daniel Dunbar0433a022009-08-19 20:04:03 +0000826 Out.str());
Mike Stump69a12322009-08-04 20:06:48 +0000827 Rtti = llvm::ConstantExpr::getBitCast(Rtti, Ptr8Ty);
828 return Rtti;
Mike Stump00df7d32009-07-31 23:15:31 +0000829}
830
Mike Stump86a859e2009-08-19 18:10:47 +0000831class VtableBuilder {
Mike Stumpf7d47a52009-08-26 20:46:33 +0000832public:
833 /// Index_t - Vtable index type.
834 typedef uint64_t Index_t;
835private:
Mike Stumpad734d12009-08-18 20:50:28 +0000836 std::vector<llvm::Constant *> &methods;
837 llvm::Type *Ptr8Ty;
Mike Stumpf07ede52009-08-21 01:45:00 +0000838 /// Class - The most derived class that this vtable is being built for.
Mike Stumpdca5e512009-08-18 21:49:00 +0000839 const CXXRecordDecl *Class;
Mike Stumpf07ede52009-08-21 01:45:00 +0000840 /// BLayout - Layout for the most derived class that this vtable is being
841 /// built for.
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000842 const ASTRecordLayout &BLayout;
Mike Stumpa7ec675d2009-08-19 14:40:47 +0000843 llvm::SmallSet<const CXXRecordDecl *, 32> IndirectPrimary;
Mike Stump2b9ba612009-08-20 02:11:48 +0000844 llvm::SmallSet<const CXXRecordDecl *, 32> SeenVBase;
Mike Stumpdca5e512009-08-18 21:49:00 +0000845 llvm::Constant *rtti;
Mike Stumpad734d12009-08-18 20:50:28 +0000846 llvm::LLVMContext &VMContext;
Mike Stump1e10cf32009-08-18 21:03:28 +0000847 CodeGenModule &CGM; // Per-module state.
Mike Stumpf07ede52009-08-21 01:45:00 +0000848 /// Index - Maps a method decl into a vtable index. Useful for virtual
849 /// dispatch codegen.
Mike Stumpf7d47a52009-08-26 20:46:33 +0000850 llvm::DenseMap<const CXXMethodDecl *, Index_t> Index;
Mike Stumpd75d3232009-08-18 22:04:08 +0000851 typedef CXXRecordDecl::method_iterator method_iter;
Mike Stumpad734d12009-08-18 20:50:28 +0000852public:
Mike Stump86a859e2009-08-19 18:10:47 +0000853 VtableBuilder(std::vector<llvm::Constant *> &meth,
854 const CXXRecordDecl *c,
855 CodeGenModule &cgm)
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000856 : methods(meth), Class(c), BLayout(cgm.getContext().getASTRecordLayout(c)),
857 rtti(cgm.GenerateRtti(c)), VMContext(cgm.getModule().getContext()),
858 CGM(cgm) {
Mike Stumpad734d12009-08-18 20:50:28 +0000859 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
860 }
Mike Stumpdca5e512009-08-18 21:49:00 +0000861
Mike Stumpf7d47a52009-08-26 20:46:33 +0000862 llvm::DenseMap<const CXXMethodDecl *, Index_t> &getIndex() { return Index; }
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000863 llvm::Constant *GenerateVcall(const CXXMethodDecl *MD,
864 const CXXRecordDecl *RD,
865 bool VBoundary,
866 bool SecondaryVirtual) {
Mike Stump00962322009-08-21 23:09:30 +0000867 typedef CXXMethodDecl::method_iterator meth_iter;
868 // No vcall for methods that don't override in primary vtables.
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000869 llvm::Constant *m = 0;
870
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000871 if (SecondaryVirtual || VBoundary)
872 m = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stump00962322009-08-21 23:09:30 +0000873
874 int64_t Offset = 0;
875 int64_t BaseOffset = 0;
876 for (meth_iter mi = MD->begin_overridden_methods(),
877 me = MD->end_overridden_methods();
878 mi != me; ++mi) {
879 const CXXRecordDecl *DefBase = (*mi)->getParent();
880 // FIXME: vcall: offset for virtual base for this function
881 // m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), 900);
882 // m = llvm::Constant::getNullValue(Ptr8Ty);
883 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
884 e = RD->bases_end(); i != e; ++i) {
885 const CXXRecordDecl *Base =
886 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
887 if (DefBase == Base) {
888 if (!i->isVirtual())
889 break;
890
891 // FIXME: drop the 700-, just for debugging
892 BaseOffset = 700- -(BLayout.getVBaseClassOffset(Base) / 8);
893 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
894 BaseOffset);
895 m = llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
896 break;
897 } else {
898 // FIXME: more searching.
899 (void)Offset;
900 }
901 }
902 }
903
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000904 return m;
905 }
906
907 void GenerateVcalls(const CXXRecordDecl *RD, bool VBoundary,
908 bool SecondaryVirtual) {
Mike Stumpad734d12009-08-18 20:50:28 +0000909 llvm::Constant *m;
Mike Stump23b238e2009-08-12 23:25:18 +0000910
Mike Stumpd75d3232009-08-18 22:04:08 +0000911 for (method_iter mi = RD->method_begin(),
Mike Stumpad734d12009-08-18 20:50:28 +0000912 me = RD->method_end(); mi != me; ++mi) {
913 if (mi->isVirtual()) {
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000914 m = GenerateVcall(*mi, RD, VBoundary, SecondaryVirtual);
915 if (m)
916 methods.push_back(m);
Mike Stumpad734d12009-08-18 20:50:28 +0000917 }
Mike Stumpf640de52009-08-12 23:14:12 +0000918 }
Mike Stump23b238e2009-08-12 23:25:18 +0000919 }
Mike Stumpf640de52009-08-12 23:14:12 +0000920
Mike Stump2b9ba612009-08-20 02:11:48 +0000921 void GenerateVBaseOffsets(std::vector<llvm::Constant *> &offsets,
Mike Stumpaf0d0452009-08-20 07:22:17 +0000922 const CXXRecordDecl *RD, uint64_t Offset) {
Mike Stump2b9ba612009-08-20 02:11:48 +0000923 for (CXXRecordDecl::base_class_const_iterator i =RD->bases_begin(),
924 e = RD->bases_end(); i != e; ++i) {
925 const CXXRecordDecl *Base =
926 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
927 if (i->isVirtual() && !SeenVBase.count(Base)) {
928 SeenVBase.insert(Base);
Mike Stumpaf0d0452009-08-20 07:22:17 +0000929 int64_t BaseOffset = -(Offset/8) + BLayout.getVBaseClassOffset(Base)/8;
Mike Stump2b9ba612009-08-20 02:11:48 +0000930 llvm::Constant *m;
Mike Stumpaf0d0452009-08-20 07:22:17 +0000931 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),BaseOffset);
Mike Stump2b9ba612009-08-20 02:11:48 +0000932 m = llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
933 offsets.push_back(m);
934 }
Mike Stumpaf0d0452009-08-20 07:22:17 +0000935 GenerateVBaseOffsets(offsets, Base, Offset);
Mike Stump2b9ba612009-08-20 02:11:48 +0000936 }
937 }
938
Mike Stumpf07ede52009-08-21 01:45:00 +0000939 void StartNewTable() {
940 SeenVBase.clear();
941 }
Mike Stumpdecd7812009-08-12 23:00:59 +0000942
Mike Stumpf7d47a52009-08-26 20:46:33 +0000943 void AddMethod(const CXXMethodDecl *MD, Index_t AddressPoint) {
Mike Stumpf07ede52009-08-21 01:45:00 +0000944 typedef CXXMethodDecl::method_iterator meth_iter;
945
946 llvm::Constant *m;
947 m = CGM.GetAddrOfFunction(GlobalDecl(MD), Ptr8Ty);
948 m = llvm::ConstantExpr::getBitCast(m, Ptr8Ty);
949
950 // FIXME: Don't like the nested loops. For very large inheritance
951 // heirarchies we could have a table on the side with the final overridder
952 // and just replace each instance of an overridden method once. Would be
953 // nice to measure the cost/benefit on real code.
954
955 // If we can find a previously allocated slot for this, reuse it.
956 for (meth_iter mi = MD->begin_overridden_methods(),
957 e = MD->end_overridden_methods();
958 mi != e; ++mi) {
959 const CXXMethodDecl *OMD = *mi;
960 llvm::Constant *om;
961 om = CGM.GetAddrOfFunction(GlobalDecl(OMD), Ptr8Ty);
962 om = llvm::ConstantExpr::getBitCast(om, Ptr8Ty);
963
Mike Stumpf7d47a52009-08-26 20:46:33 +0000964 for (Index_t i = AddressPoint, e = methods.size();
965 i != e; ++i) {
Mike Stumpf07ede52009-08-21 01:45:00 +0000966 // FIXME: begin_overridden_methods might be too lax, covariance */
967 if (methods[i] == om) {
968 methods[i] = m;
Mike Stumpf7d47a52009-08-26 20:46:33 +0000969 Index[MD] = i - AddressPoint;
Mike Stumpf07ede52009-08-21 01:45:00 +0000970 return;
971 }
Mike Stump1e10cf32009-08-18 21:03:28 +0000972 }
Mike Stumpdecd7812009-08-12 23:00:59 +0000973 }
Mike Stumpf07ede52009-08-21 01:45:00 +0000974
975 // else allocate a new slot.
Mike Stumpf7d47a52009-08-26 20:46:33 +0000976 Index[MD] = methods.size() - AddressPoint;
Mike Stumpf07ede52009-08-21 01:45:00 +0000977 methods.push_back(m);
978 }
979
Mike Stumpf7d47a52009-08-26 20:46:33 +0000980 void GenerateMethods(const CXXRecordDecl *RD, Index_t AddressPoint) {
Mike Stumpf07ede52009-08-21 01:45:00 +0000981 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
982 ++mi)
983 if (mi->isVirtual())
Mike Stumpf7d47a52009-08-26 20:46:33 +0000984 AddMethod(*mi, AddressPoint);
Mike Stumpdecd7812009-08-12 23:00:59 +0000985 }
Mike Stump1e10cf32009-08-18 21:03:28 +0000986
Mike Stump00962322009-08-21 23:09:30 +0000987 int64_t GenerateVtableForBase(const CXXRecordDecl *RD,
988 bool forPrimary,
989 bool VBoundary,
990 int64_t Offset,
Mike Stumpf7d47a52009-08-26 20:46:33 +0000991 bool ForVirtualBase) {
Mike Stump7bae1282009-08-18 21:30:21 +0000992 llvm::Constant *m = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stump00962322009-08-21 23:09:30 +0000993 int64_t AddressPoint=0;
Mike Stumpc57b8272009-08-16 01:46:26 +0000994
Mike Stump7bae1282009-08-18 21:30:21 +0000995 if (RD && !RD->isDynamicClass())
Mike Stump00962322009-08-21 23:09:30 +0000996 return 0;
Mike Stump7bae1282009-08-18 21:30:21 +0000997
998 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
999 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
1000 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
1001
Mike Stumpb6ff81e2009-08-19 02:06:38 +00001002 if (VBoundary || forPrimary || ForVirtualBase) {
1003 // then comes the the vcall offsets for all our functions...
1004 GenerateVcalls(RD, VBoundary, !forPrimary && ForVirtualBase);
1005 }
1006
Mike Stump7bae1282009-08-18 21:30:21 +00001007 // The virtual base offsets come first...
1008 // FIXME: Audit, is this right?
Mike Stump4c1c8912009-08-19 02:53:08 +00001009 if (PrimaryBase == 0 || forPrimary || !PrimaryBaseWasVirtual) {
Mike Stump7bae1282009-08-18 21:30:21 +00001010 std::vector<llvm::Constant *> offsets;
Mike Stumpaf0d0452009-08-20 07:22:17 +00001011 GenerateVBaseOffsets(offsets, RD, Offset);
Mike Stump7bae1282009-08-18 21:30:21 +00001012 for (std::vector<llvm::Constant *>::reverse_iterator i = offsets.rbegin(),
1013 e = offsets.rend(); i != e; ++i)
1014 methods.push_back(*i);
1015 }
1016
Mike Stump7bae1282009-08-18 21:30:21 +00001017 bool Top = true;
1018
1019 // vtables are composed from the chain of primaries.
1020 if (PrimaryBase) {
1021 if (PrimaryBaseWasVirtual)
1022 IndirectPrimary.insert(PrimaryBase);
1023 Top = false;
Mike Stumpf7d47a52009-08-26 20:46:33 +00001024 AddressPoint = GenerateVtableForBase(PrimaryBase, true,
1025 PrimaryBaseWasVirtual|VBoundary,
1026 Offset, PrimaryBaseWasVirtual);
Mike Stump7bae1282009-08-18 21:30:21 +00001027 }
1028
1029 if (Top) {
1030 int64_t BaseOffset;
1031 if (ForVirtualBase) {
Mike Stump7bae1282009-08-18 21:30:21 +00001032 BaseOffset = -(BLayout.getVBaseClassOffset(RD) / 8);
1033 } else
1034 BaseOffset = -Offset/8;
Mike Stumpc57b8272009-08-16 01:46:26 +00001035 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), BaseOffset);
1036 m = llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
1037 methods.push_back(m);
Mike Stump7bae1282009-08-18 21:30:21 +00001038 methods.push_back(rtti);
Mike Stump00962322009-08-21 23:09:30 +00001039 AddressPoint = methods.size();
Mike Stumpc57b8272009-08-16 01:46:26 +00001040 }
Mike Stump2eade572009-08-13 22:53:07 +00001041
Mike Stump7bae1282009-08-18 21:30:21 +00001042 // And add the virtuals for the class to the primary vtable.
Mike Stumpf7d47a52009-08-26 20:46:33 +00001043 GenerateMethods(RD, AddressPoint);
Mike Stump7bae1282009-08-18 21:30:21 +00001044
1045 // and then the non-virtual bases.
1046 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1047 e = RD->bases_end(); i != e; ++i) {
1048 if (i->isVirtual())
1049 continue;
1050 const CXXRecordDecl *Base =
1051 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1052 if (Base != PrimaryBase || PrimaryBaseWasVirtual) {
1053 uint64_t o = Offset + Layout.getBaseClassOffset(Base);
Mike Stumpf07ede52009-08-21 01:45:00 +00001054 StartNewTable();
Mike Stumpf7d47a52009-08-26 20:46:33 +00001055 GenerateVtableForBase(Base, true, false, o, false);
Mike Stump7bae1282009-08-18 21:30:21 +00001056 }
1057 }
Mike Stump00962322009-08-21 23:09:30 +00001058 return AddressPoint;
Mike Stump7bae1282009-08-18 21:30:21 +00001059 }
1060
1061 void GenerateVtableForVBases(const CXXRecordDecl *RD,
Mike Stumpa7ec675d2009-08-19 14:40:47 +00001062 const CXXRecordDecl *Class) {
Mike Stump7bae1282009-08-18 21:30:21 +00001063 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1064 e = RD->bases_end(); i != e; ++i) {
1065 const CXXRecordDecl *Base =
1066 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1067 if (i->isVirtual() && !IndirectPrimary.count(Base)) {
1068 // Mark it so we don't output it twice.
1069 IndirectPrimary.insert(Base);
Mike Stumpf07ede52009-08-21 01:45:00 +00001070 StartNewTable();
Mike Stumpaf0d0452009-08-20 07:22:17 +00001071 int64_t BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stumpf7d47a52009-08-26 20:46:33 +00001072 GenerateVtableForBase(Base, false, true, BaseOffset, true);
Mike Stump7bae1282009-08-18 21:30:21 +00001073 }
1074 if (Base->getNumVBases())
Mike Stumpa7ec675d2009-08-19 14:40:47 +00001075 GenerateVtableForVBases(Base, Class);
Mike Stumpc57b8272009-08-16 01:46:26 +00001076 }
1077 }
Mike Stump7bae1282009-08-18 21:30:21 +00001078};
Mike Stumpd6f22d82009-08-06 15:50:11 +00001079
Mike Stumpf7d47a52009-08-26 20:46:33 +00001080class VtableInfo {
1081public:
1082 typedef VtableBuilder::Index_t Index_t;
1083private:
1084 CodeGenModule &CGM; // Per-module state.
1085 /// Index_t - Vtable index type.
1086 typedef llvm::DenseMap<const CXXMethodDecl *, Index_t> ElTy;
1087 typedef llvm::DenseMap<const CXXRecordDecl *, ElTy *> MapTy;
1088 // FIXME: Move to Context.
1089 static MapTy IndexFor;
1090public:
1091 VtableInfo(CodeGenModule &cgm) : CGM(cgm) { }
1092 void register_index(const CXXRecordDecl *RD, const ElTy &e) {
1093 assert(IndexFor.find(RD) == IndexFor.end() && "Don't compute vtbl twice");
1094 // We own a copy of this, it will go away shortly.
1095 new ElTy (e);
1096 IndexFor[RD] = new ElTy (e);
1097 }
1098 Index_t lookup(const CXXMethodDecl *MD) {
1099 const CXXRecordDecl *RD = MD->getParent();
1100 MapTy::iterator I = IndexFor.find(RD);
1101 if (I == IndexFor.end()) {
1102 std::vector<llvm::Constant *> methods;
1103 VtableBuilder b(methods, RD, CGM);
1104 b.GenerateVtableForBase(RD, true, false, 0, false);
1105 b.GenerateVtableForVBases(RD, RD);
1106 register_index(RD, b.getIndex());
1107 I = IndexFor.find(RD);
1108 }
1109 assert(I->second->find(MD)!=I->second->end() && "Can't find vtable index");
1110 return (*I->second)[MD];
1111 }
1112};
1113
1114// FIXME: Move to Context.
1115VtableInfo::MapTy VtableInfo::IndexFor;
1116
Mike Stump7e8c9932009-07-31 18:25:34 +00001117llvm::Value *CodeGenFunction::GenerateVtable(const CXXRecordDecl *RD) {
Mike Stump7e8c9932009-07-31 18:25:34 +00001118 llvm::SmallString<256> OutName;
1119 llvm::raw_svector_ostream Out(OutName);
1120 QualType ClassTy;
Mike Stumpe7545622009-08-07 18:05:12 +00001121 ClassTy = getContext().getTagDeclType(RD);
Mike Stump7e8c9932009-07-31 18:25:34 +00001122 mangleCXXVtable(ClassTy, getContext(), Out);
Mike Stumpd0672782009-07-31 21:43:43 +00001123 llvm::GlobalVariable::LinkageTypes linktype;
1124 linktype = llvm::GlobalValue::WeakAnyLinkage;
1125 std::vector<llvm::Constant *> methods;
Mike Stumpc57b8272009-08-16 01:46:26 +00001126 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
Mike Stump00962322009-08-21 23:09:30 +00001127 int64_t Offset;
Mike Stump8b82eeb2009-08-05 22:37:18 +00001128
Mike Stump86a859e2009-08-19 18:10:47 +00001129 VtableBuilder b(methods, RD, CGM);
Mike Stump7bae1282009-08-18 21:30:21 +00001130
Mike Stumpc57b8272009-08-16 01:46:26 +00001131 // First comes the vtables for all the non-virtual bases...
Mike Stumpf7d47a52009-08-26 20:46:33 +00001132 Offset = b.GenerateVtableForBase(RD, true, false, 0, false);
Mike Stump42368bb2009-08-14 01:44:03 +00001133
Mike Stumpc57b8272009-08-16 01:46:26 +00001134 // then the vtables for all the virtual bases.
Mike Stumpa7ec675d2009-08-19 14:40:47 +00001135 b.GenerateVtableForVBases(RD, RD);
Mike Stumpf3371782009-08-04 21:58:42 +00001136
Mike Stumpd0672782009-07-31 21:43:43 +00001137 llvm::Constant *C;
1138 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, methods.size());
1139 C = llvm::ConstantArray::get(type, methods);
1140 llvm::Value *vtable = new llvm::GlobalVariable(CGM.getModule(), type, true,
Daniel Dunbar0433a022009-08-19 20:04:03 +00001141 linktype, C, Out.str());
Mike Stump7e8c9932009-07-31 18:25:34 +00001142 vtable = Builder.CreateBitCast(vtable, Ptr8Ty);
Mike Stump7e8c9932009-07-31 18:25:34 +00001143 vtable = Builder.CreateGEP(vtable,
Mike Stumpc57b8272009-08-16 01:46:26 +00001144 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
Mike Stump00962322009-08-21 23:09:30 +00001145 Offset*LLVMPointerWidth/8));
Mike Stump7e8c9932009-07-31 18:25:34 +00001146 return vtable;
1147}
1148
Mike Stumpf7d47a52009-08-26 20:46:33 +00001149// FIXME: move to Context
1150static VtableInfo *vtableinfo;
1151
1152llvm::Value *
1153CodeGenFunction::BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *&This,
1154 const llvm::Type *Ty) {
1155 // FIXME: If we know the dynamic type, we don't have to do a virtual dispatch.
1156
1157 // FIXME: move to Context
1158 if (vtableinfo == 0)
1159 vtableinfo = new VtableInfo(CGM);
1160
1161 VtableInfo::Index_t Idx = vtableinfo->lookup(MD);
1162
1163 Ty = llvm::PointerType::get(Ty, 0);
1164 Ty = llvm::PointerType::get(Ty, 0);
1165 Ty = llvm::PointerType::get(Ty, 0);
1166 llvm::Value *vtbl = Builder.CreateBitCast(This, Ty);
1167 vtbl = Builder.CreateLoad(vtbl);
1168 llvm::Value *vfn = Builder.CreateConstInBoundsGEP1_64(vtbl,
1169 Idx, "vfn");
1170 vfn = Builder.CreateLoad(vfn);
1171 return vfn;
1172}
1173
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001174/// EmitClassAggrMemberwiseCopy - This routine generates code to copy a class
1175/// array of objects from SrcValue to DestValue. Copying can be either a bitwise
1176/// copy or via a copy constructor call.
Fariborz Jahanian58a7eca2009-08-26 00:23:27 +00001177// FIXME. Consolidate this with EmitCXXAggrConstructorCall.
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001178void CodeGenFunction::EmitClassAggrMemberwiseCopy(llvm::Value *Dest,
1179 llvm::Value *Src,
1180 const ArrayType *Array,
1181 const CXXRecordDecl *BaseClassDecl,
1182 QualType Ty) {
1183 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1184 assert(CA && "VLA cannot be copied over");
1185 bool BitwiseCopy = BaseClassDecl->hasTrivialCopyConstructor();
1186
1187 // Create a temporary for the loop index and initialize it with 0.
1188 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1189 "loop.index");
1190 llvm::Value* zeroConstant =
1191 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
1192 Builder.CreateStore(zeroConstant, IndexPtr, false);
1193 // Start the loop with a block that tests the condition.
1194 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1195 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1196
1197 EmitBlock(CondBlock);
1198
1199 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1200 // Generate: if (loop-index < number-of-elements fall to the loop body,
1201 // otherwise, go to the block after the for-loop.
1202 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
1203 llvm::Value * NumElementsPtr =
1204 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1205 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1206 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
1207 "isless");
1208 // If the condition is true, execute the body.
1209 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1210
1211 EmitBlock(ForBody);
1212 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1213 // Inside the loop body, emit the constructor call on the array element.
1214 Counter = Builder.CreateLoad(IndexPtr);
1215 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1216 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1217 if (BitwiseCopy)
1218 EmitAggregateCopy(Dest, Src, Ty);
1219 else if (CXXConstructorDecl *BaseCopyCtor =
1220 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
1221 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
1222 Ctor_Complete);
1223 CallArgList CallArgs;
1224 // Push the this (Dest) ptr.
1225 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1226 BaseCopyCtor->getThisType(getContext())));
1227
1228 // Push the Src ptr.
1229 CallArgs.push_back(std::make_pair(RValue::get(Src),
1230 BaseCopyCtor->getParamDecl(0)->getType()));
1231 QualType ResultType =
1232 BaseCopyCtor->getType()->getAsFunctionType()->getResultType();
1233 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1234 Callee, CallArgs, BaseCopyCtor);
1235 }
1236 EmitBlock(ContinueBlock);
1237
1238 // Emit the increment of the loop counter.
1239 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1240 Counter = Builder.CreateLoad(IndexPtr);
1241 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1242 Builder.CreateStore(NextVal, IndexPtr, false);
1243
1244 // Finally, branch back up to the condition for the next iteration.
1245 EmitBranch(CondBlock);
1246
1247 // Emit the fall-through block.
1248 EmitBlock(AfterFor, true);
1249}
1250
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001251/// EmitClassAggrCopyAssignment - This routine generates code to assign a class
1252/// array of objects from SrcValue to DestValue. Assignment can be either a
1253/// bitwise assignment or via a copy assignment operator function call.
1254/// FIXME. This can be consolidated with EmitClassAggrMemberwiseCopy
1255void CodeGenFunction::EmitClassAggrCopyAssignment(llvm::Value *Dest,
1256 llvm::Value *Src,
1257 const ArrayType *Array,
1258 const CXXRecordDecl *BaseClassDecl,
1259 QualType Ty) {
1260 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1261 assert(CA && "VLA cannot be asssigned");
1262 bool BitwiseAssign = BaseClassDecl->hasTrivialCopyAssignment();
1263
1264 // Create a temporary for the loop index and initialize it with 0.
1265 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1266 "loop.index");
1267 llvm::Value* zeroConstant =
1268 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
1269 Builder.CreateStore(zeroConstant, IndexPtr, false);
1270 // Start the loop with a block that tests the condition.
1271 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1272 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1273
1274 EmitBlock(CondBlock);
1275
1276 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1277 // Generate: if (loop-index < number-of-elements fall to the loop body,
1278 // otherwise, go to the block after the for-loop.
1279 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
1280 llvm::Value * NumElementsPtr =
1281 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1282 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1283 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
1284 "isless");
1285 // If the condition is true, execute the body.
1286 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1287
1288 EmitBlock(ForBody);
1289 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1290 // Inside the loop body, emit the assignment operator call on array element.
1291 Counter = Builder.CreateLoad(IndexPtr);
1292 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1293 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1294 const CXXMethodDecl *MD = 0;
1295 if (BitwiseAssign)
1296 EmitAggregateCopy(Dest, Src, Ty);
1297 else {
1298 bool hasCopyAssign = BaseClassDecl->hasConstCopyAssignment(getContext(),
1299 MD);
1300 assert(hasCopyAssign && "EmitClassAggrCopyAssignment - No user assign");
1301 (void)hasCopyAssign;
1302 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
1303 const llvm::Type *LTy =
1304 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1305 FPT->isVariadic());
1306 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), LTy);
1307
1308 CallArgList CallArgs;
1309 // Push the this (Dest) ptr.
1310 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1311 MD->getThisType(getContext())));
1312
1313 // Push the Src ptr.
1314 CallArgs.push_back(std::make_pair(RValue::get(Src),
1315 MD->getParamDecl(0)->getType()));
1316 QualType ResultType =
1317 MD->getType()->getAsFunctionType()->getResultType();
1318 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1319 Callee, CallArgs, MD);
1320 }
1321 EmitBlock(ContinueBlock);
1322
1323 // Emit the increment of the loop counter.
1324 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1325 Counter = Builder.CreateLoad(IndexPtr);
1326 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1327 Builder.CreateStore(NextVal, IndexPtr, false);
1328
1329 // Finally, branch back up to the condition for the next iteration.
1330 EmitBranch(CondBlock);
1331
1332 // Emit the fall-through block.
1333 EmitBlock(AfterFor, true);
1334}
1335
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001336/// EmitClassMemberwiseCopy - This routine generates code to copy a class
1337/// object from SrcValue to DestValue. Copying can be either a bitwise copy
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001338/// or via a copy constructor call.
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001339void CodeGenFunction::EmitClassMemberwiseCopy(
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001340 llvm::Value *Dest, llvm::Value *Src,
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001341 const CXXRecordDecl *ClassDecl,
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001342 const CXXRecordDecl *BaseClassDecl, QualType Ty) {
1343 if (ClassDecl) {
1344 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
1345 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
1346 }
1347 if (BaseClassDecl->hasTrivialCopyConstructor()) {
1348 EmitAggregateCopy(Dest, Src, Ty);
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001349 return;
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001350 }
1351
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001352 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanianfbe08772009-08-08 00:59:58 +00001353 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001354 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
1355 Ctor_Complete);
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001356 CallArgList CallArgs;
1357 // Push the this (Dest) ptr.
1358 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1359 BaseCopyCtor->getThisType(getContext())));
1360
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001361 // Push the Src ptr.
1362 CallArgs.push_back(std::make_pair(RValue::get(Src),
Fariborz Jahanian0dfaec42009-08-10 17:20:45 +00001363 BaseCopyCtor->getParamDecl(0)->getType()));
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001364 QualType ResultType =
1365 BaseCopyCtor->getType()->getAsFunctionType()->getResultType();
1366 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1367 Callee, CallArgs, BaseCopyCtor);
1368 }
1369}
Fariborz Jahaniane39fab62009-08-10 18:46:38 +00001370
Fariborz Jahanian04500242009-08-12 23:34:46 +00001371/// EmitClassCopyAssignment - This routine generates code to copy assign a class
1372/// object from SrcValue to DestValue. Assignment can be either a bitwise
1373/// assignment of via an assignment operator call.
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001374// FIXME. Consolidate this with EmitClassMemberwiseCopy as they share a lot.
Fariborz Jahanian04500242009-08-12 23:34:46 +00001375void CodeGenFunction::EmitClassCopyAssignment(
1376 llvm::Value *Dest, llvm::Value *Src,
1377 const CXXRecordDecl *ClassDecl,
1378 const CXXRecordDecl *BaseClassDecl,
1379 QualType Ty) {
1380 if (ClassDecl) {
1381 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
1382 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
1383 }
1384 if (BaseClassDecl->hasTrivialCopyAssignment()) {
1385 EmitAggregateCopy(Dest, Src, Ty);
1386 return;
1387 }
1388
1389 const CXXMethodDecl *MD = 0;
Fariborz Jahanian84bd6532009-08-13 00:53:36 +00001390 bool ConstCopyAssignOp = BaseClassDecl->hasConstCopyAssignment(getContext(),
1391 MD);
1392 assert(ConstCopyAssignOp && "EmitClassCopyAssignment - missing copy assign");
1393 (void)ConstCopyAssignOp;
1394
1395 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
1396 const llvm::Type *LTy =
1397 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1398 FPT->isVariadic());
1399 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), LTy);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001400
Fariborz Jahanian84bd6532009-08-13 00:53:36 +00001401 CallArgList CallArgs;
1402 // Push the this (Dest) ptr.
1403 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1404 MD->getThisType(getContext())));
Fariborz Jahanian04500242009-08-12 23:34:46 +00001405
Fariborz Jahanian84bd6532009-08-13 00:53:36 +00001406 // Push the Src ptr.
1407 CallArgs.push_back(std::make_pair(RValue::get(Src),
1408 MD->getParamDecl(0)->getType()));
1409 QualType ResultType =
1410 MD->getType()->getAsFunctionType()->getResultType();
1411 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1412 Callee, CallArgs, MD);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001413}
1414
Fariborz Jahaniane39fab62009-08-10 18:46:38 +00001415/// SynthesizeDefaultConstructor - synthesize a default constructor
1416void
1417CodeGenFunction::SynthesizeDefaultConstructor(const CXXConstructorDecl *CD,
1418 const FunctionDecl *FD,
1419 llvm::Function *Fn,
1420 const FunctionArgList &Args) {
1421 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1422 EmitCtorPrologue(CD);
1423 FinishFunction();
1424}
1425
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001426/// SynthesizeCXXCopyConstructor - This routine implicitly defines body of a copy
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001427/// constructor, in accordance with section 12.8 (p7 and p8) of C++03
1428/// The implicitly-defined copy constructor for class X performs a memberwise
1429/// copy of its subobjects. The order of copying is the same as the order
1430/// of initialization of bases and members in a user-defined constructor
1431/// Each subobject is copied in the manner appropriate to its type:
1432/// if the subobject is of class type, the copy constructor for the class is
1433/// used;
1434/// if the subobject is an array, each element is copied, in the manner
1435/// appropriate to the element type;
1436/// if the subobject is of scalar type, the built-in assignment operator is
1437/// used.
1438/// Virtual base class subobjects shall be copied only once by the
1439/// implicitly-defined copy constructor
1440
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001441void CodeGenFunction::SynthesizeCXXCopyConstructor(const CXXConstructorDecl *CD,
1442 const FunctionDecl *FD,
1443 llvm::Function *Fn,
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001444 const FunctionArgList &Args) {
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001445 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1446 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001447 "SynthesizeCXXCopyConstructor - copy constructor has definition already");
1448 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001449
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001450 FunctionArgList::const_iterator i = Args.begin();
1451 const VarDecl *ThisArg = i->first;
1452 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1453 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1454 const VarDecl *SrcArg = (i+1)->first;
1455 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1456 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1457
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001458 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1459 Base != ClassDecl->bases_end(); ++Base) {
1460 // FIXME. copy constrution of virtual base NYI
1461 if (Base->isVirtual())
1462 continue;
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001463
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001464 CXXRecordDecl *BaseClassDecl
1465 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001466 EmitClassMemberwiseCopy(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1467 Base->getType());
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001468 }
1469
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001470 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1471 FieldEnd = ClassDecl->field_end();
1472 Field != FieldEnd; ++Field) {
1473 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001474 const ConstantArrayType *Array =
1475 getContext().getAsConstantArrayType(FieldType);
1476 if (Array)
1477 FieldType = getContext().getBaseElementType(FieldType);
1478
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001479 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1480 CXXRecordDecl *FieldClassDecl
1481 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1482 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1483 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001484 if (Array) {
1485 const llvm::Type *BasePtr = ConvertType(FieldType);
1486 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1487 llvm::Value *DestBaseAddrPtr =
1488 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1489 llvm::Value *SrcBaseAddrPtr =
1490 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1491 EmitClassAggrMemberwiseCopy(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1492 FieldClassDecl, FieldType);
1493 }
1494 else
1495 EmitClassMemberwiseCopy(LHS.getAddress(), RHS.getAddress(),
1496 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001497 continue;
1498 }
Fariborz Jahanian08d99e92009-08-10 18:34:26 +00001499 // Do a built-in assignment of scalar data members.
1500 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1501 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1502 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1503 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001504 }
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001505 FinishFunction();
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001506}
1507
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001508/// SynthesizeCXXCopyAssignment - Implicitly define copy assignment operator.
1509/// Before the implicitly-declared copy assignment operator for a class is
1510/// implicitly defined, all implicitly- declared copy assignment operators for
1511/// its direct base classes and its nonstatic data members shall have been
1512/// implicitly defined. [12.8-p12]
1513/// The implicitly-defined copy assignment operator for class X performs
1514/// memberwise assignment of its subob- jects. The direct base classes of X are
1515/// assigned first, in the order of their declaration in
1516/// the base-specifier-list, and then the immediate nonstatic data members of X
1517/// are assigned, in the order in which they were declared in the class
1518/// definition.Each subobject is assigned in the manner appropriate to its type:
Fariborz Jahanian04500242009-08-12 23:34:46 +00001519/// if the subobject is of class type, the copy assignment operator for the
1520/// class is used (as if by explicit qualification; that is, ignoring any
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001521/// possible virtual overriding functions in more derived classes);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001522///
1523/// if the subobject is an array, each element is assigned, in the manner
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001524/// appropriate to the element type;
Fariborz Jahanian04500242009-08-12 23:34:46 +00001525///
1526/// if the subobject is of scalar type, the built-in assignment operator is
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001527/// used.
1528void CodeGenFunction::SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD,
1529 const FunctionDecl *FD,
1530 llvm::Function *Fn,
1531 const FunctionArgList &Args) {
Fariborz Jahanian04500242009-08-12 23:34:46 +00001532
1533 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1534 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
1535 "SynthesizeCXXCopyAssignment - copy assignment has user declaration");
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001536 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1537
Fariborz Jahanian04500242009-08-12 23:34:46 +00001538 FunctionArgList::const_iterator i = Args.begin();
1539 const VarDecl *ThisArg = i->first;
1540 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1541 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1542 const VarDecl *SrcArg = (i+1)->first;
1543 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1544 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
1545
1546 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1547 Base != ClassDecl->bases_end(); ++Base) {
1548 // FIXME. copy assignment of virtual base NYI
1549 if (Base->isVirtual())
1550 continue;
1551
1552 CXXRecordDecl *BaseClassDecl
1553 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1554 EmitClassCopyAssignment(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1555 Base->getType());
1556 }
1557
1558 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1559 FieldEnd = ClassDecl->field_end();
1560 Field != FieldEnd; ++Field) {
1561 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001562 const ConstantArrayType *Array =
1563 getContext().getAsConstantArrayType(FieldType);
1564 if (Array)
1565 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001566
1567 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1568 CXXRecordDecl *FieldClassDecl
1569 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1570 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1571 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001572 if (Array) {
1573 const llvm::Type *BasePtr = ConvertType(FieldType);
1574 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1575 llvm::Value *DestBaseAddrPtr =
1576 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1577 llvm::Value *SrcBaseAddrPtr =
1578 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1579 EmitClassAggrCopyAssignment(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1580 FieldClassDecl, FieldType);
1581 }
1582 else
1583 EmitClassCopyAssignment(LHS.getAddress(), RHS.getAddress(),
1584 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001585 continue;
1586 }
1587 // Do a built-in assignment of scalar data members.
1588 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1589 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1590 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1591 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanianc47460d2009-08-14 00:01:54 +00001592 }
1593
1594 // return *this;
1595 Builder.CreateStore(LoadOfThis, ReturnValue);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001596
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001597 FinishFunction();
1598}
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001599
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001600/// EmitCtorPrologue - This routine generates necessary code to initialize
1601/// base classes and non-static data members belonging to this constructor.
1602void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD) {
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001603 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
Mike Stump05207212009-08-06 13:41:24 +00001604 // FIXME: Add vbase initialization
Mike Stump7e8c9932009-07-31 18:25:34 +00001605 llvm::Value *LoadOfThis = 0;
Fariborz Jahanian70277012009-07-28 18:09:28 +00001606
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001607 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001608 E = CD->init_end();
1609 B != E; ++B) {
1610 CXXBaseOrMemberInitializer *Member = (*B);
1611 if (Member->isBaseInitializer()) {
Mike Stump7e8c9932009-07-31 18:25:34 +00001612 LoadOfThis = LoadCXXThis();
Fariborz Jahanian70277012009-07-28 18:09:28 +00001613 Type *BaseType = Member->getBaseClass();
1614 CXXRecordDecl *BaseClassDecl =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001615 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
Fariborz Jahanian70277012009-07-28 18:09:28 +00001616 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1617 BaseClassDecl);
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001618 EmitCXXConstructorCall(Member->getConstructor(),
1619 Ctor_Complete, V,
1620 Member->const_arg_begin(),
1621 Member->const_arg_end());
Mike Stump487ce382009-07-30 22:28:39 +00001622 } else {
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001623 // non-static data member initilaizers.
1624 FieldDecl *Field = Member->getMember();
1625 QualType FieldType = getContext().getCanonicalType((Field)->getType());
Fariborz Jahanianc7b8d9a2009-08-21 17:09:38 +00001626 const ConstantArrayType *Array =
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001627 getContext().getAsConstantArrayType(FieldType);
Fariborz Jahanianc7b8d9a2009-08-21 17:09:38 +00001628 if (Array)
1629 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian32cea8b2009-08-10 23:56:17 +00001630
Mike Stump7e8c9932009-07-31 18:25:34 +00001631 LoadOfThis = LoadCXXThis();
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001632 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001633 if (FieldType->getAs<RecordType>()) {
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +00001634 if (!Field->isAnonymousStructOrUnion()) {
Fariborz Jahanian56baceb2009-07-24 17:57:02 +00001635 assert(Member->getConstructor() &&
1636 "EmitCtorPrologue - no constructor to initialize member");
Fariborz Jahanianc7b8d9a2009-08-21 17:09:38 +00001637 if (Array) {
1638 const llvm::Type *BasePtr = ConvertType(FieldType);
1639 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1640 llvm::Value *BaseAddrPtr =
1641 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1642 EmitCXXAggrConstructorCall(Member->getConstructor(),
1643 Array, BaseAddrPtr);
1644 }
1645 else
1646 EmitCXXConstructorCall(Member->getConstructor(),
1647 Ctor_Complete, LHS.getAddress(),
1648 Member->const_arg_begin(),
1649 Member->const_arg_end());
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +00001650 continue;
1651 }
1652 else {
1653 // Initializing an anonymous union data member.
1654 FieldDecl *anonMember = Member->getAnonUnionMember();
1655 LHS = EmitLValueForField(LHS.getAddress(), anonMember, false, 0);
1656 FieldType = anonMember->getType();
1657 }
Fariborz Jahanian56baceb2009-07-24 17:57:02 +00001658 }
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001659
1660 assert(Member->getNumArgs() == 1 && "Initializer count must be 1 only");
Fariborz Jahanian56baceb2009-07-24 17:57:02 +00001661 Expr *RhsExpr = *Member->arg_begin();
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001662 llvm::Value *RHS = EmitScalarExpr(RhsExpr, true);
Fariborz Jahanian32cea8b2009-08-10 23:56:17 +00001663 EmitStoreThroughLValue(RValue::get(RHS), LHS, FieldType);
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001664 }
1665 }
Mike Stump7e8c9932009-07-31 18:25:34 +00001666
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001667 if (!CD->getNumBaseOrMemberInitializers() && !CD->isTrivial()) {
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001668 // Nontrivial default constructor with no initializer list. It may still
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001669 // have bases classes and/or contain non-static data members which require
1670 // construction.
1671 for (CXXRecordDecl::base_class_const_iterator Base =
1672 ClassDecl->bases_begin();
1673 Base != ClassDecl->bases_end(); ++Base) {
1674 // FIXME. copy assignment of virtual base NYI
1675 if (Base->isVirtual())
1676 continue;
1677
1678 CXXRecordDecl *BaseClassDecl
1679 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1680 if (BaseClassDecl->hasTrivialConstructor())
1681 continue;
1682 if (CXXConstructorDecl *BaseCX =
1683 BaseClassDecl->getDefaultConstructor(getContext())) {
1684 LoadOfThis = LoadCXXThis();
1685 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1686 BaseClassDecl);
1687 EmitCXXConstructorCall(BaseCX, Ctor_Complete, V, 0, 0);
1688 }
1689 }
1690
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001691 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1692 FieldEnd = ClassDecl->field_end();
1693 Field != FieldEnd; ++Field) {
1694 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +00001695 const ConstantArrayType *Array =
1696 getContext().getAsConstantArrayType(FieldType);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001697 if (Array)
1698 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001699 if (!FieldType->getAs<RecordType>() || Field->isAnonymousStructOrUnion())
1700 continue;
1701 const RecordType *ClassRec = FieldType->getAs<RecordType>();
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001702 CXXRecordDecl *MemberClassDecl =
1703 dyn_cast<CXXRecordDecl>(ClassRec->getDecl());
1704 if (!MemberClassDecl || MemberClassDecl->hasTrivialConstructor())
1705 continue;
1706 if (CXXConstructorDecl *MamberCX =
1707 MemberClassDecl->getDefaultConstructor(getContext())) {
1708 LoadOfThis = LoadCXXThis();
1709 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +00001710 if (Array) {
1711 const llvm::Type *BasePtr = ConvertType(FieldType);
1712 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1713 llvm::Value *BaseAddrPtr =
1714 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1715 EmitCXXAggrConstructorCall(MamberCX, Array, BaseAddrPtr);
1716 }
1717 else
1718 EmitCXXConstructorCall(MamberCX, Ctor_Complete, LHS.getAddress(),
1719 0, 0);
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001720 }
1721 }
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001722 }
1723
Mike Stump7e8c9932009-07-31 18:25:34 +00001724 // Initialize the vtable pointer
Mike Stumpeec46a72009-08-05 22:59:44 +00001725 if (ClassDecl->isDynamicClass()) {
Mike Stump7e8c9932009-07-31 18:25:34 +00001726 if (!LoadOfThis)
1727 LoadOfThis = LoadCXXThis();
1728 llvm::Value *VtableField;
1729 llvm::Type *Ptr8Ty, *PtrPtr8Ty;
Owen Anderson3f5cc0a2009-08-13 21:57:51 +00001730 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Mike Stump7e8c9932009-07-31 18:25:34 +00001731 PtrPtr8Ty = llvm::PointerType::get(Ptr8Ty, 0);
1732 VtableField = Builder.CreateBitCast(LoadOfThis, PtrPtr8Ty);
1733 llvm::Value *vtable = GenerateVtable(ClassDecl);
1734 Builder.CreateStore(vtable, VtableField);
1735 }
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001736}
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001737
1738/// EmitDtorEpilogue - Emit all code that comes at the end of class's
1739/// destructor. This is to call destructors on members and base classes
1740/// in reverse order of their construction.
1741void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD) {
1742 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(DD->getDeclContext());
1743 assert(!ClassDecl->isPolymorphic() &&
1744 "FIXME. polymorphic destruction not supported");
1745 (void)ClassDecl; // prevent warning.
1746
1747 for (CXXDestructorDecl::destr_const_iterator *B = DD->destr_begin(),
1748 *E = DD->destr_end(); B != E; ++B) {
1749 uintptr_t BaseOrMember = (*B);
1750 if (DD->isMemberToDestroy(BaseOrMember)) {
1751 FieldDecl *FD = DD->getMemberToDestroy(BaseOrMember);
1752 QualType FieldType = getContext().getCanonicalType((FD)->getType());
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001753 const ConstantArrayType *Array =
1754 getContext().getAsConstantArrayType(FieldType);
1755 if (Array)
1756 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001757 const RecordType *RT = FieldType->getAs<RecordType>();
1758 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1759 if (FieldClassDecl->hasTrivialDestructor())
1760 continue;
1761 llvm::Value *LoadOfThis = LoadCXXThis();
1762 LValue LHS = EmitLValueForField(LoadOfThis, FD, false, 0);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001763 if (Array) {
1764 const llvm::Type *BasePtr = ConvertType(FieldType);
1765 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1766 llvm::Value *BaseAddrPtr =
1767 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1768 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1769 Array, BaseAddrPtr);
1770 }
1771 else
1772 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1773 Dtor_Complete, LHS.getAddress());
Mike Stump487ce382009-07-30 22:28:39 +00001774 } else {
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001775 const RecordType *RT =
1776 DD->getAnyBaseClassToDestroy(BaseOrMember)->getAs<RecordType>();
1777 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1778 if (BaseClassDecl->hasTrivialDestructor())
1779 continue;
1780 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
1781 ClassDecl,BaseClassDecl);
1782 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1783 Dtor_Complete, V);
1784 }
1785 }
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001786 if (DD->getNumBaseOrMemberDestructions() || DD->isTrivial())
1787 return;
1788 // Case of destructor synthesis with fields and base classes
1789 // which have non-trivial destructors. They must be destructed in
1790 // reverse order of their construction.
1791 llvm::SmallVector<FieldDecl *, 16> DestructedFields;
1792
1793 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1794 FieldEnd = ClassDecl->field_end();
1795 Field != FieldEnd; ++Field) {
1796 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001797 if (getContext().getAsConstantArrayType(FieldType))
1798 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001799 if (const RecordType *RT = FieldType->getAs<RecordType>()) {
1800 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1801 if (FieldClassDecl->hasTrivialDestructor())
1802 continue;
1803 DestructedFields.push_back(*Field);
1804 }
1805 }
1806 if (!DestructedFields.empty())
1807 for (int i = DestructedFields.size() -1; i >= 0; --i) {
1808 FieldDecl *Field = DestructedFields[i];
1809 QualType FieldType = Field->getType();
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001810 const ConstantArrayType *Array =
1811 getContext().getAsConstantArrayType(FieldType);
1812 if (Array)
1813 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001814 const RecordType *RT = FieldType->getAs<RecordType>();
1815 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1816 llvm::Value *LoadOfThis = LoadCXXThis();
1817 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001818 if (Array) {
1819 const llvm::Type *BasePtr = ConvertType(FieldType);
1820 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1821 llvm::Value *BaseAddrPtr =
1822 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1823 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1824 Array, BaseAddrPtr);
1825 }
1826 else
1827 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1828 Dtor_Complete, LHS.getAddress());
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001829 }
1830
1831 llvm::SmallVector<CXXRecordDecl*, 4> DestructedBases;
1832 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1833 Base != ClassDecl->bases_end(); ++Base) {
1834 // FIXME. copy assignment of virtual base NYI
1835 if (Base->isVirtual())
1836 continue;
1837
1838 CXXRecordDecl *BaseClassDecl
1839 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1840 if (BaseClassDecl->hasTrivialDestructor())
1841 continue;
1842 DestructedBases.push_back(BaseClassDecl);
1843 }
1844 if (DestructedBases.empty())
1845 return;
1846 for (int i = DestructedBases.size() -1; i >= 0; --i) {
1847 CXXRecordDecl *BaseClassDecl = DestructedBases[i];
1848 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
1849 ClassDecl,BaseClassDecl);
1850 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1851 Dtor_Complete, V);
1852 }
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001853}
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001854
1855void CodeGenFunction::SynthesizeDefaultDestructor(const CXXDestructorDecl *CD,
1856 const FunctionDecl *FD,
1857 llvm::Function *Fn,
1858 const FunctionArgList &Args) {
1859
1860 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1861 assert(!ClassDecl->hasUserDeclaredDestructor() &&
1862 "SynthesizeDefaultDestructor - destructor has user declaration");
1863 (void) ClassDecl;
1864
1865 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1866 EmitDtorEpilogue(CD);
1867 FinishFunction();
1868}