blob: 375c9ac40e40868c21a4785f59068bf64a2bfabe [file] [log] [blame]
Anders Carlssone1b29ef2008-08-22 16:00:37 +00001//===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with C++ code generation.
11//
12//===----------------------------------------------------------------------===//
13
14// We might split this into multiple files if it gets too unwieldy
15
16#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
Anders Carlsson283a0622009-04-13 18:03:33 +000018#include "Mangle.h"
Anders Carlssone1b29ef2008-08-22 16:00:37 +000019#include "clang/AST/ASTContext.h"
Fariborz Jahanian742cd1b2009-07-25 21:12:28 +000020#include "clang/AST/RecordLayout.h"
Anders Carlssone1b29ef2008-08-22 16:00:37 +000021#include "clang/AST/Decl.h"
Anders Carlsson774e7c62009-04-03 22:50:24 +000022#include "clang/AST/DeclCXX.h"
Anders Carlsson86e96442008-08-23 19:42:54 +000023#include "clang/AST/DeclObjC.h"
Anders Carlssone1b29ef2008-08-22 16:00:37 +000024#include "llvm/ADT/StringExtras.h"
Anders Carlssone1b29ef2008-08-22 16:00:37 +000025using namespace clang;
26using namespace CodeGen;
27
Daniel Dunbar0096acf2009-02-25 19:24:29 +000028void
29CodeGenFunction::GenerateStaticCXXBlockVarDeclInit(const VarDecl &D,
30 llvm::GlobalVariable *GV) {
31 // FIXME: This should use __cxa_guard_{acquire,release}?
32
Anders Carlssone1b29ef2008-08-22 16:00:37 +000033 assert(!getContext().getLangOptions().ThreadsafeStatics &&
34 "thread safe statics are currently not supported!");
Anders Carlssone1b29ef2008-08-22 16:00:37 +000035
Anders Carlsson283a0622009-04-13 18:03:33 +000036 llvm::SmallString<256> GuardVName;
37 llvm::raw_svector_ostream GuardVOut(GuardVName);
38 mangleGuardVariable(&D, getContext(), GuardVOut);
39
Anders Carlssone1b29ef2008-08-22 16:00:37 +000040 // Create the guard variable.
41 llvm::GlobalValue *GuardV =
Owen Anderson1c431b32009-07-08 19:05:04 +000042 new llvm::GlobalVariable(CGM.getModule(), llvm::Type::Int64Ty, false,
Daniel Dunbar0096acf2009-02-25 19:24:29 +000043 GV->getLinkage(),
Owen Andersonc9c88b42009-07-31 20:28:54 +000044 llvm::Constant::getNullValue(llvm::Type::Int64Ty),
Owen Anderson1c431b32009-07-08 19:05:04 +000045 GuardVName.c_str());
Anders Carlssone1b29ef2008-08-22 16:00:37 +000046
Anders Carlssone1b29ef2008-08-22 16:00:37 +000047 // Load the first byte of the guard variable.
Owen Anderson96e0fc72009-07-29 22:16:19 +000048 const llvm::Type *PtrTy = llvm::PointerType::get(llvm::Type::Int8Ty, 0);
Anders Carlssone1b29ef2008-08-22 16:00:37 +000049 llvm::Value *V = Builder.CreateLoad(Builder.CreateBitCast(GuardV, PtrTy),
50 "tmp");
51
52 // Compare it against 0.
Owen Andersonc9c88b42009-07-31 20:28:54 +000053 llvm::Value *nullValue = llvm::Constant::getNullValue(llvm::Type::Int8Ty);
Anders Carlssone1b29ef2008-08-22 16:00:37 +000054 llvm::Value *ICmp = Builder.CreateICmpEQ(V, nullValue , "tobool");
55
Daniel Dunbar55e87422008-11-11 02:29:29 +000056 llvm::BasicBlock *InitBlock = createBasicBlock("init");
Daniel Dunbar9615ecb2008-11-13 01:38:36 +000057 llvm::BasicBlock *EndBlock = createBasicBlock("init.end");
Anders Carlssone1b29ef2008-08-22 16:00:37 +000058
59 // If the guard variable is 0, jump to the initializer code.
60 Builder.CreateCondBr(ICmp, InitBlock, EndBlock);
61
62 EmitBlock(InitBlock);
63
Anders Carlssone1b29ef2008-08-22 16:00:37 +000064 const Expr *Init = D.getInit();
65 if (!hasAggregateLLVMType(Init->getType())) {
66 llvm::Value *V = EmitScalarExpr(Init);
67 Builder.CreateStore(V, GV, D.getType().isVolatileQualified());
68 } else if (Init->getType()->isAnyComplexType()) {
69 EmitComplexExprIntoAddr(Init, GV, D.getType().isVolatileQualified());
70 } else {
71 EmitAggExpr(Init, GV, D.getType().isVolatileQualified());
72 }
73
Owen Anderson4a28d5d2009-07-24 23:12:58 +000074 Builder.CreateStore(llvm::ConstantInt::get(llvm::Type::Int8Ty, 1),
Anders Carlssone1b29ef2008-08-22 16:00:37 +000075 Builder.CreateBitCast(GuardV, PtrTy));
76
77 EmitBlock(EndBlock);
Anders Carlssone1b29ef2008-08-22 16:00:37 +000078}
79
Anders Carlssonb9de2c52009-05-11 23:37:08 +000080RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
81 llvm::Value *Callee,
82 llvm::Value *This,
83 CallExpr::const_arg_iterator ArgBeg,
84 CallExpr::const_arg_iterator ArgEnd) {
85 assert(MD->isInstance() &&
86 "Trying to emit a member call expr on a static method!");
87
88 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
89
90 CallArgList Args;
91
92 // Push the this ptr.
93 Args.push_back(std::make_pair(RValue::get(This),
94 MD->getThisType(getContext())));
95
96 // And the rest of the call args
97 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
98
99 QualType ResultType = MD->getType()->getAsFunctionType()->getResultType();
100 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args),
101 Callee, Args, MD);
102}
103
Anders Carlsson774e7c62009-04-03 22:50:24 +0000104RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE) {
105 const MemberExpr *ME = cast<MemberExpr>(CE->getCallee());
106 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000107
Anders Carlssone9918d22009-04-08 20:31:57 +0000108 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
Mike Stump7116da12009-07-30 21:47:44 +0000109
Mike Stumpf1216772009-07-31 18:25:34 +0000110 if (MD->isVirtual()) {
Mike Stump7116da12009-07-30 21:47:44 +0000111 ErrorUnsupported(CE, "virtual dispatch");
112 }
113
Anders Carlsson774e7c62009-04-03 22:50:24 +0000114 const llvm::Type *Ty =
Anders Carlssone9918d22009-04-08 20:31:57 +0000115 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
116 FPT->isVariadic());
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000117 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty);
Anders Carlsson774e7c62009-04-03 22:50:24 +0000118
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000119 llvm::Value *This;
Anders Carlsson774e7c62009-04-03 22:50:24 +0000120
Anders Carlsson774e7c62009-04-03 22:50:24 +0000121 if (ME->isArrow())
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000122 This = EmitScalarExpr(ME->getBase());
Anders Carlsson774e7c62009-04-03 22:50:24 +0000123 else {
124 LValue BaseLV = EmitLValue(ME->getBase());
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000125 This = BaseLV.getAddress();
Anders Carlsson774e7c62009-04-03 22:50:24 +0000126 }
127
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000128 return EmitCXXMemberCall(MD, Callee, This,
129 CE->arg_begin(), CE->arg_end());
Anders Carlsson774e7c62009-04-03 22:50:24 +0000130}
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000131
Anders Carlsson0f294632009-05-27 04:18:27 +0000132RValue
133CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
134 const CXXMethodDecl *MD) {
135 assert(MD->isInstance() &&
136 "Trying to emit a member call expr on a static method!");
137
138
139 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
140 const llvm::Type *Ty =
141 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
142 FPT->isVariadic());
143 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty);
144
145 llvm::Value *This = EmitLValue(E->getArg(0)).getAddress();
146
147 return EmitCXXMemberCall(MD, Callee, This,
148 E->arg_begin() + 1, E->arg_end());
149}
150
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000151llvm::Value *CodeGenFunction::LoadCXXThis() {
152 assert(isa<CXXMethodDecl>(CurFuncDecl) &&
153 "Must be in a C++ member function decl to load 'this'");
154 assert(cast<CXXMethodDecl>(CurFuncDecl)->isInstance() &&
155 "Must be in a C++ member function decl to load 'this'");
156
157 // FIXME: What if we're inside a block?
Mike Stumpf5408fe2009-05-16 07:57:57 +0000158 // ans: See how CodeGenFunction::LoadObjCSelf() uses
159 // CodeGenFunction::BlockForwardSelf() for how to do this.
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000160 return Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
161}
Anders Carlsson95d4e5d2009-04-15 15:55:24 +0000162
Fariborz Jahanianc238a792009-07-30 00:10:25 +0000163static bool
164GetNestedPaths(llvm::SmallVectorImpl<const CXXRecordDecl *> &NestedBasePaths,
165 const CXXRecordDecl *ClassDecl,
166 const CXXRecordDecl *BaseClassDecl) {
Fariborz Jahanianc238a792009-07-30 00:10:25 +0000167 for (CXXRecordDecl::base_class_const_iterator i = ClassDecl->bases_begin(),
168 e = ClassDecl->bases_end(); i != e; ++i) {
169 if (i->isVirtual())
170 continue;
171 const CXXRecordDecl *Base =
Mike Stump104ffaa2009-08-04 21:58:42 +0000172 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanianc238a792009-07-30 00:10:25 +0000173 if (Base == BaseClassDecl) {
174 NestedBasePaths.push_back(BaseClassDecl);
175 return true;
176 }
177 }
178 // BaseClassDecl not an immediate base of ClassDecl.
179 for (CXXRecordDecl::base_class_const_iterator i = ClassDecl->bases_begin(),
180 e = ClassDecl->bases_end(); i != e; ++i) {
181 if (i->isVirtual())
182 continue;
183 const CXXRecordDecl *Base =
184 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
185 if (GetNestedPaths(NestedBasePaths, Base, BaseClassDecl)) {
186 NestedBasePaths.push_back(Base);
187 return true;
188 }
189 }
190 return false;
191}
192
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000193llvm::Value *CodeGenFunction::AddressCXXOfBaseClass(llvm::Value *BaseValue,
Fariborz Jahanian6d0bdaa2009-07-28 18:09:28 +0000194 const CXXRecordDecl *ClassDecl,
195 const CXXRecordDecl *BaseClassDecl) {
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000196 if (ClassDecl == BaseClassDecl)
197 return BaseValue;
198
Fariborz Jahanianc238a792009-07-30 00:10:25 +0000199 llvm::Type *I8Ptr = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
200 llvm::SmallVector<const CXXRecordDecl *, 16> NestedBasePaths;
201 GetNestedPaths(NestedBasePaths, ClassDecl, BaseClassDecl);
202 assert(NestedBasePaths.size() > 0 &&
203 "AddressCXXOfBaseClass - inheritence path failed");
204 NestedBasePaths.push_back(ClassDecl);
205 uint64_t Offset = 0;
206
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000207 // Accessing a member of the base class. Must add delata to
208 // the load of 'this'.
Fariborz Jahanianc238a792009-07-30 00:10:25 +0000209 for (unsigned i = NestedBasePaths.size()-1; i > 0; i--) {
210 const CXXRecordDecl *DerivedClass = NestedBasePaths[i];
211 const CXXRecordDecl *BaseClass = NestedBasePaths[i-1];
212 const ASTRecordLayout &Layout =
213 getContext().getASTRecordLayout(DerivedClass);
214 Offset += Layout.getBaseClassOffset(BaseClass) / 8;
215 }
Fariborz Jahanian5a8503b2009-07-29 15:54:56 +0000216 llvm::Value *OffsetVal =
217 llvm::ConstantInt::get(
218 CGM.getTypes().ConvertType(CGM.getContext().LongTy), Offset);
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000219 BaseValue = Builder.CreateBitCast(BaseValue, I8Ptr);
220 BaseValue = Builder.CreateGEP(BaseValue, OffsetVal, "add.ptr");
221 QualType BTy =
222 getContext().getCanonicalType(
Fariborz Jahanian6d0bdaa2009-07-28 18:09:28 +0000223 getContext().getTypeDeclType(const_cast<CXXRecordDecl*>(BaseClassDecl)));
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000224 const llvm::Type *BasePtr = ConvertType(BTy);
Owen Anderson96e0fc72009-07-29 22:16:19 +0000225 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Fariborz Jahanian9e809e72009-07-28 17:38:28 +0000226 BaseValue = Builder.CreateBitCast(BaseValue, BasePtr);
227 return BaseValue;
228}
229
Anders Carlssonb14095a2009-04-17 00:06:03 +0000230void
231CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
232 CXXCtorType Type,
233 llvm::Value *This,
234 CallExpr::const_arg_iterator ArgBeg,
235 CallExpr::const_arg_iterator ArgEnd) {
Anders Carlssonb9de2c52009-05-11 23:37:08 +0000236 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
237
238 EmitCXXMemberCall(D, Callee, This, ArgBeg, ArgEnd);
Anders Carlssonb14095a2009-04-17 00:06:03 +0000239}
240
Anders Carlsson7267c162009-05-29 21:03:38 +0000241void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *D,
242 CXXDtorType Type,
243 llvm::Value *This) {
244 llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(D, Type);
245
246 EmitCXXMemberCall(D, Callee, This, 0, 0);
247}
248
Anders Carlssonb14095a2009-04-17 00:06:03 +0000249void
Anders Carlsson31ccf372009-05-03 17:47:16 +0000250CodeGenFunction::EmitCXXConstructExpr(llvm::Value *Dest,
251 const CXXConstructExpr *E) {
Anders Carlssonb14095a2009-04-17 00:06:03 +0000252 assert(Dest && "Must have a destination!");
253
254 const CXXRecordDecl *RD =
Ted Kremenek6217b802009-07-29 21:53:49 +0000255 cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
Anders Carlssonb14095a2009-04-17 00:06:03 +0000256 if (RD->hasTrivialConstructor())
257 return;
258
259 // Call the constructor.
260 EmitCXXConstructorCall(E->getConstructor(), Ctor_Complete, Dest,
261 E->arg_begin(), E->arg_end());
262}
263
Anders Carlssona00703d2009-05-31 01:40:14 +0000264llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
Anders Carlssoned4e3672009-05-31 20:21:44 +0000265 if (E->isArray()) {
266 ErrorUnsupported(E, "new[] expression");
Owen Anderson03e20502009-07-30 23:11:26 +0000267 return llvm::UndefValue::get(ConvertType(E->getType()));
Anders Carlssoned4e3672009-05-31 20:21:44 +0000268 }
269
270 QualType AllocType = E->getAllocatedType();
271 FunctionDecl *NewFD = E->getOperatorNew();
272 const FunctionProtoType *NewFTy = NewFD->getType()->getAsFunctionProtoType();
273
274 CallArgList NewArgs;
275
276 // The allocation size is the first argument.
277 QualType SizeTy = getContext().getSizeType();
278 llvm::Value *AllocSize =
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000279 llvm::ConstantInt::get(ConvertType(SizeTy),
Anders Carlssoned4e3672009-05-31 20:21:44 +0000280 getContext().getTypeSize(AllocType) / 8);
281
282 NewArgs.push_back(std::make_pair(RValue::get(AllocSize), SizeTy));
283
284 // Emit the rest of the arguments.
285 // FIXME: Ideally, this should just use EmitCallArgs.
286 CXXNewExpr::const_arg_iterator NewArg = E->placement_arg_begin();
287
288 // First, use the types from the function type.
289 // We start at 1 here because the first argument (the allocation size)
290 // has already been emitted.
291 for (unsigned i = 1, e = NewFTy->getNumArgs(); i != e; ++i, ++NewArg) {
292 QualType ArgType = NewFTy->getArgType(i);
293
294 assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
295 getTypePtr() ==
296 getContext().getCanonicalType(NewArg->getType()).getTypePtr() &&
297 "type mismatch in call argument!");
298
299 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
300 ArgType));
301
302 }
303
304 // Either we've emitted all the call args, or we have a call to a
305 // variadic function.
306 assert((NewArg == E->placement_arg_end() || NewFTy->isVariadic()) &&
307 "Extra arguments in non-variadic function!");
308
309 // If we still have any arguments, emit them using the type of the argument.
310 for (CXXNewExpr::const_arg_iterator NewArgEnd = E->placement_arg_end();
311 NewArg != NewArgEnd; ++NewArg) {
312 QualType ArgType = NewArg->getType();
313 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
314 ArgType));
315 }
316
317 // Emit the call to new.
318 RValue RV =
319 EmitCall(CGM.getTypes().getFunctionInfo(NewFTy->getResultType(), NewArgs),
320 CGM.GetAddrOfFunction(GlobalDecl(NewFD)),
321 NewArgs, NewFD);
322
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000323 // If an allocation function is declared with an empty exception specification
324 // it returns null to indicate failure to allocate storage. [expr.new]p13.
325 // (We don't need to check for null when there's no new initializer and
326 // we're allocating a POD type).
327 bool NullCheckResult = NewFTy->hasEmptyExceptionSpec() &&
328 !(AllocType->isPODType() && !E->hasInitializer());
Anders Carlssoned4e3672009-05-31 20:21:44 +0000329
Anders Carlssonf1108532009-06-01 00:05:16 +0000330 llvm::BasicBlock *NewNull = 0;
331 llvm::BasicBlock *NewNotNull = 0;
332 llvm::BasicBlock *NewEnd = 0;
333
334 llvm::Value *NewPtr = RV.getScalarVal();
335
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000336 if (NullCheckResult) {
Anders Carlssonf1108532009-06-01 00:05:16 +0000337 NewNull = createBasicBlock("new.null");
338 NewNotNull = createBasicBlock("new.notnull");
339 NewEnd = createBasicBlock("new.end");
340
341 llvm::Value *IsNull =
342 Builder.CreateICmpEQ(NewPtr,
Owen Andersonc9c88b42009-07-31 20:28:54 +0000343 llvm::Constant::getNullValue(NewPtr->getType()),
Anders Carlssonf1108532009-06-01 00:05:16 +0000344 "isnull");
345
346 Builder.CreateCondBr(IsNull, NewNull, NewNotNull);
347 EmitBlock(NewNotNull);
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000348 }
349
Anders Carlssonf1108532009-06-01 00:05:16 +0000350 NewPtr = Builder.CreateBitCast(NewPtr, ConvertType(E->getType()));
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000351
Anders Carlsson6d0ffad2009-05-31 20:56:36 +0000352 if (AllocType->isPODType()) {
Anders Carlsson215bd202009-06-01 00:26:14 +0000353 if (E->getNumConstructorArgs() > 0) {
Anders Carlsson6d0ffad2009-05-31 20:56:36 +0000354 assert(E->getNumConstructorArgs() == 1 &&
355 "Can only have one argument to initializer of POD type.");
356
357 const Expr *Init = E->getConstructorArg(0);
358
Anders Carlsson3923e952009-05-31 21:07:58 +0000359 if (!hasAggregateLLVMType(AllocType))
Anders Carlsson6d0ffad2009-05-31 20:56:36 +0000360 Builder.CreateStore(EmitScalarExpr(Init), NewPtr);
Anders Carlsson3923e952009-05-31 21:07:58 +0000361 else if (AllocType->isAnyComplexType())
362 EmitComplexExprIntoAddr(Init, NewPtr, AllocType.isVolatileQualified());
Anders Carlsson627a3e52009-05-31 21:12:26 +0000363 else
364 EmitAggExpr(Init, NewPtr, AllocType.isVolatileQualified());
Anders Carlsson6d0ffad2009-05-31 20:56:36 +0000365 }
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000366 } else {
367 // Call the constructor.
368 CXXConstructorDecl *Ctor = E->getConstructor();
Anders Carlsson6d0ffad2009-05-31 20:56:36 +0000369
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000370 EmitCXXConstructorCall(Ctor, Ctor_Complete, NewPtr,
371 E->constructor_arg_begin(),
372 E->constructor_arg_end());
Anders Carlssoned4e3672009-05-31 20:21:44 +0000373 }
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000374
Anders Carlssonf1108532009-06-01 00:05:16 +0000375 if (NullCheckResult) {
376 Builder.CreateBr(NewEnd);
377 EmitBlock(NewNull);
378 Builder.CreateBr(NewEnd);
379 EmitBlock(NewEnd);
380
381 llvm::PHINode *PHI = Builder.CreatePHI(NewPtr->getType());
382 PHI->reserveOperandSpace(2);
383 PHI->addIncoming(NewPtr, NewNotNull);
Owen Andersonc9c88b42009-07-31 20:28:54 +0000384 PHI->addIncoming(llvm::Constant::getNullValue(NewPtr->getType()), NewNull);
Anders Carlssonf1108532009-06-01 00:05:16 +0000385
386 NewPtr = PHI;
387 }
388
Anders Carlssond3fd6ba2009-05-31 21:53:59 +0000389 return NewPtr;
Anders Carlssona00703d2009-05-31 01:40:14 +0000390}
391
Anders Carlsson27ae5362009-04-17 01:58:57 +0000392static bool canGenerateCXXstructor(const CXXRecordDecl *RD,
393 ASTContext &Context) {
Anders Carlsson59d8e0f2009-04-15 21:02:13 +0000394 // The class has base classes - we don't support that right now.
395 if (RD->getNumBases() > 0)
396 return false;
397
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000398 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
399 I != E; ++I) {
Anders Carlsson59d8e0f2009-04-15 21:02:13 +0000400 // We don't support ctors for fields that aren't POD.
401 if (!I->getType()->isPODType())
402 return false;
403 }
404
405 return true;
406}
407
Anders Carlsson95d4e5d2009-04-15 15:55:24 +0000408void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) {
Anders Carlsson27ae5362009-04-17 01:58:57 +0000409 if (!canGenerateCXXstructor(D->getParent(), getContext())) {
Anders Carlsson59d8e0f2009-04-15 21:02:13 +0000410 ErrorUnsupported(D, "C++ constructor", true);
411 return;
412 }
Anders Carlsson95d4e5d2009-04-15 15:55:24 +0000413
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000414 EmitGlobal(GlobalDecl(D, Ctor_Complete));
415 EmitGlobal(GlobalDecl(D, Ctor_Base));
Anders Carlsson95d4e5d2009-04-15 15:55:24 +0000416}
Anders Carlsson363c1842009-04-16 23:57:24 +0000417
Anders Carlsson27ae5362009-04-17 01:58:57 +0000418void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D,
419 CXXCtorType Type) {
420
421 llvm::Function *Fn = GetAddrOfCXXConstructor(D, Type);
422
423 CodeGenFunction(*this).GenerateCode(D, Fn);
424
425 SetFunctionDefinitionAttributes(D, Fn);
426 SetLLVMFunctionAttributesForDefinition(D, Fn);
427}
428
Anders Carlsson363c1842009-04-16 23:57:24 +0000429llvm::Function *
430CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
431 CXXCtorType Type) {
432 const llvm::FunctionType *FTy =
433 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false);
434
435 const char *Name = getMangledCXXCtorName(D, Type);
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000436 return cast<llvm::Function>(
437 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson363c1842009-04-16 23:57:24 +0000438}
Anders Carlsson27ae5362009-04-17 01:58:57 +0000439
440const char *CodeGenModule::getMangledCXXCtorName(const CXXConstructorDecl *D,
441 CXXCtorType Type) {
442 llvm::SmallString<256> Name;
443 llvm::raw_svector_ostream Out(Name);
444 mangleCXXCtor(D, Type, Context, Out);
445
446 Name += '\0';
447 return UniqueMangledName(Name.begin(), Name.end());
448}
449
450void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) {
451 if (!canGenerateCXXstructor(D->getParent(), getContext())) {
452 ErrorUnsupported(D, "C++ destructor", true);
453 return;
454 }
455
456 EmitCXXDestructor(D, Dtor_Complete);
457 EmitCXXDestructor(D, Dtor_Base);
458}
459
460void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D,
461 CXXDtorType Type) {
462 llvm::Function *Fn = GetAddrOfCXXDestructor(D, Type);
463
464 CodeGenFunction(*this).GenerateCode(D, Fn);
465
466 SetFunctionDefinitionAttributes(D, Fn);
467 SetLLVMFunctionAttributesForDefinition(D, Fn);
468}
469
470llvm::Function *
471CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D,
472 CXXDtorType Type) {
473 const llvm::FunctionType *FTy =
474 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false);
475
476 const char *Name = getMangledCXXDtorName(D, Type);
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000477 return cast<llvm::Function>(
478 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson27ae5362009-04-17 01:58:57 +0000479}
480
481const char *CodeGenModule::getMangledCXXDtorName(const CXXDestructorDecl *D,
482 CXXDtorType Type) {
483 llvm::SmallString<256> Name;
484 llvm::raw_svector_ostream Out(Name);
485 mangleCXXDtor(D, Type, Context, Out);
486
487 Name += '\0';
488 return UniqueMangledName(Name.begin(), Name.end());
489}
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +0000490
Mike Stump738f8c22009-07-31 23:15:31 +0000491llvm::Constant *CodeGenFunction::GenerateRtti(const CXXRecordDecl *RD) {
492 llvm::Type *Ptr8Ty;
493 Ptr8Ty = llvm::PointerType::get(llvm::Type::Int8Ty, 0);
Mike Stumpcb1b5d32009-08-04 20:06:48 +0000494 llvm::Constant *Rtti = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stump738f8c22009-07-31 23:15:31 +0000495
496 if (!getContext().getLangOptions().Rtti)
Mike Stumpcb1b5d32009-08-04 20:06:48 +0000497 return Rtti;
Mike Stump738f8c22009-07-31 23:15:31 +0000498
499 llvm::SmallString<256> OutName;
500 llvm::raw_svector_ostream Out(OutName);
501 QualType ClassTy;
502 // FIXME: What is the design on getTagDeclType when it requires casting
503 // away const? mutable?
504 ClassTy = getContext().getTagDeclType(const_cast<CXXRecordDecl*>(RD));
505 mangleCXXRtti(ClassTy, getContext(), Out);
506 const char *Name = OutName.c_str();
507 llvm::GlobalVariable::LinkageTypes linktype;
508 linktype = llvm::GlobalValue::WeakAnyLinkage;
509 std::vector<llvm::Constant *> info;
510 assert (0 && "FIXME: implement rtti descriptor");
511 // FIXME: descriptor
512 info.push_back(llvm::Constant::getNullValue(Ptr8Ty));
513 assert (0 && "FIXME: implement rtti ts");
514 // FIXME: TS
515 info.push_back(llvm::Constant::getNullValue(Ptr8Ty));
516
517 llvm::Constant *C;
518 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, info.size());
519 C = llvm::ConstantArray::get(type, info);
Mike Stumpcb1b5d32009-08-04 20:06:48 +0000520 Rtti = new llvm::GlobalVariable(CGM.getModule(), type, true, linktype, C,
Mike Stump738f8c22009-07-31 23:15:31 +0000521 Name);
Mike Stumpcb1b5d32009-08-04 20:06:48 +0000522 Rtti = llvm::ConstantExpr::getBitCast(Rtti, Ptr8Ty);
523 return Rtti;
Mike Stump738f8c22009-07-31 23:15:31 +0000524}
525
Mike Stumpf1216772009-07-31 18:25:34 +0000526llvm::Value *CodeGenFunction::GenerateVtable(const CXXRecordDecl *RD) {
Mike Stumpf1216772009-07-31 18:25:34 +0000527 llvm::SmallString<256> OutName;
528 llvm::raw_svector_ostream Out(OutName);
529 QualType ClassTy;
530 // FIXME: What is the design on getTagDeclType when it requires casting
531 // away const? mutable?
532 ClassTy = getContext().getTagDeclType(const_cast<CXXRecordDecl*>(RD));
533 mangleCXXVtable(ClassTy, getContext(), Out);
534 const char *Name = OutName.c_str();
Mike Stump82b56962009-07-31 21:43:43 +0000535 llvm::GlobalVariable::LinkageTypes linktype;
536 linktype = llvm::GlobalValue::WeakAnyLinkage;
537 std::vector<llvm::Constant *> methods;
Mike Stumpf1216772009-07-31 18:25:34 +0000538 typedef CXXRecordDecl::method_iterator meth_iter;
Mike Stump82b56962009-07-31 21:43:43 +0000539 llvm::Constant *m;
Mike Stumpf1216772009-07-31 18:25:34 +0000540 llvm::Type *Ptr8Ty;
541 Ptr8Ty = llvm::PointerType::get(llvm::Type::Int8Ty, 0);
Mike Stump82b56962009-07-31 21:43:43 +0000542 m = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stump6f376332009-08-05 22:37:18 +0000543 int64_t Offset = 0;
544 methods.push_back(m); Offset += LLVMPointerWidth;
545 methods.push_back(GenerateRtti(RD)); Offset += LLVMPointerWidth;
546
547 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
548 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
Mike Stump104ffaa2009-08-04 21:58:42 +0000549
550 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
551 e = RD->bases_end(); i != e; ++i) {
552 if (i->isVirtual())
553 continue;
554 const CXXRecordDecl *Base =
555 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Mike Stump6f376332009-08-05 22:37:18 +0000556 if (PrimaryBase != Base) {
557 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
558 int64_t BaseOffset = -(Layout.getBaseClassOffset(Base) / 8);
559 m = llvm::ConstantInt::get(llvm::Type::Int64Ty, BaseOffset);
560 m = llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
561 methods.push_back(m);
562 // FIXME: GenerateRtti for Base in RD.
563 m = llvm::Constant::getNullValue(Ptr8Ty);
564 methods.push_back(m);
565 }
Mike Stump104ffaa2009-08-04 21:58:42 +0000566 for (meth_iter mi = Base->method_begin(), me = Base->method_end(); mi != me;
567 ++mi) {
568 if (mi->isVirtual()) {
569 m = CGM.GetAddrOfFunction(GlobalDecl(*mi));
570 m = llvm::ConstantExpr::getBitCast(m, Ptr8Ty);
571 methods.push_back(m);
572 }
573 }
Mike Stump6f376332009-08-05 22:37:18 +0000574 if (PrimaryBase == Base) {
575 for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
576 ++mi) {
577 if (mi->isVirtual()) {
578 m = CGM.GetAddrOfFunction(GlobalDecl(*mi));
579 m = llvm::ConstantExpr::getBitCast(m, Ptr8Ty);
580 methods.push_back(m);
581 }
582 }
583 }
584 }
585 if (PrimaryBase == 0) {
586 for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
587 ++mi) {
588 if (mi->isVirtual()) {
589 m = CGM.GetAddrOfFunction(GlobalDecl(*mi));
590 m = llvm::ConstantExpr::getBitCast(m, Ptr8Ty);
591 methods.push_back(m);
592 }
593 }
Mike Stump104ffaa2009-08-04 21:58:42 +0000594 }
595
Mike Stump82b56962009-07-31 21:43:43 +0000596 llvm::Constant *C;
597 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, methods.size());
598 C = llvm::ConstantArray::get(type, methods);
599 llvm::Value *vtable = new llvm::GlobalVariable(CGM.getModule(), type, true,
600 linktype, C, Name);
Mike Stumpf1216772009-07-31 18:25:34 +0000601 vtable = Builder.CreateBitCast(vtable, Ptr8Ty);
Mike Stump82b56962009-07-31 21:43:43 +0000602 // FIXME: finish layout for virtual bases
Mike Stumpf1216772009-07-31 18:25:34 +0000603 vtable = Builder.CreateGEP(vtable,
604 llvm::ConstantInt::get(llvm::Type::Int64Ty,
Mike Stump6f376332009-08-05 22:37:18 +0000605 Offset/8));
Mike Stumpf1216772009-07-31 18:25:34 +0000606 return vtable;
607}
608
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +0000609/// EmitCtorPrologue - This routine generates necessary code to initialize
610/// base classes and non-static data members belonging to this constructor.
611void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD) {
Fariborz Jahanian742cd1b2009-07-25 21:12:28 +0000612 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
Mike Stump7116da12009-07-30 21:47:44 +0000613 assert(ClassDecl->getNumVBases() == 0
614 && "FIXME: virtual base initialization unsupported");
Mike Stumpf1216772009-07-31 18:25:34 +0000615 llvm::Value *LoadOfThis = 0;
616
Fariborz Jahanian6d0bdaa2009-07-28 18:09:28 +0000617
Fariborz Jahanian742cd1b2009-07-25 21:12:28 +0000618 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +0000619 E = CD->init_end();
620 B != E; ++B) {
621 CXXBaseOrMemberInitializer *Member = (*B);
622 if (Member->isBaseInitializer()) {
Mike Stumpf1216772009-07-31 18:25:34 +0000623 LoadOfThis = LoadCXXThis();
Fariborz Jahanian6d0bdaa2009-07-28 18:09:28 +0000624 Type *BaseType = Member->getBaseClass();
625 CXXRecordDecl *BaseClassDecl =
Ted Kremenek6217b802009-07-29 21:53:49 +0000626 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
Fariborz Jahanian6d0bdaa2009-07-28 18:09:28 +0000627 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
628 BaseClassDecl);
Fariborz Jahanian742cd1b2009-07-25 21:12:28 +0000629 EmitCXXConstructorCall(Member->getConstructor(),
630 Ctor_Complete, V,
631 Member->const_arg_begin(),
632 Member->const_arg_end());
Mike Stumpb3589f42009-07-30 22:28:39 +0000633 } else {
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +0000634 // non-static data member initilaizers.
635 FieldDecl *Field = Member->getMember();
636 QualType FieldType = getContext().getCanonicalType((Field)->getType());
637 assert(!getContext().getAsArrayType(FieldType)
638 && "FIXME. Field arrays initialization unsupported");
Fariborz Jahanian50b8eea2009-07-24 17:57:02 +0000639
Mike Stumpf1216772009-07-31 18:25:34 +0000640 LoadOfThis = LoadCXXThis();
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +0000641 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
Ted Kremenek6217b802009-07-29 21:53:49 +0000642 if (FieldType->getAs<RecordType>()) {
Fariborz Jahanian50b8eea2009-07-24 17:57:02 +0000643
644 assert(Member->getConstructor() &&
645 "EmitCtorPrologue - no constructor to initialize member");
646 EmitCXXConstructorCall(Member->getConstructor(),
647 Ctor_Complete, LHS.getAddress(),
648 Member->const_arg_begin(),
649 Member->const_arg_end());
650 continue;
651 }
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +0000652
653 assert(Member->getNumArgs() == 1 && "Initializer count must be 1 only");
Fariborz Jahanian50b8eea2009-07-24 17:57:02 +0000654 Expr *RhsExpr = *Member->arg_begin();
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +0000655 llvm::Value *RHS = EmitScalarExpr(RhsExpr, true);
656 if (LHS.isBitfield())
657 EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, FieldType, 0);
658 else
659 EmitStoreThroughLValue(RValue::get(RHS), LHS, FieldType);
660 }
661 }
Mike Stumpf1216772009-07-31 18:25:34 +0000662
663 // Initialize the vtable pointer
664 if (ClassDecl->isPolymorphic() || ClassDecl->getNumVBases()) {
665 if (!LoadOfThis)
666 LoadOfThis = LoadCXXThis();
667 llvm::Value *VtableField;
668 llvm::Type *Ptr8Ty, *PtrPtr8Ty;
669 Ptr8Ty = llvm::PointerType::get(llvm::Type::Int8Ty, 0);
670 PtrPtr8Ty = llvm::PointerType::get(Ptr8Ty, 0);
671 VtableField = Builder.CreateBitCast(LoadOfThis, PtrPtr8Ty);
672 llvm::Value *vtable = GenerateVtable(ClassDecl);
673 Builder.CreateStore(vtable, VtableField);
674 }
Fariborz Jahaniane7d346b2009-07-20 23:18:55 +0000675}
Fariborz Jahanian426cc382009-07-30 17:49:11 +0000676
677/// EmitDtorEpilogue - Emit all code that comes at the end of class's
678/// destructor. This is to call destructors on members and base classes
679/// in reverse order of their construction.
680void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD) {
681 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(DD->getDeclContext());
682 assert(!ClassDecl->isPolymorphic() &&
683 "FIXME. polymorphic destruction not supported");
684 (void)ClassDecl; // prevent warning.
685
686 for (CXXDestructorDecl::destr_const_iterator *B = DD->destr_begin(),
687 *E = DD->destr_end(); B != E; ++B) {
688 uintptr_t BaseOrMember = (*B);
689 if (DD->isMemberToDestroy(BaseOrMember)) {
690 FieldDecl *FD = DD->getMemberToDestroy(BaseOrMember);
691 QualType FieldType = getContext().getCanonicalType((FD)->getType());
692 assert(!getContext().getAsArrayType(FieldType)
693 && "FIXME. Field arrays destruction unsupported");
694 const RecordType *RT = FieldType->getAs<RecordType>();
695 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
696 if (FieldClassDecl->hasTrivialDestructor())
697 continue;
698 llvm::Value *LoadOfThis = LoadCXXThis();
699 LValue LHS = EmitLValueForField(LoadOfThis, FD, false, 0);
700 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
701 Dtor_Complete, LHS.getAddress());
Mike Stumpb3589f42009-07-30 22:28:39 +0000702 } else {
Fariborz Jahanian426cc382009-07-30 17:49:11 +0000703 const RecordType *RT =
704 DD->getAnyBaseClassToDestroy(BaseOrMember)->getAs<RecordType>();
705 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
706 if (BaseClassDecl->hasTrivialDestructor())
707 continue;
708 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
709 ClassDecl,BaseClassDecl);
710 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
711 Dtor_Complete, V);
712 }
713 }
714}