• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
20 using namespace clang;
21 using namespace CodeGen;
22 
EmitDeclInit(CodeGenFunction & CGF,const VarDecl & D,llvm::Constant * DeclPtr)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!");
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.
EmitDeclDestroy(CodeGenFunction & CGF,const VarDecl & D,llvm::Constant * addr)57 static 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.
EmitDeclInvariant(CodeGenFunction & CGF,const VarDecl & D,llvm::Constant * Addr)106 static void EmitDeclInvariant(CodeGenFunction &CGF, const VarDecl &D,
107                               llvm::Constant *Addr) {
108   // Don't emit the intrinsic if we're not optimizing.
109   if (!CGF.CGM.getCodeGenOpts().OptimizationLevel)
110     return;
111 
112   // Grab the llvm.invariant.start intrinsic.
113   llvm::Intrinsic::ID InvStartID = llvm::Intrinsic::invariant_start;
114   llvm::Constant *InvariantStart = CGF.CGM.getIntrinsic(InvStartID);
115 
116   // Emit a call with the size in bytes of the object.
117   CharUnits WidthChars = CGF.getContext().getTypeSizeInChars(D.getType());
118   uint64_t Width = WidthChars.getQuantity();
119   llvm::Value *Args[2] = { llvm::ConstantInt::getSigned(CGF.Int64Ty, Width),
120                            llvm::ConstantExpr::getBitCast(Addr, CGF.Int8PtrTy)};
121   CGF.Builder.CreateCall(InvariantStart, Args);
122 }
123 
EmitCXXGlobalVarDeclInit(const VarDecl & D,llvm::Constant * DeclPtr,bool PerformInit)124 void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
125                                                llvm::Constant *DeclPtr,
126                                                bool PerformInit) {
127 
128   const Expr *Init = D.getInit();
129   QualType T = D.getType();
130 
131   if (!T->isReferenceType()) {
132     if (PerformInit)
133       EmitDeclInit(*this, D, DeclPtr);
134     if (CGM.isTypeConstant(D.getType(), true))
135       EmitDeclInvariant(*this, D, DeclPtr);
136     else
137       EmitDeclDestroy(*this, D, DeclPtr);
138     return;
139   }
140 
141   assert(PerformInit && "cannot have constant initializer which needs "
142          "destruction for reference");
143   unsigned Alignment = getContext().getDeclAlign(&D).getQuantity();
144   RValue RV = EmitReferenceBindingToExpr(Init, &D);
145   EmitStoreOfScalar(RV.getScalarVal(), DeclPtr, false, Alignment, T);
146 }
147 
148 /// Register a global destructor using __cxa_atexit.
emitGlobalDtorWithCXAAtExit(CodeGenFunction & CGF,llvm::Constant * dtor,llvm::Constant * addr)149 static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
150                                         llvm::Constant *dtor,
151                                         llvm::Constant *addr) {
152   // We're assuming that the destructor function is something we can
153   // reasonably call with the default CC.  Go ahead and cast it to the
154   // right prototype.
155   llvm::Type *dtorTy =
156     llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
157 
158   // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
159   llvm::Type *paramTys[] = { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
160   llvm::FunctionType *atexitTy =
161     llvm::FunctionType::get(CGF.IntTy, paramTys, false);
162 
163   // Fetch the actual function.
164   llvm::Constant *atexit =
165     CGF.CGM.CreateRuntimeFunction(atexitTy, "__cxa_atexit");
166   if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
167     fn->setDoesNotThrow();
168 
169   // Create a variable that binds the atexit to this shared object.
170   llvm::Constant *handle =
171     CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
172 
173   llvm::Value *args[] = {
174     llvm::ConstantExpr::getBitCast(dtor, dtorTy),
175     llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
176     handle
177   };
178   CGF.Builder.CreateCall(atexit, args);
179 }
180 
181 static llvm::Function *
182 CreateGlobalInitOrDestructFunction(CodeGenModule &CGM,
183                                    llvm::FunctionType *ty,
184                                    const Twine &name);
185 
186 /// Create a stub function, suitable for being passed to atexit,
187 /// which passes the given address to the given destructor function.
createAtExitStub(CodeGenModule & CGM,llvm::Constant * dtor,llvm::Constant * addr)188 static llvm::Constant *createAtExitStub(CodeGenModule &CGM,
189                                         llvm::Constant *dtor,
190                                         llvm::Constant *addr) {
191   // Get the destructor function type, void(*)(void).
192   llvm::FunctionType *ty = llvm::FunctionType::get(CGM.VoidTy, false);
193   llvm::Function *fn =
194     CreateGlobalInitOrDestructFunction(CGM, ty,
195                                        Twine("__dtor_", addr->getName()));
196 
197   CodeGenFunction CGF(CGM);
198 
199   CGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, fn,
200                     CGM.getTypes().arrangeNullaryFunction(),
201                     FunctionArgList(), SourceLocation());
202 
203   llvm::CallInst *call = CGF.Builder.CreateCall(dtor, addr);
204 
205  // Make sure the call and the callee agree on calling convention.
206   if (llvm::Function *dtorFn =
207         dyn_cast<llvm::Function>(dtor->stripPointerCasts()))
208     call->setCallingConv(dtorFn->getCallingConv());
209 
210   CGF.FinishFunction();
211 
212   return fn;
213 }
214 
215 /// Register a global destructor using atexit.
emitGlobalDtorWithAtExit(CodeGenFunction & CGF,llvm::Constant * dtor,llvm::Constant * addr)216 static void emitGlobalDtorWithAtExit(CodeGenFunction &CGF,
217                                      llvm::Constant *dtor,
218                                      llvm::Constant *addr) {
219   // Create a function which calls the destructor.
220   llvm::Constant *dtorStub = createAtExitStub(CGF.CGM, dtor, addr);
221 
222   // extern "C" int atexit(void (*f)(void));
223   llvm::FunctionType *atexitTy =
224     llvm::FunctionType::get(CGF.IntTy, dtorStub->getType(), false);
225 
226   llvm::Constant *atexit =
227     CGF.CGM.CreateRuntimeFunction(atexitTy, "atexit");
228   if (llvm::Function *atexitFn = dyn_cast<llvm::Function>(atexit))
229     atexitFn->setDoesNotThrow();
230 
231   CGF.Builder.CreateCall(atexit, dtorStub);
232 }
233 
EmitCXXGlobalDtorRegistration(llvm::Constant * dtor,llvm::Constant * addr)234 void CodeGenFunction::EmitCXXGlobalDtorRegistration(llvm::Constant *dtor,
235                                                     llvm::Constant *addr) {
236   // Use __cxa_atexit if available.
237   if (CGM.getCodeGenOpts().CXAAtExit) {
238     emitGlobalDtorWithCXAAtExit(*this, dtor, addr);
239     return;
240   }
241 
242   // In Apple kexts, we want to add a global destructor entry.
243   // FIXME: shouldn't this be guarded by some variable?
244   if (CGM.getContext().getLangOpts().AppleKext) {
245     // Generate a global destructor entry.
246     CGM.AddCXXDtorEntry(dtor, addr);
247     return;
248   }
249 
250   // Otherwise, we just use atexit.
251   emitGlobalDtorWithAtExit(*this, dtor, addr);
252 }
253 
EmitCXXGuardedInit(const VarDecl & D,llvm::GlobalVariable * DeclPtr,bool PerformInit)254 void CodeGenFunction::EmitCXXGuardedInit(const VarDecl &D,
255                                          llvm::GlobalVariable *DeclPtr,
256                                          bool PerformInit) {
257   // If we've been asked to forbid guard variables, emit an error now.
258   // This diagnostic is hard-coded for Darwin's use case;  we can find
259   // better phrasing if someone else needs it.
260   if (CGM.getCodeGenOpts().ForbidGuardVariables)
261     CGM.Error(D.getLocation(),
262               "this initialization requires a guard variable, which "
263               "the kernel does not support");
264 
265   CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr, PerformInit);
266 }
267 
268 static llvm::Function *
CreateGlobalInitOrDestructFunction(CodeGenModule & CGM,llvm::FunctionType * FTy,const Twine & Name)269 CreateGlobalInitOrDestructFunction(CodeGenModule &CGM,
270                                    llvm::FunctionType *FTy,
271                                    const Twine &Name) {
272   llvm::Function *Fn =
273     llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
274                            Name, &CGM.getModule());
275   if (!CGM.getContext().getLangOpts().AppleKext) {
276     // Set the section if needed.
277     if (const char *Section =
278           CGM.getContext().getTargetInfo().getStaticInitSectionSpecifier())
279       Fn->setSection(Section);
280   }
281 
282   if (!CGM.getLangOpts().Exceptions)
283     Fn->setDoesNotThrow();
284 
285   return Fn;
286 }
287 
288 void
EmitCXXGlobalVarDeclInitFunc(const VarDecl * D,llvm::GlobalVariable * Addr,bool PerformInit)289 CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
290                                             llvm::GlobalVariable *Addr,
291                                             bool PerformInit) {
292   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
293 
294   // Create a variable initialization function.
295   llvm::Function *Fn =
296     CreateGlobalInitOrDestructFunction(*this, FTy, "__cxx_global_var_init");
297 
298   CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr,
299                                                           PerformInit);
300 
301   if (D->hasAttr<InitPriorityAttr>()) {
302     unsigned int order = D->getAttr<InitPriorityAttr>()->getPriority();
303     OrderGlobalInits Key(order, PrioritizedCXXGlobalInits.size());
304     PrioritizedCXXGlobalInits.push_back(std::make_pair(Key, Fn));
305     DelayedCXXInitPosition.erase(D);
306   }
307   else {
308     llvm::DenseMap<const Decl *, unsigned>::iterator I =
309       DelayedCXXInitPosition.find(D);
310     if (I == DelayedCXXInitPosition.end()) {
311       CXXGlobalInits.push_back(Fn);
312     } else {
313       assert(CXXGlobalInits[I->second] == 0);
314       CXXGlobalInits[I->second] = Fn;
315       DelayedCXXInitPosition.erase(I);
316     }
317   }
318 }
319 
320 void
EmitCXXGlobalInitFunc()321 CodeGenModule::EmitCXXGlobalInitFunc() {
322   while (!CXXGlobalInits.empty() && !CXXGlobalInits.back())
323     CXXGlobalInits.pop_back();
324 
325   if (CXXGlobalInits.empty() && PrioritizedCXXGlobalInits.empty())
326     return;
327 
328   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
329 
330   // Create our global initialization function.
331   llvm::Function *Fn =
332     CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__I_a");
333 
334   if (!PrioritizedCXXGlobalInits.empty()) {
335     SmallVector<llvm::Constant*, 8> LocalCXXGlobalInits;
336     llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(),
337                          PrioritizedCXXGlobalInits.end());
338     for (unsigned i = 0; i < PrioritizedCXXGlobalInits.size(); i++) {
339       llvm::Function *Fn = PrioritizedCXXGlobalInits[i].second;
340       LocalCXXGlobalInits.push_back(Fn);
341     }
342     LocalCXXGlobalInits.append(CXXGlobalInits.begin(), CXXGlobalInits.end());
343     CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
344                                                     &LocalCXXGlobalInits[0],
345                                                     LocalCXXGlobalInits.size());
346   }
347   else
348     CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
349                                                      &CXXGlobalInits[0],
350                                                      CXXGlobalInits.size());
351   AddGlobalCtor(Fn);
352   CXXGlobalInits.clear();
353   PrioritizedCXXGlobalInits.clear();
354 }
355 
EmitCXXGlobalDtorFunc()356 void CodeGenModule::EmitCXXGlobalDtorFunc() {
357   if (CXXGlobalDtors.empty())
358     return;
359 
360   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
361 
362   // Create our global destructor function.
363   llvm::Function *Fn =
364     CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__D_a");
365 
366   CodeGenFunction(*this).GenerateCXXGlobalDtorsFunc(Fn, CXXGlobalDtors);
367   AddGlobalDtor(Fn);
368 }
369 
370 /// Emit the code necessary to initialize the given global variable.
GenerateCXXGlobalVarDeclInitFunc(llvm::Function * Fn,const VarDecl * D,llvm::GlobalVariable * Addr,bool PerformInit)371 void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
372                                                        const VarDecl *D,
373                                                  llvm::GlobalVariable *Addr,
374                                                        bool PerformInit) {
375   StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
376                 getTypes().arrangeNullaryFunction(),
377                 FunctionArgList(), SourceLocation());
378 
379   // Use guarded initialization if the global variable is weak. This
380   // occurs for, e.g., instantiated static data members and
381   // definitions explicitly marked weak.
382   if (Addr->getLinkage() == llvm::GlobalValue::WeakODRLinkage ||
383       Addr->getLinkage() == llvm::GlobalValue::WeakAnyLinkage) {
384     EmitCXXGuardedInit(*D, Addr, PerformInit);
385   } else {
386     EmitCXXGlobalVarDeclInit(*D, Addr, PerformInit);
387   }
388 
389   FinishFunction();
390 }
391 
GenerateCXXGlobalInitFunc(llvm::Function * Fn,llvm::Constant ** Decls,unsigned NumDecls)392 void CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
393                                                 llvm::Constant **Decls,
394                                                 unsigned NumDecls) {
395   StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
396                 getTypes().arrangeNullaryFunction(),
397                 FunctionArgList(), SourceLocation());
398 
399   RunCleanupsScope Scope(*this);
400 
401   // When building in Objective-C++ ARC mode, create an autorelease pool
402   // around the global initializers.
403   if (getLangOpts().ObjCAutoRefCount && getLangOpts().CPlusPlus) {
404     llvm::Value *token = EmitObjCAutoreleasePoolPush();
405     EmitObjCAutoreleasePoolCleanup(token);
406   }
407 
408   for (unsigned i = 0; i != NumDecls; ++i)
409     if (Decls[i])
410       Builder.CreateCall(Decls[i]);
411 
412   Scope.ForceCleanup();
413 
414   FinishFunction();
415 }
416 
GenerateCXXGlobalDtorsFunc(llvm::Function * Fn,const std::vector<std::pair<llvm::WeakVH,llvm::Constant * >> & DtorsAndObjects)417 void CodeGenFunction::GenerateCXXGlobalDtorsFunc(llvm::Function *Fn,
418                   const std::vector<std::pair<llvm::WeakVH, llvm::Constant*> >
419                                                 &DtorsAndObjects) {
420   StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
421                 getTypes().arrangeNullaryFunction(),
422                 FunctionArgList(), SourceLocation());
423 
424   // Emit the dtors, in reverse order from construction.
425   for (unsigned i = 0, e = DtorsAndObjects.size(); i != e; ++i) {
426     llvm::Value *Callee = DtorsAndObjects[e - i - 1].first;
427     llvm::CallInst *CI = Builder.CreateCall(Callee,
428                                             DtorsAndObjects[e - i - 1].second);
429     // Make sure the call and the callee agree on calling convention.
430     if (llvm::Function *F = dyn_cast<llvm::Function>(Callee))
431       CI->setCallingConv(F->getCallingConv());
432   }
433 
434   FinishFunction();
435 }
436 
437 /// generateDestroyHelper - Generates a helper function which, when
438 /// invoked, destroys the given object.
439 llvm::Function *
generateDestroyHelper(llvm::Constant * addr,QualType type,Destroyer * destroyer,bool useEHCleanupForArray)440 CodeGenFunction::generateDestroyHelper(llvm::Constant *addr,
441                                        QualType type,
442                                        Destroyer *destroyer,
443                                        bool useEHCleanupForArray) {
444   FunctionArgList args;
445   ImplicitParamDecl dst(0, SourceLocation(), 0, getContext().VoidPtrTy);
446   args.push_back(&dst);
447 
448   const CGFunctionInfo &FI =
449     CGM.getTypes().arrangeFunctionDeclaration(getContext().VoidTy, args,
450                                               FunctionType::ExtInfo(),
451                                               /*variadic*/ false);
452   llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
453   llvm::Function *fn =
454     CreateGlobalInitOrDestructFunction(CGM, FTy, "__cxx_global_array_dtor");
455 
456   StartFunction(GlobalDecl(), getContext().VoidTy, fn, FI, args,
457                 SourceLocation());
458 
459   emitDestroy(addr, type, destroyer, useEHCleanupForArray);
460 
461   FinishFunction();
462 
463   return fn;
464 }
465