ModuleBuilder.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. //===--- ModuleBuilder.cpp - Emit LLVM Code from ASTs ---------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This builds an AST and converts it to LLVM Code.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/CodeGen/ModuleBuilder.h"
  13. #include "CGDebugInfo.h"
  14. #include "CodeGenModule.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/DeclObjC.h"
  17. #include "clang/AST/Expr.h"
  18. #include "clang/Basic/CodeGenOptions.h"
  19. #include "clang/Basic/Diagnostic.h"
  20. #include "clang/Basic/TargetInfo.h"
  21. #include "llvm/ADT/StringRef.h"
  22. #include "llvm/IR/DataLayout.h"
  23. #include "llvm/IR/LLVMContext.h"
  24. #include "llvm/IR/Module.h"
  25. #include <memory>
  26. using namespace clang;
  27. using namespace CodeGen;
  28. namespace {
  29. class CodeGeneratorImpl : public CodeGenerator {
  30. DiagnosticsEngine &Diags;
  31. ASTContext *Ctx;
  32. const HeaderSearchOptions &HeaderSearchOpts; // Only used for debug info.
  33. const PreprocessorOptions &PreprocessorOpts; // Only used for debug info.
  34. const CodeGenOptions CodeGenOpts; // Intentionally copied in.
  35. unsigned HandlingTopLevelDecls;
  36. /// Use this when emitting decls to block re-entrant decl emission. It will
  37. /// emit all deferred decls on scope exit. Set EmitDeferred to false if decl
  38. /// emission must be deferred longer, like at the end of a tag definition.
  39. struct HandlingTopLevelDeclRAII {
  40. CodeGeneratorImpl &Self;
  41. bool EmitDeferred;
  42. HandlingTopLevelDeclRAII(CodeGeneratorImpl &Self,
  43. bool EmitDeferred = true)
  44. : Self(Self), EmitDeferred(EmitDeferred) {
  45. ++Self.HandlingTopLevelDecls;
  46. }
  47. ~HandlingTopLevelDeclRAII() {
  48. unsigned Level = --Self.HandlingTopLevelDecls;
  49. if (Level == 0 && EmitDeferred)
  50. Self.EmitDeferredDecls();
  51. }
  52. };
  53. CoverageSourceInfo *CoverageInfo;
  54. protected:
  55. std::unique_ptr<llvm::Module> M;
  56. std::unique_ptr<CodeGen::CodeGenModule> Builder;
  57. private:
  58. SmallVector<FunctionDecl *, 8> DeferredInlineMemberFuncDefs;
  59. public:
  60. CodeGeneratorImpl(DiagnosticsEngine &diags, llvm::StringRef ModuleName,
  61. const HeaderSearchOptions &HSO,
  62. const PreprocessorOptions &PPO, const CodeGenOptions &CGO,
  63. llvm::LLVMContext &C,
  64. CoverageSourceInfo *CoverageInfo = nullptr)
  65. : Diags(diags), Ctx(nullptr), HeaderSearchOpts(HSO),
  66. PreprocessorOpts(PPO), CodeGenOpts(CGO), HandlingTopLevelDecls(0),
  67. CoverageInfo(CoverageInfo), M(new llvm::Module(ModuleName, C)) {
  68. C.setDiscardValueNames(CGO.DiscardValueNames);
  69. }
  70. ~CodeGeneratorImpl() override {
  71. // There should normally not be any leftover inline method definitions.
  72. assert(DeferredInlineMemberFuncDefs.empty() ||
  73. Diags.hasErrorOccurred());
  74. }
  75. CodeGenModule &CGM() {
  76. return *Builder;
  77. }
  78. llvm::Module *GetModule() {
  79. return M.get();
  80. }
  81. CGDebugInfo *getCGDebugInfo() {
  82. return Builder->getModuleDebugInfo();
  83. }
  84. llvm::Module *ReleaseModule() {
  85. return M.release();
  86. }
  87. const Decl *GetDeclForMangledName(StringRef MangledName) {
  88. GlobalDecl Result;
  89. if (!Builder->lookupRepresentativeDecl(MangledName, Result))
  90. return nullptr;
  91. const Decl *D = Result.getCanonicalDecl().getDecl();
  92. if (auto FD = dyn_cast<FunctionDecl>(D)) {
  93. if (FD->hasBody(FD))
  94. return FD;
  95. } else if (auto TD = dyn_cast<TagDecl>(D)) {
  96. if (auto Def = TD->getDefinition())
  97. return Def;
  98. }
  99. return D;
  100. }
  101. llvm::Constant *GetAddrOfGlobal(GlobalDecl global, bool isForDefinition) {
  102. return Builder->GetAddrOfGlobal(global, ForDefinition_t(isForDefinition));
  103. }
  104. llvm::Module *StartModule(llvm::StringRef ModuleName,
  105. llvm::LLVMContext &C) {
  106. assert(!M && "Replacing existing Module?");
  107. M.reset(new llvm::Module(ModuleName, C));
  108. Initialize(*Ctx);
  109. return M.get();
  110. }
  111. void Initialize(ASTContext &Context) override {
  112. Ctx = &Context;
  113. M->setTargetTriple(Ctx->getTargetInfo().getTriple().getTriple());
  114. M->setDataLayout(Ctx->getTargetInfo().getDataLayout());
  115. const auto &SDKVersion = Ctx->getTargetInfo().getSDKVersion();
  116. if (!SDKVersion.empty())
  117. M->setSDKVersion(SDKVersion);
  118. Builder.reset(new CodeGen::CodeGenModule(Context, HeaderSearchOpts,
  119. PreprocessorOpts, CodeGenOpts,
  120. *M, Diags, CoverageInfo));
  121. for (auto &&Lib : CodeGenOpts.DependentLibraries)
  122. Builder->AddDependentLib(Lib);
  123. for (auto &&Opt : CodeGenOpts.LinkerOptions)
  124. Builder->AppendLinkerOptions(Opt);
  125. }
  126. void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
  127. if (Diags.hasErrorOccurred())
  128. return;
  129. Builder->HandleCXXStaticMemberVarInstantiation(VD);
  130. }
  131. bool HandleTopLevelDecl(DeclGroupRef DG) override {
  132. if (Diags.hasErrorOccurred())
  133. return true;
  134. HandlingTopLevelDeclRAII HandlingDecl(*this);
  135. // Make sure to emit all elements of a Decl.
  136. for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
  137. Builder->EmitTopLevelDecl(*I);
  138. return true;
  139. }
  140. void EmitDeferredDecls() {
  141. if (DeferredInlineMemberFuncDefs.empty())
  142. return;
  143. // Emit any deferred inline method definitions. Note that more deferred
  144. // methods may be added during this loop, since ASTConsumer callbacks
  145. // can be invoked if AST inspection results in declarations being added.
  146. HandlingTopLevelDeclRAII HandlingDecl(*this);
  147. for (unsigned I = 0; I != DeferredInlineMemberFuncDefs.size(); ++I)
  148. Builder->EmitTopLevelDecl(DeferredInlineMemberFuncDefs[I]);
  149. DeferredInlineMemberFuncDefs.clear();
  150. }
  151. void HandleInlineFunctionDefinition(FunctionDecl *D) override {
  152. if (Diags.hasErrorOccurred())
  153. return;
  154. assert(D->doesThisDeclarationHaveABody());
  155. // We may want to emit this definition. However, that decision might be
  156. // based on computing the linkage, and we have to defer that in case we
  157. // are inside of something that will change the method's final linkage,
  158. // e.g.
  159. // typedef struct {
  160. // void bar();
  161. // void foo() { bar(); }
  162. // } A;
  163. DeferredInlineMemberFuncDefs.push_back(D);
  164. // Provide some coverage mapping even for methods that aren't emitted.
  165. // Don't do this for templated classes though, as they may not be
  166. // instantiable.
  167. if (!D->getLexicalDeclContext()->isDependentContext())
  168. Builder->AddDeferredUnusedCoverageMapping(D);
  169. }
  170. /// HandleTagDeclDefinition - This callback is invoked each time a TagDecl
  171. /// to (e.g. struct, union, enum, class) is completed. This allows the
  172. /// client hack on the type, which can occur at any point in the file
  173. /// (because these can be defined in declspecs).
  174. void HandleTagDeclDefinition(TagDecl *D) override {
  175. if (Diags.hasErrorOccurred())
  176. return;
  177. // Don't allow re-entrant calls to CodeGen triggered by PCH
  178. // deserialization to emit deferred decls.
  179. HandlingTopLevelDeclRAII HandlingDecl(*this, /*EmitDeferred=*/false);
  180. Builder->UpdateCompletedType(D);
  181. // For MSVC compatibility, treat declarations of static data members with
  182. // inline initializers as definitions.
  183. if (Ctx->getTargetInfo().getCXXABI().isMicrosoft()) {
  184. for (Decl *Member : D->decls()) {
  185. if (VarDecl *VD = dyn_cast<VarDecl>(Member)) {
  186. if (Ctx->isMSStaticDataMemberInlineDefinition(VD) &&
  187. Ctx->DeclMustBeEmitted(VD)) {
  188. Builder->EmitGlobal(VD);
  189. }
  190. }
  191. }
  192. }
  193. // For OpenMP emit declare reduction functions, if required.
  194. if (Ctx->getLangOpts().OpenMP) {
  195. for (Decl *Member : D->decls()) {
  196. if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Member)) {
  197. if (Ctx->DeclMustBeEmitted(DRD))
  198. Builder->EmitGlobal(DRD);
  199. }
  200. }
  201. }
  202. }
  203. void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
  204. if (Diags.hasErrorOccurred())
  205. return;
  206. // Don't allow re-entrant calls to CodeGen triggered by PCH
  207. // deserialization to emit deferred decls.
  208. HandlingTopLevelDeclRAII HandlingDecl(*this, /*EmitDeferred=*/false);
  209. if (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo())
  210. if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
  211. DI->completeRequiredType(RD);
  212. }
  213. void HandleTranslationUnit(ASTContext &Ctx) override {
  214. // Release the Builder when there is no error.
  215. if (!Diags.hasErrorOccurred() && Builder)
  216. Builder->Release();
  217. // If there are errors before or when releasing the Builder, reset
  218. // the module to stop here before invoking the backend.
  219. if (Diags.hasErrorOccurred()) {
  220. if (Builder)
  221. Builder->clear();
  222. M.reset();
  223. return;
  224. }
  225. }
  226. void AssignInheritanceModel(CXXRecordDecl *RD) override {
  227. if (Diags.hasErrorOccurred())
  228. return;
  229. Builder->RefreshTypeCacheForClass(RD);
  230. }
  231. void CompleteTentativeDefinition(VarDecl *D) override {
  232. if (Diags.hasErrorOccurred())
  233. return;
  234. Builder->EmitTentativeDefinition(D);
  235. }
  236. void HandleVTable(CXXRecordDecl *RD) override {
  237. if (Diags.hasErrorOccurred())
  238. return;
  239. Builder->EmitVTable(RD);
  240. }
  241. };
  242. }
  243. void CodeGenerator::anchor() { }
  244. CodeGenModule &CodeGenerator::CGM() {
  245. return static_cast<CodeGeneratorImpl*>(this)->CGM();
  246. }
  247. llvm::Module *CodeGenerator::GetModule() {
  248. return static_cast<CodeGeneratorImpl*>(this)->GetModule();
  249. }
  250. llvm::Module *CodeGenerator::ReleaseModule() {
  251. return static_cast<CodeGeneratorImpl*>(this)->ReleaseModule();
  252. }
  253. CGDebugInfo *CodeGenerator::getCGDebugInfo() {
  254. return static_cast<CodeGeneratorImpl*>(this)->getCGDebugInfo();
  255. }
  256. const Decl *CodeGenerator::GetDeclForMangledName(llvm::StringRef name) {
  257. return static_cast<CodeGeneratorImpl*>(this)->GetDeclForMangledName(name);
  258. }
  259. llvm::Constant *CodeGenerator::GetAddrOfGlobal(GlobalDecl global,
  260. bool isForDefinition) {
  261. return static_cast<CodeGeneratorImpl*>(this)
  262. ->GetAddrOfGlobal(global, isForDefinition);
  263. }
  264. llvm::Module *CodeGenerator::StartModule(llvm::StringRef ModuleName,
  265. llvm::LLVMContext &C) {
  266. return static_cast<CodeGeneratorImpl*>(this)->StartModule(ModuleName, C);
  267. }
  268. CodeGenerator *clang::CreateLLVMCodeGen(
  269. DiagnosticsEngine &Diags, llvm::StringRef ModuleName,
  270. const HeaderSearchOptions &HeaderSearchOpts,
  271. const PreprocessorOptions &PreprocessorOpts, const CodeGenOptions &CGO,
  272. llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo) {
  273. return new CodeGeneratorImpl(Diags, ModuleName, HeaderSearchOpts,
  274. PreprocessorOpts, CGO, C, CoverageInfo);
  275. }