blob: 17571fccf08546001c009425e63c7269e57fd422 [file] [log] [blame]
Anders Carlsson5ec2e7c2009-12-10 00:16:00 +00001//===--- CGDeclCXX.cpp - Emit LLVM Code for C++ 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 code generation of C++ declarations
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
John McCall4c40d982010-08-31 07:33:07 +000015#include "CGCXXABI.h"
Chandler Carruth06057ce2010-06-15 23:19:56 +000016#include "clang/Frontend/CodeGenOptions.h"
Douglas Gregor86a3a032010-05-16 01:24:12 +000017#include "llvm/Intrinsics.h"
18
Anders Carlsson5ec2e7c2009-12-10 00:16:00 +000019using namespace clang;
20using namespace CodeGen;
21
Anders Carlssonfcbfdc12009-12-10 00:57:45 +000022static void EmitDeclInit(CodeGenFunction &CGF, const VarDecl &D,
23 llvm::Constant *DeclPtr) {
24 assert(D.hasGlobalStorage() && "VarDecl must have global storage!");
25 assert(!D.getType()->isReferenceType() &&
26 "Should not call EmitDeclInit on a reference!");
27
Anders Carlssonfcbfdc12009-12-10 00:57:45 +000028 ASTContext &Context = CGF.getContext();
29
Anders Carlsson5ec2e7c2009-12-10 00:16:00 +000030 const Expr *Init = D.getInit();
31 QualType T = D.getType();
Anders Carlssonfcbfdc12009-12-10 00:57:45 +000032 bool isVolatile = Context.getCanonicalType(T).isVolatileQualified();
Anders Carlsson5ec2e7c2009-12-10 00:16:00 +000033
Daniel Dunbar91a16fa2010-08-21 02:24:36 +000034 unsigned Alignment = Context.getDeclAlign(&D).getQuantity();
Anders Carlssonfcbfdc12009-12-10 00:57:45 +000035 if (!CGF.hasAggregateLLVMType(T)) {
36 llvm::Value *V = CGF.EmitScalarExpr(Init);
Daniel Dunbar91a16fa2010-08-21 02:24:36 +000037 CGF.EmitStoreOfScalar(V, DeclPtr, isVolatile, Alignment, T);
Anders Carlsson5ec2e7c2009-12-10 00:16:00 +000038 } else if (T->isAnyComplexType()) {
Anders Carlssonfcbfdc12009-12-10 00:57:45 +000039 CGF.EmitComplexExprIntoAddr(Init, DeclPtr, isVolatile);
Anders Carlsson5ec2e7c2009-12-10 00:16:00 +000040 } else {
John McCall558d2ab2010-09-15 10:14:12 +000041 CGF.EmitAggExpr(Init, AggValueSlot::forAddr(DeclPtr, isVolatile, true));
Anders Carlsson5ec2e7c2009-12-10 00:16:00 +000042 }
43}
44
John McCall5cd91b52010-09-08 01:44:27 +000045/// Emit code to cause the destruction of the given variable with
46/// static storage duration.
Douglas Gregorcc6a44b2010-05-05 15:38:32 +000047static void EmitDeclDestroy(CodeGenFunction &CGF, const VarDecl &D,
48 llvm::Constant *DeclPtr) {
49 CodeGenModule &CGM = CGF.CGM;
50 ASTContext &Context = CGF.getContext();
51
Douglas Gregorcc6a44b2010-05-05 15:38:32 +000052 QualType T = D.getType();
Douglas Gregorcc6a44b2010-05-05 15:38:32 +000053
John McCall85aca0f2010-07-30 04:56:58 +000054 // Drill down past array types.
Douglas Gregorcc6a44b2010-05-05 15:38:32 +000055 const ConstantArrayType *Array = Context.getAsConstantArrayType(T);
56 if (Array)
57 T = Context.getBaseElementType(Array);
58
John McCall85aca0f2010-07-30 04:56:58 +000059 /// If that's not a record, we're done.
60 /// FIXME: __attribute__((cleanup)) ?
Douglas Gregorcc6a44b2010-05-05 15:38:32 +000061 const RecordType *RT = T->getAs<RecordType>();
62 if (!RT)
63 return;
64
65 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
66 if (RD->hasTrivialDestructor())
67 return;
68
Douglas Gregor1d110e02010-07-01 14:13:13 +000069 CXXDestructorDecl *Dtor = RD->getDestructor();
Douglas Gregorcc6a44b2010-05-05 15:38:32 +000070
71 llvm::Constant *DtorFn;
72 if (Array) {
73 DtorFn =
Anders Carlsson02e370a2010-06-08 22:14:59 +000074 CodeGenFunction(CGM).GenerateCXXAggrDestructorHelper(Dtor, Array,
75 DeclPtr);
Douglas Gregorcc6a44b2010-05-05 15:38:32 +000076 const llvm::Type *Int8PtrTy =
Anders Carlsson02e370a2010-06-08 22:14:59 +000077 llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
Douglas Gregorcc6a44b2010-05-05 15:38:32 +000078 DeclPtr = llvm::Constant::getNullValue(Int8PtrTy);
79 } else
80 DtorFn = CGM.GetAddrOfCXXDestructor(Dtor, Dtor_Complete);
81
82 CGF.EmitCXXGlobalDtorRegistration(DtorFn, DeclPtr);
83}
84
Anders Carlssonfcbfdc12009-12-10 00:57:45 +000085void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
86 llvm::Constant *DeclPtr) {
87
88 const Expr *Init = D.getInit();
89 QualType T = D.getType();
90
91 if (!T->isReferenceType()) {
92 EmitDeclInit(*this, D, DeclPtr);
Douglas Gregorcc6a44b2010-05-05 15:38:32 +000093 EmitDeclDestroy(*this, D, DeclPtr);
Anders Carlssonfcbfdc12009-12-10 00:57:45 +000094 return;
95 }
Anders Carlsson045a6d82010-06-27 17:52:15 +000096
Daniel Dunbar91a16fa2010-08-21 02:24:36 +000097 unsigned Alignment = getContext().getDeclAlign(&D).getQuantity();
Anders Carlsson045a6d82010-06-27 17:52:15 +000098 RValue RV = EmitReferenceBindingToExpr(Init, &D);
Daniel Dunbar91a16fa2010-08-21 02:24:36 +000099 EmitStoreOfScalar(RV.getScalarVal(), DeclPtr, false, Alignment, T);
Anders Carlssonfcbfdc12009-12-10 00:57:45 +0000100}
Anders Carlssoneb4072e2009-12-10 00:30:05 +0000101
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000102void
103CodeGenFunction::EmitCXXGlobalDtorRegistration(llvm::Constant *DtorFn,
104 llvm::Constant *DeclPtr) {
105 // Generate a global destructor entry if not using __cxa_atexit.
106 if (!CGM.getCodeGenOpts().CXAAtExit) {
107 CGM.AddCXXDtorEntry(DtorFn, DeclPtr);
108 return;
109 }
110
Anders Carlssoneb4072e2009-12-10 00:30:05 +0000111 const llvm::Type *Int8PtrTy =
112 llvm::Type::getInt8Ty(VMContext)->getPointerTo();
113
114 std::vector<const llvm::Type *> Params;
115 Params.push_back(Int8PtrTy);
116
117 // Get the destructor function type
118 const llvm::Type *DtorFnTy =
119 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Params, false);
120 DtorFnTy = llvm::PointerType::getUnqual(DtorFnTy);
121
122 Params.clear();
123 Params.push_back(DtorFnTy);
124 Params.push_back(Int8PtrTy);
125 Params.push_back(Int8PtrTy);
126
127 // Get the __cxa_atexit function type
128 // extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
129 const llvm::FunctionType *AtExitFnTy =
130 llvm::FunctionType::get(ConvertType(getContext().IntTy), Params, false);
131
132 llvm::Constant *AtExitFn = CGM.CreateRuntimeFunction(AtExitFnTy,
133 "__cxa_atexit");
134
135 llvm::Constant *Handle = CGM.CreateRuntimeVariable(Int8PtrTy,
136 "__dso_handle");
137 llvm::Value *Args[3] = { llvm::ConstantExpr::getBitCast(DtorFn, DtorFnTy),
138 llvm::ConstantExpr::getBitCast(DeclPtr, Int8PtrTy),
139 llvm::ConstantExpr::getBitCast(Handle, Int8PtrTy) };
140 Builder.CreateCall(AtExitFn, &Args[0], llvm::array_endof(Args));
141}
142
John McCall3030eb82010-11-06 09:44:32 +0000143void CodeGenFunction::EmitCXXGuardedInit(const VarDecl &D,
144 llvm::GlobalVariable *DeclPtr) {
145 CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr);
John McCall5cd91b52010-09-08 01:44:27 +0000146}
147
Anders Carlsson9dc046e2010-06-08 22:40:05 +0000148static llvm::Function *
149CreateGlobalInitOrDestructFunction(CodeGenModule &CGM,
150 const llvm::FunctionType *FTy,
151 llvm::StringRef Name) {
152 llvm::Function *Fn =
153 llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
154 Name, &CGM.getModule());
155
Anders Carlsson18af3682010-06-08 22:47:50 +0000156 // Set the section if needed.
157 if (const char *Section =
158 CGM.getContext().Target.getStaticInitSectionSpecifier())
159 Fn->setSection(Section);
160
John McCall044cc542010-07-06 04:38:10 +0000161 if (!CGM.getLangOptions().Exceptions)
162 Fn->setDoesNotThrow();
163
Anders Carlsson9dc046e2010-06-08 22:40:05 +0000164 return Fn;
165}
166
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000167void
John McCall3030eb82010-11-06 09:44:32 +0000168CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
169 llvm::GlobalVariable *Addr) {
Eli Friedman6c6bda32010-01-08 00:50:11 +0000170 const llvm::FunctionType *FTy
171 = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
172 false);
173
174 // Create a variable initialization function.
175 llvm::Function *Fn =
Anders Carlsson9dc046e2010-06-08 22:40:05 +0000176 CreateGlobalInitOrDestructFunction(*this, FTy, "__cxx_global_var_init");
Eli Friedman6c6bda32010-01-08 00:50:11 +0000177
John McCall3030eb82010-11-06 09:44:32 +0000178 CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr);
Eli Friedman6c6bda32010-01-08 00:50:11 +0000179
Fariborz Jahanian9f967c52010-06-21 18:45:05 +0000180 if (D->hasAttr<InitPriorityAttr>()) {
181 unsigned int order = D->getAttr<InitPriorityAttr>()->getPriority();
Chris Lattnerec2830d2010-06-27 06:32:58 +0000182 OrderGlobalInits Key(order, PrioritizedCXXGlobalInits.size());
Fariborz Jahaniane0b691a2010-06-21 21:27:42 +0000183 PrioritizedCXXGlobalInits.push_back(std::make_pair(Key, Fn));
John McCallbf40cb52010-07-15 23:40:35 +0000184 DelayedCXXInitPosition.erase(D);
Fariborz Jahanian9f967c52010-06-21 18:45:05 +0000185 }
John McCallbf40cb52010-07-15 23:40:35 +0000186 else {
187 llvm::DenseMap<const Decl *, unsigned>::iterator I =
188 DelayedCXXInitPosition.find(D);
189 if (I == DelayedCXXInitPosition.end()) {
190 CXXGlobalInits.push_back(Fn);
191 } else {
192 assert(CXXGlobalInits[I->second] == 0);
193 CXXGlobalInits[I->second] = Fn;
194 DelayedCXXInitPosition.erase(I);
195 }
196 }
Eli Friedman6c6bda32010-01-08 00:50:11 +0000197}
198
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000199void
200CodeGenModule::EmitCXXGlobalInitFunc() {
John McCallbf40cb52010-07-15 23:40:35 +0000201 while (!CXXGlobalInits.empty() && !CXXGlobalInits.back())
202 CXXGlobalInits.pop_back();
203
Fariborz Jahanian9f967c52010-06-21 18:45:05 +0000204 if (CXXGlobalInits.empty() && PrioritizedCXXGlobalInits.empty())
Anders Carlssoneb4072e2009-12-10 00:30:05 +0000205 return;
206
207 const llvm::FunctionType *FTy
208 = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
209 false);
210
211 // Create our global initialization function.
Anders Carlsson9dc046e2010-06-08 22:40:05 +0000212 llvm::Function *Fn =
213 CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__I_a");
Anders Carlssoneb4072e2009-12-10 00:30:05 +0000214
Fariborz Jahanian9f967c52010-06-21 18:45:05 +0000215 if (!PrioritizedCXXGlobalInits.empty()) {
Fariborz Jahanian027d7ed2010-06-21 19:49:38 +0000216 llvm::SmallVector<llvm::Constant*, 8> LocalCXXGlobalInits;
217 llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(),
Fariborz Jahanianf4896882010-06-22 00:23:08 +0000218 PrioritizedCXXGlobalInits.end());
Fariborz Jahanian9f967c52010-06-21 18:45:05 +0000219 for (unsigned i = 0; i < PrioritizedCXXGlobalInits.size(); i++) {
220 llvm::Function *Fn = PrioritizedCXXGlobalInits[i].second;
221 LocalCXXGlobalInits.push_back(Fn);
222 }
John McCallbf40cb52010-07-15 23:40:35 +0000223 LocalCXXGlobalInits.append(CXXGlobalInits.begin(), CXXGlobalInits.end());
Fariborz Jahanian9f967c52010-06-21 18:45:05 +0000224 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
225 &LocalCXXGlobalInits[0],
226 LocalCXXGlobalInits.size());
227 }
228 else
229 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
230 &CXXGlobalInits[0],
231 CXXGlobalInits.size());
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000232 AddGlobalCtor(Fn);
233}
234
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000235void CodeGenModule::EmitCXXGlobalDtorFunc() {
236 if (CXXGlobalDtors.empty())
237 return;
238
239 const llvm::FunctionType *FTy
240 = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
241 false);
242
243 // Create our global destructor function.
244 llvm::Function *Fn =
Anders Carlsson9dc046e2010-06-08 22:40:05 +0000245 CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__D_a");
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000246
247 CodeGenFunction(*this).GenerateCXXGlobalDtorFunc(Fn, CXXGlobalDtors);
248 AddGlobalDtor(Fn);
249}
250
John McCall3030eb82010-11-06 09:44:32 +0000251/// Emit the code necessary to initialize the given global variable.
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000252void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
John McCall3030eb82010-11-06 09:44:32 +0000253 const VarDecl *D,
254 llvm::GlobalVariable *Addr) {
Daniel Dunbar5c6846e2010-03-20 04:15:29 +0000255 StartFunction(GlobalDecl(), getContext().VoidTy, Fn, FunctionArgList(),
256 SourceLocation());
257
John McCall3030eb82010-11-06 09:44:32 +0000258 // Use guarded initialization if the global variable is weak due to
259 // being a class template's static data member.
260 if (Addr->hasWeakLinkage() && D->getInstantiatedFromStaticDataMember()) {
261 EmitCXXGuardedInit(*D, Addr);
262 } else {
263 EmitCXXGlobalVarDeclInit(*D, Addr);
Fariborz Jahanian92d835a2010-10-26 22:47:47 +0000264 }
Daniel Dunbar5c6846e2010-03-20 04:15:29 +0000265
266 FinishFunction();
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000267}
Daniel Dunbar5c6846e2010-03-20 04:15:29 +0000268
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000269void CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
270 llvm::Constant **Decls,
271 unsigned NumDecls) {
272 StartFunction(GlobalDecl(), getContext().VoidTy, Fn, FunctionArgList(),
273 SourceLocation());
274
275 for (unsigned i = 0; i != NumDecls; ++i)
John McCallbf40cb52010-07-15 23:40:35 +0000276 if (Decls[i])
277 Builder.CreateCall(Decls[i]);
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000278
279 FinishFunction();
280}
281
282void CodeGenFunction::GenerateCXXGlobalDtorFunc(llvm::Function *Fn,
Chris Lattner810112e2010-06-19 05:52:45 +0000283 const std::vector<std::pair<llvm::WeakVH, llvm::Constant*> >
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000284 &DtorsAndObjects) {
285 StartFunction(GlobalDecl(), getContext().VoidTy, Fn, FunctionArgList(),
286 SourceLocation());
287
288 // Emit the dtors, in reverse order from construction.
Chris Lattnerc9a85f92010-04-26 20:35:54 +0000289 for (unsigned i = 0, e = DtorsAndObjects.size(); i != e; ++i) {
Chris Lattner810112e2010-06-19 05:52:45 +0000290 llvm::Value *Callee = DtorsAndObjects[e - i - 1].first;
Chris Lattnerc9a85f92010-04-26 20:35:54 +0000291 llvm::CallInst *CI = Builder.CreateCall(Callee,
292 DtorsAndObjects[e - i - 1].second);
293 // Make sure the call and the callee agree on calling convention.
294 if (llvm::Function *F = dyn_cast<llvm::Function>(Callee))
295 CI->setCallingConv(F->getCallingConv());
296 }
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000297
298 FinishFunction();
Anders Carlssoneb4072e2009-12-10 00:30:05 +0000299}
300
Anders Carlsson77291362010-06-08 22:17:27 +0000301/// GenerateCXXAggrDestructorHelper - Generates a helper function which when
302/// invoked, calls the default destructor on array elements in reverse order of
303/// construction.
304llvm::Function *
305CodeGenFunction::GenerateCXXAggrDestructorHelper(const CXXDestructorDecl *D,
306 const ArrayType *Array,
307 llvm::Value *This) {
308 FunctionArgList Args;
309 ImplicitParamDecl *Dst =
310 ImplicitParamDecl::Create(getContext(), 0,
311 SourceLocation(), 0,
312 getContext().getPointerType(getContext().VoidTy));
313 Args.push_back(std::make_pair(Dst, Dst->getType()));
314
Anders Carlsson77291362010-06-08 22:17:27 +0000315 const CGFunctionInfo &FI =
316 CGM.getTypes().getFunctionInfo(getContext().VoidTy, Args,
317 FunctionType::ExtInfo());
318 const llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI, false);
Anders Carlsson9dc046e2010-06-08 22:40:05 +0000319 llvm::Function *Fn =
320 CreateGlobalInitOrDestructFunction(CGM, FTy, "__cxx_global_array_dtor");
Anders Carlsson77291362010-06-08 22:17:27 +0000321
322 StartFunction(GlobalDecl(), getContext().VoidTy, Fn, Args, SourceLocation());
323
324 QualType BaseElementTy = getContext().getBaseElementType(Array);
325 const llvm::Type *BasePtr = ConvertType(BaseElementTy)->getPointerTo();
326 llvm::Value *BaseAddrPtr = Builder.CreateBitCast(This, BasePtr);
327
328 EmitCXXAggrDestructorCall(D, Array, BaseAddrPtr);
329
330 FinishFunction();
331
332 return Fn;
333}