blob: 1c95fc313eef9b70b5bdec53ac7bd78e66d62379 [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 =
34 llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
35
36 std::vector<const llvm::Type *> Params;
37 Params.push_back(Int8PtrTy);
38
39 // Get the destructor function type
40 const llvm::Type *DtorFnTy =
41 llvm::FunctionType::get(llvm::Type::VoidTy, Params, false);
42 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()) {
77 ErrorUnsupported(Init, "Global variable that binds to a reference");
78 } 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
99 const llvm::FunctionType *FTy = llvm::FunctionType::get(llvm::Type::VoidTy,
100 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 Anderson94148482009-07-08 19:05:04 +0000143 new llvm::GlobalVariable(CGM.getModule(), llvm::Type::Int64Ty, false,
Daniel Dunbardea59212009-02-25 19:24:29 +0000144 GV->getLinkage(),
Owen Andersonf37b84b2009-07-31 20:28:54 +0000145 llvm::Constant::getNullValue(llvm::Type::Int64Ty),
Owen Anderson94148482009-07-08 19:05:04 +0000146 GuardVName.c_str());
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000147
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000148 // Load the first byte of the guard variable.
Owen Anderson7ec2d8f2009-07-29 22:16:19 +0000149 const llvm::Type *PtrTy = llvm::PointerType::get(llvm::Type::Int8Ty, 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 Andersonf37b84b2009-07-31 20:28:54 +0000154 llvm::Value *nullValue = llvm::Constant::getNullValue(llvm::Type::Int8Ty);
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 Andersonb17ec712009-07-24 23:12:58 +0000167 Builder.CreateStore(llvm::ConstantInt::get(llvm::Type::Int8Ty, 1),
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000168 Builder.CreateBitCast(GuardV, PtrTy));
169
170 EmitBlock(EndBlock);
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000171}
172
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000173RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
174 llvm::Value *Callee,
175 llvm::Value *This,
176 CallExpr::const_arg_iterator ArgBeg,
177 CallExpr::const_arg_iterator ArgEnd) {
178 assert(MD->isInstance() &&
179 "Trying to emit a member call expr on a static method!");
180
181 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
182
183 CallArgList Args;
184
185 // Push the this ptr.
186 Args.push_back(std::make_pair(RValue::get(This),
187 MD->getThisType(getContext())));
188
189 // And the rest of the call args
190 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
191
192 QualType ResultType = MD->getType()->getAsFunctionType()->getResultType();
193 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args),
194 Callee, Args, MD);
195}
196
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000197RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE) {
198 const MemberExpr *ME = cast<MemberExpr>(CE->getCallee());
199 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000200
Anders Carlssonc5223142009-04-08 20:31:57 +0000201 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
Mike Stumpc37c8812009-07-30 21:47:44 +0000202
Mike Stump7e8c9932009-07-31 18:25:34 +0000203 if (MD->isVirtual()) {
Mike Stumpc37c8812009-07-30 21:47:44 +0000204 ErrorUnsupported(CE, "virtual dispatch");
205 }
206
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000207 const llvm::Type *Ty =
Anders Carlssonc5223142009-04-08 20:31:57 +0000208 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
209 FPT->isVariadic());
Chris Lattner80f39cc2009-05-12 21:21:08 +0000210 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty);
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000211
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000212 llvm::Value *This;
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000213
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000214 if (ME->isArrow())
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000215 This = EmitScalarExpr(ME->getBase());
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000216 else {
217 LValue BaseLV = EmitLValue(ME->getBase());
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000218 This = BaseLV.getAddress();
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000219 }
220
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000221 return EmitCXXMemberCall(MD, Callee, This,
222 CE->arg_begin(), CE->arg_end());
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000223}
Anders Carlsson49d4a572009-04-14 16:58:56 +0000224
Anders Carlsson85eca6f2009-05-27 04:18:27 +0000225RValue
226CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
227 const CXXMethodDecl *MD) {
228 assert(MD->isInstance() &&
229 "Trying to emit a member call expr on a static method!");
230
231
232 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
233 const llvm::Type *Ty =
234 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
235 FPT->isVariadic());
236 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty);
237
238 llvm::Value *This = EmitLValue(E->getArg(0)).getAddress();
239
240 return EmitCXXMemberCall(MD, Callee, This,
241 E->arg_begin() + 1, E->arg_end());
242}
243
Anders Carlsson49d4a572009-04-14 16:58:56 +0000244llvm::Value *CodeGenFunction::LoadCXXThis() {
245 assert(isa<CXXMethodDecl>(CurFuncDecl) &&
246 "Must be in a C++ member function decl to load 'this'");
247 assert(cast<CXXMethodDecl>(CurFuncDecl)->isInstance() &&
248 "Must be in a C++ member function decl to load 'this'");
249
250 // FIXME: What if we're inside a block?
Mike Stumpba2cb0e2009-05-16 07:57:57 +0000251 // ans: See how CodeGenFunction::LoadObjCSelf() uses
252 // CodeGenFunction::BlockForwardSelf() for how to do this.
Anders Carlsson49d4a572009-04-14 16:58:56 +0000253 return Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
254}
Anders Carlsson652951a2009-04-15 15:55:24 +0000255
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000256static bool
257GetNestedPaths(llvm::SmallVectorImpl<const CXXRecordDecl *> &NestedBasePaths,
258 const CXXRecordDecl *ClassDecl,
259 const CXXRecordDecl *BaseClassDecl) {
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000260 for (CXXRecordDecl::base_class_const_iterator i = ClassDecl->bases_begin(),
261 e = ClassDecl->bases_end(); i != e; ++i) {
262 if (i->isVirtual())
263 continue;
264 const CXXRecordDecl *Base =
Mike Stumpf3371782009-08-04 21:58:42 +0000265 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000266 if (Base == BaseClassDecl) {
267 NestedBasePaths.push_back(BaseClassDecl);
268 return true;
269 }
270 }
271 // BaseClassDecl not an immediate base of ClassDecl.
272 for (CXXRecordDecl::base_class_const_iterator i = ClassDecl->bases_begin(),
273 e = ClassDecl->bases_end(); i != e; ++i) {
274 if (i->isVirtual())
275 continue;
276 const CXXRecordDecl *Base =
277 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
278 if (GetNestedPaths(NestedBasePaths, Base, BaseClassDecl)) {
279 NestedBasePaths.push_back(Base);
280 return true;
281 }
282 }
283 return false;
284}
285
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000286llvm::Value *CodeGenFunction::AddressCXXOfBaseClass(llvm::Value *BaseValue,
Fariborz Jahanian70277012009-07-28 18:09:28 +0000287 const CXXRecordDecl *ClassDecl,
288 const CXXRecordDecl *BaseClassDecl) {
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000289 if (ClassDecl == BaseClassDecl)
290 return BaseValue;
291
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000292 llvm::Type *I8Ptr = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
293 llvm::SmallVector<const CXXRecordDecl *, 16> NestedBasePaths;
294 GetNestedPaths(NestedBasePaths, ClassDecl, BaseClassDecl);
295 assert(NestedBasePaths.size() > 0 &&
296 "AddressCXXOfBaseClass - inheritence path failed");
297 NestedBasePaths.push_back(ClassDecl);
298 uint64_t Offset = 0;
299
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000300 // Accessing a member of the base class. Must add delata to
301 // the load of 'this'.
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000302 for (unsigned i = NestedBasePaths.size()-1; i > 0; i--) {
303 const CXXRecordDecl *DerivedClass = NestedBasePaths[i];
304 const CXXRecordDecl *BaseClass = NestedBasePaths[i-1];
305 const ASTRecordLayout &Layout =
306 getContext().getASTRecordLayout(DerivedClass);
307 Offset += Layout.getBaseClassOffset(BaseClass) / 8;
308 }
Fariborz Jahanian83a46ed2009-07-29 15:54:56 +0000309 llvm::Value *OffsetVal =
310 llvm::ConstantInt::get(
311 CGM.getTypes().ConvertType(CGM.getContext().LongTy), Offset);
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000312 BaseValue = Builder.CreateBitCast(BaseValue, I8Ptr);
313 BaseValue = Builder.CreateGEP(BaseValue, OffsetVal, "add.ptr");
314 QualType BTy =
315 getContext().getCanonicalType(
Fariborz Jahanian70277012009-07-28 18:09:28 +0000316 getContext().getTypeDeclType(const_cast<CXXRecordDecl*>(BaseClassDecl)));
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000317 const llvm::Type *BasePtr = ConvertType(BTy);
Owen Anderson7ec2d8f2009-07-29 22:16:19 +0000318 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000319 BaseValue = Builder.CreateBitCast(BaseValue, BasePtr);
320 return BaseValue;
321}
322
Anders Carlsson72f48292009-04-17 00:06:03 +0000323void
324CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
325 CXXCtorType Type,
326 llvm::Value *This,
327 CallExpr::const_arg_iterator ArgBeg,
328 CallExpr::const_arg_iterator ArgEnd) {
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000329 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
330
331 EmitCXXMemberCall(D, Callee, This, ArgBeg, ArgEnd);
Anders Carlsson72f48292009-04-17 00:06:03 +0000332}
333
Anders Carlssond3f6b162009-05-29 21:03:38 +0000334void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *D,
335 CXXDtorType Type,
336 llvm::Value *This) {
337 llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(D, Type);
338
339 EmitCXXMemberCall(D, Callee, This, 0, 0);
340}
341
Anders Carlsson72f48292009-04-17 00:06:03 +0000342void
Anders Carlsson342aadc2009-05-03 17:47:16 +0000343CodeGenFunction::EmitCXXConstructExpr(llvm::Value *Dest,
344 const CXXConstructExpr *E) {
Anders Carlsson72f48292009-04-17 00:06:03 +0000345 assert(Dest && "Must have a destination!");
346
347 const CXXRecordDecl *RD =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000348 cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson72f48292009-04-17 00:06:03 +0000349 if (RD->hasTrivialConstructor())
350 return;
Fariborz Jahanian884036a2009-08-06 01:02:49 +0000351
352 // Code gen optimization to eliminate copy constructor and return
353 // its first argument instead.
Fariborz Jahanian325cdd82009-08-06 19:12:38 +0000354 if (E->isElidable()) {
Fariborz Jahanian884036a2009-08-06 01:02:49 +0000355 CXXConstructExpr::const_arg_iterator i = E->arg_begin();
Fariborz Jahanian325cdd82009-08-06 19:12:38 +0000356 EmitAggExpr((*i), Dest, false);
357 return;
Fariborz Jahanian884036a2009-08-06 01:02:49 +0000358 }
Anders Carlsson72f48292009-04-17 00:06:03 +0000359 // Call the constructor.
360 EmitCXXConstructorCall(E->getConstructor(), Ctor_Complete, Dest,
361 E->arg_begin(), E->arg_end());
362}
363
Anders Carlsson18e88bc2009-05-31 01:40:14 +0000364llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
Anders Carlssond5536972009-05-31 20:21:44 +0000365 if (E->isArray()) {
366 ErrorUnsupported(E, "new[] expression");
Owen Andersone0b5eff2009-07-30 23:11:26 +0000367 return llvm::UndefValue::get(ConvertType(E->getType()));
Anders Carlssond5536972009-05-31 20:21:44 +0000368 }
369
370 QualType AllocType = E->getAllocatedType();
371 FunctionDecl *NewFD = E->getOperatorNew();
372 const FunctionProtoType *NewFTy = NewFD->getType()->getAsFunctionProtoType();
373
374 CallArgList NewArgs;
375
376 // The allocation size is the first argument.
377 QualType SizeTy = getContext().getSizeType();
378 llvm::Value *AllocSize =
Owen Andersonb17ec712009-07-24 23:12:58 +0000379 llvm::ConstantInt::get(ConvertType(SizeTy),
Anders Carlssond5536972009-05-31 20:21:44 +0000380 getContext().getTypeSize(AllocType) / 8);
381
382 NewArgs.push_back(std::make_pair(RValue::get(AllocSize), SizeTy));
383
384 // Emit the rest of the arguments.
385 // FIXME: Ideally, this should just use EmitCallArgs.
386 CXXNewExpr::const_arg_iterator NewArg = E->placement_arg_begin();
387
388 // First, use the types from the function type.
389 // We start at 1 here because the first argument (the allocation size)
390 // has already been emitted.
391 for (unsigned i = 1, e = NewFTy->getNumArgs(); i != e; ++i, ++NewArg) {
392 QualType ArgType = NewFTy->getArgType(i);
393
394 assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
395 getTypePtr() ==
396 getContext().getCanonicalType(NewArg->getType()).getTypePtr() &&
397 "type mismatch in call argument!");
398
399 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
400 ArgType));
401
402 }
403
404 // Either we've emitted all the call args, or we have a call to a
405 // variadic function.
406 assert((NewArg == E->placement_arg_end() || NewFTy->isVariadic()) &&
407 "Extra arguments in non-variadic function!");
408
409 // If we still have any arguments, emit them using the type of the argument.
410 for (CXXNewExpr::const_arg_iterator NewArgEnd = E->placement_arg_end();
411 NewArg != NewArgEnd; ++NewArg) {
412 QualType ArgType = NewArg->getType();
413 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
414 ArgType));
415 }
416
417 // Emit the call to new.
418 RValue RV =
419 EmitCall(CGM.getTypes().getFunctionInfo(NewFTy->getResultType(), NewArgs),
420 CGM.GetAddrOfFunction(GlobalDecl(NewFD)),
421 NewArgs, NewFD);
422
Anders Carlsson11269042009-05-31 21:53:59 +0000423 // If an allocation function is declared with an empty exception specification
424 // it returns null to indicate failure to allocate storage. [expr.new]p13.
425 // (We don't need to check for null when there's no new initializer and
426 // we're allocating a POD type).
427 bool NullCheckResult = NewFTy->hasEmptyExceptionSpec() &&
428 !(AllocType->isPODType() && !E->hasInitializer());
Anders Carlssond5536972009-05-31 20:21:44 +0000429
Anders Carlssondbee9a52009-06-01 00:05:16 +0000430 llvm::BasicBlock *NewNull = 0;
431 llvm::BasicBlock *NewNotNull = 0;
432 llvm::BasicBlock *NewEnd = 0;
433
434 llvm::Value *NewPtr = RV.getScalarVal();
435
Anders Carlsson11269042009-05-31 21:53:59 +0000436 if (NullCheckResult) {
Anders Carlssondbee9a52009-06-01 00:05:16 +0000437 NewNull = createBasicBlock("new.null");
438 NewNotNull = createBasicBlock("new.notnull");
439 NewEnd = createBasicBlock("new.end");
440
441 llvm::Value *IsNull =
442 Builder.CreateICmpEQ(NewPtr,
Owen Andersonf37b84b2009-07-31 20:28:54 +0000443 llvm::Constant::getNullValue(NewPtr->getType()),
Anders Carlssondbee9a52009-06-01 00:05:16 +0000444 "isnull");
445
446 Builder.CreateCondBr(IsNull, NewNull, NewNotNull);
447 EmitBlock(NewNotNull);
Anders Carlsson11269042009-05-31 21:53:59 +0000448 }
449
Anders Carlssondbee9a52009-06-01 00:05:16 +0000450 NewPtr = Builder.CreateBitCast(NewPtr, ConvertType(E->getType()));
Anders Carlsson11269042009-05-31 21:53:59 +0000451
Anders Carlsson7c294782009-05-31 20:56:36 +0000452 if (AllocType->isPODType()) {
Anders Carlsson26910f62009-06-01 00:26:14 +0000453 if (E->getNumConstructorArgs() > 0) {
Anders Carlsson7c294782009-05-31 20:56:36 +0000454 assert(E->getNumConstructorArgs() == 1 &&
455 "Can only have one argument to initializer of POD type.");
456
457 const Expr *Init = E->getConstructorArg(0);
458
Anders Carlsson5f93ccf2009-05-31 21:07:58 +0000459 if (!hasAggregateLLVMType(AllocType))
Anders Carlsson7c294782009-05-31 20:56:36 +0000460 Builder.CreateStore(EmitScalarExpr(Init), NewPtr);
Anders Carlsson5f93ccf2009-05-31 21:07:58 +0000461 else if (AllocType->isAnyComplexType())
462 EmitComplexExprIntoAddr(Init, NewPtr, AllocType.isVolatileQualified());
Anders Carlssoneb39b432009-05-31 21:12:26 +0000463 else
464 EmitAggExpr(Init, NewPtr, AllocType.isVolatileQualified());
Anders Carlsson7c294782009-05-31 20:56:36 +0000465 }
Anders Carlsson11269042009-05-31 21:53:59 +0000466 } else {
467 // Call the constructor.
468 CXXConstructorDecl *Ctor = E->getConstructor();
Anders Carlsson7c294782009-05-31 20:56:36 +0000469
Anders Carlsson11269042009-05-31 21:53:59 +0000470 EmitCXXConstructorCall(Ctor, Ctor_Complete, NewPtr,
471 E->constructor_arg_begin(),
472 E->constructor_arg_end());
Anders Carlssond5536972009-05-31 20:21:44 +0000473 }
Anders Carlsson11269042009-05-31 21:53:59 +0000474
Anders Carlssondbee9a52009-06-01 00:05:16 +0000475 if (NullCheckResult) {
476 Builder.CreateBr(NewEnd);
477 EmitBlock(NewNull);
478 Builder.CreateBr(NewEnd);
479 EmitBlock(NewEnd);
480
481 llvm::PHINode *PHI = Builder.CreatePHI(NewPtr->getType());
482 PHI->reserveOperandSpace(2);
483 PHI->addIncoming(NewPtr, NewNotNull);
Owen Andersonf37b84b2009-07-31 20:28:54 +0000484 PHI->addIncoming(llvm::Constant::getNullValue(NewPtr->getType()), NewNull);
Anders Carlssondbee9a52009-06-01 00:05:16 +0000485
486 NewPtr = PHI;
487 }
488
Anders Carlsson11269042009-05-31 21:53:59 +0000489 return NewPtr;
Anders Carlsson18e88bc2009-05-31 01:40:14 +0000490}
491
Anders Carlsson4811c302009-04-17 01:58:57 +0000492static bool canGenerateCXXstructor(const CXXRecordDecl *RD,
493 ASTContext &Context) {
Anders Carlsson8496c692009-04-15 21:02:13 +0000494 // The class has base classes - we don't support that right now.
495 if (RD->getNumBases() > 0)
496 return false;
497
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000498 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
499 I != E; ++I) {
Anders Carlsson8496c692009-04-15 21:02:13 +0000500 // We don't support ctors for fields that aren't POD.
501 if (!I->getType()->isPODType())
502 return false;
503 }
504
505 return true;
506}
507
Anders Carlsson652951a2009-04-15 15:55:24 +0000508void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) {
Anders Carlsson4811c302009-04-17 01:58:57 +0000509 if (!canGenerateCXXstructor(D->getParent(), getContext())) {
Anders Carlsson8496c692009-04-15 21:02:13 +0000510 ErrorUnsupported(D, "C++ constructor", true);
511 return;
512 }
Anders Carlsson652951a2009-04-15 15:55:24 +0000513
Anders Carlsson1764af42009-05-05 04:44:02 +0000514 EmitGlobal(GlobalDecl(D, Ctor_Complete));
515 EmitGlobal(GlobalDecl(D, Ctor_Base));
Anders Carlsson652951a2009-04-15 15:55:24 +0000516}
Anders Carlsson890a9fd2009-04-16 23:57:24 +0000517
Anders Carlsson4811c302009-04-17 01:58:57 +0000518void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D,
519 CXXCtorType Type) {
520
521 llvm::Function *Fn = GetAddrOfCXXConstructor(D, Type);
522
523 CodeGenFunction(*this).GenerateCode(D, Fn);
524
525 SetFunctionDefinitionAttributes(D, Fn);
526 SetLLVMFunctionAttributesForDefinition(D, Fn);
527}
528
Anders Carlsson890a9fd2009-04-16 23:57:24 +0000529llvm::Function *
530CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
531 CXXCtorType Type) {
532 const llvm::FunctionType *FTy =
533 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false);
534
535 const char *Name = getMangledCXXCtorName(D, Type);
Chris Lattner80f39cc2009-05-12 21:21:08 +0000536 return cast<llvm::Function>(
537 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson890a9fd2009-04-16 23:57:24 +0000538}
Anders Carlsson4811c302009-04-17 01:58:57 +0000539
540const char *CodeGenModule::getMangledCXXCtorName(const CXXConstructorDecl *D,
541 CXXCtorType Type) {
542 llvm::SmallString<256> Name;
543 llvm::raw_svector_ostream Out(Name);
544 mangleCXXCtor(D, Type, Context, Out);
545
546 Name += '\0';
547 return UniqueMangledName(Name.begin(), Name.end());
548}
549
550void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) {
551 if (!canGenerateCXXstructor(D->getParent(), getContext())) {
552 ErrorUnsupported(D, "C++ destructor", true);
553 return;
554 }
555
556 EmitCXXDestructor(D, Dtor_Complete);
557 EmitCXXDestructor(D, Dtor_Base);
558}
559
560void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D,
561 CXXDtorType Type) {
562 llvm::Function *Fn = GetAddrOfCXXDestructor(D, Type);
563
564 CodeGenFunction(*this).GenerateCode(D, Fn);
565
566 SetFunctionDefinitionAttributes(D, Fn);
567 SetLLVMFunctionAttributesForDefinition(D, Fn);
568}
569
570llvm::Function *
571CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D,
572 CXXDtorType Type) {
573 const llvm::FunctionType *FTy =
574 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false);
575
576 const char *Name = getMangledCXXDtorName(D, Type);
Chris Lattner80f39cc2009-05-12 21:21:08 +0000577 return cast<llvm::Function>(
578 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson4811c302009-04-17 01:58:57 +0000579}
580
581const char *CodeGenModule::getMangledCXXDtorName(const CXXDestructorDecl *D,
582 CXXDtorType Type) {
583 llvm::SmallString<256> Name;
584 llvm::raw_svector_ostream Out(Name);
585 mangleCXXDtor(D, Type, Context, Out);
586
587 Name += '\0';
588 return UniqueMangledName(Name.begin(), Name.end());
589}
Fariborz Jahanian5400e022009-07-20 23:18:55 +0000590
Mike Stump00df7d32009-07-31 23:15:31 +0000591llvm::Constant *CodeGenFunction::GenerateRtti(const CXXRecordDecl *RD) {
592 llvm::Type *Ptr8Ty;
593 Ptr8Ty = llvm::PointerType::get(llvm::Type::Int8Ty, 0);
Mike Stump69a12322009-08-04 20:06:48 +0000594 llvm::Constant *Rtti = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stump00df7d32009-07-31 23:15:31 +0000595
596 if (!getContext().getLangOptions().Rtti)
Mike Stump69a12322009-08-04 20:06:48 +0000597 return Rtti;
Mike Stump00df7d32009-07-31 23:15:31 +0000598
599 llvm::SmallString<256> OutName;
600 llvm::raw_svector_ostream Out(OutName);
601 QualType ClassTy;
Mike Stumpe7545622009-08-07 18:05:12 +0000602 ClassTy = getContext().getTagDeclType(RD);
Mike Stump00df7d32009-07-31 23:15:31 +0000603 mangleCXXRtti(ClassTy, getContext(), Out);
604 const char *Name = OutName.c_str();
605 llvm::GlobalVariable::LinkageTypes linktype;
606 linktype = llvm::GlobalValue::WeakAnyLinkage;
607 std::vector<llvm::Constant *> info;
Mike Stump71e21302009-08-06 21:49:36 +0000608 // assert (0 && "FIXME: implement rtti descriptor");
Mike Stump00df7d32009-07-31 23:15:31 +0000609 // FIXME: descriptor
610 info.push_back(llvm::Constant::getNullValue(Ptr8Ty));
Mike Stump71e21302009-08-06 21:49:36 +0000611 // assert (0 && "FIXME: implement rtti ts");
Mike Stump00df7d32009-07-31 23:15:31 +0000612 // FIXME: TS
613 info.push_back(llvm::Constant::getNullValue(Ptr8Ty));
614
615 llvm::Constant *C;
616 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, info.size());
617 C = llvm::ConstantArray::get(type, info);
Mike Stump69a12322009-08-04 20:06:48 +0000618 Rtti = new llvm::GlobalVariable(CGM.getModule(), type, true, linktype, C,
Mike Stump00df7d32009-07-31 23:15:31 +0000619 Name);
Mike Stump69a12322009-08-04 20:06:48 +0000620 Rtti = llvm::ConstantExpr::getBitCast(Rtti, Ptr8Ty);
621 return Rtti;
Mike Stump00df7d32009-07-31 23:15:31 +0000622}
623
Mike Stumpf640de52009-08-12 23:14:12 +0000624void CodeGenFunction::GenerateVcalls(std::vector<llvm::Constant *> &methods,
625 const CXXRecordDecl *RD,
626 llvm::Type *Ptr8Ty) {
627 typedef CXXRecordDecl::method_iterator meth_iter;
628 llvm::Constant *m;
629 for (meth_iter mi = RD->method_begin(),
630 me = RD->method_end(); mi != me; ++mi) {
631 if (mi->isVirtual()) {
632 // FIXME: vcall: offset for virtual base for this function
633 m = llvm::Constant::getNullValue(Ptr8Ty);
634 methods.push_back(m);
635 }
636 }
637}
638
Mike Stumpdecd7812009-08-12 23:00:59 +0000639void CodeGenFunction::GenerateMethods(std::vector<llvm::Constant *> &methods,
640 const CXXRecordDecl *RD,
641 llvm::Type *Ptr8Ty) {
642 typedef CXXRecordDecl::method_iterator meth_iter;
643 llvm::Constant *m;
644
645 for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
646 ++mi) {
647 if (mi->isVirtual()) {
648 m = CGM.GetAddrOfFunction(GlobalDecl(*mi));
649 m = llvm::ConstantExpr::getBitCast(m, Ptr8Ty);
650 methods.push_back(m);
651 }
652 }
653}
654
Mike Stumpd6f22d82009-08-06 15:50:11 +0000655void CodeGenFunction::GenerateVtableForBase(const CXXRecordDecl *RD,
Mike Stump71e21302009-08-06 21:49:36 +0000656 const CXXRecordDecl *Class,
657 llvm::Constant *rtti,
658 std::vector<llvm::Constant *> &methods,
Mike Stump96599e22009-08-06 23:48:32 +0000659 bool isPrimary,
Mike Stumpa8b58292009-08-12 17:42:21 +0000660 bool ForVirtualBase,
661 llvm::SmallSet<const CXXRecordDecl *, 32> &IndirectPrimary) {
Mike Stumpd6f22d82009-08-06 15:50:11 +0000662 typedef CXXRecordDecl::method_iterator meth_iter;
663 llvm::Type *Ptr8Ty;
664 Ptr8Ty = llvm::PointerType::get(llvm::Type::Int8Ty, 0);
Mike Stump71e21302009-08-06 21:49:36 +0000665 llvm::Constant *m = llvm::Constant::getNullValue(Ptr8Ty);
666
667 if (RD && !RD->isDynamicClass())
668 return;
Mike Stump96599e22009-08-06 23:48:32 +0000669
Mike Stump7df1ff12009-08-11 04:03:59 +0000670 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Class);
671
Mike Stump6abe5082009-08-12 18:50:26 +0000672 if (isPrimary) {
673 // The virtual base offsets come first...
674 for (CXXRecordDecl::reverse_base_class_const_iterator i
675 = Class->bases_rbegin(),
676 e = Class->bases_rend(); i != e; ++i) {
677 if (!i->isVirtual())
678 continue;
679 const CXXRecordDecl *Base =
680 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
681 int64_t BaseOffset = Layout.getBaseClassOffset(Base) / 8;
682 llvm::Constant *m;
683 m = llvm::ConstantInt::get(llvm::Type::Int64Ty, BaseOffset);
684 m = llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
685 methods.push_back(m);
686 }
Mike Stump7df1ff12009-08-11 04:03:59 +0000687 }
688
689 // then comes the the vcall offsets for all our functions...
Mike Stump96599e22009-08-06 23:48:32 +0000690 if (isPrimary && ForVirtualBase)
Mike Stumpf640de52009-08-12 23:14:12 +0000691 GenerateVcalls(methods, Class, Ptr8Ty);
692
Mike Stump7df1ff12009-08-11 04:03:59 +0000693 bool TopPrimary = true;
694 // Primary tables are composed from the chain of primaries.
695 if (isPrimary) {
696 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
697 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
698 if (PrimaryBase) {
Mike Stumpa8b58292009-08-12 17:42:21 +0000699 if (PrimaryBaseWasVirtual)
700 IndirectPrimary.insert(PrimaryBase);
Mike Stump7df1ff12009-08-11 04:03:59 +0000701 TopPrimary = false;
702 GenerateVtableForBase(0, PrimaryBase, rtti, methods, true,
Mike Stumpa8b58292009-08-12 17:42:21 +0000703 PrimaryBaseWasVirtual, IndirectPrimary);
Mike Stump7df1ff12009-08-11 04:03:59 +0000704 }
Mike Stump71e21302009-08-06 21:49:36 +0000705 }
Mike Stump7df1ff12009-08-11 04:03:59 +0000706 // then come the vcall offsets for all our virtual bases.
707 if (!isPrimary && RD && ForVirtualBase)
Mike Stumpf640de52009-08-12 23:14:12 +0000708 GenerateVcalls(methods, RD, Ptr8Ty);
Mike Stump71e21302009-08-06 21:49:36 +0000709
Mike Stump7df1ff12009-08-11 04:03:59 +0000710 if (TopPrimary) {
711 if (RD) {
712 int64_t BaseOffset = -(Layout.getBaseClassOffset(RD) / 8);
713 m = llvm::ConstantInt::get(llvm::Type::Int64Ty, BaseOffset);
714 m = llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
715 }
716 methods.push_back(m);
717 methods.push_back(rtti);
718 }
719
Mike Stumpdd8764a2009-08-12 22:34:12 +0000720 if (!isPrimary) {
Mike Stumpdecd7812009-08-12 23:00:59 +0000721 if (RD)
722 GenerateMethods(methods, RD, Ptr8Ty);
Mike Stump71e21302009-08-06 21:49:36 +0000723 return;
Mike Stumpdd8764a2009-08-12 22:34:12 +0000724 }
Mike Stump71e21302009-08-06 21:49:36 +0000725
726 // And add the virtuals for the class to the primary vtable.
Mike Stumpdecd7812009-08-12 23:00:59 +0000727 GenerateMethods(methods, Class, Ptr8Ty);
Mike Stumpd6f22d82009-08-06 15:50:11 +0000728}
729
Mike Stump7e8c9932009-07-31 18:25:34 +0000730llvm::Value *CodeGenFunction::GenerateVtable(const CXXRecordDecl *RD) {
Mike Stump7e8c9932009-07-31 18:25:34 +0000731 llvm::SmallString<256> OutName;
732 llvm::raw_svector_ostream Out(OutName);
733 QualType ClassTy;
Mike Stumpe7545622009-08-07 18:05:12 +0000734 ClassTy = getContext().getTagDeclType(RD);
Mike Stump7e8c9932009-07-31 18:25:34 +0000735 mangleCXXVtable(ClassTy, getContext(), Out);
736 const char *Name = OutName.c_str();
Mike Stumpd0672782009-07-31 21:43:43 +0000737 llvm::GlobalVariable::LinkageTypes linktype;
738 linktype = llvm::GlobalValue::WeakAnyLinkage;
739 std::vector<llvm::Constant *> methods;
Mike Stump276a3702009-08-12 23:03:28 +0000740 llvm::Type *Ptr8Ty = llvm::PointerType::get(llvm::Type::Int8Ty, 0);
Mike Stump8b82eeb2009-08-05 22:37:18 +0000741 int64_t Offset = 0;
Mike Stump71e21302009-08-06 21:49:36 +0000742 llvm::Constant *rtti = GenerateRtti(RD);
743
744 Offset += LLVMPointerWidth;
745 Offset += LLVMPointerWidth;
Mike Stump8b82eeb2009-08-05 22:37:18 +0000746
747 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
748 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
Mike Stump030dbfb2009-08-07 20:14:05 +0000749 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
Mike Stumpa8b58292009-08-12 17:42:21 +0000750 llvm::SmallSet<const CXXRecordDecl *, 32> IndirectPrimary;
Mike Stumpf3371782009-08-04 21:58:42 +0000751
Mike Stump25cbad02009-08-06 18:05:22 +0000752 // The primary base comes first.
Mike Stumpbea9cc82009-08-07 19:00:50 +0000753 GenerateVtableForBase(PrimaryBase, RD, rtti, methods, true,
Mike Stumpa8b58292009-08-12 17:42:21 +0000754 PrimaryBaseWasVirtual, IndirectPrimary);
Mike Stumpf3371782009-08-04 21:58:42 +0000755 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
756 e = RD->bases_end(); i != e; ++i) {
757 if (i->isVirtual())
758 continue;
759 const CXXRecordDecl *Base =
760 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Mike Stump8b82eeb2009-08-05 22:37:18 +0000761 if (PrimaryBase != Base) {
Mike Stumpa8b58292009-08-12 17:42:21 +0000762 GenerateVtableForBase(Base, RD, rtti, methods, false, false,
763 IndirectPrimary);
Mike Stump8b82eeb2009-08-05 22:37:18 +0000764 }
765 }
Mike Stump25cbad02009-08-06 18:05:22 +0000766
Mike Stumpd6f22d82009-08-06 15:50:11 +0000767 // FIXME: finish layout for virtual bases
768 // FIXME: audit indirect virtual bases
769 for (CXXRecordDecl::base_class_const_iterator i = RD->vbases_begin(),
770 e = RD->vbases_end(); i != e; ++i) {
771 const CXXRecordDecl *Base =
772 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Mike Stumpa8b58292009-08-12 17:42:21 +0000773 if (!IndirectPrimary.count(Base))
774 GenerateVtableForBase(Base, RD, rtti, methods, false, true,
775 IndirectPrimary);
Mike Stumpd6f22d82009-08-06 15:50:11 +0000776 }
Mike Stumpf3371782009-08-04 21:58:42 +0000777
Mike Stumpd0672782009-07-31 21:43:43 +0000778 llvm::Constant *C;
779 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, methods.size());
780 C = llvm::ConstantArray::get(type, methods);
781 llvm::Value *vtable = new llvm::GlobalVariable(CGM.getModule(), type, true,
782 linktype, C, Name);
Mike Stump7e8c9932009-07-31 18:25:34 +0000783 vtable = Builder.CreateBitCast(vtable, Ptr8Ty);
Mike Stump7e8c9932009-07-31 18:25:34 +0000784 vtable = Builder.CreateGEP(vtable,
785 llvm::ConstantInt::get(llvm::Type::Int64Ty,
Mike Stump8b82eeb2009-08-05 22:37:18 +0000786 Offset/8));
Mike Stump7e8c9932009-07-31 18:25:34 +0000787 return vtable;
788}
789
Fariborz Jahanianfc27d292009-08-07 23:51:33 +0000790/// EmitClassMemberwiseCopy - This routine generates code to copy a class
791/// object from SrcValue to DestValue. Copying can be either a bitwise copy
792/// of via a copy constructor call.
793void CodeGenFunction::EmitClassMemberwiseCopy(
Fariborz Jahaniancefe5922009-08-08 23:32:22 +0000794 llvm::Value *Dest, llvm::Value *Src,
Fariborz Jahanianfc27d292009-08-07 23:51:33 +0000795 const CXXRecordDecl *ClassDecl,
Fariborz Jahaniancefe5922009-08-08 23:32:22 +0000796 const CXXRecordDecl *BaseClassDecl, QualType Ty) {
797 if (ClassDecl) {
798 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
799 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
800 }
801 if (BaseClassDecl->hasTrivialCopyConstructor()) {
802 EmitAggregateCopy(Dest, Src, Ty);
Fariborz Jahanianfc27d292009-08-07 23:51:33 +0000803 return;
Fariborz Jahaniancefe5922009-08-08 23:32:22 +0000804 }
805
Fariborz Jahanianfc27d292009-08-07 23:51:33 +0000806 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanianfbe08772009-08-08 00:59:58 +0000807 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
Fariborz Jahanianfc27d292009-08-07 23:51:33 +0000808 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
809 Ctor_Complete);
Fariborz Jahanianfc27d292009-08-07 23:51:33 +0000810 CallArgList CallArgs;
811 // Push the this (Dest) ptr.
812 CallArgs.push_back(std::make_pair(RValue::get(Dest),
813 BaseCopyCtor->getThisType(getContext())));
814
Fariborz Jahanianfc27d292009-08-07 23:51:33 +0000815 // Push the Src ptr.
816 CallArgs.push_back(std::make_pair(RValue::get(Src),
Fariborz Jahanian0dfaec42009-08-10 17:20:45 +0000817 BaseCopyCtor->getParamDecl(0)->getType()));
Fariborz Jahanianfc27d292009-08-07 23:51:33 +0000818 QualType ResultType =
819 BaseCopyCtor->getType()->getAsFunctionType()->getResultType();
820 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
821 Callee, CallArgs, BaseCopyCtor);
822 }
823}
Fariborz Jahaniane39fab62009-08-10 18:46:38 +0000824
825/// SynthesizeDefaultConstructor - synthesize a default constructor
826void
827CodeGenFunction::SynthesizeDefaultConstructor(const CXXConstructorDecl *CD,
828 const FunctionDecl *FD,
829 llvm::Function *Fn,
830 const FunctionArgList &Args) {
831 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
832 EmitCtorPrologue(CD);
833 FinishFunction();
834}
835
Fariborz Jahanianab840aa2009-08-08 19:31:03 +0000836/// SynthesizeCXXCopyConstructor - This routine implicitly defines body of a copy
Fariborz Jahanian5e050b82009-08-07 20:22:40 +0000837/// constructor, in accordance with section 12.8 (p7 and p8) of C++03
838/// The implicitly-defined copy constructor for class X performs a memberwise
839/// copy of its subobjects. The order of copying is the same as the order
840/// of initialization of bases and members in a user-defined constructor
841/// Each subobject is copied in the manner appropriate to its type:
842/// if the subobject is of class type, the copy constructor for the class is
843/// used;
844/// if the subobject is an array, each element is copied, in the manner
845/// appropriate to the element type;
846/// if the subobject is of scalar type, the built-in assignment operator is
847/// used.
848/// Virtual base class subobjects shall be copied only once by the
849/// implicitly-defined copy constructor
850
Fariborz Jahanianab840aa2009-08-08 19:31:03 +0000851void CodeGenFunction::SynthesizeCXXCopyConstructor(const CXXConstructorDecl *CD,
852 const FunctionDecl *FD,
853 llvm::Function *Fn,
Fariborz Jahanianfc27d292009-08-07 23:51:33 +0000854 const FunctionArgList &Args) {
Fariborz Jahanian5e050b82009-08-07 20:22:40 +0000855 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
856 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
Fariborz Jahanianab840aa2009-08-08 19:31:03 +0000857 "SynthesizeCXXCopyConstructor - copy constructor has definition already");
858 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
Fariborz Jahanian5e050b82009-08-07 20:22:40 +0000859
Fariborz Jahanian5e778e32009-08-08 00:15:41 +0000860 FunctionArgList::const_iterator i = Args.begin();
861 const VarDecl *ThisArg = i->first;
862 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
863 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
864 const VarDecl *SrcArg = (i+1)->first;
865 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
866 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
867
Fariborz Jahanian5e050b82009-08-07 20:22:40 +0000868 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
869 Base != ClassDecl->bases_end(); ++Base) {
870 // FIXME. copy constrution of virtual base NYI
871 if (Base->isVirtual())
872 continue;
Fariborz Jahanianfc27d292009-08-07 23:51:33 +0000873
Fariborz Jahanian5e050b82009-08-07 20:22:40 +0000874 CXXRecordDecl *BaseClassDecl
875 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahaniancefe5922009-08-08 23:32:22 +0000876 EmitClassMemberwiseCopy(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
877 Base->getType());
Fariborz Jahanian5e050b82009-08-07 20:22:40 +0000878 }
879
Fariborz Jahanian5e778e32009-08-08 00:15:41 +0000880 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
881 FieldEnd = ClassDecl->field_end();
882 Field != FieldEnd; ++Field) {
883 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
884
885 // FIXME. How about copying arrays!
886 assert(!getContext().getAsArrayType(FieldType) &&
887 "FIXME. Copying arrays NYI");
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +0000888
Fariborz Jahanian5e778e32009-08-08 00:15:41 +0000889 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
890 CXXRecordDecl *FieldClassDecl
891 = cast<CXXRecordDecl>(FieldClassType->getDecl());
892 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
893 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Fariborz Jahaniancefe5922009-08-08 23:32:22 +0000894
Fariborz Jahanian5e778e32009-08-08 00:15:41 +0000895 EmitClassMemberwiseCopy(LHS.getAddress(), RHS.getAddress(),
Fariborz Jahaniancefe5922009-08-08 23:32:22 +0000896 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanian5e778e32009-08-08 00:15:41 +0000897 continue;
898 }
Fariborz Jahanian08d99e92009-08-10 18:34:26 +0000899 // Do a built-in assignment of scalar data members.
900 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
901 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
902 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
903 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanian5e778e32009-08-08 00:15:41 +0000904 }
Fariborz Jahanianab840aa2009-08-08 19:31:03 +0000905 FinishFunction();
Fariborz Jahanian5e050b82009-08-07 20:22:40 +0000906}
907
Fariborz Jahanian651efb72009-08-12 21:14:35 +0000908/// SynthesizeCXXCopyAssignment - Implicitly define copy assignment operator.
909/// Before the implicitly-declared copy assignment operator for a class is
910/// implicitly defined, all implicitly- declared copy assignment operators for
911/// its direct base classes and its nonstatic data members shall have been
912/// implicitly defined. [12.8-p12]
913/// The implicitly-defined copy assignment operator for class X performs
914/// memberwise assignment of its subob- jects. The direct base classes of X are
915/// assigned first, in the order of their declaration in
916/// the base-specifier-list, and then the immediate nonstatic data members of X
917/// are assigned, in the order in which they were declared in the class
918/// definition.Each subobject is assigned in the manner appropriate to its type:
919/// — if the subobject is of class type, the copy assignment operator for the
920/// class is used (as if by explicit qual- ification; that is, ignoring any
921/// possible virtual overriding functions in more derived classes);
922/// — if the subobject is an array, each element is assigned, in the manner
923/// appropriate to the element type;
924/// — if the subobject is of scalar type, the built-in assignment operator is
925/// used.
926void CodeGenFunction::SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD,
927 const FunctionDecl *FD,
928 llvm::Function *Fn,
929 const FunctionArgList &Args) {
930 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
931
932 FinishFunction();
933}
Fariborz Jahanian5e050b82009-08-07 20:22:40 +0000934
Fariborz Jahanian5400e022009-07-20 23:18:55 +0000935/// EmitCtorPrologue - This routine generates necessary code to initialize
936/// base classes and non-static data members belonging to this constructor.
937void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD) {
Fariborz Jahaniana0107de2009-07-25 21:12:28 +0000938 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
Mike Stump05207212009-08-06 13:41:24 +0000939 // FIXME: Add vbase initialization
Mike Stump7e8c9932009-07-31 18:25:34 +0000940 llvm::Value *LoadOfThis = 0;
Fariborz Jahanian70277012009-07-28 18:09:28 +0000941
Fariborz Jahaniana0107de2009-07-25 21:12:28 +0000942 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
Fariborz Jahanian5400e022009-07-20 23:18:55 +0000943 E = CD->init_end();
944 B != E; ++B) {
945 CXXBaseOrMemberInitializer *Member = (*B);
946 if (Member->isBaseInitializer()) {
Mike Stump7e8c9932009-07-31 18:25:34 +0000947 LoadOfThis = LoadCXXThis();
Fariborz Jahanian70277012009-07-28 18:09:28 +0000948 Type *BaseType = Member->getBaseClass();
949 CXXRecordDecl *BaseClassDecl =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000950 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
Fariborz Jahanian70277012009-07-28 18:09:28 +0000951 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
952 BaseClassDecl);
Fariborz Jahaniana0107de2009-07-25 21:12:28 +0000953 EmitCXXConstructorCall(Member->getConstructor(),
954 Ctor_Complete, V,
955 Member->const_arg_begin(),
956 Member->const_arg_end());
Mike Stump487ce382009-07-30 22:28:39 +0000957 } else {
Fariborz Jahanian5400e022009-07-20 23:18:55 +0000958 // non-static data member initilaizers.
959 FieldDecl *Field = Member->getMember();
960 QualType FieldType = getContext().getCanonicalType((Field)->getType());
961 assert(!getContext().getAsArrayType(FieldType)
962 && "FIXME. Field arrays initialization unsupported");
Fariborz Jahanian32cea8b2009-08-10 23:56:17 +0000963
Mike Stump7e8c9932009-07-31 18:25:34 +0000964 LoadOfThis = LoadCXXThis();
Fariborz Jahanian5400e022009-07-20 23:18:55 +0000965 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000966 if (FieldType->getAs<RecordType>()) {
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +0000967 if (!Field->isAnonymousStructOrUnion()) {
Fariborz Jahanian56baceb2009-07-24 17:57:02 +0000968 assert(Member->getConstructor() &&
969 "EmitCtorPrologue - no constructor to initialize member");
970 EmitCXXConstructorCall(Member->getConstructor(),
971 Ctor_Complete, LHS.getAddress(),
972 Member->const_arg_begin(),
973 Member->const_arg_end());
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +0000974 continue;
975 }
976 else {
977 // Initializing an anonymous union data member.
978 FieldDecl *anonMember = Member->getAnonUnionMember();
979 LHS = EmitLValueForField(LHS.getAddress(), anonMember, false, 0);
980 FieldType = anonMember->getType();
981 }
Fariborz Jahanian56baceb2009-07-24 17:57:02 +0000982 }
Fariborz Jahanian5400e022009-07-20 23:18:55 +0000983
984 assert(Member->getNumArgs() == 1 && "Initializer count must be 1 only");
Fariborz Jahanian56baceb2009-07-24 17:57:02 +0000985 Expr *RhsExpr = *Member->arg_begin();
Fariborz Jahanian5400e022009-07-20 23:18:55 +0000986 llvm::Value *RHS = EmitScalarExpr(RhsExpr, true);
Fariborz Jahanian32cea8b2009-08-10 23:56:17 +0000987 EmitStoreThroughLValue(RValue::get(RHS), LHS, FieldType);
Fariborz Jahanian5400e022009-07-20 23:18:55 +0000988 }
989 }
Mike Stump7e8c9932009-07-31 18:25:34 +0000990
991 // Initialize the vtable pointer
Mike Stumpeec46a72009-08-05 22:59:44 +0000992 if (ClassDecl->isDynamicClass()) {
Mike Stump7e8c9932009-07-31 18:25:34 +0000993 if (!LoadOfThis)
994 LoadOfThis = LoadCXXThis();
995 llvm::Value *VtableField;
996 llvm::Type *Ptr8Ty, *PtrPtr8Ty;
997 Ptr8Ty = llvm::PointerType::get(llvm::Type::Int8Ty, 0);
998 PtrPtr8Ty = llvm::PointerType::get(Ptr8Ty, 0);
999 VtableField = Builder.CreateBitCast(LoadOfThis, PtrPtr8Ty);
1000 llvm::Value *vtable = GenerateVtable(ClassDecl);
1001 Builder.CreateStore(vtable, VtableField);
1002 }
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001003}
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001004
1005/// EmitDtorEpilogue - Emit all code that comes at the end of class's
1006/// destructor. This is to call destructors on members and base classes
1007/// in reverse order of their construction.
1008void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD) {
1009 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(DD->getDeclContext());
1010 assert(!ClassDecl->isPolymorphic() &&
1011 "FIXME. polymorphic destruction not supported");
1012 (void)ClassDecl; // prevent warning.
1013
1014 for (CXXDestructorDecl::destr_const_iterator *B = DD->destr_begin(),
1015 *E = DD->destr_end(); B != E; ++B) {
1016 uintptr_t BaseOrMember = (*B);
1017 if (DD->isMemberToDestroy(BaseOrMember)) {
1018 FieldDecl *FD = DD->getMemberToDestroy(BaseOrMember);
1019 QualType FieldType = getContext().getCanonicalType((FD)->getType());
1020 assert(!getContext().getAsArrayType(FieldType)
1021 && "FIXME. Field arrays destruction unsupported");
1022 const RecordType *RT = FieldType->getAs<RecordType>();
1023 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1024 if (FieldClassDecl->hasTrivialDestructor())
1025 continue;
1026 llvm::Value *LoadOfThis = LoadCXXThis();
1027 LValue LHS = EmitLValueForField(LoadOfThis, FD, false, 0);
1028 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1029 Dtor_Complete, LHS.getAddress());
Mike Stump487ce382009-07-30 22:28:39 +00001030 } else {
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001031 const RecordType *RT =
1032 DD->getAnyBaseClassToDestroy(BaseOrMember)->getAs<RecordType>();
1033 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1034 if (BaseClassDecl->hasTrivialDestructor())
1035 continue;
1036 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
1037 ClassDecl,BaseClassDecl);
1038 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1039 Dtor_Complete, V);
1040 }
1041 }
1042}