CGDeclCXX.cpp revision 223017
1219820Sjeff//===--- CGDeclCXX.cpp - Emit LLVM Code for C++ declarations --------------===//
2219820Sjeff//
3219820Sjeff//                     The LLVM Compiler Infrastructure
4219820Sjeff//
5219820Sjeff// This file is distributed under the University of Illinois Open Source
6219820Sjeff// License. See LICENSE.TXT for details.
7219820Sjeff//
8219820Sjeff//===----------------------------------------------------------------------===//
9219820Sjeff//
10219820Sjeff// This contains code dealing with code generation of C++ declarations
11219820Sjeff//
12219820Sjeff//===----------------------------------------------------------------------===//
13219820Sjeff
14219820Sjeff#include "CodeGenFunction.h"
15219820Sjeff#include "CGObjCRuntime.h"
16219820Sjeff#include "CGCXXABI.h"
17219820Sjeff#include "clang/Frontend/CodeGenOptions.h"
18219820Sjeff#include "llvm/Intrinsics.h"
19219820Sjeff
20219820Sjeffusing namespace clang;
21219820Sjeffusing namespace CodeGen;
22219820Sjeff
23219820Sjeffstatic void EmitDeclInit(CodeGenFunction &CGF, const VarDecl &D,
24219820Sjeff                         llvm::Constant *DeclPtr) {
25219820Sjeff  assert(D.hasGlobalStorage() && "VarDecl must have global storage!");
26219820Sjeff  assert(!D.getType()->isReferenceType() &&
27219820Sjeff         "Should not call EmitDeclInit on a reference!");
28219820Sjeff
29219820Sjeff  ASTContext &Context = CGF.getContext();
30219820Sjeff
31219820Sjeff  const Expr *Init = D.getInit();
32219820Sjeff  QualType T = D.getType();
33219820Sjeff  bool isVolatile = Context.getCanonicalType(T).isVolatileQualified();
34219820Sjeff
35219820Sjeff  unsigned Alignment = Context.getDeclAlign(&D).getQuantity();
36219820Sjeff  if (!CGF.hasAggregateLLVMType(T)) {
37219820Sjeff    llvm::Value *V = CGF.EmitScalarExpr(Init);
38219820Sjeff    CodeGenModule &CGM = CGF.CGM;
39219820Sjeff    Qualifiers::GC GCAttr = CGM.getContext().getObjCGCAttrKind(T);
40219820Sjeff    if (GCAttr == Qualifiers::Strong)
41219820Sjeff      CGM.getObjCRuntime().EmitObjCGlobalAssign(CGF, V, DeclPtr,
42219820Sjeff                                                D.isThreadSpecified());
43219820Sjeff    else if (GCAttr == Qualifiers::Weak)
44219820Sjeff      CGM.getObjCRuntime().EmitObjCWeakAssign(CGF, V, DeclPtr);
45219820Sjeff    else
46219820Sjeff      CGF.EmitStoreOfScalar(V, DeclPtr, isVolatile, Alignment, T);
47219820Sjeff  } else if (T->isAnyComplexType()) {
48219820Sjeff    CGF.EmitComplexExprIntoAddr(Init, DeclPtr, isVolatile);
49219820Sjeff  } else {
50219820Sjeff    CGF.EmitAggExpr(Init, AggValueSlot::forAddr(DeclPtr, isVolatile, true));
51219820Sjeff  }
52219820Sjeff}
53219820Sjeff
54219820Sjeff/// Emit code to cause the destruction of the given variable with
55219820Sjeff/// static storage duration.
56219820Sjeffstatic void EmitDeclDestroy(CodeGenFunction &CGF, const VarDecl &D,
57219820Sjeff                            llvm::Constant *DeclPtr) {
58219820Sjeff  CodeGenModule &CGM = CGF.CGM;
59219820Sjeff  ASTContext &Context = CGF.getContext();
60219820Sjeff
61219820Sjeff  QualType T = D.getType();
62219820Sjeff
63219820Sjeff  // Drill down past array types.
64219820Sjeff  const ConstantArrayType *Array = Context.getAsConstantArrayType(T);
65219820Sjeff  if (Array)
66219820Sjeff    T = Context.getBaseElementType(Array);
67219820Sjeff
68219820Sjeff  /// If that's not a record, we're done.
69219820Sjeff  /// FIXME:  __attribute__((cleanup)) ?
70219820Sjeff  const RecordType *RT = T->getAs<RecordType>();
71219820Sjeff  if (!RT)
72219820Sjeff    return;
73219820Sjeff
74219820Sjeff  CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
75219820Sjeff  if (RD->hasTrivialDestructor())
76219820Sjeff    return;
77219820Sjeff
78219820Sjeff  CXXDestructorDecl *Dtor = RD->getDestructor();
79219820Sjeff
80219820Sjeff  llvm::Constant *DtorFn;
81219820Sjeff  if (Array) {
82219820Sjeff    DtorFn =
83219820Sjeff      CodeGenFunction(CGM).GenerateCXXAggrDestructorHelper(Dtor, Array,
84219820Sjeff                                                           DeclPtr);
85219820Sjeff    const llvm::Type *Int8PtrTy =
86219820Sjeff      llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
87219820Sjeff    DeclPtr = llvm::Constant::getNullValue(Int8PtrTy);
88219820Sjeff  } else
89219820Sjeff    DtorFn = CGM.GetAddrOfCXXDestructor(Dtor, Dtor_Complete);
90219820Sjeff
91219820Sjeff  CGF.EmitCXXGlobalDtorRegistration(DtorFn, DeclPtr);
92219820Sjeff}
93219820Sjeff
94219820Sjeffvoid CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
95219820Sjeff                                               llvm::Constant *DeclPtr) {
96219820Sjeff
97219820Sjeff  const Expr *Init = D.getInit();
98219820Sjeff  QualType T = D.getType();
99219820Sjeff
100219820Sjeff  if (!T->isReferenceType()) {
101219820Sjeff    EmitDeclInit(*this, D, DeclPtr);
102219820Sjeff    EmitDeclDestroy(*this, D, DeclPtr);
103219820Sjeff    return;
104219820Sjeff  }
105219820Sjeff
106219820Sjeff  unsigned Alignment = getContext().getDeclAlign(&D).getQuantity();
107219820Sjeff  RValue RV = EmitReferenceBindingToExpr(Init, &D);
108219820Sjeff  EmitStoreOfScalar(RV.getScalarVal(), DeclPtr, false, Alignment, T);
109219820Sjeff}
110219820Sjeff
111219820Sjeffvoid
112219820SjeffCodeGenFunction::EmitCXXGlobalDtorRegistration(llvm::Constant *DtorFn,
113219820Sjeff                                               llvm::Constant *DeclPtr) {
114219820Sjeff  // Generate a global destructor entry if not using __cxa_atexit.
115219820Sjeff  if (!CGM.getCodeGenOpts().CXAAtExit) {
116219820Sjeff    CGM.AddCXXDtorEntry(DtorFn, DeclPtr);
117219820Sjeff    return;
118219820Sjeff  }
119219820Sjeff
120219820Sjeff  // Get the destructor function type
121219820Sjeff  const llvm::Type *DtorFnTy =
122219820Sjeff    llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()),
123219820Sjeff                            Int8PtrTy, false);
124219820Sjeff  DtorFnTy = llvm::PointerType::getUnqual(DtorFnTy);
125219820Sjeff
126219820Sjeff  const llvm::Type *Params[] = { DtorFnTy, Int8PtrTy, Int8PtrTy };
127219820Sjeff
128219820Sjeff  // Get the __cxa_atexit function type
129219820Sjeff  // extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
130219820Sjeff  const llvm::FunctionType *AtExitFnTy =
131219820Sjeff    llvm::FunctionType::get(ConvertType(getContext().IntTy), Params, false);
132219820Sjeff
133219820Sjeff  llvm::Constant *AtExitFn = CGM.CreateRuntimeFunction(AtExitFnTy,
134219820Sjeff                                                       "__cxa_atexit");
135219820Sjeff  if (llvm::Function *Fn = dyn_cast<llvm::Function>(AtExitFn))
136219820Sjeff    Fn->setDoesNotThrow();
137219820Sjeff
138219820Sjeff  llvm::Constant *Handle = CGM.CreateRuntimeVariable(Int8PtrTy,
139219820Sjeff                                                     "__dso_handle");
140219820Sjeff  llvm::Value *Args[3] = { llvm::ConstantExpr::getBitCast(DtorFn, DtorFnTy),
141219820Sjeff                           llvm::ConstantExpr::getBitCast(DeclPtr, Int8PtrTy),
142219820Sjeff                           llvm::ConstantExpr::getBitCast(Handle, Int8PtrTy) };
143  Builder.CreateCall(AtExitFn, &Args[0], llvm::array_endof(Args));
144}
145
146void CodeGenFunction::EmitCXXGuardedInit(const VarDecl &D,
147                                         llvm::GlobalVariable *DeclPtr) {
148  // If we've been asked to forbid guard variables, emit an error now.
149  // This diagnostic is hard-coded for Darwin's use case;  we can find
150  // better phrasing if someone else needs it.
151  if (CGM.getCodeGenOpts().ForbidGuardVariables)
152    CGM.Error(D.getLocation(),
153              "this initialization requires a guard variable, which "
154              "the kernel does not support");
155
156  CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr);
157}
158
159static llvm::Function *
160CreateGlobalInitOrDestructFunction(CodeGenModule &CGM,
161                                   const llvm::FunctionType *FTy,
162                                   llvm::StringRef Name) {
163  llvm::Function *Fn =
164    llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
165                           Name, &CGM.getModule());
166  if (!CGM.getContext().getLangOptions().AppleKext) {
167    // Set the section if needed.
168    if (const char *Section =
169          CGM.getContext().Target.getStaticInitSectionSpecifier())
170      Fn->setSection(Section);
171  }
172
173  if (!CGM.getLangOptions().Exceptions)
174    Fn->setDoesNotThrow();
175
176  return Fn;
177}
178
179void
180CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
181                                            llvm::GlobalVariable *Addr) {
182  const llvm::FunctionType *FTy
183    = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
184                              false);
185
186  // Create a variable initialization function.
187  llvm::Function *Fn =
188    CreateGlobalInitOrDestructFunction(*this, FTy, "__cxx_global_var_init");
189
190  CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr);
191
192  if (D->hasAttr<InitPriorityAttr>()) {
193    unsigned int order = D->getAttr<InitPriorityAttr>()->getPriority();
194    OrderGlobalInits Key(order, PrioritizedCXXGlobalInits.size());
195    PrioritizedCXXGlobalInits.push_back(std::make_pair(Key, Fn));
196    DelayedCXXInitPosition.erase(D);
197  }
198  else {
199    llvm::DenseMap<const Decl *, unsigned>::iterator I =
200      DelayedCXXInitPosition.find(D);
201    if (I == DelayedCXXInitPosition.end()) {
202      CXXGlobalInits.push_back(Fn);
203    } else {
204      assert(CXXGlobalInits[I->second] == 0);
205      CXXGlobalInits[I->second] = Fn;
206      DelayedCXXInitPosition.erase(I);
207    }
208  }
209}
210
211void
212CodeGenModule::EmitCXXGlobalInitFunc() {
213  while (!CXXGlobalInits.empty() && !CXXGlobalInits.back())
214    CXXGlobalInits.pop_back();
215
216  if (CXXGlobalInits.empty() && PrioritizedCXXGlobalInits.empty())
217    return;
218
219  const llvm::FunctionType *FTy
220    = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
221                              false);
222
223  // Create our global initialization function.
224  llvm::Function *Fn =
225    CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__I_a");
226
227  if (!PrioritizedCXXGlobalInits.empty()) {
228    llvm::SmallVector<llvm::Constant*, 8> LocalCXXGlobalInits;
229    llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(),
230                         PrioritizedCXXGlobalInits.end());
231    for (unsigned i = 0; i < PrioritizedCXXGlobalInits.size(); i++) {
232      llvm::Function *Fn = PrioritizedCXXGlobalInits[i].second;
233      LocalCXXGlobalInits.push_back(Fn);
234    }
235    LocalCXXGlobalInits.append(CXXGlobalInits.begin(), CXXGlobalInits.end());
236    CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
237                                                    &LocalCXXGlobalInits[0],
238                                                    LocalCXXGlobalInits.size());
239  }
240  else
241    CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
242                                                     &CXXGlobalInits[0],
243                                                     CXXGlobalInits.size());
244  AddGlobalCtor(Fn);
245  CXXGlobalInits.clear();
246  PrioritizedCXXGlobalInits.clear();
247}
248
249void CodeGenModule::EmitCXXGlobalDtorFunc() {
250  if (CXXGlobalDtors.empty())
251    return;
252
253  const llvm::FunctionType *FTy
254    = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
255                              false);
256
257  // Create our global destructor function.
258  llvm::Function *Fn =
259    CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__D_a");
260
261  CodeGenFunction(*this).GenerateCXXGlobalDtorFunc(Fn, CXXGlobalDtors);
262  AddGlobalDtor(Fn);
263}
264
265/// Emit the code necessary to initialize the given global variable.
266void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
267                                                       const VarDecl *D,
268                                                 llvm::GlobalVariable *Addr) {
269  StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
270                getTypes().getNullaryFunctionInfo(),
271                FunctionArgList(), SourceLocation());
272
273  // Use guarded initialization if the global variable is weak due to
274  // being a class template's static data member.  These will always
275  // have weak_odr linkage.
276  if (Addr->getLinkage() == llvm::GlobalValue::WeakODRLinkage &&
277      D->isStaticDataMember() &&
278      D->getInstantiatedFromStaticDataMember()) {
279    EmitCXXGuardedInit(*D, Addr);
280  } else {
281    EmitCXXGlobalVarDeclInit(*D, Addr);
282  }
283
284  FinishFunction();
285}
286
287void CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
288                                                llvm::Constant **Decls,
289                                                unsigned NumDecls) {
290  StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
291                getTypes().getNullaryFunctionInfo(),
292                FunctionArgList(), SourceLocation());
293
294  for (unsigned i = 0; i != NumDecls; ++i)
295    if (Decls[i])
296      Builder.CreateCall(Decls[i]);
297
298  FinishFunction();
299}
300
301void CodeGenFunction::GenerateCXXGlobalDtorFunc(llvm::Function *Fn,
302                  const std::vector<std::pair<llvm::WeakVH, llvm::Constant*> >
303                                                &DtorsAndObjects) {
304  StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
305                getTypes().getNullaryFunctionInfo(),
306                FunctionArgList(), SourceLocation());
307
308  // Emit the dtors, in reverse order from construction.
309  for (unsigned i = 0, e = DtorsAndObjects.size(); i != e; ++i) {
310    llvm::Value *Callee = DtorsAndObjects[e - i - 1].first;
311    llvm::CallInst *CI = Builder.CreateCall(Callee,
312                                            DtorsAndObjects[e - i - 1].second);
313    // Make sure the call and the callee agree on calling convention.
314    if (llvm::Function *F = dyn_cast<llvm::Function>(Callee))
315      CI->setCallingConv(F->getCallingConv());
316  }
317
318  FinishFunction();
319}
320
321/// GenerateCXXAggrDestructorHelper - Generates a helper function which when
322/// invoked, calls the default destructor on array elements in reverse order of
323/// construction.
324llvm::Function *
325CodeGenFunction::GenerateCXXAggrDestructorHelper(const CXXDestructorDecl *D,
326                                                 const ArrayType *Array,
327                                                 llvm::Value *This) {
328  FunctionArgList args;
329  ImplicitParamDecl dst(0, SourceLocation(), 0, getContext().VoidPtrTy);
330  args.push_back(&dst);
331
332  const CGFunctionInfo &FI =
333    CGM.getTypes().getFunctionInfo(getContext().VoidTy, args,
334                                   FunctionType::ExtInfo());
335  const llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI, false);
336  llvm::Function *Fn =
337    CreateGlobalInitOrDestructFunction(CGM, FTy, "__cxx_global_array_dtor");
338
339  StartFunction(GlobalDecl(), getContext().VoidTy, Fn, FI, args,
340                SourceLocation());
341
342  QualType BaseElementTy = getContext().getBaseElementType(Array);
343  const llvm::Type *BasePtr = ConvertType(BaseElementTy)->getPointerTo();
344  llvm::Value *BaseAddrPtr = Builder.CreateBitCast(This, BasePtr);
345
346  EmitCXXAggrDestructorCall(D, Array, BaseAddrPtr);
347
348  FinishFunction();
349
350  return Fn;
351}
352