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"
16 #include "CGObjCRuntime.h"
17 #include "clang/Frontend/CodeGenOptions.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/IR/Intrinsics.h"
21 using namespace clang;
22 using namespace CodeGen;
24 static void EmitDeclInit(CodeGenFunction &CGF, const VarDecl &D,
25 llvm::Constant *DeclPtr) {
26 assert(D.hasGlobalStorage() && "VarDecl must have global storage!");
27 assert(!D.getType()->isReferenceType() &&
28 "Should not call EmitDeclInit on a reference!");
30 ASTContext &Context = CGF.getContext();
32 CharUnits alignment = Context.getDeclAlign(&D);
33 QualType type = D.getType();
34 LValue lv = CGF.MakeAddrLValue(DeclPtr, type, alignment);
36 const Expr *Init = D.getInit();
37 switch (CGF.getEvaluationKind(type)) {
39 CodeGenModule &CGM = CGF.CGM;
40 if (lv.isObjCStrong())
41 CGM.getObjCRuntime().EmitObjCGlobalAssign(CGF, CGF.EmitScalarExpr(Init),
42 DeclPtr, D.isThreadSpecified());
43 else if (lv.isObjCWeak())
44 CGM.getObjCRuntime().EmitObjCWeakAssign(CGF, CGF.EmitScalarExpr(Init),
47 CGF.EmitScalarInit(Init, &D, lv, false);
51 CGF.EmitComplexExprIntoLValue(Init, lv, /*isInit*/ true);
54 CGF.EmitAggExpr(Init, AggValueSlot::forLValue(lv,AggValueSlot::IsDestructed,
55 AggValueSlot::DoesNotNeedGCBarriers,
56 AggValueSlot::IsNotAliased));
59 llvm_unreachable("bad evaluation kind");
62 /// Emit code to cause the destruction of the given variable with
63 /// static storage duration.
64 static void EmitDeclDestroy(CodeGenFunction &CGF, const VarDecl &D,
65 llvm::Constant *addr) {
66 CodeGenModule &CGM = CGF.CGM;
68 // FIXME: __attribute__((cleanup)) ?
70 QualType type = D.getType();
71 QualType::DestructionKind dtorKind = type.isDestructedType();
74 case QualType::DK_none:
77 case QualType::DK_cxx_destructor:
80 case QualType::DK_objc_strong_lifetime:
81 case QualType::DK_objc_weak_lifetime:
82 // We don't care about releasing objects during process teardown.
86 llvm::Constant *function;
87 llvm::Constant *argument;
89 // Special-case non-array C++ destructors, where there's a function
90 // with the right signature that we can just call.
91 const CXXRecordDecl *record = 0;
92 if (dtorKind == QualType::DK_cxx_destructor &&
93 (record = type->getAsCXXRecordDecl())) {
94 assert(!record->hasTrivialDestructor());
95 CXXDestructorDecl *dtor = record->getDestructor();
97 function = CGM.GetAddrOfCXXDestructor(dtor, Dtor_Complete);
100 // Otherwise, the standard logic requires a helper function.
102 function = CodeGenFunction(CGM).generateDestroyHelper(addr, type,
103 CGF.getDestroyer(dtorKind),
104 CGF.needsEHCleanup(dtorKind));
105 argument = llvm::Constant::getNullValue(CGF.Int8PtrTy);
108 CGM.getCXXABI().registerGlobalDtor(CGF, function, argument);
111 /// Emit code to cause the variable at the given address to be considered as
112 /// constant from this point onwards.
113 static void EmitDeclInvariant(CodeGenFunction &CGF, const VarDecl &D,
114 llvm::Constant *Addr) {
115 // Don't emit the intrinsic if we're not optimizing.
116 if (!CGF.CGM.getCodeGenOpts().OptimizationLevel)
119 // Grab the llvm.invariant.start intrinsic.
120 llvm::Intrinsic::ID InvStartID = llvm::Intrinsic::invariant_start;
121 llvm::Constant *InvariantStart = CGF.CGM.getIntrinsic(InvStartID);
123 // Emit a call with the size in bytes of the object.
124 CharUnits WidthChars = CGF.getContext().getTypeSizeInChars(D.getType());
125 uint64_t Width = WidthChars.getQuantity();
126 llvm::Value *Args[2] = { llvm::ConstantInt::getSigned(CGF.Int64Ty, Width),
127 llvm::ConstantExpr::getBitCast(Addr, CGF.Int8PtrTy)};
128 CGF.Builder.CreateCall(InvariantStart, Args);
131 void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
132 llvm::Constant *DeclPtr,
135 const Expr *Init = D.getInit();
136 QualType T = D.getType();
138 if (!T->isReferenceType()) {
140 EmitDeclInit(*this, D, DeclPtr);
141 if (CGM.isTypeConstant(D.getType(), true))
142 EmitDeclInvariant(*this, D, DeclPtr);
144 EmitDeclDestroy(*this, D, DeclPtr);
148 assert(PerformInit && "cannot have constant initializer which needs "
149 "destruction for reference");
150 unsigned Alignment = getContext().getDeclAlign(&D).getQuantity();
151 RValue RV = EmitReferenceBindingToExpr(Init, &D);
152 EmitStoreOfScalar(RV.getScalarVal(), DeclPtr, false, Alignment, T);
155 static llvm::Function *
156 CreateGlobalInitOrDestructFunction(CodeGenModule &CGM,
157 llvm::FunctionType *ty,
160 /// Create a stub function, suitable for being passed to atexit,
161 /// which passes the given address to the given destructor function.
162 static llvm::Constant *createAtExitStub(CodeGenModule &CGM,
163 llvm::Constant *dtor,
164 llvm::Constant *addr) {
165 // Get the destructor function type, void(*)(void).
166 llvm::FunctionType *ty = llvm::FunctionType::get(CGM.VoidTy, false);
168 CreateGlobalInitOrDestructFunction(CGM, ty,
169 Twine("__dtor_", addr->getName()));
171 CodeGenFunction CGF(CGM);
173 // Initialize debug info if needed.
174 CGF.maybeInitializeDebugInfo();
176 CGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, fn,
177 CGM.getTypes().arrangeNullaryFunction(),
178 FunctionArgList(), SourceLocation());
180 llvm::CallInst *call = CGF.Builder.CreateCall(dtor, addr);
182 // Make sure the call and the callee agree on calling convention.
183 if (llvm::Function *dtorFn =
184 dyn_cast<llvm::Function>(dtor->stripPointerCasts()))
185 call->setCallingConv(dtorFn->getCallingConv());
187 CGF.FinishFunction();
192 /// Register a global destructor using the C atexit runtime function.
193 void CodeGenFunction::registerGlobalDtorWithAtExit(llvm::Constant *dtor,
194 llvm::Constant *addr) {
195 // Create a function which calls the destructor.
196 llvm::Constant *dtorStub = createAtExitStub(CGM, dtor, addr);
198 // extern "C" int atexit(void (*f)(void));
199 llvm::FunctionType *atexitTy =
200 llvm::FunctionType::get(IntTy, dtorStub->getType(), false);
202 llvm::Constant *atexit =
203 CGM.CreateRuntimeFunction(atexitTy, "atexit");
204 if (llvm::Function *atexitFn = dyn_cast<llvm::Function>(atexit))
205 atexitFn->setDoesNotThrow();
207 EmitNounwindRuntimeCall(atexit, dtorStub);
210 void CodeGenFunction::EmitCXXGuardedInit(const VarDecl &D,
211 llvm::GlobalVariable *DeclPtr,
213 // If we've been asked to forbid guard variables, emit an error now.
214 // This diagnostic is hard-coded for Darwin's use case; we can find
215 // better phrasing if someone else needs it.
216 if (CGM.getCodeGenOpts().ForbidGuardVariables)
217 CGM.Error(D.getLocation(),
218 "this initialization requires a guard variable, which "
219 "the kernel does not support");
221 CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr, PerformInit);
224 static llvm::Function *
225 CreateGlobalInitOrDestructFunction(CodeGenModule &CGM,
226 llvm::FunctionType *FTy,
229 llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
230 Name, &CGM.getModule());
231 if (!CGM.getLangOpts().AppleKext) {
232 // Set the section if needed.
233 if (const char *Section =
234 CGM.getContext().getTargetInfo().getStaticInitSectionSpecifier())
235 Fn->setSection(Section);
238 Fn->setCallingConv(CGM.getRuntimeCC());
240 if (!CGM.getLangOpts().Exceptions)
241 Fn->setDoesNotThrow();
243 if (CGM.getSanOpts().Address)
244 Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
245 if (CGM.getSanOpts().Thread)
246 Fn->addFnAttr(llvm::Attribute::SanitizeThread);
247 if (CGM.getSanOpts().Memory)
248 Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
254 CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
255 llvm::GlobalVariable *Addr,
257 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
259 // Create a variable initialization function.
261 CreateGlobalInitOrDestructFunction(*this, FTy, "__cxx_global_var_init");
263 CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr,
266 if (D->hasAttr<InitPriorityAttr>()) {
267 unsigned int order = D->getAttr<InitPriorityAttr>()->getPriority();
268 OrderGlobalInits Key(order, PrioritizedCXXGlobalInits.size());
269 PrioritizedCXXGlobalInits.push_back(std::make_pair(Key, Fn));
270 DelayedCXXInitPosition.erase(D);
272 llvm::DenseMap<const Decl *, unsigned>::iterator I =
273 DelayedCXXInitPosition.find(D);
274 if (I == DelayedCXXInitPosition.end()) {
275 CXXGlobalInits.push_back(Fn);
277 assert(CXXGlobalInits[I->second] == 0);
278 CXXGlobalInits[I->second] = Fn;
279 DelayedCXXInitPosition.erase(I);
285 CodeGenModule::EmitCXXGlobalInitFunc() {
286 while (!CXXGlobalInits.empty() && !CXXGlobalInits.back())
287 CXXGlobalInits.pop_back();
289 if (CXXGlobalInits.empty() && PrioritizedCXXGlobalInits.empty())
292 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
295 // Create our global initialization function.
296 if (!PrioritizedCXXGlobalInits.empty()) {
297 SmallVector<llvm::Constant*, 8> LocalCXXGlobalInits;
298 llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(),
299 PrioritizedCXXGlobalInits.end());
300 // Iterate over "chunks" of ctors with same priority and emit each chunk
301 // into separate function. Note - everything is sorted first by priority,
302 // second - by lex order, so we emit ctor functions in proper order.
303 for (SmallVectorImpl<GlobalInitData >::iterator
304 I = PrioritizedCXXGlobalInits.begin(),
305 E = PrioritizedCXXGlobalInits.end(); I != E; ) {
306 SmallVectorImpl<GlobalInitData >::iterator
307 PrioE = std::upper_bound(I + 1, E, *I, GlobalInitPriorityCmp());
309 LocalCXXGlobalInits.clear();
310 unsigned Priority = I->first.priority;
311 // Compute the function suffix from priority. Prepend with zeroes to make
312 // sure the function names are also ordered as priorities.
313 std::string PrioritySuffix = llvm::utostr(Priority);
314 // Priority is always <= 65535 (enforced by sema)..
315 PrioritySuffix = std::string(6-PrioritySuffix.size(), '0')+PrioritySuffix;
317 CreateGlobalInitOrDestructFunction(*this, FTy,
318 "_GLOBAL__I_" + PrioritySuffix);
320 for (; I < PrioE; ++I)
321 LocalCXXGlobalInits.push_back(I->second);
323 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
324 &LocalCXXGlobalInits[0],
325 LocalCXXGlobalInits.size());
326 AddGlobalCtor(Fn, Priority);
331 CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__I_a");
333 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
335 CXXGlobalInits.size());
338 CXXGlobalInits.clear();
339 PrioritizedCXXGlobalInits.clear();
342 void CodeGenModule::EmitCXXGlobalDtorFunc() {
343 if (CXXGlobalDtors.empty())
346 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
348 // Create our global destructor function.
350 CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__D_a");
352 CodeGenFunction(*this).GenerateCXXGlobalDtorsFunc(Fn, CXXGlobalDtors);
356 /// Emit the code necessary to initialize the given global variable.
357 void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
359 llvm::GlobalVariable *Addr,
361 // Check if we need to emit debug info for variable initializer.
362 if (!D->hasAttr<NoDebugAttr>())
363 maybeInitializeDebugInfo();
365 StartFunction(GlobalDecl(D), getContext().VoidTy, Fn,
366 getTypes().arrangeNullaryFunction(),
367 FunctionArgList(), D->getInit()->getExprLoc());
369 // Use guarded initialization if the global variable is weak. This
370 // occurs for, e.g., instantiated static data members and
371 // definitions explicitly marked weak.
372 if (Addr->getLinkage() == llvm::GlobalValue::WeakODRLinkage ||
373 Addr->getLinkage() == llvm::GlobalValue::WeakAnyLinkage) {
374 EmitCXXGuardedInit(*D, Addr, PerformInit);
376 EmitCXXGlobalVarDeclInit(*D, Addr, PerformInit);
382 void CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
383 llvm::Constant **Decls,
385 // Initialize debug info if needed.
386 maybeInitializeDebugInfo();
388 StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
389 getTypes().arrangeNullaryFunction(),
390 FunctionArgList(), SourceLocation());
392 RunCleanupsScope Scope(*this);
394 // When building in Objective-C++ ARC mode, create an autorelease pool
395 // around the global initializers.
396 if (getLangOpts().ObjCAutoRefCount && getLangOpts().CPlusPlus) {
397 llvm::Value *token = EmitObjCAutoreleasePoolPush();
398 EmitObjCAutoreleasePoolCleanup(token);
401 for (unsigned i = 0; i != NumDecls; ++i)
403 EmitRuntimeCall(Decls[i]);
405 Scope.ForceCleanup();
410 void CodeGenFunction::GenerateCXXGlobalDtorsFunc(llvm::Function *Fn,
411 const std::vector<std::pair<llvm::WeakVH, llvm::Constant*> >
413 // Initialize debug info if needed.
414 maybeInitializeDebugInfo();
416 StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
417 getTypes().arrangeNullaryFunction(),
418 FunctionArgList(), SourceLocation());
420 // Emit the dtors, in reverse order from construction.
421 for (unsigned i = 0, e = DtorsAndObjects.size(); i != e; ++i) {
422 llvm::Value *Callee = DtorsAndObjects[e - i - 1].first;
423 llvm::CallInst *CI = Builder.CreateCall(Callee,
424 DtorsAndObjects[e - i - 1].second);
425 // Make sure the call and the callee agree on calling convention.
426 if (llvm::Function *F = dyn_cast<llvm::Function>(Callee))
427 CI->setCallingConv(F->getCallingConv());
433 /// generateDestroyHelper - Generates a helper function which, when
434 /// invoked, destroys the given object.
436 CodeGenFunction::generateDestroyHelper(llvm::Constant *addr,
438 Destroyer *destroyer,
439 bool useEHCleanupForArray) {
440 FunctionArgList args;
441 ImplicitParamDecl dst(0, SourceLocation(), 0, getContext().VoidPtrTy);
442 args.push_back(&dst);
444 const CGFunctionInfo &FI =
445 CGM.getTypes().arrangeFunctionDeclaration(getContext().VoidTy, args,
446 FunctionType::ExtInfo(),
448 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
450 CreateGlobalInitOrDestructFunction(CGM, FTy, "__cxx_global_array_dtor");
452 // Initialize debug info if needed.
453 maybeInitializeDebugInfo();
455 StartFunction(GlobalDecl(), getContext().VoidTy, fn, FI, args,
458 emitDestroy(addr, type, destroyer, useEHCleanupForArray);