ModuleBuilder.cpp 12 KB

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