blob: e311912d95fd9f1a06beb21f0edda63b300f6639 [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
Mike Stump25cf7602009-09-09 15:08:12 +000014// We might split this into multiple files if it gets too unwieldy
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +000015
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
Mike Stump25cf7602009-09-09 15:08:12 +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.
Mike Stump25cf7602009-09-09 15:08:12 +000032
33 const llvm::Type *Int8PtrTy =
Owen Anderson3f5cc0a2009-08-13 21:57:51 +000034 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Mike Stump25cf7602009-09-09 15:08:12 +000035
Anders Carlssonf2a022a2009-08-08 21:45:14 +000036 std::vector<const llvm::Type *> Params;
37 Params.push_back(Int8PtrTy);
Mike Stump25cf7602009-09-09 15:08:12 +000038
Anders Carlssonf2a022a2009-08-08 21:45:14 +000039 // Get the destructor function type
Mike Stump25cf7602009-09-09 15:08:12 +000040 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);
Mike Stump25cf7602009-09-09 15:08:12 +000043
Anders Carlssonf2a022a2009-08-08 21:45:14 +000044 Params.clear();
45 Params.push_back(DtorFnTy);
46 Params.push_back(Int8PtrTy);
47 Params.push_back(Int8PtrTy);
Mike Stump25cf7602009-09-09 15:08:12 +000048
Anders Carlssonf2a022a2009-08-08 21:45:14 +000049 // Get the __cxa_atexit function type
50 // extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
Mike Stump25cf7602009-09-09 15:08:12 +000051 const llvm::FunctionType *AtExitFnTy =
Anders Carlssonf2a022a2009-08-08 21:45:14 +000052 llvm::FunctionType::get(ConvertType(getContext().IntTy), Params, false);
Mike Stump25cf7602009-09-09 15:08:12 +000053
Anders Carlssonf2a022a2009-08-08 21:45:14 +000054 llvm::Constant *AtExitFn = CGM.CreateRuntimeFunction(AtExitFnTy,
55 "__cxa_atexit");
Mike Stump25cf7602009-09-09 15:08:12 +000056
Anders Carlssonf2a022a2009-08-08 21:45:14 +000057 llvm::Constant *Handle = CGM.CreateRuntimeVariable(Int8PtrTy,
58 "__dso_handle");
Mike Stump25cf7602009-09-09 15:08:12 +000059
Anders Carlssonf2a022a2009-08-08 21:45:14 +000060 llvm::Constant *DtorFn = CGM.GetAddrOfCXXDestructor(Dtor, Dtor_Complete);
Mike Stump25cf7602009-09-09 15:08:12 +000061
Anders Carlssonf2a022a2009-08-08 21:45:14 +000062 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
Mike Stump25cf7602009-09-09 15:08:12 +000068void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
Anders Carlssonf2a022a2009-08-08 21:45:14 +000069 llvm::Constant *DeclPtr) {
70 assert(D.hasGlobalStorage() &&
71 "VarDecl must have global storage!");
Mike Stump25cf7602009-09-09 15:08:12 +000072
Anders Carlssonf2a022a2009-08-08 21:45:14 +000073 const Expr *Init = D.getInit();
74 QualType T = D.getType();
Mike Stump25cf7602009-09-09 15:08:12 +000075
Anders Carlssonf2a022a2009-08-08 21:45:14 +000076 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());
Mike Stump25cf7602009-09-09 15:08:12 +000085
Anders Carlssonf2a022a2009-08-08 21:45:14 +000086 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;
Mike Stump25cf7602009-09-09 15:08:12 +000098
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);
Mike Stump25cf7602009-09-09 15:08:12 +0000101
Anders Carlssoncde4a862009-08-08 23:24:23 +0000102 // Create our global initialization function.
103 // FIXME: Should this be tweakable by targets?
Mike Stump25cf7602009-09-09 15:08:12 +0000104 llvm::Function *Fn =
Anders Carlssoncde4a862009-08-08 23:24:23 +0000105 llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
106 "__cxx_global_initialization", &TheModule);
Mike Stump25cf7602009-09-09 15:08:12 +0000107
Anders Carlssoncde4a862009-08-08 23:24:23 +0000108 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) {
Mike Stump25cf7602009-09-09 15:08:12 +0000117 StartFunction(0, getContext().VoidTy, Fn, FunctionArgList(),
Anders Carlssoncde4a862009-08-08 23:24:23 +0000118 SourceLocation());
Mike Stump25cf7602009-09-09 15:08:12 +0000119
Anders Carlssoncde4a862009-08-08 23:24:23 +0000120 for (unsigned i = 0; i != NumDecls; ++i) {
121 const VarDecl *D = Decls[i];
Mike Stump25cf7602009-09-09 15:08:12 +0000122
Anders Carlssoncde4a862009-08-08 23:24:23 +0000123 llvm::Constant *DeclPtr = CGM.GetAddrOfGlobalVar(D);
124 EmitCXXGlobalVarDeclInit(*D, DeclPtr);
125 }
126 FinishFunction();
127}
128
Mike Stump25cf7602009-09-09 15:08:12 +0000129void
130CodeGenFunction::EmitStaticCXXBlockVarDeclInit(const VarDecl &D,
Anders Carlssonf2a022a2009-08-08 21:45:14 +0000131 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);
Mike Stump25cf7602009-09-09 15:08:12 +0000140
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000141 // Create the guard variable.
Mike Stump25cf7602009-09-09 15:08:12 +0000142 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());
Mike Stump25cf7602009-09-09 15:08:12 +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);
Mike Stump25cf7602009-09-09 15:08:12 +0000150 llvm::Value *V = Builder.CreateLoad(Builder.CreateBitCast(GuardV, PtrTy),
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000151 "tmp");
Mike Stump25cf7602009-09-09 15:08:12 +0000152
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000153 // 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");
Mike Stump25cf7602009-09-09 15:08:12 +0000156
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);
Mike Stump25cf7602009-09-09 15:08:12 +0000162
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000163 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));
Mike Stump25cf7602009-09-09 15:08:12 +0000169
Anders Carlssonc9f8ccd2008-08-22 16:00:37 +0000170 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) {
Mike Stump25cf7602009-09-09 15:08:12 +0000178 assert(MD->isInstance() &&
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000179 "Trying to emit a member call expr on a static method!");
180
Douglas Gregor6ccc6f32009-09-04 19:04:08 +0000181 // A call to a trivial destructor requires no code generation.
182 if (const CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(MD))
183 if (Destructor->isTrivial())
184 return RValue::get(0);
Mike Stump25cf7602009-09-09 15:08:12 +0000185
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000186 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
Mike Stump25cf7602009-09-09 15:08:12 +0000187
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000188 CallArgList Args;
Mike Stump25cf7602009-09-09 15:08:12 +0000189
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000190 // Push the this ptr.
191 Args.push_back(std::make_pair(RValue::get(This),
192 MD->getThisType(getContext())));
Mike Stump25cf7602009-09-09 15:08:12 +0000193
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000194 // And the rest of the call args
195 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
Mike Stump25cf7602009-09-09 15:08:12 +0000196
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000197 QualType ResultType = MD->getType()->getAsFunctionType()->getResultType();
198 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args),
199 Callee, Args, MD);
200}
201
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000202RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE) {
203 const MemberExpr *ME = cast<MemberExpr>(CE->getCallee());
204 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000205
Anders Carlssonc5223142009-04-08 20:31:57 +0000206 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
Mike Stumpc37c8812009-07-30 21:47:44 +0000207
Mike Stump25cf7602009-09-09 15:08:12 +0000208 const llvm::Type *Ty =
209 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
Anders Carlssonc5223142009-04-08 20:31:57 +0000210 FPT->isVariadic());
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000211 llvm::Value *This;
Mike Stump25cf7602009-09-09 15:08:12 +0000212
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000213 if (ME->isArrow())
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000214 This = EmitScalarExpr(ME->getBase());
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000215 else {
216 LValue BaseLV = EmitLValue(ME->getBase());
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000217 This = BaseLV.getAddress();
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000218 }
Mike Stumpf7d47a52009-08-26 20:46:33 +0000219
Douglas Gregore399ad42009-08-26 22:36:53 +0000220 // C++ [class.virtual]p12:
Mike Stump25cf7602009-09-09 15:08:12 +0000221 // Explicit qualification with the scope operator (5.1) suppresses the
Douglas Gregore399ad42009-08-26 22:36:53 +0000222 // virtual call mechanism.
Mike Stumpf7d47a52009-08-26 20:46:33 +0000223 llvm::Value *Callee;
Douglas Gregorefccbec2009-08-31 21:41:48 +0000224 if (MD->isVirtual() && !ME->hasQualifier())
Mike Stumpf7d47a52009-08-26 20:46:33 +0000225 Callee = BuildVirtualCall(MD, This, Ty);
Mike Stump25cf7602009-09-09 15:08:12 +0000226 else if (const CXXDestructorDecl *Destructor
Douglas Gregor6ccc6f32009-09-04 19:04:08 +0000227 = dyn_cast<CXXDestructorDecl>(MD))
228 Callee = CGM.GetAddrOfFunction(GlobalDecl(Destructor, Dtor_Complete), Ty);
Douglas Gregorefccbec2009-08-31 21:41:48 +0000229 else
Mike Stumpf7d47a52009-08-26 20:46:33 +0000230 Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty);
Mike Stump25cf7602009-09-09 15:08:12 +0000231
232 return EmitCXXMemberCall(MD, Callee, This,
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000233 CE->arg_begin(), CE->arg_end());
Anders Carlsson7a9b2982009-04-03 22:50:24 +0000234}
Anders Carlsson49d4a572009-04-14 16:58:56 +0000235
Mike Stump25cf7602009-09-09 15:08:12 +0000236RValue
Anders Carlsson85eca6f2009-05-27 04:18:27 +0000237CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
238 const CXXMethodDecl *MD) {
Mike Stump25cf7602009-09-09 15:08:12 +0000239 assert(MD->isInstance() &&
Anders Carlsson85eca6f2009-05-27 04:18:27 +0000240 "Trying to emit a member call expr on a static method!");
Mike Stump25cf7602009-09-09 15:08:12 +0000241
Fariborz Jahanian9da58e42009-08-13 21:09:41 +0000242 if (MD->isCopyAssignment()) {
243 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(MD->getDeclContext());
244 if (ClassDecl->hasTrivialCopyAssignment()) {
245 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
246 "EmitCXXOperatorMemberCallExpr - user declared copy assignment");
247 llvm::Value *This = EmitLValue(E->getArg(0)).getAddress();
248 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
249 QualType Ty = E->getType();
250 EmitAggregateCopy(This, Src, Ty);
251 return RValue::get(This);
252 }
253 }
Mike Stump25cf7602009-09-09 15:08:12 +0000254
Anders Carlsson85eca6f2009-05-27 04:18:27 +0000255 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
Mike Stump25cf7602009-09-09 15:08:12 +0000256 const llvm::Type *Ty =
257 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
Mike Stumpd5b15562009-09-04 18:27:16 +0000258 FPT->isVariadic());
Anders Carlsson85eca6f2009-05-27 04:18:27 +0000259 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty);
Mike Stump25cf7602009-09-09 15:08:12 +0000260
Anders Carlsson85eca6f2009-05-27 04:18:27 +0000261 llvm::Value *This = EmitLValue(E->getArg(0)).getAddress();
Mike Stump25cf7602009-09-09 15:08:12 +0000262
Anders Carlsson85eca6f2009-05-27 04:18:27 +0000263 return EmitCXXMemberCall(MD, Callee, This,
264 E->arg_begin() + 1, E->arg_end());
265}
266
Fariborz Jahanianc8a336f2009-08-26 23:31:30 +0000267RValue
268CodeGenFunction::EmitCXXFunctionalCastExpr(const CXXFunctionalCastExpr *E) {
269 assert((E->getCastKind() == CastExpr::CK_UserDefinedConversion) &&
270 "EmitCXXFunctionalCastExpr - called with wrong cast");
Mike Stump25cf7602009-09-09 15:08:12 +0000271
Fariborz Jahanianc8a336f2009-08-26 23:31:30 +0000272 CXXMethodDecl *MD = E->getTypeConversionMethod();
Fariborz Jahanian795a3fd2009-08-28 15:11:24 +0000273 assert(MD && "EmitCXXFunctionalCastExpr - null conversion method");
274 assert(isa<CXXConversionDecl>(MD) && "EmitCXXFunctionalCastExpr - not"
275 " method decl");
Fariborz Jahanianc8a336f2009-08-26 23:31:30 +0000276 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
Mike Stump25cf7602009-09-09 15:08:12 +0000277
278 const llvm::Type *Ty =
279 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
Fariborz Jahanian795a3fd2009-08-28 15:11:24 +0000280 FPT->isVariadic());
281 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), Ty);
282 llvm::Value *This = EmitLValue(E->getSubExpr()).getAddress();
283 RValue RV = EmitCXXMemberCall(MD, Callee, This, 0, 0);
284 if (RV.isAggregate())
Mike Stump25cf7602009-09-09 15:08:12 +0000285 RV = RValue::get(RV.getAggregateAddr());
Fariborz Jahanian795a3fd2009-08-28 15:11:24 +0000286 return RV;
Fariborz Jahanianc8a336f2009-08-26 23:31:30 +0000287}
288
Anders Carlsson49d4a572009-04-14 16:58:56 +0000289llvm::Value *CodeGenFunction::LoadCXXThis() {
Mike Stump25cf7602009-09-09 15:08:12 +0000290 assert(isa<CXXMethodDecl>(CurFuncDecl) &&
Anders Carlsson49d4a572009-04-14 16:58:56 +0000291 "Must be in a C++ member function decl to load 'this'");
292 assert(cast<CXXMethodDecl>(CurFuncDecl)->isInstance() &&
293 "Must be in a C++ member function decl to load 'this'");
Mike Stump25cf7602009-09-09 15:08:12 +0000294
Anders Carlsson49d4a572009-04-14 16:58:56 +0000295 // FIXME: What if we're inside a block?
Mike Stumpba2cb0e2009-05-16 07:57:57 +0000296 // ans: See how CodeGenFunction::LoadObjCSelf() uses
297 // CodeGenFunction::BlockForwardSelf() for how to do this.
Anders Carlsson49d4a572009-04-14 16:58:56 +0000298 return Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
299}
Anders Carlsson652951a2009-04-15 15:55:24 +0000300
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000301static bool
302GetNestedPaths(llvm::SmallVectorImpl<const CXXRecordDecl *> &NestedBasePaths,
303 const CXXRecordDecl *ClassDecl,
304 const CXXRecordDecl *BaseClassDecl) {
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000305 for (CXXRecordDecl::base_class_const_iterator i = ClassDecl->bases_begin(),
306 e = ClassDecl->bases_end(); i != e; ++i) {
307 if (i->isVirtual())
308 continue;
Mike Stump25cf7602009-09-09 15:08:12 +0000309 const CXXRecordDecl *Base =
Mike Stumpf3371782009-08-04 21:58:42 +0000310 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000311 if (Base == BaseClassDecl) {
312 NestedBasePaths.push_back(BaseClassDecl);
313 return true;
314 }
315 }
316 // BaseClassDecl not an immediate base of ClassDecl.
317 for (CXXRecordDecl::base_class_const_iterator i = ClassDecl->bases_begin(),
318 e = ClassDecl->bases_end(); i != e; ++i) {
319 if (i->isVirtual())
320 continue;
Mike Stump25cf7602009-09-09 15:08:12 +0000321 const CXXRecordDecl *Base =
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000322 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
323 if (GetNestedPaths(NestedBasePaths, Base, BaseClassDecl)) {
324 NestedBasePaths.push_back(Base);
325 return true;
326 }
327 }
328 return false;
329}
330
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000331llvm::Value *CodeGenFunction::AddressCXXOfBaseClass(llvm::Value *BaseValue,
Mike Stump25cf7602009-09-09 15:08:12 +0000332 const CXXRecordDecl *ClassDecl,
Fariborz Jahanian70277012009-07-28 18:09:28 +0000333 const CXXRecordDecl *BaseClassDecl) {
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000334 if (ClassDecl == BaseClassDecl)
335 return BaseValue;
Mike Stump25cf7602009-09-09 15:08:12 +0000336
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000337 llvm::Type *I8Ptr = llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000338 llvm::SmallVector<const CXXRecordDecl *, 16> NestedBasePaths;
339 GetNestedPaths(NestedBasePaths, ClassDecl, BaseClassDecl);
Mike Stump25cf7602009-09-09 15:08:12 +0000340 assert(NestedBasePaths.size() > 0 &&
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000341 "AddressCXXOfBaseClass - inheritence path failed");
342 NestedBasePaths.push_back(ClassDecl);
343 uint64_t Offset = 0;
Mike Stump25cf7602009-09-09 15:08:12 +0000344
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000345 // Accessing a member of the base class. Must add delata to
346 // the load of 'this'.
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000347 for (unsigned i = NestedBasePaths.size()-1; i > 0; i--) {
348 const CXXRecordDecl *DerivedClass = NestedBasePaths[i];
349 const CXXRecordDecl *BaseClass = NestedBasePaths[i-1];
Mike Stump25cf7602009-09-09 15:08:12 +0000350 const ASTRecordLayout &Layout =
Fariborz Jahanian5fe7f472009-07-30 00:10:25 +0000351 getContext().getASTRecordLayout(DerivedClass);
352 Offset += Layout.getBaseClassOffset(BaseClass) / 8;
353 }
Mike Stump25cf7602009-09-09 15:08:12 +0000354 llvm::Value *OffsetVal =
Fariborz Jahanian83a46ed2009-07-29 15:54:56 +0000355 llvm::ConstantInt::get(
356 CGM.getTypes().ConvertType(CGM.getContext().LongTy), Offset);
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000357 BaseValue = Builder.CreateBitCast(BaseValue, I8Ptr);
358 BaseValue = Builder.CreateGEP(BaseValue, OffsetVal, "add.ptr");
Mike Stump25cf7602009-09-09 15:08:12 +0000359 QualType BTy =
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000360 getContext().getCanonicalType(
Fariborz Jahanian70277012009-07-28 18:09:28 +0000361 getContext().getTypeDeclType(const_cast<CXXRecordDecl*>(BaseClassDecl)));
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000362 const llvm::Type *BasePtr = ConvertType(BTy);
Owen Anderson7ec2d8f2009-07-29 22:16:19 +0000363 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Fariborz Jahaniand3f67282009-07-28 17:38:28 +0000364 BaseValue = Builder.CreateBitCast(BaseValue, BasePtr);
365 return BaseValue;
366}
367
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000368/// EmitCXXAggrConstructorCall - This routine essentially creates a (nested)
369/// for-loop to call the default constructor on individual members of the
370/// array. 'Array' is the array type, 'This' is llvm pointer of the start
371/// of the array and 'D' is the default costructor Decl for elements of the
372/// array. It is assumed that all relevant checks have been made by the
373/// caller.
374void
375CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
376 const ArrayType *Array,
377 llvm::Value *This) {
378 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
379 assert(CA && "Do we support VLA for construction ?");
Mike Stump25cf7602009-09-09 15:08:12 +0000380
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000381 // Create a temporary for the loop index and initialize it with 0.
Fariborz Jahaniandae3e752009-08-21 16:31:06 +0000382 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000383 "loop.index");
Mike Stump25cf7602009-09-09 15:08:12 +0000384 llvm::Value* zeroConstant =
Fariborz Jahaniandae3e752009-08-21 16:31:06 +0000385 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000386 Builder.CreateStore(zeroConstant, IndexPtr, false);
Mike Stump25cf7602009-09-09 15:08:12 +0000387
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000388 // Start the loop with a block that tests the condition.
389 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
390 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Mike Stump25cf7602009-09-09 15:08:12 +0000391
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000392 EmitBlock(CondBlock);
Mike Stump25cf7602009-09-09 15:08:12 +0000393
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000394 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
Mike Stump25cf7602009-09-09 15:08:12 +0000395
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000396 // Generate: if (loop-index < number-of-elements fall to the loop body,
397 // otherwise, go to the block after the for-loop.
Fariborz Jahanian58a7eca2009-08-26 00:23:27 +0000398 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
Mike Stump25cf7602009-09-09 15:08:12 +0000399 llvm::Value * NumElementsPtr =
Fariborz Jahanian58a7eca2009-08-26 00:23:27 +0000400 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000401 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
Mike Stump25cf7602009-09-09 15:08:12 +0000402 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000403 "isless");
404 // If the condition is true, execute the body.
405 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
Mike Stump25cf7602009-09-09 15:08:12 +0000406
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000407 EmitBlock(ForBody);
Mike Stump25cf7602009-09-09 15:08:12 +0000408
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000409 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000410 // Inside the loop body, emit the constructor call on the array element.
Fariborz Jahaniana0ab7352009-08-20 01:01:06 +0000411 Counter = Builder.CreateLoad(IndexPtr);
Fariborz Jahanian58a7eca2009-08-26 00:23:27 +0000412 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
413 EmitCXXConstructorCall(D, Ctor_Complete, Address, 0, 0);
Mike Stump25cf7602009-09-09 15:08:12 +0000414
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000415 EmitBlock(ContinueBlock);
Mike Stump25cf7602009-09-09 15:08:12 +0000416
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000417 // Emit the increment of the loop counter.
418 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
419 Counter = Builder.CreateLoad(IndexPtr);
420 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
421 Builder.CreateStore(NextVal, IndexPtr, false);
Mike Stump25cf7602009-09-09 15:08:12 +0000422
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000423 // Finally, branch back up to the condition for the next iteration.
424 EmitBranch(CondBlock);
Mike Stump25cf7602009-09-09 15:08:12 +0000425
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000426 // Emit the fall-through block.
427 EmitBlock(AfterFor, true);
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +0000428}
429
Fariborz Jahanian25879ce2009-08-20 23:02:58 +0000430/// EmitCXXAggrDestructorCall - calls the default destructor on array
431/// elements in reverse order of construction.
Anders Carlsson72f48292009-04-17 00:06:03 +0000432void
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +0000433CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
434 const ArrayType *Array,
435 llvm::Value *This) {
Fariborz Jahanian25879ce2009-08-20 23:02:58 +0000436 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
437 assert(CA && "Do we support VLA for destruction ?");
Mike Stump25cf7602009-09-09 15:08:12 +0000438 llvm::Value *One = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
Fariborz Jahanian25879ce2009-08-20 23:02:58 +0000439 1);
Fariborz Jahaniandae3e752009-08-21 16:31:06 +0000440 uint64_t ElementCount = getContext().getConstantArrayElementCount(CA);
Fariborz Jahanian25879ce2009-08-20 23:02:58 +0000441 // Create a temporary for the loop index and initialize it with count of
442 // array elements.
443 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
444 "loop.index");
445 // Index = ElementCount;
Mike Stump25cf7602009-09-09 15:08:12 +0000446 llvm::Value* UpperCount =
Fariborz Jahanian25879ce2009-08-20 23:02:58 +0000447 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), ElementCount);
448 Builder.CreateStore(UpperCount, IndexPtr, false);
Mike Stump25cf7602009-09-09 15:08:12 +0000449
Fariborz Jahanian25879ce2009-08-20 23:02:58 +0000450 // Start the loop with a block that tests the condition.
451 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
452 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Mike Stump25cf7602009-09-09 15:08:12 +0000453
Fariborz Jahanian25879ce2009-08-20 23:02:58 +0000454 EmitBlock(CondBlock);
Mike Stump25cf7602009-09-09 15:08:12 +0000455
Fariborz Jahanian25879ce2009-08-20 23:02:58 +0000456 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
Mike Stump25cf7602009-09-09 15:08:12 +0000457
Fariborz Jahanian25879ce2009-08-20 23:02:58 +0000458 // Generate: if (loop-index != 0 fall to the loop body,
459 // otherwise, go to the block after the for-loop.
Mike Stump25cf7602009-09-09 15:08:12 +0000460 llvm::Value* zeroConstant =
Fariborz Jahanian25879ce2009-08-20 23:02:58 +0000461 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
462 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
463 llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant,
464 "isne");
465 // If the condition is true, execute the body.
466 Builder.CreateCondBr(IsNE, ForBody, AfterFor);
Mike Stump25cf7602009-09-09 15:08:12 +0000467
Fariborz Jahanian25879ce2009-08-20 23:02:58 +0000468 EmitBlock(ForBody);
Mike Stump25cf7602009-09-09 15:08:12 +0000469
Fariborz Jahanian25879ce2009-08-20 23:02:58 +0000470 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
471 // Inside the loop body, emit the constructor call on the array element.
472 Counter = Builder.CreateLoad(IndexPtr);
473 Counter = Builder.CreateSub(Counter, One);
474 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
475 EmitCXXDestructorCall(D, Dtor_Complete, Address);
Mike Stump25cf7602009-09-09 15:08:12 +0000476
Fariborz Jahanian25879ce2009-08-20 23:02:58 +0000477 EmitBlock(ContinueBlock);
Mike Stump25cf7602009-09-09 15:08:12 +0000478
Fariborz Jahanian25879ce2009-08-20 23:02:58 +0000479 // Emit the decrement of the loop counter.
480 Counter = Builder.CreateLoad(IndexPtr);
481 Counter = Builder.CreateSub(Counter, One, "dec");
482 Builder.CreateStore(Counter, IndexPtr, false);
Mike Stump25cf7602009-09-09 15:08:12 +0000483
Fariborz Jahanian25879ce2009-08-20 23:02:58 +0000484 // Finally, branch back up to the condition for the next iteration.
485 EmitBranch(CondBlock);
Mike Stump25cf7602009-09-09 15:08:12 +0000486
Fariborz Jahanian25879ce2009-08-20 23:02:58 +0000487 // Emit the fall-through block.
488 EmitBlock(AfterFor, true);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +0000489}
490
491void
Mike Stump25cf7602009-09-09 15:08:12 +0000492CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
493 CXXCtorType Type,
Anders Carlsson72f48292009-04-17 00:06:03 +0000494 llvm::Value *This,
495 CallExpr::const_arg_iterator ArgBeg,
496 CallExpr::const_arg_iterator ArgEnd) {
Fariborz Jahanian0fc5f252009-08-14 20:11:43 +0000497 if (D->isCopyConstructor(getContext())) {
498 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D->getDeclContext());
499 if (ClassDecl->hasTrivialCopyConstructor()) {
500 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
501 "EmitCXXConstructorCall - user declared copy constructor");
502 const Expr *E = (*ArgBeg);
503 QualType Ty = E->getType();
504 llvm::Value *Src = EmitLValue(E).getAddress();
505 EmitAggregateCopy(This, Src, Ty);
506 return;
507 }
508 }
Mike Stump25cf7602009-09-09 15:08:12 +0000509
Anders Carlssonf91d9f22009-05-11 23:37:08 +0000510 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
511
512 EmitCXXMemberCall(D, Callee, This, ArgBeg, ArgEnd);
Anders Carlsson72f48292009-04-17 00:06:03 +0000513}
514
Mike Stump25cf7602009-09-09 15:08:12 +0000515void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *D,
Anders Carlssond3f6b162009-05-29 21:03:38 +0000516 CXXDtorType Type,
517 llvm::Value *This) {
518 llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(D, Type);
Mike Stump25cf7602009-09-09 15:08:12 +0000519
Anders Carlssond3f6b162009-05-29 21:03:38 +0000520 EmitCXXMemberCall(D, Callee, This, 0, 0);
521}
522
Mike Stump25cf7602009-09-09 15:08:12 +0000523void
524CodeGenFunction::EmitCXXConstructExpr(llvm::Value *Dest,
Anders Carlsson342aadc2009-05-03 17:47:16 +0000525 const CXXConstructExpr *E) {
Anders Carlsson72f48292009-04-17 00:06:03 +0000526 assert(Dest && "Must have a destination!");
Mike Stump25cf7602009-09-09 15:08:12 +0000527
528 const CXXRecordDecl *RD =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000529 cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson72f48292009-04-17 00:06:03 +0000530 if (RD->hasTrivialConstructor())
531 return;
Fariborz Jahanian884036a2009-08-06 01:02:49 +0000532
Mike Stump25cf7602009-09-09 15:08:12 +0000533 // Code gen optimization to eliminate copy constructor and return
Fariborz Jahanian884036a2009-08-06 01:02:49 +0000534 // its first argument instead.
Anders Carlsson9a0c2a52009-08-22 22:30:33 +0000535 if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
Fariborz Jahanian884036a2009-08-06 01:02:49 +0000536 CXXConstructExpr::const_arg_iterator i = E->arg_begin();
Fariborz Jahanian325cdd82009-08-06 19:12:38 +0000537 EmitAggExpr((*i), Dest, false);
538 return;
Fariborz Jahanian884036a2009-08-06 01:02:49 +0000539 }
Anders Carlsson72f48292009-04-17 00:06:03 +0000540 // Call the constructor.
Mike Stump25cf7602009-09-09 15:08:12 +0000541 EmitCXXConstructorCall(E->getConstructor(), Ctor_Complete, Dest,
Anders Carlsson72f48292009-04-17 00:06:03 +0000542 E->arg_begin(), E->arg_end());
543}
544
Anders Carlsson18e88bc2009-05-31 01:40:14 +0000545llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
Anders Carlssond5536972009-05-31 20:21:44 +0000546 if (E->isArray()) {
547 ErrorUnsupported(E, "new[] expression");
Owen Andersone0b5eff2009-07-30 23:11:26 +0000548 return llvm::UndefValue::get(ConvertType(E->getType()));
Anders Carlssond5536972009-05-31 20:21:44 +0000549 }
Mike Stump25cf7602009-09-09 15:08:12 +0000550
Anders Carlssond5536972009-05-31 20:21:44 +0000551 QualType AllocType = E->getAllocatedType();
552 FunctionDecl *NewFD = E->getOperatorNew();
553 const FunctionProtoType *NewFTy = NewFD->getType()->getAsFunctionProtoType();
Mike Stump25cf7602009-09-09 15:08:12 +0000554
Anders Carlssond5536972009-05-31 20:21:44 +0000555 CallArgList NewArgs;
556
557 // The allocation size is the first argument.
558 QualType SizeTy = getContext().getSizeType();
Mike Stump25cf7602009-09-09 15:08:12 +0000559 llvm::Value *AllocSize =
560 llvm::ConstantInt::get(ConvertType(SizeTy),
Anders Carlssond5536972009-05-31 20:21:44 +0000561 getContext().getTypeSize(AllocType) / 8);
562
563 NewArgs.push_back(std::make_pair(RValue::get(AllocSize), SizeTy));
Mike Stump25cf7602009-09-09 15:08:12 +0000564
Anders Carlssond5536972009-05-31 20:21:44 +0000565 // Emit the rest of the arguments.
566 // FIXME: Ideally, this should just use EmitCallArgs.
567 CXXNewExpr::const_arg_iterator NewArg = E->placement_arg_begin();
568
569 // First, use the types from the function type.
570 // We start at 1 here because the first argument (the allocation size)
571 // has already been emitted.
572 for (unsigned i = 1, e = NewFTy->getNumArgs(); i != e; ++i, ++NewArg) {
573 QualType ArgType = NewFTy->getArgType(i);
Mike Stump25cf7602009-09-09 15:08:12 +0000574
Anders Carlssond5536972009-05-31 20:21:44 +0000575 assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
Mike Stump25cf7602009-09-09 15:08:12 +0000576 getTypePtr() ==
577 getContext().getCanonicalType(NewArg->getType()).getTypePtr() &&
Anders Carlssond5536972009-05-31 20:21:44 +0000578 "type mismatch in call argument!");
Mike Stump25cf7602009-09-09 15:08:12 +0000579
580 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
Anders Carlssond5536972009-05-31 20:21:44 +0000581 ArgType));
Mike Stump25cf7602009-09-09 15:08:12 +0000582
Anders Carlssond5536972009-05-31 20:21:44 +0000583 }
Mike Stump25cf7602009-09-09 15:08:12 +0000584
585 // Either we've emitted all the call args, or we have a call to a
Anders Carlssond5536972009-05-31 20:21:44 +0000586 // variadic function.
Mike Stump25cf7602009-09-09 15:08:12 +0000587 assert((NewArg == E->placement_arg_end() || NewFTy->isVariadic()) &&
Anders Carlssond5536972009-05-31 20:21:44 +0000588 "Extra arguments in non-variadic function!");
Mike Stump25cf7602009-09-09 15:08:12 +0000589
Anders Carlssond5536972009-05-31 20:21:44 +0000590 // If we still have any arguments, emit them using the type of the argument.
Mike Stump25cf7602009-09-09 15:08:12 +0000591 for (CXXNewExpr::const_arg_iterator NewArgEnd = E->placement_arg_end();
Anders Carlssond5536972009-05-31 20:21:44 +0000592 NewArg != NewArgEnd; ++NewArg) {
593 QualType ArgType = NewArg->getType();
594 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
595 ArgType));
596 }
597
598 // Emit the call to new.
Mike Stump25cf7602009-09-09 15:08:12 +0000599 RValue RV =
Anders Carlssond5536972009-05-31 20:21:44 +0000600 EmitCall(CGM.getTypes().getFunctionInfo(NewFTy->getResultType(), NewArgs),
601 CGM.GetAddrOfFunction(GlobalDecl(NewFD)),
602 NewArgs, NewFD);
603
Anders Carlsson11269042009-05-31 21:53:59 +0000604 // If an allocation function is declared with an empty exception specification
605 // it returns null to indicate failure to allocate storage. [expr.new]p13.
606 // (We don't need to check for null when there's no new initializer and
607 // we're allocating a POD type).
608 bool NullCheckResult = NewFTy->hasEmptyExceptionSpec() &&
609 !(AllocType->isPODType() && !E->hasInitializer());
Anders Carlssond5536972009-05-31 20:21:44 +0000610
Anders Carlssondbee9a52009-06-01 00:05:16 +0000611 llvm::BasicBlock *NewNull = 0;
612 llvm::BasicBlock *NewNotNull = 0;
613 llvm::BasicBlock *NewEnd = 0;
614
615 llvm::Value *NewPtr = RV.getScalarVal();
616
Anders Carlsson11269042009-05-31 21:53:59 +0000617 if (NullCheckResult) {
Anders Carlssondbee9a52009-06-01 00:05:16 +0000618 NewNull = createBasicBlock("new.null");
619 NewNotNull = createBasicBlock("new.notnull");
620 NewEnd = createBasicBlock("new.end");
Mike Stump25cf7602009-09-09 15:08:12 +0000621
622 llvm::Value *IsNull =
623 Builder.CreateICmpEQ(NewPtr,
Owen Andersonf37b84b2009-07-31 20:28:54 +0000624 llvm::Constant::getNullValue(NewPtr->getType()),
Anders Carlssondbee9a52009-06-01 00:05:16 +0000625 "isnull");
Mike Stump25cf7602009-09-09 15:08:12 +0000626
Anders Carlssondbee9a52009-06-01 00:05:16 +0000627 Builder.CreateCondBr(IsNull, NewNull, NewNotNull);
628 EmitBlock(NewNotNull);
Anders Carlsson11269042009-05-31 21:53:59 +0000629 }
Mike Stump25cf7602009-09-09 15:08:12 +0000630
Anders Carlssondbee9a52009-06-01 00:05:16 +0000631 NewPtr = Builder.CreateBitCast(NewPtr, ConvertType(E->getType()));
Mike Stump25cf7602009-09-09 15:08:12 +0000632
Anders Carlsson7c294782009-05-31 20:56:36 +0000633 if (AllocType->isPODType()) {
Anders Carlsson26910f62009-06-01 00:26:14 +0000634 if (E->getNumConstructorArgs() > 0) {
Mike Stump25cf7602009-09-09 15:08:12 +0000635 assert(E->getNumConstructorArgs() == 1 &&
Anders Carlsson7c294782009-05-31 20:56:36 +0000636 "Can only have one argument to initializer of POD type.");
637
638 const Expr *Init = E->getConstructorArg(0);
Mike Stump25cf7602009-09-09 15:08:12 +0000639
640 if (!hasAggregateLLVMType(AllocType))
Anders Carlsson7c294782009-05-31 20:56:36 +0000641 Builder.CreateStore(EmitScalarExpr(Init), NewPtr);
Anders Carlsson5f93ccf2009-05-31 21:07:58 +0000642 else if (AllocType->isAnyComplexType())
643 EmitComplexExprIntoAddr(Init, NewPtr, AllocType.isVolatileQualified());
Anders Carlssoneb39b432009-05-31 21:12:26 +0000644 else
645 EmitAggExpr(Init, NewPtr, AllocType.isVolatileQualified());
Anders Carlsson7c294782009-05-31 20:56:36 +0000646 }
Anders Carlsson11269042009-05-31 21:53:59 +0000647 } else {
Mike Stump25cf7602009-09-09 15:08:12 +0000648 // Call the constructor.
Anders Carlsson11269042009-05-31 21:53:59 +0000649 CXXConstructorDecl *Ctor = E->getConstructor();
Mike Stump25cf7602009-09-09 15:08:12 +0000650
651 EmitCXXConstructorCall(Ctor, Ctor_Complete, NewPtr,
652 E->constructor_arg_begin(),
Anders Carlsson11269042009-05-31 21:53:59 +0000653 E->constructor_arg_end());
Anders Carlssond5536972009-05-31 20:21:44 +0000654 }
Anders Carlsson11269042009-05-31 21:53:59 +0000655
Anders Carlssondbee9a52009-06-01 00:05:16 +0000656 if (NullCheckResult) {
657 Builder.CreateBr(NewEnd);
658 EmitBlock(NewNull);
659 Builder.CreateBr(NewEnd);
660 EmitBlock(NewEnd);
Mike Stump25cf7602009-09-09 15:08:12 +0000661
Anders Carlssondbee9a52009-06-01 00:05:16 +0000662 llvm::PHINode *PHI = Builder.CreatePHI(NewPtr->getType());
663 PHI->reserveOperandSpace(2);
664 PHI->addIncoming(NewPtr, NewNotNull);
Owen Andersonf37b84b2009-07-31 20:28:54 +0000665 PHI->addIncoming(llvm::Constant::getNullValue(NewPtr->getType()), NewNull);
Mike Stump25cf7602009-09-09 15:08:12 +0000666
Anders Carlssondbee9a52009-06-01 00:05:16 +0000667 NewPtr = PHI;
668 }
Mike Stump25cf7602009-09-09 15:08:12 +0000669
Anders Carlsson11269042009-05-31 21:53:59 +0000670 return NewPtr;
Anders Carlsson18e88bc2009-05-31 01:40:14 +0000671}
672
Anders Carlsson133fdaf2009-08-16 21:13:42 +0000673void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
674 if (E->isArrayForm()) {
675 ErrorUnsupported(E, "delete[] expression");
676 return;
677 };
678
Mike Stump25cf7602009-09-09 15:08:12 +0000679 QualType DeleteTy =
Anders Carlsson133fdaf2009-08-16 21:13:42 +0000680 E->getArgument()->getType()->getAs<PointerType>()->getPointeeType();
Mike Stump25cf7602009-09-09 15:08:12 +0000681
Anders Carlsson133fdaf2009-08-16 21:13:42 +0000682 llvm::Value *Ptr = EmitScalarExpr(E->getArgument());
Mike Stump25cf7602009-09-09 15:08:12 +0000683
Anders Carlsson133fdaf2009-08-16 21:13:42 +0000684 // Null check the pointer.
685 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
686 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
687
Mike Stump25cf7602009-09-09 15:08:12 +0000688 llvm::Value *IsNull =
Anders Carlsson133fdaf2009-08-16 21:13:42 +0000689 Builder.CreateICmpEQ(Ptr, llvm::Constant::getNullValue(Ptr->getType()),
690 "isnull");
Mike Stump25cf7602009-09-09 15:08:12 +0000691
Anders Carlsson133fdaf2009-08-16 21:13:42 +0000692 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
693 EmitBlock(DeleteNotNull);
Mike Stump25cf7602009-09-09 15:08:12 +0000694
Anders Carlsson133fdaf2009-08-16 21:13:42 +0000695 // Call the destructor if necessary.
696 if (const RecordType *RT = DeleteTy->getAs<RecordType>()) {
697 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
698 if (!RD->hasTrivialDestructor()) {
699 const CXXDestructorDecl *Dtor = RD->getDestructor(getContext());
700 if (Dtor->isVirtual()) {
701 ErrorUnsupported(E, "delete expression with virtual destructor");
702 return;
703 }
Mike Stump25cf7602009-09-09 15:08:12 +0000704
Anders Carlsson133fdaf2009-08-16 21:13:42 +0000705 EmitCXXDestructorCall(Dtor, Dtor_Complete, Ptr);
706 }
707 }
708 }
Mike Stump25cf7602009-09-09 15:08:12 +0000709
Anders Carlsson133fdaf2009-08-16 21:13:42 +0000710 // Call delete.
711 FunctionDecl *DeleteFD = E->getOperatorDelete();
Mike Stump25cf7602009-09-09 15:08:12 +0000712 const FunctionProtoType *DeleteFTy =
Anders Carlsson133fdaf2009-08-16 21:13:42 +0000713 DeleteFD->getType()->getAsFunctionProtoType();
Mike Stump25cf7602009-09-09 15:08:12 +0000714
Anders Carlsson133fdaf2009-08-16 21:13:42 +0000715 CallArgList DeleteArgs;
716
717 QualType ArgTy = DeleteFTy->getArgType(0);
718 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
719 DeleteArgs.push_back(std::make_pair(RValue::get(DeletePtr), ArgTy));
Mike Stump25cf7602009-09-09 15:08:12 +0000720
Anders Carlsson133fdaf2009-08-16 21:13:42 +0000721 // Emit the call to delete.
Mike Stump25cf7602009-09-09 15:08:12 +0000722 EmitCall(CGM.getTypes().getFunctionInfo(DeleteFTy->getResultType(),
Anders Carlsson133fdaf2009-08-16 21:13:42 +0000723 DeleteArgs),
724 CGM.GetAddrOfFunction(GlobalDecl(DeleteFD)),
725 DeleteArgs, DeleteFD);
Mike Stump25cf7602009-09-09 15:08:12 +0000726
Anders Carlsson133fdaf2009-08-16 21:13:42 +0000727 EmitBlock(DeleteEnd);
728}
729
Anders Carlsson652951a2009-04-15 15:55:24 +0000730void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) {
Anders Carlsson1764af42009-05-05 04:44:02 +0000731 EmitGlobal(GlobalDecl(D, Ctor_Complete));
732 EmitGlobal(GlobalDecl(D, Ctor_Base));
Anders Carlsson652951a2009-04-15 15:55:24 +0000733}
Anders Carlsson890a9fd2009-04-16 23:57:24 +0000734
Mike Stump25cf7602009-09-09 15:08:12 +0000735void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D,
Anders Carlsson4811c302009-04-17 01:58:57 +0000736 CXXCtorType Type) {
Mike Stump25cf7602009-09-09 15:08:12 +0000737
Anders Carlsson4811c302009-04-17 01:58:57 +0000738 llvm::Function *Fn = GetAddrOfCXXConstructor(D, Type);
Mike Stump25cf7602009-09-09 15:08:12 +0000739
Anders Carlsson4811c302009-04-17 01:58:57 +0000740 CodeGenFunction(*this).GenerateCode(D, Fn);
Mike Stump25cf7602009-09-09 15:08:12 +0000741
Anders Carlsson4811c302009-04-17 01:58:57 +0000742 SetFunctionDefinitionAttributes(D, Fn);
743 SetLLVMFunctionAttributesForDefinition(D, Fn);
744}
745
Anders Carlsson890a9fd2009-04-16 23:57:24 +0000746llvm::Function *
Mike Stump25cf7602009-09-09 15:08:12 +0000747CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
Anders Carlsson890a9fd2009-04-16 23:57:24 +0000748 CXXCtorType Type) {
749 const llvm::FunctionType *FTy =
750 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false);
Mike Stump25cf7602009-09-09 15:08:12 +0000751
Anders Carlsson890a9fd2009-04-16 23:57:24 +0000752 const char *Name = getMangledCXXCtorName(D, Type);
Chris Lattner80f39cc2009-05-12 21:21:08 +0000753 return cast<llvm::Function>(
754 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson890a9fd2009-04-16 23:57:24 +0000755}
Anders Carlsson4811c302009-04-17 01:58:57 +0000756
Mike Stump25cf7602009-09-09 15:08:12 +0000757const char *CodeGenModule::getMangledCXXCtorName(const CXXConstructorDecl *D,
Anders Carlsson4811c302009-04-17 01:58:57 +0000758 CXXCtorType Type) {
759 llvm::SmallString<256> Name;
760 llvm::raw_svector_ostream Out(Name);
761 mangleCXXCtor(D, Type, Context, Out);
Mike Stump25cf7602009-09-09 15:08:12 +0000762
Anders Carlsson4811c302009-04-17 01:58:57 +0000763 Name += '\0';
764 return UniqueMangledName(Name.begin(), Name.end());
765}
766
767void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) {
Anders Carlsson4811c302009-04-17 01:58:57 +0000768 EmitCXXDestructor(D, Dtor_Complete);
769 EmitCXXDestructor(D, Dtor_Base);
770}
771
Mike Stump25cf7602009-09-09 15:08:12 +0000772void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D,
Anders Carlsson4811c302009-04-17 01:58:57 +0000773 CXXDtorType Type) {
774 llvm::Function *Fn = GetAddrOfCXXDestructor(D, Type);
Mike Stump25cf7602009-09-09 15:08:12 +0000775
Anders Carlsson4811c302009-04-17 01:58:57 +0000776 CodeGenFunction(*this).GenerateCode(D, Fn);
Mike Stump25cf7602009-09-09 15:08:12 +0000777
Anders Carlsson4811c302009-04-17 01:58:57 +0000778 SetFunctionDefinitionAttributes(D, Fn);
779 SetLLVMFunctionAttributesForDefinition(D, Fn);
780}
781
782llvm::Function *
Mike Stump25cf7602009-09-09 15:08:12 +0000783CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D,
Anders Carlsson4811c302009-04-17 01:58:57 +0000784 CXXDtorType Type) {
785 const llvm::FunctionType *FTy =
786 getTypes().GetFunctionType(getTypes().getFunctionInfo(D), false);
Mike Stump25cf7602009-09-09 15:08:12 +0000787
Anders Carlsson4811c302009-04-17 01:58:57 +0000788 const char *Name = getMangledCXXDtorName(D, Type);
Chris Lattner80f39cc2009-05-12 21:21:08 +0000789 return cast<llvm::Function>(
790 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
Anders Carlsson4811c302009-04-17 01:58:57 +0000791}
792
Mike Stump25cf7602009-09-09 15:08:12 +0000793const char *CodeGenModule::getMangledCXXDtorName(const CXXDestructorDecl *D,
Anders Carlsson4811c302009-04-17 01:58:57 +0000794 CXXDtorType Type) {
795 llvm::SmallString<256> Name;
796 llvm::raw_svector_ostream Out(Name);
797 mangleCXXDtor(D, Type, Context, Out);
Mike Stump25cf7602009-09-09 15:08:12 +0000798
Anders Carlsson4811c302009-04-17 01:58:57 +0000799 Name += '\0';
800 return UniqueMangledName(Name.begin(), Name.end());
801}
Fariborz Jahanian5400e022009-07-20 23:18:55 +0000802
Mike Stumpdca5e512009-08-18 21:49:00 +0000803llvm::Constant *CodeGenModule::GenerateRtti(const CXXRecordDecl *RD) {
Mike Stump00df7d32009-07-31 23:15:31 +0000804 llvm::Type *Ptr8Ty;
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000805 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Mike Stump69a12322009-08-04 20:06:48 +0000806 llvm::Constant *Rtti = llvm::Constant::getNullValue(Ptr8Ty);
Mike Stump00df7d32009-07-31 23:15:31 +0000807
808 if (!getContext().getLangOptions().Rtti)
Mike Stump69a12322009-08-04 20:06:48 +0000809 return Rtti;
Mike Stump00df7d32009-07-31 23:15:31 +0000810
811 llvm::SmallString<256> OutName;
812 llvm::raw_svector_ostream Out(OutName);
813 QualType ClassTy;
Mike Stumpe7545622009-08-07 18:05:12 +0000814 ClassTy = getContext().getTagDeclType(RD);
Mike Stump00df7d32009-07-31 23:15:31 +0000815 mangleCXXRtti(ClassTy, getContext(), Out);
Mike Stump00df7d32009-07-31 23:15:31 +0000816 llvm::GlobalVariable::LinkageTypes linktype;
817 linktype = llvm::GlobalValue::WeakAnyLinkage;
818 std::vector<llvm::Constant *> info;
Mike Stump2eade572009-08-13 22:53:07 +0000819 // assert(0 && "FIXME: implement rtti descriptor");
Mike Stump00df7d32009-07-31 23:15:31 +0000820 // FIXME: descriptor
821 info.push_back(llvm::Constant::getNullValue(Ptr8Ty));
Mike Stump2eade572009-08-13 22:53:07 +0000822 // assert(0 && "FIXME: implement rtti ts");
Mike Stump00df7d32009-07-31 23:15:31 +0000823 // FIXME: TS
824 info.push_back(llvm::Constant::getNullValue(Ptr8Ty));
825
826 llvm::Constant *C;
827 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, info.size());
828 C = llvm::ConstantArray::get(type, info);
Mike Stumpdca5e512009-08-18 21:49:00 +0000829 Rtti = new llvm::GlobalVariable(getModule(), type, true, linktype, C,
Daniel Dunbar0433a022009-08-19 20:04:03 +0000830 Out.str());
Mike Stump69a12322009-08-04 20:06:48 +0000831 Rtti = llvm::ConstantExpr::getBitCast(Rtti, Ptr8Ty);
832 return Rtti;
Mike Stump00df7d32009-07-31 23:15:31 +0000833}
834
Mike Stump86a859e2009-08-19 18:10:47 +0000835class VtableBuilder {
Mike Stumpf7d47a52009-08-26 20:46:33 +0000836public:
837 /// Index_t - Vtable index type.
838 typedef uint64_t Index_t;
839private:
Mike Stumpad734d12009-08-18 20:50:28 +0000840 std::vector<llvm::Constant *> &methods;
Mike Stumpf3245642009-08-28 23:22:54 +0000841 std::vector<llvm::Constant *> submethods;
Mike Stumpad734d12009-08-18 20:50:28 +0000842 llvm::Type *Ptr8Ty;
Mike Stumpf07ede52009-08-21 01:45:00 +0000843 /// Class - The most derived class that this vtable is being built for.
Mike Stumpdca5e512009-08-18 21:49:00 +0000844 const CXXRecordDecl *Class;
Mike Stumpf07ede52009-08-21 01:45:00 +0000845 /// BLayout - Layout for the most derived class that this vtable is being
846 /// built for.
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000847 const ASTRecordLayout &BLayout;
Mike Stumpa7ec675d2009-08-19 14:40:47 +0000848 llvm::SmallSet<const CXXRecordDecl *, 32> IndirectPrimary;
Mike Stump2b9ba612009-08-20 02:11:48 +0000849 llvm::SmallSet<const CXXRecordDecl *, 32> SeenVBase;
Mike Stumpdca5e512009-08-18 21:49:00 +0000850 llvm::Constant *rtti;
Mike Stumpad734d12009-08-18 20:50:28 +0000851 llvm::LLVMContext &VMContext;
Mike Stump1e10cf32009-08-18 21:03:28 +0000852 CodeGenModule &CGM; // Per-module state.
Mike Stumpf07ede52009-08-21 01:45:00 +0000853 /// Index - Maps a method decl into a vtable index. Useful for virtual
854 /// dispatch codegen.
Mike Stumpf7d47a52009-08-26 20:46:33 +0000855 llvm::DenseMap<const CXXMethodDecl *, Index_t> Index;
Mike Stumpf3245642009-08-28 23:22:54 +0000856 llvm::DenseMap<const CXXMethodDecl *, Index_t> VCall;
857 llvm::DenseMap<const CXXMethodDecl *, Index_t> VCallOffset;
Mike Stump58256412009-09-05 07:20:32 +0000858 typedef llvm::DenseMap<const CXXMethodDecl *,
859 std::pair<Index_t, Index_t> > Thunks_t;
860 Thunks_t Thunks;
Mike Stumpf3245642009-08-28 23:22:54 +0000861 std::vector<Index_t> VCalls;
Mike Stumpd75d3232009-08-18 22:04:08 +0000862 typedef CXXRecordDecl::method_iterator method_iter;
Mike Stumpd5b15562009-09-04 18:27:16 +0000863 // FIXME: Linkage should follow vtable
864 const bool Extern;
Mike Stump58256412009-09-05 07:20:32 +0000865 const uint32_t LLVMPointerWidth;
866 Index_t extra;
Mike Stumpad734d12009-08-18 20:50:28 +0000867public:
Mike Stump86a859e2009-08-19 18:10:47 +0000868 VtableBuilder(std::vector<llvm::Constant *> &meth,
869 const CXXRecordDecl *c,
870 CodeGenModule &cgm)
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000871 : methods(meth), Class(c), BLayout(cgm.getContext().getASTRecordLayout(c)),
872 rtti(cgm.GenerateRtti(c)), VMContext(cgm.getModule().getContext()),
Mike Stump58256412009-09-05 07:20:32 +0000873 CGM(cgm), Extern(true),
874 LLVMPointerWidth(cgm.getContext().Target.getPointerWidth(0)) {
Mike Stumpad734d12009-08-18 20:50:28 +0000875 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
876 }
Mike Stumpdca5e512009-08-18 21:49:00 +0000877
Mike Stumpf7d47a52009-08-26 20:46:33 +0000878 llvm::DenseMap<const CXXMethodDecl *, Index_t> &getIndex() { return Index; }
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000879
Mike Stumpf3245642009-08-28 23:22:54 +0000880 llvm::Constant *wrap(Index_t i) {
881 llvm::Constant *m;
882 m = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), i);
883 return llvm::ConstantExpr::getIntToPtr(m, Ptr8Ty);
Mike Stumpb6ff81e2009-08-19 02:06:38 +0000884 }
885
Mike Stumpf3245642009-08-28 23:22:54 +0000886 llvm::Constant *wrap(llvm::Constant *m) {
887 return llvm::ConstantExpr::getBitCast(m, Ptr8Ty);
Mike Stump23b238e2009-08-12 23:25:18 +0000888 }
Mike Stumpf640de52009-08-12 23:14:12 +0000889
Mike Stump2b9ba612009-08-20 02:11:48 +0000890 void GenerateVBaseOffsets(std::vector<llvm::Constant *> &offsets,
Mike Stumpaf0d0452009-08-20 07:22:17 +0000891 const CXXRecordDecl *RD, uint64_t Offset) {
Mike Stump2b9ba612009-08-20 02:11:48 +0000892 for (CXXRecordDecl::base_class_const_iterator i =RD->bases_begin(),
893 e = RD->bases_end(); i != e; ++i) {
Mike Stump25cf7602009-09-09 15:08:12 +0000894 const CXXRecordDecl *Base =
Mike Stump2b9ba612009-08-20 02:11:48 +0000895 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
896 if (i->isVirtual() && !SeenVBase.count(Base)) {
897 SeenVBase.insert(Base);
Mike Stumpaf0d0452009-08-20 07:22:17 +0000898 int64_t BaseOffset = -(Offset/8) + BLayout.getVBaseClassOffset(Base)/8;
Mike Stumpf3245642009-08-28 23:22:54 +0000899 llvm::Constant *m = wrap(BaseOffset);
900 m = wrap((0?700:0) + BaseOffset);
Mike Stump2b9ba612009-08-20 02:11:48 +0000901 offsets.push_back(m);
902 }
Mike Stumpaf0d0452009-08-20 07:22:17 +0000903 GenerateVBaseOffsets(offsets, Base, Offset);
Mike Stump2b9ba612009-08-20 02:11:48 +0000904 }
905 }
906
Mike Stumpf07ede52009-08-21 01:45:00 +0000907 void StartNewTable() {
908 SeenVBase.clear();
909 }
Mike Stumpdecd7812009-08-12 23:00:59 +0000910
Mike Stump35af2b12009-09-01 22:20:28 +0000911 bool OverrideMethod(const CXXMethodDecl *MD, llvm::Constant *m,
Mike Stumpbb3126c2009-09-07 04:27:52 +0000912 bool MorallyVirtual, Index_t Offset) {
Mike Stumpf07ede52009-08-21 01:45:00 +0000913 typedef CXXMethodDecl::method_iterator meth_iter;
914
Mike Stumpf07ede52009-08-21 01:45:00 +0000915 // FIXME: Don't like the nested loops. For very large inheritance
916 // heirarchies we could have a table on the side with the final overridder
917 // and just replace each instance of an overridden method once. Would be
918 // nice to measure the cost/benefit on real code.
919
Mike Stumpf07ede52009-08-21 01:45:00 +0000920 for (meth_iter mi = MD->begin_overridden_methods(),
921 e = MD->end_overridden_methods();
922 mi != e; ++mi) {
923 const CXXMethodDecl *OMD = *mi;
924 llvm::Constant *om;
925 om = CGM.GetAddrOfFunction(GlobalDecl(OMD), Ptr8Ty);
926 om = llvm::ConstantExpr::getBitCast(om, Ptr8Ty);
927
Mike Stumpbb3126c2009-09-07 04:27:52 +0000928 for (Index_t i = 0, e = submethods.size();
Mike Stumpf7d47a52009-08-26 20:46:33 +0000929 i != e; ++i) {
Mike Stumpf07ede52009-08-21 01:45:00 +0000930 // FIXME: begin_overridden_methods might be too lax, covariance */
Mike Stump58256412009-09-05 07:20:32 +0000931 if (submethods[i] != om)
932 continue;
Mike Stumpbb3126c2009-09-07 04:27:52 +0000933 Index[MD] = i;
Mike Stump58256412009-09-05 07:20:32 +0000934 submethods[i] = m;
Mike Stump58256412009-09-05 07:20:32 +0000935
936 Thunks.erase(OMD);
937 if (MorallyVirtual) {
Mike Stump58256412009-09-05 07:20:32 +0000938 Index_t &idx = VCall[OMD];
939 if (idx == 0) {
Mike Stumpbb3126c2009-09-07 04:27:52 +0000940 VCallOffset[MD] = Offset/8;
Mike Stump58256412009-09-05 07:20:32 +0000941 idx = VCalls.size()+1;
942 VCalls.push_back(0);
Mike Stumpbb3126c2009-09-07 04:27:52 +0000943 } else {
944 VCallOffset[MD] = VCallOffset[OMD];
945 VCalls[idx-1] = -VCallOffset[OMD] + Offset/8;
Mike Stumpf3245642009-08-28 23:22:54 +0000946 }
Mike Stump58256412009-09-05 07:20:32 +0000947 VCall[MD] = idx;
948 // FIXME: 0?
949 Thunks[MD] = std::make_pair(0, -((idx+extra+2)*LLVMPointerWidth/8));
Mike Stump35af2b12009-09-01 22:20:28 +0000950 return true;
Mike Stumpf07ede52009-08-21 01:45:00 +0000951 }
Mike Stump58256412009-09-05 07:20:32 +0000952#if 0
953 // FIXME: finish off
954 int64_t O = VCallOffset[OMD] - Offset/8;
955 if (O) {
956 Thunks[MD] = std::make_pair(O, 0);
957 }
958#endif
959 return true;
Mike Stump1e10cf32009-08-18 21:03:28 +0000960 }
Mike Stumpdecd7812009-08-12 23:00:59 +0000961 }
Mike Stumpf07ede52009-08-21 01:45:00 +0000962
Mike Stump35af2b12009-09-01 22:20:28 +0000963 return false;
964 }
965
Mike Stumpf0415ae2009-09-05 11:28:33 +0000966 void InstallThunks() {
Mike Stump58256412009-09-05 07:20:32 +0000967 for (Thunks_t::iterator i = Thunks.begin(), e = Thunks.end();
968 i != e; ++i) {
969 const CXXMethodDecl *MD = i->first;
970 Index_t idx = Index[MD];
971 Index_t nv_O = i->second.first;
972 Index_t v_O = i->second.second;
Mike Stumpf0415ae2009-09-05 11:28:33 +0000973 submethods[idx] = CGM.BuildThunk(MD, Extern, nv_O, v_O);
Mike Stump58256412009-09-05 07:20:32 +0000974 }
975 Thunks.clear();
976 }
977
Mike Stumpbb3126c2009-09-07 04:27:52 +0000978 void OverrideMethods(std::vector<std::pair<const CXXRecordDecl *,
979 int64_t> > *Path, bool MorallyVirtual) {
980 for (std::vector<std::pair<const CXXRecordDecl *,
981 int64_t> >::reverse_iterator i =Path->rbegin(),
Mike Stumpf0415ae2009-09-05 11:28:33 +0000982 e = Path->rend(); i != e; ++i) {
Mike Stumpbb3126c2009-09-07 04:27:52 +0000983 const CXXRecordDecl *RD = i->first;
984 int64_t Offset = i->second;
Mike Stumpf0415ae2009-09-05 11:28:33 +0000985 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
986 ++mi)
987 if (mi->isVirtual()) {
988 const CXXMethodDecl *MD = *mi;
989 llvm::Constant *m = wrap(CGM.GetAddrOfFunction(GlobalDecl(MD),
990 Ptr8Ty));
Mike Stumpbb3126c2009-09-07 04:27:52 +0000991 OverrideMethod(MD, m, MorallyVirtual, Offset);
Mike Stumpf0415ae2009-09-05 11:28:33 +0000992 }
993 }
Mike Stump35240ec2009-09-01 23:22:44 +0000994 }
995
Mike Stump53f32982009-09-05 07:49:12 +0000996 void AddMethod(const CXXMethodDecl *MD, bool MorallyVirtual, Index_t Offset) {
Mike Stump35240ec2009-09-01 23:22:44 +0000997 llvm::Constant *m = wrap(CGM.GetAddrOfFunction(GlobalDecl(MD), Ptr8Ty));
Mike Stump58256412009-09-05 07:20:32 +0000998 // If we can find a previously allocated slot for this, reuse it.
Mike Stumpbb3126c2009-09-07 04:27:52 +0000999 if (OverrideMethod(MD, m, MorallyVirtual, Offset))
Mike Stump35af2b12009-09-01 22:20:28 +00001000 return;
Mike Stump25cf7602009-09-09 15:08:12 +00001001
Mike Stumpf07ede52009-08-21 01:45:00 +00001002 // else allocate a new slot.
Mike Stumpf3245642009-08-28 23:22:54 +00001003 Index[MD] = submethods.size();
Mike Stumpbb3126c2009-09-07 04:27:52 +00001004 submethods.push_back(m);
Mike Stumpf3245642009-08-28 23:22:54 +00001005 if (MorallyVirtual) {
1006 VCallOffset[MD] = Offset/8;
1007 Index_t &idx = VCall[MD];
1008 // Allocate the first one, after that, we reuse the previous one.
1009 if (idx == 0) {
1010 idx = VCalls.size()+1;
Mike Stumpf3245642009-08-28 23:22:54 +00001011 VCalls.push_back(0);
1012 }
1013 }
Mike Stumpf07ede52009-08-21 01:45:00 +00001014 }
1015
Mike Stump53f32982009-09-05 07:49:12 +00001016 void AddMethods(const CXXRecordDecl *RD, bool MorallyVirtual,
1017 Index_t Offset) {
Mike Stumpf07ede52009-08-21 01:45:00 +00001018 for (method_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
1019 ++mi)
1020 if (mi->isVirtual())
Mike Stump53f32982009-09-05 07:49:12 +00001021 AddMethod(*mi, MorallyVirtual, Offset);
Mike Stumpdecd7812009-08-12 23:00:59 +00001022 }
Mike Stump1e10cf32009-08-18 21:03:28 +00001023
Mike Stump58256412009-09-05 07:20:32 +00001024 void NonVirtualBases(const CXXRecordDecl *RD, const ASTRecordLayout &Layout,
1025 const CXXRecordDecl *PrimaryBase,
1026 bool PrimaryBaseWasVirtual, bool MorallyVirtual,
1027 int64_t Offset) {
1028 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1029 e = RD->bases_end(); i != e; ++i) {
1030 if (i->isVirtual())
1031 continue;
Mike Stump25cf7602009-09-09 15:08:12 +00001032 const CXXRecordDecl *Base =
Mike Stump58256412009-09-05 07:20:32 +00001033 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1034 if (Base != PrimaryBase || PrimaryBaseWasVirtual) {
1035 uint64_t o = Offset + Layout.getBaseClassOffset(Base);
1036 StartNewTable();
Mike Stumpbb3126c2009-09-07 04:27:52 +00001037 std::vector<std::pair<const CXXRecordDecl *,
1038 int64_t> > S;
1039 S.push_back(std::make_pair(RD, Offset));
Mike Stumpf0415ae2009-09-05 11:28:33 +00001040 GenerateVtableForBase(Base, MorallyVirtual, o, false, &S);
Mike Stump58256412009-09-05 07:20:32 +00001041 }
1042 }
1043 }
1044
Mike Stump53f32982009-09-05 07:49:12 +00001045 Index_t end(const CXXRecordDecl *RD, std::vector<llvm::Constant *> &offsets,
1046 const ASTRecordLayout &Layout,
1047 const CXXRecordDecl *PrimaryBase,
1048 bool PrimaryBaseWasVirtual, bool MorallyVirtual,
1049 int64_t Offset, bool ForVirtualBase) {
1050 StartNewTable();
1051 extra = 0;
1052 // FIXME: Cleanup.
1053 if (!ForVirtualBase) {
1054 // then virtual base offsets...
1055 for (std::vector<llvm::Constant *>::reverse_iterator i = offsets.rbegin(),
1056 e = offsets.rend(); i != e; ++i)
1057 methods.push_back(*i);
1058 }
1059
1060 // The vcalls come first...
Mike Stumpbb3126c2009-09-07 04:27:52 +00001061 for (std::vector<Index_t>::reverse_iterator i=VCalls.rbegin(),
1062 e=VCalls.rend();
1063 i != e; ++i)
Mike Stump53f32982009-09-05 07:49:12 +00001064 methods.push_back(wrap((0?600:0) + *i));
1065 VCalls.clear();
1066
1067 if (ForVirtualBase) {
1068 // then virtual base offsets...
1069 for (std::vector<llvm::Constant *>::reverse_iterator i = offsets.rbegin(),
1070 e = offsets.rend(); i != e; ++i)
1071 methods.push_back(*i);
1072 }
1073
1074 methods.push_back(wrap(-(Offset/8)));
1075 methods.push_back(rtti);
1076 Index_t AddressPoint = methods.size();
1077
Mike Stumpf0415ae2009-09-05 11:28:33 +00001078 InstallThunks();
Mike Stump53f32982009-09-05 07:49:12 +00001079 methods.insert(methods.end(), submethods.begin(), submethods.end());
1080 submethods.clear();
Mike Stump53f32982009-09-05 07:49:12 +00001081
1082 // and then the non-virtual bases.
1083 NonVirtualBases(RD, Layout, PrimaryBase, PrimaryBaseWasVirtual,
1084 MorallyVirtual, Offset);
1085 return AddressPoint;
1086 }
1087
Mike Stump8e0f10f2009-09-05 08:40:18 +00001088 void Primaries(const CXXRecordDecl *RD, bool MorallyVirtual, int64_t Offset) {
Mike Stumpfd9b3d02009-09-05 08:37:03 +00001089 if (!RD->isDynamicClass())
1090 return;
1091
1092 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
Mike Stump25cf7602009-09-09 15:08:12 +00001093 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
Mike Stumpfd9b3d02009-09-05 08:37:03 +00001094 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
1095
Mike Stumpfd9b3d02009-09-05 08:37:03 +00001096 // vtables are composed from the chain of primaries.
1097 if (PrimaryBase) {
1098 if (PrimaryBaseWasVirtual)
1099 IndirectPrimary.insert(PrimaryBase);
Mike Stump8e0f10f2009-09-05 08:40:18 +00001100 Primaries(PrimaryBase, PrimaryBaseWasVirtual|MorallyVirtual, Offset);
Mike Stumpfd9b3d02009-09-05 08:37:03 +00001101 }
1102
1103 // And add the virtuals for the class to the primary vtable.
1104 AddMethods(RD, MorallyVirtual, Offset);
1105 }
1106
Mike Stump634ef532009-09-05 09:10:58 +00001107 int64_t GenerateVtableForBase(const CXXRecordDecl *RD,
Mike Stump3cd18e42009-09-05 09:24:43 +00001108 bool MorallyVirtual = false, int64_t Offset = 0,
1109 bool ForVirtualBase = false,
Mike Stumpbb3126c2009-09-07 04:27:52 +00001110 std::vector<std::pair<const CXXRecordDecl *,
1111 int64_t> > *Path = 0) {
Mike Stump900acd32009-09-05 08:07:32 +00001112 if (!RD->isDynamicClass())
Mike Stump00962322009-08-21 23:09:30 +00001113 return 0;
Mike Stump7bae1282009-08-18 21:30:21 +00001114
1115 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
Mike Stump25cf7602009-09-09 15:08:12 +00001116 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
Mike Stump7bae1282009-08-18 21:30:21 +00001117 const bool PrimaryBaseWasVirtual = Layout.getPrimaryBaseWasVirtual();
1118
Mike Stumpf3245642009-08-28 23:22:54 +00001119 std::vector<llvm::Constant *> offsets;
Mike Stump8e8e0f42009-09-05 08:45:02 +00001120 extra = 0;
1121 GenerateVBaseOffsets(offsets, RD, Offset);
1122 if (ForVirtualBase)
1123 extra = offsets.size();
Mike Stump7bae1282009-08-18 21:30:21 +00001124
1125 // vtables are composed from the chain of primaries.
1126 if (PrimaryBase) {
1127 if (PrimaryBaseWasVirtual)
1128 IndirectPrimary.insert(PrimaryBase);
Mike Stump8e0f10f2009-09-05 08:40:18 +00001129 Primaries(PrimaryBase, PrimaryBaseWasVirtual|MorallyVirtual, Offset);
Mike Stump7bae1282009-08-18 21:30:21 +00001130 }
1131
Mike Stumpf3245642009-08-28 23:22:54 +00001132 // And add the virtuals for the class to the primary vtable.
Mike Stump53f32982009-09-05 07:49:12 +00001133 AddMethods(RD, MorallyVirtual, Offset);
Mike Stumpf3245642009-08-28 23:22:54 +00001134
Mike Stumpf0415ae2009-09-05 11:28:33 +00001135 if (Path)
Mike Stumpbb3126c2009-09-07 04:27:52 +00001136 OverrideMethods(Path, MorallyVirtual);
Mike Stumpf0415ae2009-09-05 11:28:33 +00001137
Mike Stump53f32982009-09-05 07:49:12 +00001138 return end(RD, offsets, Layout, PrimaryBase, PrimaryBaseWasVirtual,
1139 MorallyVirtual, Offset, ForVirtualBase);
Mike Stump7bae1282009-08-18 21:30:21 +00001140 }
1141
Mike Stumpf0415ae2009-09-05 11:28:33 +00001142 void GenerateVtableForVBases(const CXXRecordDecl *RD,
Mike Stumpbb3126c2009-09-07 04:27:52 +00001143 int64_t Offset = 0,
1144 std::vector<std::pair<const CXXRecordDecl *,
1145 int64_t> > *Path = 0) {
Mike Stumpf0415ae2009-09-05 11:28:33 +00001146 bool alloc = false;
1147 if (Path == 0) {
1148 alloc = true;
Mike Stumpbb3126c2009-09-07 04:27:52 +00001149 Path = new std::vector<std::pair<const CXXRecordDecl *,
1150 int64_t> >;
Mike Stumpf0415ae2009-09-05 11:28:33 +00001151 }
1152 // FIXME: We also need to override using all paths to a virtual base,
1153 // right now, we just process the first path
Mike Stumpbb3126c2009-09-07 04:27:52 +00001154 Path->push_back(std::make_pair(RD, Offset));
Mike Stump7bae1282009-08-18 21:30:21 +00001155 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
1156 e = RD->bases_end(); i != e; ++i) {
Mike Stump25cf7602009-09-09 15:08:12 +00001157 const CXXRecordDecl *Base =
Mike Stump7bae1282009-08-18 21:30:21 +00001158 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1159 if (i->isVirtual() && !IndirectPrimary.count(Base)) {
1160 // Mark it so we don't output it twice.
1161 IndirectPrimary.insert(Base);
Mike Stumpf07ede52009-08-21 01:45:00 +00001162 StartNewTable();
Mike Stumpaf0d0452009-08-20 07:22:17 +00001163 int64_t BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stumpf0415ae2009-09-05 11:28:33 +00001164 GenerateVtableForBase(Base, true, BaseOffset, true, Path);
Mike Stump7bae1282009-08-18 21:30:21 +00001165 }
Mike Stumpbb3126c2009-09-07 04:27:52 +00001166 int64_t BaseOffset = Offset;
1167 if (i->isVirtual())
1168 BaseOffset = BLayout.getVBaseClassOffset(Base);
Mike Stump7bae1282009-08-18 21:30:21 +00001169 if (Base->getNumVBases())
Mike Stumpbb3126c2009-09-07 04:27:52 +00001170 GenerateVtableForVBases(Base, BaseOffset, Path);
Mike Stumpc57b8272009-08-16 01:46:26 +00001171 }
Mike Stumpf0415ae2009-09-05 11:28:33 +00001172 Path->pop_back();
1173 if (alloc)
1174 delete Path;
Mike Stumpc57b8272009-08-16 01:46:26 +00001175 }
Mike Stump7bae1282009-08-18 21:30:21 +00001176};
Mike Stumpd6f22d82009-08-06 15:50:11 +00001177
Mike Stumpf7d47a52009-08-26 20:46:33 +00001178class VtableInfo {
1179public:
1180 typedef VtableBuilder::Index_t Index_t;
1181private:
1182 CodeGenModule &CGM; // Per-module state.
1183 /// Index_t - Vtable index type.
1184 typedef llvm::DenseMap<const CXXMethodDecl *, Index_t> ElTy;
1185 typedef llvm::DenseMap<const CXXRecordDecl *, ElTy *> MapTy;
1186 // FIXME: Move to Context.
1187 static MapTy IndexFor;
1188public:
1189 VtableInfo(CodeGenModule &cgm) : CGM(cgm) { }
1190 void register_index(const CXXRecordDecl *RD, const ElTy &e) {
1191 assert(IndexFor.find(RD) == IndexFor.end() && "Don't compute vtbl twice");
1192 // We own a copy of this, it will go away shortly.
1193 new ElTy (e);
1194 IndexFor[RD] = new ElTy (e);
1195 }
1196 Index_t lookup(const CXXMethodDecl *MD) {
1197 const CXXRecordDecl *RD = MD->getParent();
1198 MapTy::iterator I = IndexFor.find(RD);
1199 if (I == IndexFor.end()) {
1200 std::vector<llvm::Constant *> methods;
1201 VtableBuilder b(methods, RD, CGM);
Mike Stump3cd18e42009-09-05 09:24:43 +00001202 b.GenerateVtableForBase(RD);
Mike Stump900acd32009-09-05 08:07:32 +00001203 b.GenerateVtableForVBases(RD);
Mike Stumpf7d47a52009-08-26 20:46:33 +00001204 register_index(RD, b.getIndex());
1205 I = IndexFor.find(RD);
1206 }
1207 assert(I->second->find(MD)!=I->second->end() && "Can't find vtable index");
1208 return (*I->second)[MD];
1209 }
1210};
1211
1212// FIXME: Move to Context.
1213VtableInfo::MapTy VtableInfo::IndexFor;
1214
Mike Stump7e8c9932009-07-31 18:25:34 +00001215llvm::Value *CodeGenFunction::GenerateVtable(const CXXRecordDecl *RD) {
Mike Stump7e8c9932009-07-31 18:25:34 +00001216 llvm::SmallString<256> OutName;
1217 llvm::raw_svector_ostream Out(OutName);
1218 QualType ClassTy;
Mike Stumpe7545622009-08-07 18:05:12 +00001219 ClassTy = getContext().getTagDeclType(RD);
Mike Stump7e8c9932009-07-31 18:25:34 +00001220 mangleCXXVtable(ClassTy, getContext(), Out);
Mike Stumpd0672782009-07-31 21:43:43 +00001221 llvm::GlobalVariable::LinkageTypes linktype;
1222 linktype = llvm::GlobalValue::WeakAnyLinkage;
1223 std::vector<llvm::Constant *> methods;
Mike Stumpc57b8272009-08-16 01:46:26 +00001224 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
Mike Stumpf0415ae2009-09-05 11:28:33 +00001225 int64_t AddressPoint;
Mike Stump8b82eeb2009-08-05 22:37:18 +00001226
Mike Stump86a859e2009-08-19 18:10:47 +00001227 VtableBuilder b(methods, RD, CGM);
Mike Stump7bae1282009-08-18 21:30:21 +00001228
Mike Stumpc57b8272009-08-16 01:46:26 +00001229 // First comes the vtables for all the non-virtual bases...
Mike Stumpf0415ae2009-09-05 11:28:33 +00001230 AddressPoint = b.GenerateVtableForBase(RD);
Mike Stump42368bb2009-08-14 01:44:03 +00001231
Mike Stumpc57b8272009-08-16 01:46:26 +00001232 // then the vtables for all the virtual bases.
Mike Stump900acd32009-09-05 08:07:32 +00001233 b.GenerateVtableForVBases(RD);
Mike Stumpf3371782009-08-04 21:58:42 +00001234
Mike Stumpd0672782009-07-31 21:43:43 +00001235 llvm::Constant *C;
1236 llvm::ArrayType *type = llvm::ArrayType::get(Ptr8Ty, methods.size());
1237 C = llvm::ConstantArray::get(type, methods);
1238 llvm::Value *vtable = new llvm::GlobalVariable(CGM.getModule(), type, true,
Daniel Dunbar0433a022009-08-19 20:04:03 +00001239 linktype, C, Out.str());
Mike Stump7e8c9932009-07-31 18:25:34 +00001240 vtable = Builder.CreateBitCast(vtable, Ptr8Ty);
Mike Stump7e8c9932009-07-31 18:25:34 +00001241 vtable = Builder.CreateGEP(vtable,
Mike Stumpc57b8272009-08-16 01:46:26 +00001242 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
Mike Stumpf0415ae2009-09-05 11:28:33 +00001243 AddressPoint*LLVMPointerWidth/8));
Mike Stump7e8c9932009-07-31 18:25:34 +00001244 return vtable;
1245}
1246
Mike Stumpf7d47a52009-08-26 20:46:33 +00001247// FIXME: move to Context
1248static VtableInfo *vtableinfo;
1249
Mike Stumpd5b15562009-09-04 18:27:16 +00001250llvm::Constant *CodeGenFunction::GenerateThunk(llvm::Function *Fn,
1251 const CXXMethodDecl *MD,
Mike Stump58256412009-09-05 07:20:32 +00001252 bool Extern, int64_t nv,
1253 int64_t v) {
Mike Stumpd5b15562009-09-04 18:27:16 +00001254 QualType R = MD->getType()->getAsFunctionType()->getResultType();
1255
1256 FunctionArgList Args;
1257 ImplicitParamDecl *ThisDecl =
1258 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
1259 MD->getThisType(getContext()));
1260 Args.push_back(std::make_pair(ThisDecl, ThisDecl->getType()));
1261 for (FunctionDecl::param_const_iterator i = MD->param_begin(),
1262 e = MD->param_end();
1263 i != e; ++i) {
1264 ParmVarDecl *D = *i;
1265 Args.push_back(std::make_pair(D, D->getType()));
1266 }
1267 IdentifierInfo *II
1268 = &CGM.getContext().Idents.get("__thunk_named_foo_");
1269 FunctionDecl *FD = FunctionDecl::Create(getContext(),
1270 getContext().getTranslationUnitDecl(),
1271 SourceLocation(), II, R, 0,
1272 Extern
1273 ? FunctionDecl::Extern
1274 : FunctionDecl::Static,
1275 false, true);
1276 StartFunction(FD, R, Fn, Args, SourceLocation());
1277 // FIXME: generate body
1278 FinishFunction();
1279 return Fn;
1280}
1281
Mike Stump58256412009-09-05 07:20:32 +00001282llvm::Constant *CodeGenModule::BuildThunk(const CXXMethodDecl *MD, bool Extern,
1283 int64_t nv, int64_t v) {
Mike Stumpd5b15562009-09-04 18:27:16 +00001284 llvm::SmallString<256> OutName;
1285 llvm::raw_svector_ostream Out(OutName);
Mike Stump58256412009-09-05 07:20:32 +00001286 mangleThunk(MD, nv, v, getContext(), Out);
Mike Stumpd5b15562009-09-04 18:27:16 +00001287 llvm::GlobalVariable::LinkageTypes linktype;
1288 linktype = llvm::GlobalValue::WeakAnyLinkage;
1289 if (!Extern)
1290 linktype = llvm::GlobalValue::InternalLinkage;
1291 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0);
1292 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
1293 const llvm::FunctionType *FTy =
1294 getTypes().GetFunctionType(getTypes().getFunctionInfo(MD),
1295 FPT->isVariadic());
1296
1297 llvm::Function *Fn = llvm::Function::Create(FTy, linktype, Out.str(),
1298 &getModule());
Mike Stump58256412009-09-05 07:20:32 +00001299 CodeGenFunction(*this).GenerateThunk(Fn, MD, Extern, nv, v);
Mike Stumpd5b15562009-09-04 18:27:16 +00001300 // Fn = Builder.CreateBitCast(Fn, Ptr8Ty);
1301 llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty);
1302 return m;
1303}
1304
Mike Stumpf7d47a52009-08-26 20:46:33 +00001305llvm::Value *
1306CodeGenFunction::BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *&This,
1307 const llvm::Type *Ty) {
1308 // FIXME: If we know the dynamic type, we don't have to do a virtual dispatch.
Mike Stump25cf7602009-09-09 15:08:12 +00001309
Mike Stumpf7d47a52009-08-26 20:46:33 +00001310 // FIXME: move to Context
1311 if (vtableinfo == 0)
1312 vtableinfo = new VtableInfo(CGM);
1313
1314 VtableInfo::Index_t Idx = vtableinfo->lookup(MD);
1315
1316 Ty = llvm::PointerType::get(Ty, 0);
1317 Ty = llvm::PointerType::get(Ty, 0);
1318 Ty = llvm::PointerType::get(Ty, 0);
1319 llvm::Value *vtbl = Builder.CreateBitCast(This, Ty);
1320 vtbl = Builder.CreateLoad(vtbl);
1321 llvm::Value *vfn = Builder.CreateConstInBoundsGEP1_64(vtbl,
1322 Idx, "vfn");
1323 vfn = Builder.CreateLoad(vfn);
1324 return vfn;
1325}
1326
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001327/// EmitClassAggrMemberwiseCopy - This routine generates code to copy a class
1328/// array of objects from SrcValue to DestValue. Copying can be either a bitwise
1329/// copy or via a copy constructor call.
Fariborz Jahanian58a7eca2009-08-26 00:23:27 +00001330// FIXME. Consolidate this with EmitCXXAggrConstructorCall.
Mike Stump25cf7602009-09-09 15:08:12 +00001331void CodeGenFunction::EmitClassAggrMemberwiseCopy(llvm::Value *Dest,
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001332 llvm::Value *Src,
1333 const ArrayType *Array,
Mike Stump25cf7602009-09-09 15:08:12 +00001334 const CXXRecordDecl *BaseClassDecl,
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001335 QualType Ty) {
1336 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1337 assert(CA && "VLA cannot be copied over");
1338 bool BitwiseCopy = BaseClassDecl->hasTrivialCopyConstructor();
Mike Stump25cf7602009-09-09 15:08:12 +00001339
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001340 // Create a temporary for the loop index and initialize it with 0.
1341 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1342 "loop.index");
Mike Stump25cf7602009-09-09 15:08:12 +00001343 llvm::Value* zeroConstant =
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001344 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
1345 Builder.CreateStore(zeroConstant, IndexPtr, false);
1346 // Start the loop with a block that tests the condition.
1347 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1348 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Mike Stump25cf7602009-09-09 15:08:12 +00001349
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001350 EmitBlock(CondBlock);
Mike Stump25cf7602009-09-09 15:08:12 +00001351
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001352 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1353 // Generate: if (loop-index < number-of-elements fall to the loop body,
1354 // otherwise, go to the block after the for-loop.
1355 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
Mike Stump25cf7602009-09-09 15:08:12 +00001356 llvm::Value * NumElementsPtr =
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001357 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1358 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
Mike Stump25cf7602009-09-09 15:08:12 +00001359 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001360 "isless");
1361 // If the condition is true, execute the body.
1362 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
Mike Stump25cf7602009-09-09 15:08:12 +00001363
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001364 EmitBlock(ForBody);
1365 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1366 // Inside the loop body, emit the constructor call on the array element.
1367 Counter = Builder.CreateLoad(IndexPtr);
1368 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1369 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1370 if (BitwiseCopy)
1371 EmitAggregateCopy(Dest, Src, Ty);
Mike Stump25cf7602009-09-09 15:08:12 +00001372 else if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001373 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
Mike Stump25cf7602009-09-09 15:08:12 +00001374 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001375 Ctor_Complete);
1376 CallArgList CallArgs;
1377 // Push the this (Dest) ptr.
1378 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1379 BaseCopyCtor->getThisType(getContext())));
Mike Stump25cf7602009-09-09 15:08:12 +00001380
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001381 // Push the Src ptr.
1382 CallArgs.push_back(std::make_pair(RValue::get(Src),
1383 BaseCopyCtor->getParamDecl(0)->getType()));
Mike Stump25cf7602009-09-09 15:08:12 +00001384 QualType ResultType =
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001385 BaseCopyCtor->getType()->getAsFunctionType()->getResultType();
1386 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1387 Callee, CallArgs, BaseCopyCtor);
1388 }
1389 EmitBlock(ContinueBlock);
Mike Stump25cf7602009-09-09 15:08:12 +00001390
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001391 // Emit the increment of the loop counter.
1392 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1393 Counter = Builder.CreateLoad(IndexPtr);
1394 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1395 Builder.CreateStore(NextVal, IndexPtr, false);
Mike Stump25cf7602009-09-09 15:08:12 +00001396
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001397 // Finally, branch back up to the condition for the next iteration.
1398 EmitBranch(CondBlock);
Mike Stump25cf7602009-09-09 15:08:12 +00001399
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001400 // Emit the fall-through block.
1401 EmitBlock(AfterFor, true);
1402}
1403
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001404/// EmitClassAggrCopyAssignment - This routine generates code to assign a class
Mike Stump25cf7602009-09-09 15:08:12 +00001405/// array of objects from SrcValue to DestValue. Assignment can be either a
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001406/// bitwise assignment or via a copy assignment operator function call.
1407/// FIXME. This can be consolidated with EmitClassAggrMemberwiseCopy
Mike Stump25cf7602009-09-09 15:08:12 +00001408void CodeGenFunction::EmitClassAggrCopyAssignment(llvm::Value *Dest,
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001409 llvm::Value *Src,
1410 const ArrayType *Array,
Mike Stump25cf7602009-09-09 15:08:12 +00001411 const CXXRecordDecl *BaseClassDecl,
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001412 QualType Ty) {
1413 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1414 assert(CA && "VLA cannot be asssigned");
1415 bool BitwiseAssign = BaseClassDecl->hasTrivialCopyAssignment();
Mike Stump25cf7602009-09-09 15:08:12 +00001416
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001417 // Create a temporary for the loop index and initialize it with 0.
1418 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
1419 "loop.index");
Mike Stump25cf7602009-09-09 15:08:12 +00001420 llvm::Value* zeroConstant =
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001421 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
1422 Builder.CreateStore(zeroConstant, IndexPtr, false);
1423 // Start the loop with a block that tests the condition.
1424 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1425 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Mike Stump25cf7602009-09-09 15:08:12 +00001426
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001427 EmitBlock(CondBlock);
Mike Stump25cf7602009-09-09 15:08:12 +00001428
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001429 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1430 // Generate: if (loop-index < number-of-elements fall to the loop body,
1431 // otherwise, go to the block after the for-loop.
1432 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
Mike Stump25cf7602009-09-09 15:08:12 +00001433 llvm::Value * NumElementsPtr =
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001434 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
1435 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
Mike Stump25cf7602009-09-09 15:08:12 +00001436 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001437 "isless");
1438 // If the condition is true, execute the body.
1439 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
Mike Stump25cf7602009-09-09 15:08:12 +00001440
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001441 EmitBlock(ForBody);
1442 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1443 // Inside the loop body, emit the assignment operator call on array element.
1444 Counter = Builder.CreateLoad(IndexPtr);
1445 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
1446 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
1447 const CXXMethodDecl *MD = 0;
1448 if (BitwiseAssign)
1449 EmitAggregateCopy(Dest, Src, Ty);
1450 else {
1451 bool hasCopyAssign = BaseClassDecl->hasConstCopyAssignment(getContext(),
1452 MD);
1453 assert(hasCopyAssign && "EmitClassAggrCopyAssignment - No user assign");
1454 (void)hasCopyAssign;
1455 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
1456 const llvm::Type *LTy =
1457 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1458 FPT->isVariadic());
1459 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), LTy);
Mike Stump25cf7602009-09-09 15:08:12 +00001460
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001461 CallArgList CallArgs;
1462 // Push the this (Dest) ptr.
1463 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1464 MD->getThisType(getContext())));
Mike Stump25cf7602009-09-09 15:08:12 +00001465
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001466 // Push the Src ptr.
1467 CallArgs.push_back(std::make_pair(RValue::get(Src),
1468 MD->getParamDecl(0)->getType()));
Mike Stumpd5b15562009-09-04 18:27:16 +00001469 QualType ResultType = MD->getType()->getAsFunctionType()->getResultType();
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001470 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1471 Callee, CallArgs, MD);
1472 }
1473 EmitBlock(ContinueBlock);
Mike Stump25cf7602009-09-09 15:08:12 +00001474
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001475 // Emit the increment of the loop counter.
1476 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
1477 Counter = Builder.CreateLoad(IndexPtr);
1478 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1479 Builder.CreateStore(NextVal, IndexPtr, false);
Mike Stump25cf7602009-09-09 15:08:12 +00001480
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001481 // Finally, branch back up to the condition for the next iteration.
1482 EmitBranch(CondBlock);
Mike Stump25cf7602009-09-09 15:08:12 +00001483
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001484 // Emit the fall-through block.
1485 EmitBlock(AfterFor, true);
1486}
1487
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001488/// EmitClassMemberwiseCopy - This routine generates code to copy a class
1489/// object from SrcValue to DestValue. Copying can be either a bitwise copy
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001490/// or via a copy constructor call.
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001491void CodeGenFunction::EmitClassMemberwiseCopy(
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001492 llvm::Value *Dest, llvm::Value *Src,
Mike Stump25cf7602009-09-09 15:08:12 +00001493 const CXXRecordDecl *ClassDecl,
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001494 const CXXRecordDecl *BaseClassDecl, QualType Ty) {
1495 if (ClassDecl) {
1496 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
1497 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
1498 }
1499 if (BaseClassDecl->hasTrivialCopyConstructor()) {
1500 EmitAggregateCopy(Dest, Src, Ty);
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001501 return;
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001502 }
Mike Stump25cf7602009-09-09 15:08:12 +00001503
1504 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanianfbe08772009-08-08 00:59:58 +00001505 BaseClassDecl->getCopyConstructor(getContext(), 0)) {
Mike Stump25cf7602009-09-09 15:08:12 +00001506 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor,
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001507 Ctor_Complete);
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001508 CallArgList CallArgs;
1509 // Push the this (Dest) ptr.
1510 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1511 BaseCopyCtor->getThisType(getContext())));
Mike Stump25cf7602009-09-09 15:08:12 +00001512
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001513 // Push the Src ptr.
1514 CallArgs.push_back(std::make_pair(RValue::get(Src),
Fariborz Jahanian0dfaec42009-08-10 17:20:45 +00001515 BaseCopyCtor->getParamDecl(0)->getType()));
Mike Stump25cf7602009-09-09 15:08:12 +00001516 QualType ResultType =
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001517 BaseCopyCtor->getType()->getAsFunctionType()->getResultType();
1518 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1519 Callee, CallArgs, BaseCopyCtor);
1520 }
1521}
Fariborz Jahaniane39fab62009-08-10 18:46:38 +00001522
Fariborz Jahanian04500242009-08-12 23:34:46 +00001523/// EmitClassCopyAssignment - This routine generates code to copy assign a class
Mike Stump25cf7602009-09-09 15:08:12 +00001524/// object from SrcValue to DestValue. Assignment can be either a bitwise
Fariborz Jahanian04500242009-08-12 23:34:46 +00001525/// assignment of via an assignment operator call.
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001526// FIXME. Consolidate this with EmitClassMemberwiseCopy as they share a lot.
Fariborz Jahanian04500242009-08-12 23:34:46 +00001527void CodeGenFunction::EmitClassCopyAssignment(
1528 llvm::Value *Dest, llvm::Value *Src,
Mike Stump25cf7602009-09-09 15:08:12 +00001529 const CXXRecordDecl *ClassDecl,
1530 const CXXRecordDecl *BaseClassDecl,
Fariborz Jahanian04500242009-08-12 23:34:46 +00001531 QualType Ty) {
1532 if (ClassDecl) {
1533 Dest = AddressCXXOfBaseClass(Dest, ClassDecl, BaseClassDecl);
1534 Src = AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl) ;
1535 }
1536 if (BaseClassDecl->hasTrivialCopyAssignment()) {
1537 EmitAggregateCopy(Dest, Src, Ty);
1538 return;
1539 }
Mike Stump25cf7602009-09-09 15:08:12 +00001540
Fariborz Jahanian04500242009-08-12 23:34:46 +00001541 const CXXMethodDecl *MD = 0;
Mike Stump25cf7602009-09-09 15:08:12 +00001542 bool ConstCopyAssignOp = BaseClassDecl->hasConstCopyAssignment(getContext(),
Fariborz Jahanian84bd6532009-08-13 00:53:36 +00001543 MD);
1544 assert(ConstCopyAssignOp && "EmitClassCopyAssignment - missing copy assign");
1545 (void)ConstCopyAssignOp;
1546
1547 const FunctionProtoType *FPT = MD->getType()->getAsFunctionProtoType();
Mike Stump25cf7602009-09-09 15:08:12 +00001548 const llvm::Type *LTy =
1549 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
Fariborz Jahanian84bd6532009-08-13 00:53:36 +00001550 FPT->isVariadic());
1551 llvm::Constant *Callee = CGM.GetAddrOfFunction(GlobalDecl(MD), LTy);
Mike Stump25cf7602009-09-09 15:08:12 +00001552
Fariborz Jahanian84bd6532009-08-13 00:53:36 +00001553 CallArgList CallArgs;
1554 // Push the this (Dest) ptr.
1555 CallArgs.push_back(std::make_pair(RValue::get(Dest),
1556 MD->getThisType(getContext())));
Mike Stump25cf7602009-09-09 15:08:12 +00001557
Fariborz Jahanian84bd6532009-08-13 00:53:36 +00001558 // Push the Src ptr.
1559 CallArgs.push_back(std::make_pair(RValue::get(Src),
1560 MD->getParamDecl(0)->getType()));
Mike Stump25cf7602009-09-09 15:08:12 +00001561 QualType ResultType =
Fariborz Jahanian84bd6532009-08-13 00:53:36 +00001562 MD->getType()->getAsFunctionType()->getResultType();
1563 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs),
1564 Callee, CallArgs, MD);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001565}
1566
Fariborz Jahaniane39fab62009-08-10 18:46:38 +00001567/// SynthesizeDefaultConstructor - synthesize a default constructor
Mike Stump25cf7602009-09-09 15:08:12 +00001568void
Fariborz Jahaniane39fab62009-08-10 18:46:38 +00001569CodeGenFunction::SynthesizeDefaultConstructor(const CXXConstructorDecl *CD,
1570 const FunctionDecl *FD,
1571 llvm::Function *Fn,
1572 const FunctionArgList &Args) {
1573 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
1574 EmitCtorPrologue(CD);
1575 FinishFunction();
1576}
1577
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001578/// SynthesizeCXXCopyConstructor - This routine implicitly defines body of a copy
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001579/// constructor, in accordance with section 12.8 (p7 and p8) of C++03
Mike Stump25cf7602009-09-09 15:08:12 +00001580/// The implicitly-defined copy constructor for class X performs a memberwise
1581/// copy of its subobjects. The order of copying is the same as the order
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001582/// of initialization of bases and members in a user-defined constructor
1583/// Each subobject is copied in the manner appropriate to its type:
Mike Stump25cf7602009-09-09 15:08:12 +00001584/// if the subobject is of class type, the copy constructor for the class is
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001585/// used;
Mike Stump25cf7602009-09-09 15:08:12 +00001586/// if the subobject is an array, each element is copied, in the manner
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001587/// appropriate to the element type;
Mike Stump25cf7602009-09-09 15:08:12 +00001588/// if the subobject is of scalar type, the built-in assignment operator is
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001589/// used.
Mike Stump25cf7602009-09-09 15:08:12 +00001590/// Virtual base class subobjects shall be copied only once by the
1591/// implicitly-defined copy constructor
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001592
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001593void CodeGenFunction::SynthesizeCXXCopyConstructor(const CXXConstructorDecl *CD,
1594 const FunctionDecl *FD,
1595 llvm::Function *Fn,
Fariborz Jahanianfc27d292009-08-07 23:51:33 +00001596 const FunctionArgList &Args) {
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001597 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1598 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001599 "SynthesizeCXXCopyConstructor - copy constructor has definition already");
1600 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
Mike Stump25cf7602009-09-09 15:08:12 +00001601
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001602 FunctionArgList::const_iterator i = Args.begin();
1603 const VarDecl *ThisArg = i->first;
1604 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1605 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1606 const VarDecl *SrcArg = (i+1)->first;
1607 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1608 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
Mike Stump25cf7602009-09-09 15:08:12 +00001609
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001610 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1611 Base != ClassDecl->bases_end(); ++Base) {
1612 // FIXME. copy constrution of virtual base NYI
1613 if (Base->isVirtual())
1614 continue;
Mike Stump25cf7602009-09-09 15:08:12 +00001615
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001616 CXXRecordDecl *BaseClassDecl
1617 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahaniancefe5922009-08-08 23:32:22 +00001618 EmitClassMemberwiseCopy(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1619 Base->getType());
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001620 }
Mike Stump25cf7602009-09-09 15:08:12 +00001621
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001622 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1623 FieldEnd = ClassDecl->field_end();
1624 Field != FieldEnd; ++Field) {
1625 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Mike Stump25cf7602009-09-09 15:08:12 +00001626 const ConstantArrayType *Array =
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001627 getContext().getAsConstantArrayType(FieldType);
1628 if (Array)
1629 FieldType = getContext().getBaseElementType(FieldType);
Mike Stump25cf7602009-09-09 15:08:12 +00001630
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001631 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1632 CXXRecordDecl *FieldClassDecl
1633 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1634 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1635 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001636 if (Array) {
1637 const llvm::Type *BasePtr = ConvertType(FieldType);
1638 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Mike Stump25cf7602009-09-09 15:08:12 +00001639 llvm::Value *DestBaseAddrPtr =
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001640 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
Mike Stump25cf7602009-09-09 15:08:12 +00001641 llvm::Value *SrcBaseAddrPtr =
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001642 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1643 EmitClassAggrMemberwiseCopy(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1644 FieldClassDecl, FieldType);
1645 }
Mike Stump25cf7602009-09-09 15:08:12 +00001646 else
1647 EmitClassMemberwiseCopy(LHS.getAddress(), RHS.getAddress(),
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001648 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001649 continue;
1650 }
Fariborz Jahanian08d99e92009-08-10 18:34:26 +00001651 // Do a built-in assignment of scalar data members.
1652 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1653 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1654 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1655 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanian5e778e32009-08-08 00:15:41 +00001656 }
Fariborz Jahanianab840aa2009-08-08 19:31:03 +00001657 FinishFunction();
Mike Stump25cf7602009-09-09 15:08:12 +00001658}
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001659
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001660/// SynthesizeCXXCopyAssignment - Implicitly define copy assignment operator.
Mike Stump25cf7602009-09-09 15:08:12 +00001661/// Before the implicitly-declared copy assignment operator for a class is
1662/// implicitly defined, all implicitly- declared copy assignment operators for
1663/// its direct base classes and its nonstatic data members shall have been
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001664/// implicitly defined. [12.8-p12]
Mike Stump25cf7602009-09-09 15:08:12 +00001665/// The implicitly-defined copy assignment operator for class X performs
1666/// memberwise assignment of its subob- jects. The direct base classes of X are
1667/// assigned first, in the order of their declaration in
1668/// the base-specifier-list, and then the immediate nonstatic data members of X
1669/// are assigned, in the order in which they were declared in the class
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001670/// definition.Each subobject is assigned in the manner appropriate to its type:
Mike Stump25cf7602009-09-09 15:08:12 +00001671/// if the subobject is of class type, the copy assignment operator for the
1672/// class is used (as if by explicit qualification; that is, ignoring any
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001673/// possible virtual overriding functions in more derived classes);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001674///
Mike Stump25cf7602009-09-09 15:08:12 +00001675/// if the subobject is an array, each element is assigned, in the manner
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001676/// appropriate to the element type;
Fariborz Jahanian04500242009-08-12 23:34:46 +00001677///
Mike Stump25cf7602009-09-09 15:08:12 +00001678/// if the subobject is of scalar type, the built-in assignment operator is
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001679/// used.
1680void CodeGenFunction::SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD,
1681 const FunctionDecl *FD,
1682 llvm::Function *Fn,
1683 const FunctionArgList &Args) {
Fariborz Jahanian04500242009-08-12 23:34:46 +00001684
1685 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
1686 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
1687 "SynthesizeCXXCopyAssignment - copy assignment has user declaration");
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001688 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
Mike Stump25cf7602009-09-09 15:08:12 +00001689
Fariborz Jahanian04500242009-08-12 23:34:46 +00001690 FunctionArgList::const_iterator i = Args.begin();
1691 const VarDecl *ThisArg = i->first;
1692 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
1693 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
1694 const VarDecl *SrcArg = (i+1)->first;
1695 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
1696 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
Mike Stump25cf7602009-09-09 15:08:12 +00001697
Fariborz Jahanian04500242009-08-12 23:34:46 +00001698 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
1699 Base != ClassDecl->bases_end(); ++Base) {
1700 // FIXME. copy assignment of virtual base NYI
1701 if (Base->isVirtual())
1702 continue;
Mike Stump25cf7602009-09-09 15:08:12 +00001703
Fariborz Jahanian04500242009-08-12 23:34:46 +00001704 CXXRecordDecl *BaseClassDecl
1705 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1706 EmitClassCopyAssignment(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
1707 Base->getType());
1708 }
Mike Stump25cf7602009-09-09 15:08:12 +00001709
Fariborz Jahanian04500242009-08-12 23:34:46 +00001710 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1711 FieldEnd = ClassDecl->field_end();
1712 Field != FieldEnd; ++Field) {
1713 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Mike Stump25cf7602009-09-09 15:08:12 +00001714 const ConstantArrayType *Array =
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001715 getContext().getAsConstantArrayType(FieldType);
1716 if (Array)
1717 FieldType = getContext().getBaseElementType(FieldType);
Mike Stump25cf7602009-09-09 15:08:12 +00001718
Fariborz Jahanian04500242009-08-12 23:34:46 +00001719 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
1720 CXXRecordDecl *FieldClassDecl
1721 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1722 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1723 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001724 if (Array) {
1725 const llvm::Type *BasePtr = ConvertType(FieldType);
1726 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1727 llvm::Value *DestBaseAddrPtr =
1728 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1729 llvm::Value *SrcBaseAddrPtr =
1730 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
1731 EmitClassAggrCopyAssignment(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
1732 FieldClassDecl, FieldType);
1733 }
1734 else
Mike Stump25cf7602009-09-09 15:08:12 +00001735 EmitClassCopyAssignment(LHS.getAddress(), RHS.getAddress(),
Fariborz Jahanianccd93282009-08-21 22:34:55 +00001736 0 /*ClassDecl*/, FieldClassDecl, FieldType);
Fariborz Jahanian04500242009-08-12 23:34:46 +00001737 continue;
1738 }
1739 // Do a built-in assignment of scalar data members.
1740 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
1741 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0);
1742 RValue RVRHS = EmitLoadOfLValue(RHS, FieldType);
1743 EmitStoreThroughLValue(RVRHS, LHS, FieldType);
Fariborz Jahanianc47460d2009-08-14 00:01:54 +00001744 }
Mike Stump25cf7602009-09-09 15:08:12 +00001745
Fariborz Jahanianc47460d2009-08-14 00:01:54 +00001746 // return *this;
1747 Builder.CreateStore(LoadOfThis, ReturnValue);
Mike Stump25cf7602009-09-09 15:08:12 +00001748
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001749 FinishFunction();
Mike Stump25cf7602009-09-09 15:08:12 +00001750}
Fariborz Jahanian5e050b82009-08-07 20:22:40 +00001751
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001752/// EmitCtorPrologue - This routine generates necessary code to initialize
1753/// base classes and non-static data members belonging to this constructor.
Anders Carlsson4bdc0332009-09-01 18:33:46 +00001754/// FIXME: This needs to take a CXXCtorType.
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001755void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD) {
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001756 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
Mike Stump05207212009-08-06 13:41:24 +00001757 // FIXME: Add vbase initialization
Mike Stump7e8c9932009-07-31 18:25:34 +00001758 llvm::Value *LoadOfThis = 0;
Mike Stump25cf7602009-09-09 15:08:12 +00001759
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001760 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001761 E = CD->init_end();
1762 B != E; ++B) {
1763 CXXBaseOrMemberInitializer *Member = (*B);
1764 if (Member->isBaseInitializer()) {
Mike Stump7e8c9932009-07-31 18:25:34 +00001765 LoadOfThis = LoadCXXThis();
Fariborz Jahanian70277012009-07-28 18:09:28 +00001766 Type *BaseType = Member->getBaseClass();
Mike Stump25cf7602009-09-09 15:08:12 +00001767 CXXRecordDecl *BaseClassDecl =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001768 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
Mike Stump25cf7602009-09-09 15:08:12 +00001769 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
Fariborz Jahanian70277012009-07-28 18:09:28 +00001770 BaseClassDecl);
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001771 EmitCXXConstructorCall(Member->getConstructor(),
1772 Ctor_Complete, V,
Mike Stump25cf7602009-09-09 15:08:12 +00001773 Member->const_arg_begin(),
Fariborz Jahaniana0107de2009-07-25 21:12:28 +00001774 Member->const_arg_end());
Mike Stump487ce382009-07-30 22:28:39 +00001775 } else {
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001776 // non-static data member initilaizers.
1777 FieldDecl *Field = Member->getMember();
1778 QualType FieldType = getContext().getCanonicalType((Field)->getType());
Mike Stump25cf7602009-09-09 15:08:12 +00001779 const ConstantArrayType *Array =
Fariborz Jahanian86328d22009-08-21 18:30:26 +00001780 getContext().getAsConstantArrayType(FieldType);
Fariborz Jahanianc7b8d9a2009-08-21 17:09:38 +00001781 if (Array)
1782 FieldType = getContext().getBaseElementType(FieldType);
Mike Stump25cf7602009-09-09 15:08:12 +00001783
Mike Stump7e8c9932009-07-31 18:25:34 +00001784 LoadOfThis = LoadCXXThis();
Eli Friedman13bce3d2009-08-29 20:58:20 +00001785 LValue LHS;
1786 if (FieldType->isReferenceType()) {
1787 // FIXME: This is really ugly; should be refactored somehow
1788 unsigned idx = CGM.getTypes().getLLVMFieldNo(Field);
1789 llvm::Value *V = Builder.CreateStructGEP(LoadOfThis, idx, "tmp");
1790 LHS = LValue::MakeAddr(V, FieldType.getCVRQualifiers(),
1791 QualType::GCNone, FieldType.getAddressSpace());
1792 } else {
1793 LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
1794 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001795 if (FieldType->getAs<RecordType>()) {
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +00001796 if (!Field->isAnonymousStructOrUnion()) {
Mike Stump25cf7602009-09-09 15:08:12 +00001797 assert(Member->getConstructor() &&
Fariborz Jahanian56baceb2009-07-24 17:57:02 +00001798 "EmitCtorPrologue - no constructor to initialize member");
Fariborz Jahanianc7b8d9a2009-08-21 17:09:38 +00001799 if (Array) {
1800 const llvm::Type *BasePtr = ConvertType(FieldType);
1801 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Mike Stump25cf7602009-09-09 15:08:12 +00001802 llvm::Value *BaseAddrPtr =
Fariborz Jahanianc7b8d9a2009-08-21 17:09:38 +00001803 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
Mike Stump25cf7602009-09-09 15:08:12 +00001804 EmitCXXAggrConstructorCall(Member->getConstructor(),
Fariborz Jahanianc7b8d9a2009-08-21 17:09:38 +00001805 Array, BaseAddrPtr);
1806 }
1807 else
1808 EmitCXXConstructorCall(Member->getConstructor(),
1809 Ctor_Complete, LHS.getAddress(),
Mike Stump25cf7602009-09-09 15:08:12 +00001810 Member->const_arg_begin(),
Fariborz Jahanianc7b8d9a2009-08-21 17:09:38 +00001811 Member->const_arg_end());
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +00001812 continue;
1813 }
1814 else {
1815 // Initializing an anonymous union data member.
1816 FieldDecl *anonMember = Member->getAnonUnionMember();
Mike Stump25cf7602009-09-09 15:08:12 +00001817 LHS = EmitLValueForField(LHS.getAddress(), anonMember,
Anders Carlsson9e00ce72009-09-02 21:14:47 +00001818 /*IsUnion=*/true, 0);
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +00001819 FieldType = anonMember->getType();
1820 }
Fariborz Jahanian56baceb2009-07-24 17:57:02 +00001821 }
Mike Stump25cf7602009-09-09 15:08:12 +00001822
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001823 assert(Member->getNumArgs() == 1 && "Initializer count must be 1 only");
Fariborz Jahanian56baceb2009-07-24 17:57:02 +00001824 Expr *RhsExpr = *Member->arg_begin();
Eli Friedman13bce3d2009-08-29 20:58:20 +00001825 RValue RHS;
1826 if (FieldType->isReferenceType())
1827 RHS = EmitReferenceBindingToExpr(RhsExpr, FieldType,
1828 /*IsInitializer=*/true);
1829 else
1830 RHS = RValue::get(EmitScalarExpr(RhsExpr, true));
1831 EmitStoreThroughLValue(RHS, LHS, FieldType);
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001832 }
1833 }
Mike Stump7e8c9932009-07-31 18:25:34 +00001834
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001835 if (!CD->getNumBaseOrMemberInitializers() && !CD->isTrivial()) {
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001836 // Nontrivial default constructor with no initializer list. It may still
Mike Stump25cf7602009-09-09 15:08:12 +00001837 // have bases classes and/or contain non-static data members which require
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001838 // construction.
Mike Stump25cf7602009-09-09 15:08:12 +00001839 for (CXXRecordDecl::base_class_const_iterator Base =
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001840 ClassDecl->bases_begin();
1841 Base != ClassDecl->bases_end(); ++Base) {
1842 // FIXME. copy assignment of virtual base NYI
1843 if (Base->isVirtual())
1844 continue;
Mike Stump25cf7602009-09-09 15:08:12 +00001845
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001846 CXXRecordDecl *BaseClassDecl
1847 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1848 if (BaseClassDecl->hasTrivialConstructor())
1849 continue;
Mike Stump25cf7602009-09-09 15:08:12 +00001850 if (CXXConstructorDecl *BaseCX =
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001851 BaseClassDecl->getDefaultConstructor(getContext())) {
1852 LoadOfThis = LoadCXXThis();
1853 llvm::Value *V = AddressCXXOfBaseClass(LoadOfThis, ClassDecl,
1854 BaseClassDecl);
1855 EmitCXXConstructorCall(BaseCX, Ctor_Complete, V, 0, 0);
1856 }
1857 }
Mike Stump25cf7602009-09-09 15:08:12 +00001858
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001859 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1860 FieldEnd = ClassDecl->field_end();
1861 Field != FieldEnd; ++Field) {
1862 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Mike Stump25cf7602009-09-09 15:08:12 +00001863 const ConstantArrayType *Array =
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +00001864 getContext().getAsConstantArrayType(FieldType);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001865 if (Array)
1866 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001867 if (!FieldType->getAs<RecordType>() || Field->isAnonymousStructOrUnion())
1868 continue;
1869 const RecordType *ClassRec = FieldType->getAs<RecordType>();
Mike Stump25cf7602009-09-09 15:08:12 +00001870 CXXRecordDecl *MemberClassDecl =
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001871 dyn_cast<CXXRecordDecl>(ClassRec->getDecl());
1872 if (!MemberClassDecl || MemberClassDecl->hasTrivialConstructor())
1873 continue;
Mike Stump25cf7602009-09-09 15:08:12 +00001874 if (CXXConstructorDecl *MamberCX =
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001875 MemberClassDecl->getDefaultConstructor(getContext())) {
1876 LoadOfThis = LoadCXXThis();
1877 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0);
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +00001878 if (Array) {
1879 const llvm::Type *BasePtr = ConvertType(FieldType);
1880 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Mike Stump25cf7602009-09-09 15:08:12 +00001881 llvm::Value *BaseAddrPtr =
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +00001882 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1883 EmitCXXAggrConstructorCall(MamberCX, Array, BaseAddrPtr);
1884 }
1885 else
Mike Stump25cf7602009-09-09 15:08:12 +00001886 EmitCXXConstructorCall(MamberCX, Ctor_Complete, LHS.getAddress(),
Fariborz Jahanian2f4b91b2009-08-19 20:55:16 +00001887 0, 0);
Fariborz Jahanian63d6c232009-08-15 18:55:17 +00001888 }
1889 }
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001890 }
Mike Stump25cf7602009-09-09 15:08:12 +00001891
Mike Stump7e8c9932009-07-31 18:25:34 +00001892 // Initialize the vtable pointer
Mike Stumpeec46a72009-08-05 22:59:44 +00001893 if (ClassDecl->isDynamicClass()) {
Mike Stump7e8c9932009-07-31 18:25:34 +00001894 if (!LoadOfThis)
1895 LoadOfThis = LoadCXXThis();
1896 llvm::Value *VtableField;
1897 llvm::Type *Ptr8Ty, *PtrPtr8Ty;
Owen Anderson3f5cc0a2009-08-13 21:57:51 +00001898 Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0);
Mike Stump7e8c9932009-07-31 18:25:34 +00001899 PtrPtr8Ty = llvm::PointerType::get(Ptr8Ty, 0);
1900 VtableField = Builder.CreateBitCast(LoadOfThis, PtrPtr8Ty);
1901 llvm::Value *vtable = GenerateVtable(ClassDecl);
1902 Builder.CreateStore(vtable, VtableField);
1903 }
Fariborz Jahanian5400e022009-07-20 23:18:55 +00001904}
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001905
1906/// EmitDtorEpilogue - Emit all code that comes at the end of class's
Mike Stump25cf7602009-09-09 15:08:12 +00001907/// destructor. This is to call destructors on members and base classes
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001908/// in reverse order of their construction.
Anders Carlsson4bdc0332009-09-01 18:33:46 +00001909/// FIXME: This needs to take a CXXDtorType.
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001910void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD) {
1911 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(DD->getDeclContext());
Anders Carlssona82465d2009-09-01 21:12:16 +00001912 assert(!ClassDecl->getNumVBases() &&
1913 "FIXME: Destruction of virtual bases not supported");
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001914 (void)ClassDecl; // prevent warning.
Mike Stump25cf7602009-09-09 15:08:12 +00001915
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001916 for (CXXDestructorDecl::destr_const_iterator *B = DD->destr_begin(),
1917 *E = DD->destr_end(); B != E; ++B) {
1918 uintptr_t BaseOrMember = (*B);
1919 if (DD->isMemberToDestroy(BaseOrMember)) {
1920 FieldDecl *FD = DD->getMemberToDestroy(BaseOrMember);
1921 QualType FieldType = getContext().getCanonicalType((FD)->getType());
Mike Stump25cf7602009-09-09 15:08:12 +00001922 const ConstantArrayType *Array =
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001923 getContext().getAsConstantArrayType(FieldType);
1924 if (Array)
1925 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001926 const RecordType *RT = FieldType->getAs<RecordType>();
1927 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1928 if (FieldClassDecl->hasTrivialDestructor())
1929 continue;
1930 llvm::Value *LoadOfThis = LoadCXXThis();
1931 LValue LHS = EmitLValueForField(LoadOfThis, FD, false, 0);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001932 if (Array) {
1933 const llvm::Type *BasePtr = ConvertType(FieldType);
1934 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Mike Stump25cf7602009-09-09 15:08:12 +00001935 llvm::Value *BaseAddrPtr =
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001936 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
Mike Stump25cf7602009-09-09 15:08:12 +00001937 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001938 Array, BaseAddrPtr);
1939 }
1940 else
1941 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1942 Dtor_Complete, LHS.getAddress());
Mike Stump487ce382009-07-30 22:28:39 +00001943 } else {
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001944 const RecordType *RT =
1945 DD->getAnyBaseClassToDestroy(BaseOrMember)->getAs<RecordType>();
1946 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1947 if (BaseClassDecl->hasTrivialDestructor())
1948 continue;
Mike Stump25cf7602009-09-09 15:08:12 +00001949 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00001950 ClassDecl,BaseClassDecl);
1951 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
1952 Dtor_Complete, V);
1953 }
1954 }
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001955 if (DD->getNumBaseOrMemberDestructions() || DD->isTrivial())
1956 return;
1957 // Case of destructor synthesis with fields and base classes
Mike Stump25cf7602009-09-09 15:08:12 +00001958 // which have non-trivial destructors. They must be destructed in
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001959 // reverse order of their construction.
1960 llvm::SmallVector<FieldDecl *, 16> DestructedFields;
Mike Stump25cf7602009-09-09 15:08:12 +00001961
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001962 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1963 FieldEnd = ClassDecl->field_end();
1964 Field != FieldEnd; ++Field) {
1965 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001966 if (getContext().getAsConstantArrayType(FieldType))
1967 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001968 if (const RecordType *RT = FieldType->getAs<RecordType>()) {
1969 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1970 if (FieldClassDecl->hasTrivialDestructor())
1971 continue;
1972 DestructedFields.push_back(*Field);
1973 }
1974 }
1975 if (!DestructedFields.empty())
1976 for (int i = DestructedFields.size() -1; i >= 0; --i) {
1977 FieldDecl *Field = DestructedFields[i];
1978 QualType FieldType = Field->getType();
Mike Stump25cf7602009-09-09 15:08:12 +00001979 const ConstantArrayType *Array =
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001980 getContext().getAsConstantArrayType(FieldType);
1981 if (Array)
1982 FieldType = getContext().getBaseElementType(FieldType);
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001983 const RecordType *RT = FieldType->getAs<RecordType>();
1984 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1985 llvm::Value *LoadOfThis = LoadCXXThis();
1986 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001987 if (Array) {
1988 const llvm::Type *BasePtr = ConvertType(FieldType);
1989 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Mike Stump25cf7602009-09-09 15:08:12 +00001990 llvm::Value *BaseAddrPtr =
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001991 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
Mike Stump25cf7602009-09-09 15:08:12 +00001992 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
Fariborz Jahaniana0903aa2009-08-20 20:54:15 +00001993 Array, BaseAddrPtr);
1994 }
1995 else
1996 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1997 Dtor_Complete, LHS.getAddress());
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00001998 }
Mike Stump25cf7602009-09-09 15:08:12 +00001999
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00002000 llvm::SmallVector<CXXRecordDecl*, 4> DestructedBases;
2001 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
2002 Base != ClassDecl->bases_end(); ++Base) {
2003 // FIXME. copy assignment of virtual base NYI
2004 if (Base->isVirtual())
2005 continue;
Mike Stump25cf7602009-09-09 15:08:12 +00002006
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00002007 CXXRecordDecl *BaseClassDecl
2008 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2009 if (BaseClassDecl->hasTrivialDestructor())
2010 continue;
2011 DestructedBases.push_back(BaseClassDecl);
2012 }
2013 if (DestructedBases.empty())
2014 return;
2015 for (int i = DestructedBases.size() -1; i >= 0; --i) {
2016 CXXRecordDecl *BaseClassDecl = DestructedBases[i];
Mike Stump25cf7602009-09-09 15:08:12 +00002017 llvm::Value *V = AddressCXXOfBaseClass(LoadCXXThis(),
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00002018 ClassDecl,BaseClassDecl);
2019 EmitCXXDestructorCall(BaseClassDecl->getDestructor(getContext()),
2020 Dtor_Complete, V);
2021 }
Fariborz Jahanian36a0ec02009-07-30 17:49:11 +00002022}
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00002023
2024void CodeGenFunction::SynthesizeDefaultDestructor(const CXXDestructorDecl *CD,
2025 const FunctionDecl *FD,
2026 llvm::Function *Fn,
2027 const FunctionArgList &Args) {
Mike Stump25cf7602009-09-09 15:08:12 +00002028
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00002029 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
2030 assert(!ClassDecl->hasUserDeclaredDestructor() &&
2031 "SynthesizeDefaultDestructor - destructor has user declaration");
2032 (void) ClassDecl;
Mike Stump25cf7602009-09-09 15:08:12 +00002033
Fariborz Jahanian4252dbc2009-08-17 19:04:50 +00002034 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
2035 EmitDtorEpilogue(CD);
2036 FinishFunction();
Mike Stump25cf7602009-09-09 15:08:12 +00002037}