ModuleBuilder.cpp 13 KB

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