ModuleBuilder.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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. static llvm::StringRef ExpandModuleName(llvm::StringRef ModuleName,
  60. const CodeGenOptions &CGO) {
  61. if (ModuleName == "-" && !CGO.MainFileName.empty())
  62. return CGO.MainFileName;
  63. return ModuleName;
  64. }
  65. public:
  66. CodeGeneratorImpl(DiagnosticsEngine &diags, llvm::StringRef ModuleName,
  67. const HeaderSearchOptions &HSO,
  68. const PreprocessorOptions &PPO, const CodeGenOptions &CGO,
  69. llvm::LLVMContext &C,
  70. CoverageSourceInfo *CoverageInfo = nullptr)
  71. : Diags(diags), Ctx(nullptr), HeaderSearchOpts(HSO),
  72. PreprocessorOpts(PPO), CodeGenOpts(CGO), HandlingTopLevelDecls(0),
  73. CoverageInfo(CoverageInfo),
  74. M(new llvm::Module(ExpandModuleName(ModuleName, CGO), C)) {
  75. C.setDiscardValueNames(CGO.DiscardValueNames);
  76. }
  77. ~CodeGeneratorImpl() override {
  78. // There should normally not be any leftover inline method definitions.
  79. assert(DeferredInlineMemberFuncDefs.empty() ||
  80. Diags.hasErrorOccurred());
  81. }
  82. CodeGenModule &CGM() {
  83. return *Builder;
  84. }
  85. llvm::Module *GetModule() {
  86. return M.get();
  87. }
  88. CGDebugInfo *getCGDebugInfo() {
  89. return Builder->getModuleDebugInfo();
  90. }
  91. llvm::Module *ReleaseModule() {
  92. return M.release();
  93. }
  94. const Decl *GetDeclForMangledName(StringRef MangledName) {
  95. GlobalDecl Result;
  96. if (!Builder->lookupRepresentativeDecl(MangledName, Result))
  97. return nullptr;
  98. const Decl *D = Result.getCanonicalDecl().getDecl();
  99. if (auto FD = dyn_cast<FunctionDecl>(D)) {
  100. if (FD->hasBody(FD))
  101. return FD;
  102. } else if (auto TD = dyn_cast<TagDecl>(D)) {
  103. if (auto Def = TD->getDefinition())
  104. return Def;
  105. }
  106. return D;
  107. }
  108. llvm::StringRef GetMangledName(GlobalDecl GD) {
  109. return Builder->getMangledName(GD);
  110. }
  111. llvm::Constant *GetAddrOfGlobal(GlobalDecl global, bool isForDefinition) {
  112. return Builder->GetAddrOfGlobal(global, ForDefinition_t(isForDefinition));
  113. }
  114. llvm::Module *StartModule(llvm::StringRef ModuleName,
  115. llvm::LLVMContext &C) {
  116. assert(!M && "Replacing existing Module?");
  117. M.reset(new llvm::Module(ExpandModuleName(ModuleName, CodeGenOpts), C));
  118. Initialize(*Ctx);
  119. return M.get();
  120. }
  121. void Initialize(ASTContext &Context) override {
  122. Ctx = &Context;
  123. M->setTargetTriple(Ctx->getTargetInfo().getTriple().getTriple());
  124. M->setDataLayout(Ctx->getTargetInfo().getDataLayoutString());
  125. const auto &SDKVersion = Ctx->getTargetInfo().getSDKVersion();
  126. if (!SDKVersion.empty())
  127. M->setSDKVersion(SDKVersion);
  128. Builder.reset(new CodeGen::CodeGenModule(Context, HeaderSearchOpts,
  129. PreprocessorOpts, CodeGenOpts,
  130. *M, Diags, CoverageInfo));
  131. for (auto &&Lib : CodeGenOpts.DependentLibraries)
  132. Builder->AddDependentLib(Lib);
  133. for (auto &&Opt : CodeGenOpts.LinkerOptions)
  134. Builder->AppendLinkerOptions(Opt);
  135. }
  136. void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
  137. if (Diags.hasErrorOccurred())
  138. return;
  139. Builder->HandleCXXStaticMemberVarInstantiation(VD);
  140. }
  141. bool HandleTopLevelDecl(DeclGroupRef DG) override {
  142. if (Diags.hasErrorOccurred())
  143. return true;
  144. HandlingTopLevelDeclRAII HandlingDecl(*this);
  145. // Make sure to emit all elements of a Decl.
  146. for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
  147. Builder->EmitTopLevelDecl(*I);
  148. return true;
  149. }
  150. void EmitDeferredDecls() {
  151. if (DeferredInlineMemberFuncDefs.empty())
  152. return;
  153. // Emit any deferred inline method definitions. Note that more deferred
  154. // methods may be added during this loop, since ASTConsumer callbacks
  155. // can be invoked if AST inspection results in declarations being added.
  156. HandlingTopLevelDeclRAII HandlingDecl(*this);
  157. for (unsigned I = 0; I != DeferredInlineMemberFuncDefs.size(); ++I)
  158. Builder->EmitTopLevelDecl(DeferredInlineMemberFuncDefs[I]);
  159. DeferredInlineMemberFuncDefs.clear();
  160. }
  161. void HandleInlineFunctionDefinition(FunctionDecl *D) override {
  162. if (Diags.hasErrorOccurred())
  163. return;
  164. assert(D->doesThisDeclarationHaveABody());
  165. // We may want to emit this definition. However, that decision might be
  166. // based on computing the linkage, and we have to defer that in case we
  167. // are inside of something that will change the method's final linkage,
  168. // e.g.
  169. // typedef struct {
  170. // void bar();
  171. // void foo() { bar(); }
  172. // } A;
  173. DeferredInlineMemberFuncDefs.push_back(D);
  174. // Provide some coverage mapping even for methods that aren't emitted.
  175. // Don't do this for templated classes though, as they may not be
  176. // instantiable.
  177. if (!D->getLexicalDeclContext()->isDependentContext())
  178. Builder->AddDeferredUnusedCoverageMapping(D);
  179. }
  180. /// HandleTagDeclDefinition - This callback is invoked each time a TagDecl
  181. /// to (e.g. struct, union, enum, class) is completed. This allows the
  182. /// client hack on the type, which can occur at any point in the file
  183. /// (because these can be defined in declspecs).
  184. void HandleTagDeclDefinition(TagDecl *D) override {
  185. if (Diags.hasErrorOccurred())
  186. return;
  187. // Don't allow re-entrant calls to CodeGen triggered by PCH
  188. // deserialization to emit deferred decls.
  189. HandlingTopLevelDeclRAII HandlingDecl(*this, /*EmitDeferred=*/false);
  190. Builder->UpdateCompletedType(D);
  191. // For MSVC compatibility, treat declarations of static data members with
  192. // inline initializers as definitions.
  193. if (Ctx->getTargetInfo().getCXXABI().isMicrosoft()) {
  194. for (Decl *Member : D->decls()) {
  195. if (VarDecl *VD = dyn_cast<VarDecl>(Member)) {
  196. if (Ctx->isMSStaticDataMemberInlineDefinition(VD) &&
  197. Ctx->DeclMustBeEmitted(VD)) {
  198. Builder->EmitGlobal(VD);
  199. }
  200. }
  201. }
  202. }
  203. // For OpenMP emit declare reduction functions, if required.
  204. if (Ctx->getLangOpts().OpenMP) {
  205. for (Decl *Member : D->decls()) {
  206. if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Member)) {
  207. if (Ctx->DeclMustBeEmitted(DRD))
  208. Builder->EmitGlobal(DRD);
  209. } else if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Member)) {
  210. if (Ctx->DeclMustBeEmitted(DMD))
  211. Builder->EmitGlobal(DMD);
  212. }
  213. }
  214. }
  215. }
  216. void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
  217. if (Diags.hasErrorOccurred())
  218. return;
  219. // Don't allow re-entrant calls to CodeGen triggered by PCH
  220. // deserialization to emit deferred decls.
  221. HandlingTopLevelDeclRAII HandlingDecl(*this, /*EmitDeferred=*/false);
  222. if (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo())
  223. if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
  224. DI->completeRequiredType(RD);
  225. }
  226. void HandleTranslationUnit(ASTContext &Ctx) override {
  227. // Release the Builder when there is no error.
  228. if (!Diags.hasErrorOccurred() && Builder)
  229. Builder->Release();
  230. // If there are errors before or when releasing the Builder, reset
  231. // the module to stop here before invoking the backend.
  232. if (Diags.hasErrorOccurred()) {
  233. if (Builder)
  234. Builder->clear();
  235. M.reset();
  236. return;
  237. }
  238. }
  239. void AssignInheritanceModel(CXXRecordDecl *RD) override {
  240. if (Diags.hasErrorOccurred())
  241. return;
  242. Builder->RefreshTypeCacheForClass(RD);
  243. }
  244. void CompleteTentativeDefinition(VarDecl *D) override {
  245. if (Diags.hasErrorOccurred())
  246. return;
  247. Builder->EmitTentativeDefinition(D);
  248. }
  249. void CompleteExternalDeclaration(VarDecl *D) override {
  250. Builder->EmitExternalDeclaration(D);
  251. }
  252. void HandleVTable(CXXRecordDecl *RD) override {
  253. if (Diags.hasErrorOccurred())
  254. return;
  255. Builder->EmitVTable(RD);
  256. }
  257. };
  258. }
  259. void CodeGenerator::anchor() { }
  260. CodeGenModule &CodeGenerator::CGM() {
  261. return static_cast<CodeGeneratorImpl*>(this)->CGM();
  262. }
  263. llvm::Module *CodeGenerator::GetModule() {
  264. return static_cast<CodeGeneratorImpl*>(this)->GetModule();
  265. }
  266. llvm::Module *CodeGenerator::ReleaseModule() {
  267. return static_cast<CodeGeneratorImpl*>(this)->ReleaseModule();
  268. }
  269. CGDebugInfo *CodeGenerator::getCGDebugInfo() {
  270. return static_cast<CodeGeneratorImpl*>(this)->getCGDebugInfo();
  271. }
  272. const Decl *CodeGenerator::GetDeclForMangledName(llvm::StringRef name) {
  273. return static_cast<CodeGeneratorImpl*>(this)->GetDeclForMangledName(name);
  274. }
  275. llvm::StringRef CodeGenerator::GetMangledName(GlobalDecl GD) {
  276. return static_cast<CodeGeneratorImpl *>(this)->GetMangledName(GD);
  277. }
  278. llvm::Constant *CodeGenerator::GetAddrOfGlobal(GlobalDecl global,
  279. bool isForDefinition) {
  280. return static_cast<CodeGeneratorImpl*>(this)
  281. ->GetAddrOfGlobal(global, isForDefinition);
  282. }
  283. llvm::Module *CodeGenerator::StartModule(llvm::StringRef ModuleName,
  284. llvm::LLVMContext &C) {
  285. return static_cast<CodeGeneratorImpl*>(this)->StartModule(ModuleName, C);
  286. }
  287. CodeGenerator *clang::CreateLLVMCodeGen(
  288. DiagnosticsEngine &Diags, llvm::StringRef ModuleName,
  289. const HeaderSearchOptions &HeaderSearchOpts,
  290. const PreprocessorOptions &PreprocessorOpts, const CodeGenOptions &CGO,
  291. llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo) {
  292. return new CodeGeneratorImpl(Diags, ModuleName, HeaderSearchOpts,
  293. PreprocessorOpts, CGO, C, CoverageInfo);
  294. }