1 //===--- CGDeclCXX.cpp - Emit LLVM Code for C++ declarations --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This contains code dealing with code generation of C++ declarations
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenFunction.h"
15 #include "CGObjCRuntime.h"
17 #include "clang/Frontend/CodeGenOptions.h"
18 #include "llvm/Intrinsics.h"
20 using namespace clang;
21 using namespace CodeGen;
23 static void EmitDeclInit(CodeGenFunction &CGF, const VarDecl &D,
24 llvm::Constant *DeclPtr) {
25 assert(D.hasGlobalStorage() && "VarDecl must have global storage!");
26 assert(!D.getType()->isReferenceType() &&
27 "Should not call EmitDeclInit on a reference!");
29 ASTContext &Context = CGF.getContext();
31 unsigned alignment = Context.getDeclAlign(&D).getQuantity();
32 QualType type = D.getType();
33 LValue lv = CGF.MakeAddrLValue(DeclPtr, type, alignment);
35 const Expr *Init = D.getInit();
36 if (!CGF.hasAggregateLLVMType(type)) {
37 CodeGenModule &CGM = CGF.CGM;
38 if (lv.isObjCStrong())
39 CGM.getObjCRuntime().EmitObjCGlobalAssign(CGF, CGF.EmitScalarExpr(Init),
40 DeclPtr, D.isThreadSpecified());
41 else if (lv.isObjCWeak())
42 CGM.getObjCRuntime().EmitObjCWeakAssign(CGF, CGF.EmitScalarExpr(Init),
45 CGF.EmitScalarInit(Init, &D, lv, false);
46 } else if (type->isAnyComplexType()) {
47 CGF.EmitComplexExprIntoAddr(Init, DeclPtr, lv.isVolatile());
49 CGF.EmitAggExpr(Init, AggValueSlot::forLValue(lv, true));
53 /// Emit code to cause the destruction of the given variable with
54 /// static storage duration.
55 static void EmitDeclDestroy(CodeGenFunction &CGF, const VarDecl &D,
56 llvm::Constant *addr) {
57 CodeGenModule &CGM = CGF.CGM;
59 // FIXME: __attribute__((cleanup)) ?
61 QualType type = D.getType();
62 QualType::DestructionKind dtorKind = type.isDestructedType();
65 case QualType::DK_none:
68 case QualType::DK_cxx_destructor:
71 case QualType::DK_objc_strong_lifetime:
72 case QualType::DK_objc_weak_lifetime:
73 // We don't care about releasing objects during process teardown.
77 llvm::Constant *function;
78 llvm::Constant *argument;
80 // Special-case non-array C++ destructors, where there's a function
81 // with the right signature that we can just call.
82 const CXXRecordDecl *record = 0;
83 if (dtorKind == QualType::DK_cxx_destructor &&
84 (record = type->getAsCXXRecordDecl())) {
85 assert(!record->hasTrivialDestructor());
86 CXXDestructorDecl *dtor = record->getDestructor();
88 function = CGM.GetAddrOfCXXDestructor(dtor, Dtor_Complete);
91 // Otherwise, the standard logic requires a helper function.
93 function = CodeGenFunction(CGM).generateDestroyHelper(addr, type,
94 CGF.getDestroyer(dtorKind),
95 CGF.needsEHCleanup(dtorKind));
96 argument = llvm::Constant::getNullValue(CGF.Int8PtrTy);
99 CGF.EmitCXXGlobalDtorRegistration(function, argument);
102 void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
103 llvm::Constant *DeclPtr) {
105 const Expr *Init = D.getInit();
106 QualType T = D.getType();
108 if (!T->isReferenceType()) {
109 EmitDeclInit(*this, D, DeclPtr);
110 EmitDeclDestroy(*this, D, DeclPtr);
114 unsigned Alignment = getContext().getDeclAlign(&D).getQuantity();
115 RValue RV = EmitReferenceBindingToExpr(Init, &D);
116 EmitStoreOfScalar(RV.getScalarVal(), DeclPtr, false, Alignment, T);
120 CodeGenFunction::EmitCXXGlobalDtorRegistration(llvm::Constant *DtorFn,
121 llvm::Constant *DeclPtr) {
122 // Generate a global destructor entry if not using __cxa_atexit.
123 if (!CGM.getCodeGenOpts().CXAAtExit) {
124 CGM.AddCXXDtorEntry(DtorFn, DeclPtr);
128 // Get the destructor function type
129 llvm::Type *ArgTys[] = { Int8PtrTy };
130 llvm::Type *DtorFnTy =
131 llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()),
133 DtorFnTy = llvm::PointerType::getUnqual(DtorFnTy);
135 llvm::Type *Params[] = { DtorFnTy, Int8PtrTy, Int8PtrTy };
137 // Get the __cxa_atexit function type
138 // extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
139 const llvm::FunctionType *AtExitFnTy =
140 llvm::FunctionType::get(ConvertType(getContext().IntTy), Params, false);
142 llvm::Constant *AtExitFn = CGM.CreateRuntimeFunction(AtExitFnTy,
144 if (llvm::Function *Fn = dyn_cast<llvm::Function>(AtExitFn))
145 Fn->setDoesNotThrow();
147 llvm::Constant *Handle = CGM.CreateRuntimeVariable(Int8PtrTy,
149 llvm::Value *Args[3] = { llvm::ConstantExpr::getBitCast(DtorFn, DtorFnTy),
150 llvm::ConstantExpr::getBitCast(DeclPtr, Int8PtrTy),
151 llvm::ConstantExpr::getBitCast(Handle, Int8PtrTy) };
152 Builder.CreateCall(AtExitFn, Args);
155 void CodeGenFunction::EmitCXXGuardedInit(const VarDecl &D,
156 llvm::GlobalVariable *DeclPtr) {
157 // If we've been asked to forbid guard variables, emit an error now.
158 // This diagnostic is hard-coded for Darwin's use case; we can find
159 // better phrasing if someone else needs it.
160 if (CGM.getCodeGenOpts().ForbidGuardVariables)
161 CGM.Error(D.getLocation(),
162 "this initialization requires a guard variable, which "
163 "the kernel does not support");
165 CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr);
168 static llvm::Function *
169 CreateGlobalInitOrDestructFunction(CodeGenModule &CGM,
170 const llvm::FunctionType *FTy,
171 llvm::StringRef Name) {
173 llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
174 Name, &CGM.getModule());
175 if (!CGM.getContext().getLangOptions().AppleKext) {
176 // Set the section if needed.
177 if (const char *Section =
178 CGM.getContext().Target.getStaticInitSectionSpecifier())
179 Fn->setSection(Section);
182 if (!CGM.getLangOptions().Exceptions)
183 Fn->setDoesNotThrow();
189 CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
190 llvm::GlobalVariable *Addr) {
191 const llvm::FunctionType *FTy
192 = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
195 // Create a variable initialization function.
197 CreateGlobalInitOrDestructFunction(*this, FTy, "__cxx_global_var_init");
199 CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr);
201 if (D->hasAttr<InitPriorityAttr>()) {
202 unsigned int order = D->getAttr<InitPriorityAttr>()->getPriority();
203 OrderGlobalInits Key(order, PrioritizedCXXGlobalInits.size());
204 PrioritizedCXXGlobalInits.push_back(std::make_pair(Key, Fn));
205 DelayedCXXInitPosition.erase(D);
208 llvm::DenseMap<const Decl *, unsigned>::iterator I =
209 DelayedCXXInitPosition.find(D);
210 if (I == DelayedCXXInitPosition.end()) {
211 CXXGlobalInits.push_back(Fn);
213 assert(CXXGlobalInits[I->second] == 0);
214 CXXGlobalInits[I->second] = Fn;
215 DelayedCXXInitPosition.erase(I);
221 CodeGenModule::EmitCXXGlobalInitFunc() {
222 while (!CXXGlobalInits.empty() && !CXXGlobalInits.back())
223 CXXGlobalInits.pop_back();
225 if (CXXGlobalInits.empty() && PrioritizedCXXGlobalInits.empty())
228 const llvm::FunctionType *FTy
229 = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
232 // Create our global initialization function.
234 CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__I_a");
236 if (!PrioritizedCXXGlobalInits.empty()) {
237 llvm::SmallVector<llvm::Constant*, 8> LocalCXXGlobalInits;
238 llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(),
239 PrioritizedCXXGlobalInits.end());
240 for (unsigned i = 0; i < PrioritizedCXXGlobalInits.size(); i++) {
241 llvm::Function *Fn = PrioritizedCXXGlobalInits[i].second;
242 LocalCXXGlobalInits.push_back(Fn);
244 LocalCXXGlobalInits.append(CXXGlobalInits.begin(), CXXGlobalInits.end());
245 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
246 &LocalCXXGlobalInits[0],
247 LocalCXXGlobalInits.size());
250 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
252 CXXGlobalInits.size());
254 CXXGlobalInits.clear();
255 PrioritizedCXXGlobalInits.clear();
258 void CodeGenModule::EmitCXXGlobalDtorFunc() {
259 if (CXXGlobalDtors.empty())
262 const llvm::FunctionType *FTy
263 = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
266 // Create our global destructor function.
268 CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__D_a");
270 CodeGenFunction(*this).GenerateCXXGlobalDtorFunc(Fn, CXXGlobalDtors);
274 /// Emit the code necessary to initialize the given global variable.
275 void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
277 llvm::GlobalVariable *Addr) {
278 StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
279 getTypes().getNullaryFunctionInfo(),
280 FunctionArgList(), SourceLocation());
282 // Use guarded initialization if the global variable is weak. This
283 // occurs for, e.g., instantiated static data members and
284 // definitions explicitly marked weak.
285 if (Addr->getLinkage() == llvm::GlobalValue::WeakODRLinkage ||
286 Addr->getLinkage() == llvm::GlobalValue::WeakAnyLinkage) {
287 EmitCXXGuardedInit(*D, Addr);
289 EmitCXXGlobalVarDeclInit(*D, Addr);
295 void CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
296 llvm::Constant **Decls,
298 StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
299 getTypes().getNullaryFunctionInfo(),
300 FunctionArgList(), SourceLocation());
302 RunCleanupsScope Scope(*this);
304 // When building in Objective-C++ ARC mode, create an autorelease pool
305 // around the global initializers.
306 if (getLangOptions().ObjCAutoRefCount && getLangOptions().CPlusPlus) {
307 llvm::Value *token = EmitObjCAutoreleasePoolPush();
308 EmitObjCAutoreleasePoolCleanup(token);
311 for (unsigned i = 0; i != NumDecls; ++i)
313 Builder.CreateCall(Decls[i]);
315 Scope.ForceCleanup();
320 void CodeGenFunction::GenerateCXXGlobalDtorFunc(llvm::Function *Fn,
321 const std::vector<std::pair<llvm::WeakVH, llvm::Constant*> >
323 StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
324 getTypes().getNullaryFunctionInfo(),
325 FunctionArgList(), SourceLocation());
327 // Emit the dtors, in reverse order from construction.
328 for (unsigned i = 0, e = DtorsAndObjects.size(); i != e; ++i) {
329 llvm::Value *Callee = DtorsAndObjects[e - i - 1].first;
330 llvm::CallInst *CI = Builder.CreateCall(Callee,
331 DtorsAndObjects[e - i - 1].second);
332 // Make sure the call and the callee agree on calling convention.
333 if (llvm::Function *F = dyn_cast<llvm::Function>(Callee))
334 CI->setCallingConv(F->getCallingConv());
340 /// generateDestroyHelper - Generates a helper function which, when
341 /// invoked, destroys the given object.
343 CodeGenFunction::generateDestroyHelper(llvm::Constant *addr,
345 Destroyer &destroyer,
346 bool useEHCleanupForArray) {
347 FunctionArgList args;
348 ImplicitParamDecl dst(0, SourceLocation(), 0, getContext().VoidPtrTy);
349 args.push_back(&dst);
351 const CGFunctionInfo &FI =
352 CGM.getTypes().getFunctionInfo(getContext().VoidTy, args,
353 FunctionType::ExtInfo());
354 const llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI, false);
356 CreateGlobalInitOrDestructFunction(CGM, FTy, "__cxx_global_array_dtor");
358 StartFunction(GlobalDecl(), getContext().VoidTy, fn, FI, args,
361 emitDestroy(addr, type, destroyer, useEHCleanupForArray);