CGDeclCXX.cpp revision 224145
1//===--- 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"
15#include "CGObjCRuntime.h"
16#include "CGCXXABI.h"
17#include "clang/Frontend/CodeGenOptions.h"
18#include "llvm/Intrinsics.h"
19
20using namespace clang;
21using namespace CodeGen;
22
23static 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!");
28
29  ASTContext &Context = CGF.getContext();
30
31  unsigned alignment = Context.getDeclAlign(&D).getQuantity();
32  QualType type = D.getType();
33  LValue lv = CGF.MakeAddrLValue(DeclPtr, type, alignment);
34
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),
43                                              DeclPtr);
44    else
45      CGF.EmitScalarInit(Init, &D, lv, false);
46  } else if (type->isAnyComplexType()) {
47    CGF.EmitComplexExprIntoAddr(Init, DeclPtr, lv.isVolatile());
48  } else {
49    CGF.EmitAggExpr(Init, AggValueSlot::forLValue(lv, true));
50  }
51}
52
53/// Emit code to cause the destruction of the given variable with
54/// static storage duration.
55static void EmitDeclDestroy(CodeGenFunction &CGF, const VarDecl &D,
56                            llvm::Constant *addr) {
57  CodeGenModule &CGM = CGF.CGM;
58
59  // FIXME:  __attribute__((cleanup)) ?
60
61  QualType type = D.getType();
62  QualType::DestructionKind dtorKind = type.isDestructedType();
63
64  switch (dtorKind) {
65  case QualType::DK_none:
66    return;
67
68  case QualType::DK_cxx_destructor:
69    break;
70
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.
74    return;
75  }
76
77  llvm::Constant *function;
78  llvm::Constant *argument;
79
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();
87
88    function = CGM.GetAddrOfCXXDestructor(dtor, Dtor_Complete);
89    argument = addr;
90
91  // Otherwise, the standard logic requires a helper function.
92  } else {
93    function = CodeGenFunction(CGM).generateDestroyHelper(addr, type,
94                                                  CGF.getDestroyer(dtorKind),
95                                                  CGF.needsEHCleanup(dtorKind));
96    argument = llvm::Constant::getNullValue(CGF.Int8PtrTy);
97  }
98
99  CGF.EmitCXXGlobalDtorRegistration(function, argument);
100}
101
102void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
103                                               llvm::Constant *DeclPtr) {
104
105  const Expr *Init = D.getInit();
106  QualType T = D.getType();
107
108  if (!T->isReferenceType()) {
109    EmitDeclInit(*this, D, DeclPtr);
110    EmitDeclDestroy(*this, D, DeclPtr);
111    return;
112  }
113
114  unsigned Alignment = getContext().getDeclAlign(&D).getQuantity();
115  RValue RV = EmitReferenceBindingToExpr(Init, &D);
116  EmitStoreOfScalar(RV.getScalarVal(), DeclPtr, false, Alignment, T);
117}
118
119void
120CodeGenFunction::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);
125    return;
126  }
127
128  // Get the destructor function type
129  llvm::Type *ArgTys[] = { Int8PtrTy };
130  llvm::Type *DtorFnTy =
131    llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()),
132                            ArgTys, false);
133  DtorFnTy = llvm::PointerType::getUnqual(DtorFnTy);
134
135  llvm::Type *Params[] = { DtorFnTy, Int8PtrTy, Int8PtrTy };
136
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);
141
142  llvm::Constant *AtExitFn = CGM.CreateRuntimeFunction(AtExitFnTy,
143                                                       "__cxa_atexit");
144  if (llvm::Function *Fn = dyn_cast<llvm::Function>(AtExitFn))
145    Fn->setDoesNotThrow();
146
147  llvm::Constant *Handle = CGM.CreateRuntimeVariable(Int8PtrTy,
148                                                     "__dso_handle");
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);
153}
154
155void 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");
164
165  CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr);
166}
167
168static llvm::Function *
169CreateGlobalInitOrDestructFunction(CodeGenModule &CGM,
170                                   const llvm::FunctionType *FTy,
171                                   llvm::StringRef Name) {
172  llvm::Function *Fn =
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);
180  }
181
182  if (!CGM.getLangOptions().Exceptions)
183    Fn->setDoesNotThrow();
184
185  return Fn;
186}
187
188void
189CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
190                                            llvm::GlobalVariable *Addr) {
191  const llvm::FunctionType *FTy
192    = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
193                              false);
194
195  // Create a variable initialization function.
196  llvm::Function *Fn =
197    CreateGlobalInitOrDestructFunction(*this, FTy, "__cxx_global_var_init");
198
199  CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr);
200
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);
206  }
207  else {
208    llvm::DenseMap<const Decl *, unsigned>::iterator I =
209      DelayedCXXInitPosition.find(D);
210    if (I == DelayedCXXInitPosition.end()) {
211      CXXGlobalInits.push_back(Fn);
212    } else {
213      assert(CXXGlobalInits[I->second] == 0);
214      CXXGlobalInits[I->second] = Fn;
215      DelayedCXXInitPosition.erase(I);
216    }
217  }
218}
219
220void
221CodeGenModule::EmitCXXGlobalInitFunc() {
222  while (!CXXGlobalInits.empty() && !CXXGlobalInits.back())
223    CXXGlobalInits.pop_back();
224
225  if (CXXGlobalInits.empty() && PrioritizedCXXGlobalInits.empty())
226    return;
227
228  const llvm::FunctionType *FTy
229    = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
230                              false);
231
232  // Create our global initialization function.
233  llvm::Function *Fn =
234    CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__I_a");
235
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);
243    }
244    LocalCXXGlobalInits.append(CXXGlobalInits.begin(), CXXGlobalInits.end());
245    CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
246                                                    &LocalCXXGlobalInits[0],
247                                                    LocalCXXGlobalInits.size());
248  }
249  else
250    CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
251                                                     &CXXGlobalInits[0],
252                                                     CXXGlobalInits.size());
253  AddGlobalCtor(Fn);
254  CXXGlobalInits.clear();
255  PrioritizedCXXGlobalInits.clear();
256}
257
258void CodeGenModule::EmitCXXGlobalDtorFunc() {
259  if (CXXGlobalDtors.empty())
260    return;
261
262  const llvm::FunctionType *FTy
263    = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
264                              false);
265
266  // Create our global destructor function.
267  llvm::Function *Fn =
268    CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__D_a");
269
270  CodeGenFunction(*this).GenerateCXXGlobalDtorFunc(Fn, CXXGlobalDtors);
271  AddGlobalDtor(Fn);
272}
273
274/// Emit the code necessary to initialize the given global variable.
275void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
276                                                       const VarDecl *D,
277                                                 llvm::GlobalVariable *Addr) {
278  StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
279                getTypes().getNullaryFunctionInfo(),
280                FunctionArgList(), SourceLocation());
281
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);
288  } else {
289    EmitCXXGlobalVarDeclInit(*D, Addr);
290  }
291
292  FinishFunction();
293}
294
295void CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
296                                                llvm::Constant **Decls,
297                                                unsigned NumDecls) {
298  StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
299                getTypes().getNullaryFunctionInfo(),
300                FunctionArgList(), SourceLocation());
301
302  RunCleanupsScope Scope(*this);
303
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);
309  }
310
311  for (unsigned i = 0; i != NumDecls; ++i)
312    if (Decls[i])
313      Builder.CreateCall(Decls[i]);
314
315  Scope.ForceCleanup();
316
317  FinishFunction();
318}
319
320void CodeGenFunction::GenerateCXXGlobalDtorFunc(llvm::Function *Fn,
321                  const std::vector<std::pair<llvm::WeakVH, llvm::Constant*> >
322                                                &DtorsAndObjects) {
323  StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
324                getTypes().getNullaryFunctionInfo(),
325                FunctionArgList(), SourceLocation());
326
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());
335  }
336
337  FinishFunction();
338}
339
340/// generateDestroyHelper - Generates a helper function which, when
341/// invoked, destroys the given object.
342llvm::Function *
343CodeGenFunction::generateDestroyHelper(llvm::Constant *addr,
344                                       QualType type,
345                                       Destroyer &destroyer,
346                                       bool useEHCleanupForArray) {
347  FunctionArgList args;
348  ImplicitParamDecl dst(0, SourceLocation(), 0, getContext().VoidPtrTy);
349  args.push_back(&dst);
350
351  const CGFunctionInfo &FI =
352    CGM.getTypes().getFunctionInfo(getContext().VoidTy, args,
353                                   FunctionType::ExtInfo());
354  const llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI, false);
355  llvm::Function *fn =
356    CreateGlobalInitOrDestructFunction(CGM, FTy, "__cxx_global_array_dtor");
357
358  StartFunction(GlobalDecl(), getContext().VoidTy, fn, FI, args,
359                SourceLocation());
360
361  emitDestroy(addr, type, destroyer, useEHCleanupForArray);
362
363  FinishFunction();
364
365  return fn;
366}
367
368