CGDeclCXX.cpp revision 00a8c3f6c979a11b15b2a4a4ce08c7888634d6cd
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  CharUnits alignment = Context.getDeclAlign(&D);
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,AggValueSlot::IsDestructed,
50                                          AggValueSlot::DoesNotNeedGCBarriers,
51                                                  AggValueSlot::IsNotAliased));
52  }
53}
54
55/// Emit code to cause the destruction of the given variable with
56/// static storage duration.
57static void EmitDeclDestroy(CodeGenFunction &CGF, const VarDecl &D,
58                            llvm::Constant *addr) {
59  CodeGenModule &CGM = CGF.CGM;
60
61  // FIXME:  __attribute__((cleanup)) ?
62
63  QualType type = D.getType();
64  QualType::DestructionKind dtorKind = type.isDestructedType();
65
66  switch (dtorKind) {
67  case QualType::DK_none:
68    return;
69
70  case QualType::DK_cxx_destructor:
71    break;
72
73  case QualType::DK_objc_strong_lifetime:
74  case QualType::DK_objc_weak_lifetime:
75    // We don't care about releasing objects during process teardown.
76    return;
77  }
78
79  llvm::Constant *function;
80  llvm::Constant *argument;
81
82  // Special-case non-array C++ destructors, where there's a function
83  // with the right signature that we can just call.
84  const CXXRecordDecl *record = 0;
85  if (dtorKind == QualType::DK_cxx_destructor &&
86      (record = type->getAsCXXRecordDecl())) {
87    assert(!record->hasTrivialDestructor());
88    CXXDestructorDecl *dtor = record->getDestructor();
89
90    function = CGM.GetAddrOfCXXDestructor(dtor, Dtor_Complete);
91    argument = addr;
92
93  // Otherwise, the standard logic requires a helper function.
94  } else {
95    function = CodeGenFunction(CGM).generateDestroyHelper(addr, type,
96                                                  CGF.getDestroyer(dtorKind),
97                                                  CGF.needsEHCleanup(dtorKind));
98    argument = llvm::Constant::getNullValue(CGF.Int8PtrTy);
99  }
100
101  CGF.EmitCXXGlobalDtorRegistration(function, argument);
102}
103
104/// Emit code to cause the variable at the given address to be considered as
105/// constant from this point onwards.
106static void EmitDeclInvariant(CodeGenFunction &CGF, llvm::Constant *Addr) {
107  // Don't emit the intrinsic if we're not optimizing.
108  if (!CGF.CGM.getCodeGenOpts().OptimizationLevel)
109    return;
110
111  // Grab the llvm.invariant.start intrinsic.
112  llvm::Intrinsic::ID InvStartID = llvm::Intrinsic::invariant_start;
113  llvm::Constant *InvariantStart = CGF.CGM.getIntrinsic(InvStartID);
114
115  // Emit a call, with size -1 signifying the whole object.
116  llvm::Value *Args[2] = { llvm::ConstantInt::getSigned(CGF.Int64Ty, -1),
117                           llvm::ConstantExpr::getBitCast(Addr, CGF.Int8PtrTy)};
118  CGF.Builder.CreateCall(InvariantStart, Args);
119}
120
121void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
122                                               llvm::Constant *DeclPtr,
123                                               bool PerformInit) {
124
125  const Expr *Init = D.getInit();
126  QualType T = D.getType();
127
128  if (!T->isReferenceType()) {
129    if (PerformInit)
130      EmitDeclInit(*this, D, DeclPtr);
131    if (CGM.isTypeConstant(D.getType(), true))
132      EmitDeclInvariant(*this, DeclPtr);
133    else
134      EmitDeclDestroy(*this, D, DeclPtr);
135    return;
136  }
137
138  assert(PerformInit && "cannot have constant initializer which needs "
139         "destruction for reference");
140  unsigned Alignment = getContext().getDeclAlign(&D).getQuantity();
141  RValue RV = EmitReferenceBindingToExpr(Init, &D);
142  EmitStoreOfScalar(RV.getScalarVal(), DeclPtr, false, Alignment, T);
143}
144
145void
146CodeGenFunction::EmitCXXGlobalDtorRegistration(llvm::Constant *DtorFn,
147                                               llvm::Constant *DeclPtr) {
148  // Generate a global destructor entry if not using __cxa_atexit.
149  if (!CGM.getCodeGenOpts().CXAAtExit) {
150    CGM.AddCXXDtorEntry(DtorFn, DeclPtr);
151    return;
152  }
153
154  // Get the destructor function type
155  llvm::Type *DtorFnTy = llvm::FunctionType::get(VoidTy, Int8PtrTy, false);
156  DtorFnTy = llvm::PointerType::getUnqual(DtorFnTy);
157
158  llvm::Type *Params[] = { DtorFnTy, Int8PtrTy, Int8PtrTy };
159
160  // Get the __cxa_atexit function type
161  // extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
162  llvm::FunctionType *AtExitFnTy =
163    llvm::FunctionType::get(ConvertType(getContext().IntTy), Params, false);
164
165  llvm::Constant *AtExitFn = CGM.CreateRuntimeFunction(AtExitFnTy,
166                                                       "__cxa_atexit");
167  if (llvm::Function *Fn = dyn_cast<llvm::Function>(AtExitFn))
168    Fn->setDoesNotThrow();
169
170  llvm::Constant *Handle = CGM.CreateRuntimeVariable(Int8PtrTy,
171                                                     "__dso_handle");
172  llvm::Value *Args[3] = { llvm::ConstantExpr::getBitCast(DtorFn, DtorFnTy),
173                           llvm::ConstantExpr::getBitCast(DeclPtr, Int8PtrTy),
174                           llvm::ConstantExpr::getBitCast(Handle, Int8PtrTy) };
175  Builder.CreateCall(AtExitFn, Args);
176}
177
178void CodeGenFunction::EmitCXXGuardedInit(const VarDecl &D,
179                                         llvm::GlobalVariable *DeclPtr,
180                                         bool PerformInit) {
181  // If we've been asked to forbid guard variables, emit an error now.
182  // This diagnostic is hard-coded for Darwin's use case;  we can find
183  // better phrasing if someone else needs it.
184  if (CGM.getCodeGenOpts().ForbidGuardVariables)
185    CGM.Error(D.getLocation(),
186              "this initialization requires a guard variable, which "
187              "the kernel does not support");
188
189  CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr, PerformInit);
190}
191
192static llvm::Function *
193CreateGlobalInitOrDestructFunction(CodeGenModule &CGM,
194                                   llvm::FunctionType *FTy,
195                                   StringRef Name) {
196  llvm::Function *Fn =
197    llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
198                           Name, &CGM.getModule());
199  if (!CGM.getContext().getLangOptions().AppleKext) {
200    // Set the section if needed.
201    if (const char *Section =
202          CGM.getContext().getTargetInfo().getStaticInitSectionSpecifier())
203      Fn->setSection(Section);
204  }
205
206  if (!CGM.getLangOptions().Exceptions)
207    Fn->setDoesNotThrow();
208
209  return Fn;
210}
211
212void
213CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
214                                            llvm::GlobalVariable *Addr,
215                                            bool PerformInit) {
216  llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
217
218  // Create a variable initialization function.
219  llvm::Function *Fn =
220    CreateGlobalInitOrDestructFunction(*this, FTy, "__cxx_global_var_init");
221
222  CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr,
223                                                          PerformInit);
224
225  if (D->hasAttr<InitPriorityAttr>()) {
226    unsigned int order = D->getAttr<InitPriorityAttr>()->getPriority();
227    OrderGlobalInits Key(order, PrioritizedCXXGlobalInits.size());
228    PrioritizedCXXGlobalInits.push_back(std::make_pair(Key, Fn));
229    DelayedCXXInitPosition.erase(D);
230  }
231  else {
232    llvm::DenseMap<const Decl *, unsigned>::iterator I =
233      DelayedCXXInitPosition.find(D);
234    if (I == DelayedCXXInitPosition.end()) {
235      CXXGlobalInits.push_back(Fn);
236    } else {
237      assert(CXXGlobalInits[I->second] == 0);
238      CXXGlobalInits[I->second] = Fn;
239      DelayedCXXInitPosition.erase(I);
240    }
241  }
242}
243
244void
245CodeGenModule::EmitCXXGlobalInitFunc() {
246  while (!CXXGlobalInits.empty() && !CXXGlobalInits.back())
247    CXXGlobalInits.pop_back();
248
249  if (CXXGlobalInits.empty() && PrioritizedCXXGlobalInits.empty())
250    return;
251
252  llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
253
254  // Create our global initialization function.
255  llvm::Function *Fn =
256    CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__I_a");
257
258  if (!PrioritizedCXXGlobalInits.empty()) {
259    SmallVector<llvm::Constant*, 8> LocalCXXGlobalInits;
260    llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(),
261                         PrioritizedCXXGlobalInits.end());
262    for (unsigned i = 0; i < PrioritizedCXXGlobalInits.size(); i++) {
263      llvm::Function *Fn = PrioritizedCXXGlobalInits[i].second;
264      LocalCXXGlobalInits.push_back(Fn);
265    }
266    LocalCXXGlobalInits.append(CXXGlobalInits.begin(), CXXGlobalInits.end());
267    CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
268                                                    &LocalCXXGlobalInits[0],
269                                                    LocalCXXGlobalInits.size());
270  }
271  else
272    CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
273                                                     &CXXGlobalInits[0],
274                                                     CXXGlobalInits.size());
275  AddGlobalCtor(Fn);
276  CXXGlobalInits.clear();
277  PrioritizedCXXGlobalInits.clear();
278}
279
280void CodeGenModule::EmitCXXGlobalDtorFunc() {
281  if (CXXGlobalDtors.empty())
282    return;
283
284  llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
285
286  // Create our global destructor function.
287  llvm::Function *Fn =
288    CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__D_a");
289
290  CodeGenFunction(*this).GenerateCXXGlobalDtorFunc(Fn, CXXGlobalDtors);
291  AddGlobalDtor(Fn);
292}
293
294/// Emit the code necessary to initialize the given global variable.
295void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
296                                                       const VarDecl *D,
297                                                 llvm::GlobalVariable *Addr,
298                                                       bool PerformInit) {
299  StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
300                getTypes().arrangeNullaryFunction(),
301                FunctionArgList(), SourceLocation());
302
303  // Use guarded initialization if the global variable is weak. This
304  // occurs for, e.g., instantiated static data members and
305  // definitions explicitly marked weak.
306  if (Addr->getLinkage() == llvm::GlobalValue::WeakODRLinkage ||
307      Addr->getLinkage() == llvm::GlobalValue::WeakAnyLinkage) {
308    EmitCXXGuardedInit(*D, Addr, PerformInit);
309  } else {
310    EmitCXXGlobalVarDeclInit(*D, Addr, PerformInit);
311  }
312
313  FinishFunction();
314}
315
316void CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
317                                                llvm::Constant **Decls,
318                                                unsigned NumDecls) {
319  StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
320                getTypes().arrangeNullaryFunction(),
321                FunctionArgList(), SourceLocation());
322
323  RunCleanupsScope Scope(*this);
324
325  // When building in Objective-C++ ARC mode, create an autorelease pool
326  // around the global initializers.
327  if (getLangOptions().ObjCAutoRefCount && getLangOptions().CPlusPlus) {
328    llvm::Value *token = EmitObjCAutoreleasePoolPush();
329    EmitObjCAutoreleasePoolCleanup(token);
330  }
331
332  for (unsigned i = 0; i != NumDecls; ++i)
333    if (Decls[i])
334      Builder.CreateCall(Decls[i]);
335
336  Scope.ForceCleanup();
337
338  FinishFunction();
339}
340
341void CodeGenFunction::GenerateCXXGlobalDtorFunc(llvm::Function *Fn,
342                  const std::vector<std::pair<llvm::WeakVH, llvm::Constant*> >
343                                                &DtorsAndObjects) {
344  StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
345                getTypes().arrangeNullaryFunction(),
346                FunctionArgList(), SourceLocation());
347
348  // Emit the dtors, in reverse order from construction.
349  for (unsigned i = 0, e = DtorsAndObjects.size(); i != e; ++i) {
350    llvm::Value *Callee = DtorsAndObjects[e - i - 1].first;
351    llvm::CallInst *CI = Builder.CreateCall(Callee,
352                                            DtorsAndObjects[e - i - 1].second);
353    // Make sure the call and the callee agree on calling convention.
354    if (llvm::Function *F = dyn_cast<llvm::Function>(Callee))
355      CI->setCallingConv(F->getCallingConv());
356  }
357
358  FinishFunction();
359}
360
361/// generateDestroyHelper - Generates a helper function which, when
362/// invoked, destroys the given object.
363llvm::Function *
364CodeGenFunction::generateDestroyHelper(llvm::Constant *addr,
365                                       QualType type,
366                                       Destroyer *destroyer,
367                                       bool useEHCleanupForArray) {
368  FunctionArgList args;
369  ImplicitParamDecl dst(0, SourceLocation(), 0, getContext().VoidPtrTy);
370  args.push_back(&dst);
371
372  const CGFunctionInfo &FI =
373    CGM.getTypes().arrangeFunctionDeclaration(getContext().VoidTy, args,
374                                              FunctionType::ExtInfo(),
375                                              /*variadic*/ false);
376  llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
377  llvm::Function *fn =
378    CreateGlobalInitOrDestructFunction(CGM, FTy, "__cxx_global_array_dtor");
379
380  StartFunction(GlobalDecl(), getContext().VoidTy, fn, FI, args,
381                SourceLocation());
382
383  emitDestroy(addr, type, destroyer, useEHCleanupForArray);
384
385  FinishFunction();
386
387  return fn;
388}
389