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 
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.
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.
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 
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.
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.
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.
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 
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   }
248 
249   // Otherwise, we just use atexit.
250   emitGlobalDtorWithAtExit(*this, dtor, addr);
251 }
252 
253 void CodeGenFunction::EmitCXXGuardedInit(const VarDecl &D,
254                                          llvm::GlobalVariable *DeclPtr,
255                                          bool PerformInit) {
256   // If we've been asked to forbid guard variables, emit an error now.
257   // This diagnostic is hard-coded for Darwin's use case;  we can find
258   // better phrasing if someone else needs it.
259   if (CGM.getCodeGenOpts().ForbidGuardVariables)
260     CGM.Error(D.getLocation(),
261               "this initialization requires a guard variable, which "
262               "the kernel does not support");
263 
264   CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr, PerformInit);
265 }
266 
267 static llvm::Function *
268 CreateGlobalInitOrDestructFunction(CodeGenModule &CGM,
269                                    llvm::FunctionType *FTy,
270                                    const Twine &Name) {
271   llvm::Function *Fn =
272     llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
273                            Name, &CGM.getModule());
274   if (!CGM.getContext().getLangOpts().AppleKext) {
275     // Set the section if needed.
276     if (const char *Section =
277           CGM.getContext().getTargetInfo().getStaticInitSectionSpecifier())
278       Fn->setSection(Section);
279   }
280 
281   if (!CGM.getLangOpts().Exceptions)
282     Fn->setDoesNotThrow();
283 
284   return Fn;
285 }
286 
287 void
288 CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
289                                             llvm::GlobalVariable *Addr,
290                                             bool PerformInit) {
291   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
292 
293   // Create a variable initialization function.
294   llvm::Function *Fn =
295     CreateGlobalInitOrDestructFunction(*this, FTy, "__cxx_global_var_init");
296 
297   CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr,
298                                                           PerformInit);
299 
300   if (D->hasAttr<InitPriorityAttr>()) {
301     unsigned int order = D->getAttr<InitPriorityAttr>()->getPriority();
302     OrderGlobalInits Key(order, PrioritizedCXXGlobalInits.size());
303     PrioritizedCXXGlobalInits.push_back(std::make_pair(Key, Fn));
304     DelayedCXXInitPosition.erase(D);
305   }
306   else {
307     llvm::DenseMap<const Decl *, unsigned>::iterator I =
308       DelayedCXXInitPosition.find(D);
309     if (I == DelayedCXXInitPosition.end()) {
310       CXXGlobalInits.push_back(Fn);
311     } else {
312       assert(CXXGlobalInits[I->second] == 0);
313       CXXGlobalInits[I->second] = Fn;
314       DelayedCXXInitPosition.erase(I);
315     }
316   }
317 }
318 
319 void
320 CodeGenModule::EmitCXXGlobalInitFunc() {
321   while (!CXXGlobalInits.empty() && !CXXGlobalInits.back())
322     CXXGlobalInits.pop_back();
323 
324   if (CXXGlobalInits.empty() && PrioritizedCXXGlobalInits.empty())
325     return;
326 
327   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
328 
329   // Create our global initialization function.
330   llvm::Function *Fn =
331     CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__I_a");
332 
333   if (!PrioritizedCXXGlobalInits.empty()) {
334     SmallVector<llvm::Constant*, 8> LocalCXXGlobalInits;
335     llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(),
336                          PrioritizedCXXGlobalInits.end());
337     for (unsigned i = 0; i < PrioritizedCXXGlobalInits.size(); i++) {
338       llvm::Function *Fn = PrioritizedCXXGlobalInits[i].second;
339       LocalCXXGlobalInits.push_back(Fn);
340     }
341     LocalCXXGlobalInits.append(CXXGlobalInits.begin(), CXXGlobalInits.end());
342     CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
343                                                     &LocalCXXGlobalInits[0],
344                                                     LocalCXXGlobalInits.size());
345   }
346   else
347     CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
348                                                      &CXXGlobalInits[0],
349                                                      CXXGlobalInits.size());
350   AddGlobalCtor(Fn);
351   CXXGlobalInits.clear();
352   PrioritizedCXXGlobalInits.clear();
353 }
354 
355 void CodeGenModule::EmitCXXGlobalDtorFunc() {
356   if (CXXGlobalDtors.empty())
357     return;
358 
359   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
360 
361   // Create our global destructor function.
362   llvm::Function *Fn =
363     CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__D_a");
364 
365   CodeGenFunction(*this).GenerateCXXGlobalDtorsFunc(Fn, CXXGlobalDtors);
366   AddGlobalDtor(Fn);
367 }
368 
369 /// Emit the code necessary to initialize the given global variable.
370 void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
371                                                        const VarDecl *D,
372                                                  llvm::GlobalVariable *Addr,
373                                                        bool PerformInit) {
374   StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
375                 getTypes().arrangeNullaryFunction(),
376                 FunctionArgList(), SourceLocation());
377 
378   // Use guarded initialization if the global variable is weak. This
379   // occurs for, e.g., instantiated static data members and
380   // definitions explicitly marked weak.
381   if (Addr->getLinkage() == llvm::GlobalValue::WeakODRLinkage ||
382       Addr->getLinkage() == llvm::GlobalValue::WeakAnyLinkage) {
383     EmitCXXGuardedInit(*D, Addr, PerformInit);
384   } else {
385     EmitCXXGlobalVarDeclInit(*D, Addr, PerformInit);
386   }
387 
388   FinishFunction();
389 }
390 
391 void CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
392                                                 llvm::Constant **Decls,
393                                                 unsigned NumDecls) {
394   StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
395                 getTypes().arrangeNullaryFunction(),
396                 FunctionArgList(), SourceLocation());
397 
398   RunCleanupsScope Scope(*this);
399 
400   // When building in Objective-C++ ARC mode, create an autorelease pool
401   // around the global initializers.
402   if (getLangOpts().ObjCAutoRefCount && getLangOpts().CPlusPlus) {
403     llvm::Value *token = EmitObjCAutoreleasePoolPush();
404     EmitObjCAutoreleasePoolCleanup(token);
405   }
406 
407   for (unsigned i = 0; i != NumDecls; ++i)
408     if (Decls[i])
409       Builder.CreateCall(Decls[i]);
410 
411   Scope.ForceCleanup();
412 
413   FinishFunction();
414 }
415 
416 void CodeGenFunction::GenerateCXXGlobalDtorsFunc(llvm::Function *Fn,
417                   const std::vector<std::pair<llvm::WeakVH, llvm::Constant*> >
418                                                 &DtorsAndObjects) {
419   StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
420                 getTypes().arrangeNullaryFunction(),
421                 FunctionArgList(), SourceLocation());
422 
423   // Emit the dtors, in reverse order from construction.
424   for (unsigned i = 0, e = DtorsAndObjects.size(); i != e; ++i) {
425     llvm::Value *Callee = DtorsAndObjects[e - i - 1].first;
426     llvm::CallInst *CI = Builder.CreateCall(Callee,
427                                             DtorsAndObjects[e - i - 1].second);
428     // Make sure the call and the callee agree on calling convention.
429     if (llvm::Function *F = dyn_cast<llvm::Function>(Callee))
430       CI->setCallingConv(F->getCallingConv());
431   }
432 
433   FinishFunction();
434 }
435 
436 /// generateDestroyHelper - Generates a helper function which, when
437 /// invoked, destroys the given object.
438 llvm::Function *
439 CodeGenFunction::generateDestroyHelper(llvm::Constant *addr,
440                                        QualType type,
441                                        Destroyer *destroyer,
442                                        bool useEHCleanupForArray) {
443   FunctionArgList args;
444   ImplicitParamDecl dst(0, SourceLocation(), 0, getContext().VoidPtrTy);
445   args.push_back(&dst);
446 
447   const CGFunctionInfo &FI =
448     CGM.getTypes().arrangeFunctionDeclaration(getContext().VoidTy, args,
449                                               FunctionType::ExtInfo(),
450                                               /*variadic*/ false);
451   llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
452   llvm::Function *fn =
453     CreateGlobalInitOrDestructFunction(CGM, FTy, "__cxx_global_array_dtor");
454 
455   StartFunction(GlobalDecl(), getContext().VoidTy, fn, FI, args,
456                 SourceLocation());
457 
458   emitDestroy(addr, type, destroyer, useEHCleanupForArray);
459 
460   FinishFunction();
461 
462   return fn;
463 }
464