CGDeclCXX.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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. #include "CodeGenFunction.h"
  14. #include "CGObjCRuntime.h"
  15. #include "CGCXXABI.h"
  16. #include "clang/Frontend/CodeGenOptions.h"
  17. #include "llvm/Intrinsics.h"
  18. using namespace clang;
  19. using namespace CodeGen;
  20. static void EmitDeclInit(CodeGenFunction &CGF, const VarDecl &D,
  21. llvm::Constant *DeclPtr) {
  22. assert(D.hasGlobalStorage() && "VarDecl must have global storage!");
  23. assert(!D.getType()->isReferenceType() &&
  24. "Should not call EmitDeclInit on a reference!");
  25. ASTContext &Context = CGF.getContext();
  26. CharUnits alignment = Context.getDeclAlign(&D);
  27. QualType type = D.getType();
  28. LValue lv = CGF.MakeAddrLValue(DeclPtr, type, alignment);
  29. const Expr *Init = D.getInit();
  30. if (!CGF.hasAggregateLLVMType(type)) {
  31. CodeGenModule &CGM = CGF.CGM;
  32. if (lv.isObjCStrong())
  33. CGM.getObjCRuntime().EmitObjCGlobalAssign(CGF, CGF.EmitScalarExpr(Init),
  34. DeclPtr, D.isThreadSpecified());
  35. else if (lv.isObjCWeak())
  36. CGM.getObjCRuntime().EmitObjCWeakAssign(CGF, CGF.EmitScalarExpr(Init),
  37. DeclPtr);
  38. else
  39. CGF.EmitScalarInit(Init, &D, lv, false);
  40. } else if (type->isAnyComplexType()) {
  41. CGF.EmitComplexExprIntoAddr(Init, DeclPtr, lv.isVolatile());
  42. } else {
  43. CGF.EmitAggExpr(Init, AggValueSlot::forLValue(lv,AggValueSlot::IsDestructed,
  44. AggValueSlot::DoesNotNeedGCBarriers,
  45. AggValueSlot::IsNotAliased));
  46. }
  47. }
  48. /// Emit code to cause the destruction of the given variable with
  49. /// static storage duration.
  50. static void EmitDeclDestroy(CodeGenFunction &CGF, const VarDecl &D,
  51. llvm::Constant *addr) {
  52. CodeGenModule &CGM = CGF.CGM;
  53. // FIXME: __attribute__((cleanup)) ?
  54. QualType type = D.getType();
  55. QualType::DestructionKind dtorKind = type.isDestructedType();
  56. switch (dtorKind) {
  57. case QualType::DK_none:
  58. return;
  59. case QualType::DK_cxx_destructor:
  60. break;
  61. case QualType::DK_objc_strong_lifetime:
  62. case QualType::DK_objc_weak_lifetime:
  63. // We don't care about releasing objects during process teardown.
  64. return;
  65. }
  66. llvm::Constant *function;
  67. llvm::Constant *argument;
  68. // Special-case non-array C++ destructors, where there's a function
  69. // with the right signature that we can just call.
  70. const CXXRecordDecl *record = 0;
  71. if (dtorKind == QualType::DK_cxx_destructor &&
  72. (record = type->getAsCXXRecordDecl())) {
  73. assert(!record->hasTrivialDestructor());
  74. CXXDestructorDecl *dtor = record->getDestructor();
  75. function = CGM.GetAddrOfCXXDestructor(dtor, Dtor_Complete);
  76. argument = addr;
  77. // Otherwise, the standard logic requires a helper function.
  78. } else {
  79. function = CodeGenFunction(CGM).generateDestroyHelper(addr, type,
  80. CGF.getDestroyer(dtorKind),
  81. CGF.needsEHCleanup(dtorKind));
  82. argument = llvm::Constant::getNullValue(CGF.Int8PtrTy);
  83. }
  84. CGF.EmitCXXGlobalDtorRegistration(function, argument);
  85. }
  86. void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
  87. llvm::Constant *DeclPtr,
  88. bool PerformInit) {
  89. const Expr *Init = D.getInit();
  90. QualType T = D.getType();
  91. if (!T->isReferenceType()) {
  92. if (PerformInit)
  93. EmitDeclInit(*this, D, DeclPtr);
  94. EmitDeclDestroy(*this, D, DeclPtr);
  95. return;
  96. }
  97. assert(PerformInit && "cannot have constant initializer which needs "
  98. "destruction for reference");
  99. unsigned Alignment = getContext().getDeclAlign(&D).getQuantity();
  100. RValue RV = EmitReferenceBindingToExpr(Init, &D);
  101. EmitStoreOfScalar(RV.getScalarVal(), DeclPtr, false, Alignment, T);
  102. }
  103. void
  104. CodeGenFunction::EmitCXXGlobalDtorRegistration(llvm::Constant *DtorFn,
  105. llvm::Constant *DeclPtr) {
  106. // Generate a global destructor entry if not using __cxa_atexit.
  107. if (!CGM.getCodeGenOpts().CXAAtExit) {
  108. CGM.AddCXXDtorEntry(DtorFn, DeclPtr);
  109. return;
  110. }
  111. // Get the destructor function type
  112. llvm::Type *DtorFnTy = llvm::FunctionType::get(VoidTy, Int8PtrTy, false);
  113. DtorFnTy = llvm::PointerType::getUnqual(DtorFnTy);
  114. llvm::Type *Params[] = { DtorFnTy, Int8PtrTy, Int8PtrTy };
  115. // Get the __cxa_atexit function type
  116. // extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
  117. llvm::FunctionType *AtExitFnTy =
  118. llvm::FunctionType::get(ConvertType(getContext().IntTy), Params, false);
  119. llvm::Constant *AtExitFn = CGM.CreateRuntimeFunction(AtExitFnTy,
  120. "__cxa_atexit");
  121. if (llvm::Function *Fn = dyn_cast<llvm::Function>(AtExitFn))
  122. Fn->setDoesNotThrow();
  123. llvm::Constant *Handle = CGM.CreateRuntimeVariable(Int8PtrTy,
  124. "__dso_handle");
  125. llvm::Value *Args[3] = { llvm::ConstantExpr::getBitCast(DtorFn, DtorFnTy),
  126. llvm::ConstantExpr::getBitCast(DeclPtr, Int8PtrTy),
  127. llvm::ConstantExpr::getBitCast(Handle, Int8PtrTy) };
  128. Builder.CreateCall(AtExitFn, Args);
  129. }
  130. void CodeGenFunction::EmitCXXGuardedInit(const VarDecl &D,
  131. llvm::GlobalVariable *DeclPtr,
  132. bool PerformInit) {
  133. // If we've been asked to forbid guard variables, emit an error now.
  134. // This diagnostic is hard-coded for Darwin's use case; we can find
  135. // better phrasing if someone else needs it.
  136. if (CGM.getCodeGenOpts().ForbidGuardVariables)
  137. CGM.Error(D.getLocation(),
  138. "this initialization requires a guard variable, which "
  139. "the kernel does not support");
  140. CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr, PerformInit);
  141. }
  142. static llvm::Function *
  143. CreateGlobalInitOrDestructFunction(CodeGenModule &CGM,
  144. llvm::FunctionType *FTy,
  145. StringRef Name) {
  146. llvm::Function *Fn =
  147. llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
  148. Name, &CGM.getModule());
  149. if (!CGM.getContext().getLangOptions().AppleKext) {
  150. // Set the section if needed.
  151. if (const char *Section =
  152. CGM.getContext().getTargetInfo().getStaticInitSectionSpecifier())
  153. Fn->setSection(Section);
  154. }
  155. if (!CGM.getLangOptions().Exceptions)
  156. Fn->setDoesNotThrow();
  157. return Fn;
  158. }
  159. void
  160. CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
  161. llvm::GlobalVariable *Addr,
  162. bool PerformInit) {
  163. llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
  164. // Create a variable initialization function.
  165. llvm::Function *Fn =
  166. CreateGlobalInitOrDestructFunction(*this, FTy, "__cxx_global_var_init");
  167. CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr,
  168. PerformInit);
  169. if (D->hasAttr<InitPriorityAttr>()) {
  170. unsigned int order = D->getAttr<InitPriorityAttr>()->getPriority();
  171. OrderGlobalInits Key(order, PrioritizedCXXGlobalInits.size());
  172. PrioritizedCXXGlobalInits.push_back(std::make_pair(Key, Fn));
  173. DelayedCXXInitPosition.erase(D);
  174. }
  175. else {
  176. llvm::DenseMap<const Decl *, unsigned>::iterator I =
  177. DelayedCXXInitPosition.find(D);
  178. if (I == DelayedCXXInitPosition.end()) {
  179. CXXGlobalInits.push_back(Fn);
  180. } else {
  181. assert(CXXGlobalInits[I->second] == 0);
  182. CXXGlobalInits[I->second] = Fn;
  183. DelayedCXXInitPosition.erase(I);
  184. }
  185. }
  186. }
  187. void
  188. CodeGenModule::EmitCXXGlobalInitFunc() {
  189. while (!CXXGlobalInits.empty() && !CXXGlobalInits.back())
  190. CXXGlobalInits.pop_back();
  191. if (CXXGlobalInits.empty() && PrioritizedCXXGlobalInits.empty())
  192. return;
  193. llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
  194. // Create our global initialization function.
  195. llvm::Function *Fn =
  196. CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__I_a");
  197. if (!PrioritizedCXXGlobalInits.empty()) {
  198. SmallVector<llvm::Constant*, 8> LocalCXXGlobalInits;
  199. llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(),
  200. PrioritizedCXXGlobalInits.end());
  201. for (unsigned i = 0; i < PrioritizedCXXGlobalInits.size(); i++) {
  202. llvm::Function *Fn = PrioritizedCXXGlobalInits[i].second;
  203. LocalCXXGlobalInits.push_back(Fn);
  204. }
  205. LocalCXXGlobalInits.append(CXXGlobalInits.begin(), CXXGlobalInits.end());
  206. CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
  207. &LocalCXXGlobalInits[0],
  208. LocalCXXGlobalInits.size());
  209. }
  210. else
  211. CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
  212. &CXXGlobalInits[0],
  213. CXXGlobalInits.size());
  214. AddGlobalCtor(Fn);
  215. CXXGlobalInits.clear();
  216. PrioritizedCXXGlobalInits.clear();
  217. }
  218. void CodeGenModule::EmitCXXGlobalDtorFunc() {
  219. if (CXXGlobalDtors.empty())
  220. return;
  221. llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
  222. // Create our global destructor function.
  223. llvm::Function *Fn =
  224. CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__D_a");
  225. CodeGenFunction(*this).GenerateCXXGlobalDtorFunc(Fn, CXXGlobalDtors);
  226. AddGlobalDtor(Fn);
  227. }
  228. /// Emit the code necessary to initialize the given global variable.
  229. void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
  230. const VarDecl *D,
  231. llvm::GlobalVariable *Addr,
  232. bool PerformInit) {
  233. StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
  234. getTypes().arrangeNullaryFunction(),
  235. FunctionArgList(), SourceLocation());
  236. // Use guarded initialization if the global variable is weak. This
  237. // occurs for, e.g., instantiated static data members and
  238. // definitions explicitly marked weak.
  239. if (Addr->getLinkage() == llvm::GlobalValue::WeakODRLinkage ||
  240. Addr->getLinkage() == llvm::GlobalValue::WeakAnyLinkage) {
  241. EmitCXXGuardedInit(*D, Addr, PerformInit);
  242. } else {
  243. EmitCXXGlobalVarDeclInit(*D, Addr, PerformInit);
  244. }
  245. FinishFunction();
  246. }
  247. void CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
  248. llvm::Constant **Decls,
  249. unsigned NumDecls) {
  250. StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
  251. getTypes().arrangeNullaryFunction(),
  252. FunctionArgList(), SourceLocation());
  253. RunCleanupsScope Scope(*this);
  254. // When building in Objective-C++ ARC mode, create an autorelease pool
  255. // around the global initializers.
  256. if (getLangOptions().ObjCAutoRefCount && getLangOptions().CPlusPlus) {
  257. llvm::Value *token = EmitObjCAutoreleasePoolPush();
  258. EmitObjCAutoreleasePoolCleanup(token);
  259. }
  260. for (unsigned i = 0; i != NumDecls; ++i)
  261. if (Decls[i])
  262. Builder.CreateCall(Decls[i]);
  263. Scope.ForceCleanup();
  264. FinishFunction();
  265. }
  266. void CodeGenFunction::GenerateCXXGlobalDtorFunc(llvm::Function *Fn,
  267. const std::vector<std::pair<llvm::WeakVH, llvm::Constant*> >
  268. &DtorsAndObjects) {
  269. StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
  270. getTypes().arrangeNullaryFunction(),
  271. FunctionArgList(), SourceLocation());
  272. // Emit the dtors, in reverse order from construction.
  273. for (unsigned i = 0, e = DtorsAndObjects.size(); i != e; ++i) {
  274. llvm::Value *Callee = DtorsAndObjects[e - i - 1].first;
  275. llvm::CallInst *CI = Builder.CreateCall(Callee,
  276. DtorsAndObjects[e - i - 1].second);
  277. // Make sure the call and the callee agree on calling convention.
  278. if (llvm::Function *F = dyn_cast<llvm::Function>(Callee))
  279. CI->setCallingConv(F->getCallingConv());
  280. }
  281. FinishFunction();
  282. }
  283. /// generateDestroyHelper - Generates a helper function which, when
  284. /// invoked, destroys the given object.
  285. llvm::Function *
  286. CodeGenFunction::generateDestroyHelper(llvm::Constant *addr,
  287. QualType type,
  288. Destroyer *destroyer,
  289. bool useEHCleanupForArray) {
  290. FunctionArgList args;
  291. ImplicitParamDecl dst(0, SourceLocation(), 0, getContext().VoidPtrTy);
  292. args.push_back(&dst);
  293. const CGFunctionInfo &FI =
  294. CGM.getTypes().arrangeFunctionDeclaration(getContext().VoidTy, args,
  295. FunctionType::ExtInfo(),
  296. /*variadic*/ false);
  297. llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
  298. llvm::Function *fn =
  299. CreateGlobalInitOrDestructFunction(CGM, FTy, "__cxx_global_array_dtor");
  300. StartFunction(GlobalDecl(), getContext().VoidTy, fn, FI, args,
  301. SourceLocation());
  302. emitDestroy(addr, type, destroyer, useEHCleanupForArray);
  303. FinishFunction();
  304. return fn;
  305. }