ModuleBuilder.cpp 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. //===--- ModuleBuilder.cpp - Emit LLVM Code from ASTs ---------------------===//
  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 builds an AST and converts it to LLVM Code.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/CodeGen/ModuleBuilder.h"
  14. #include "CGDebugInfo.h"
  15. #include "CodeGenModule.h"
  16. #include "clang/AST/ASTContext.h"
  17. #include "clang/AST/DeclObjC.h"
  18. #include "clang/AST/Expr.h"
  19. #include "clang/Basic/Diagnostic.h"
  20. #include "clang/Basic/TargetInfo.h"
  21. #include "clang/Frontend/CodeGenOptions.h"
  22. #include "llvm/ADT/StringRef.h"
  23. #include "llvm/IR/DataLayout.h"
  24. #include "llvm/IR/LLVMContext.h"
  25. #include "llvm/IR/Module.h"
  26. #include <memory>
  27. using namespace clang;
  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. struct HandlingTopLevelDeclRAII {
  37. CodeGeneratorImpl &Self;
  38. HandlingTopLevelDeclRAII(CodeGeneratorImpl &Self) : Self(Self) {
  39. ++Self.HandlingTopLevelDecls;
  40. }
  41. ~HandlingTopLevelDeclRAII() {
  42. if (--Self.HandlingTopLevelDecls == 0)
  43. Self.EmitDeferredDecls();
  44. }
  45. };
  46. CoverageSourceInfo *CoverageInfo;
  47. protected:
  48. std::unique_ptr<llvm::Module> M;
  49. std::unique_ptr<CodeGen::CodeGenModule> Builder;
  50. private:
  51. SmallVector<CXXMethodDecl *, 8> DeferredInlineMethodDefinitions;
  52. public:
  53. CodeGeneratorImpl(DiagnosticsEngine &diags, const std::string &ModuleName,
  54. const HeaderSearchOptions &HSO,
  55. const PreprocessorOptions &PPO, const CodeGenOptions &CGO,
  56. llvm::LLVMContext &C,
  57. CoverageSourceInfo *CoverageInfo = nullptr)
  58. : Diags(diags), Ctx(nullptr), HeaderSearchOpts(HSO),
  59. PreprocessorOpts(PPO), CodeGenOpts(CGO), HandlingTopLevelDecls(0),
  60. CoverageInfo(CoverageInfo), M(new llvm::Module(ModuleName, C)) {
  61. C.setDiscardValueNames(CGO.DiscardValueNames);
  62. }
  63. ~CodeGeneratorImpl() override {
  64. // There should normally not be any leftover inline method definitions.
  65. assert(DeferredInlineMethodDefinitions.empty() ||
  66. Diags.hasErrorOccurred());
  67. }
  68. llvm::Module* GetModule() override {
  69. return M.get();
  70. }
  71. const Decl *GetDeclForMangledName(StringRef MangledName) override {
  72. GlobalDecl Result;
  73. if (!Builder->lookupRepresentativeDecl(MangledName, Result))
  74. return nullptr;
  75. const Decl *D = Result.getCanonicalDecl().getDecl();
  76. if (auto FD = dyn_cast<FunctionDecl>(D)) {
  77. if (FD->hasBody(FD))
  78. return FD;
  79. } else if (auto TD = dyn_cast<TagDecl>(D)) {
  80. if (auto Def = TD->getDefinition())
  81. return Def;
  82. }
  83. return D;
  84. }
  85. llvm::Module *ReleaseModule() override { return M.release(); }
  86. void Initialize(ASTContext &Context) override {
  87. Ctx = &Context;
  88. M->setTargetTriple(Ctx->getTargetInfo().getTriple().getTriple());
  89. M->setDataLayout(Ctx->getTargetInfo().getDataLayout());
  90. Builder.reset(new CodeGen::CodeGenModule(Context, HeaderSearchOpts,
  91. PreprocessorOpts, CodeGenOpts,
  92. *M, Diags, CoverageInfo));
  93. for (auto &&Lib : CodeGenOpts.DependentLibraries)
  94. Builder->AddDependentLib(Lib);
  95. for (auto &&Opt : CodeGenOpts.LinkerOptions)
  96. Builder->AppendLinkerOptions(Opt);
  97. }
  98. void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
  99. if (Diags.hasErrorOccurred())
  100. return;
  101. Builder->HandleCXXStaticMemberVarInstantiation(VD);
  102. }
  103. bool HandleTopLevelDecl(DeclGroupRef DG) override {
  104. if (Diags.hasErrorOccurred())
  105. return true;
  106. HandlingTopLevelDeclRAII HandlingDecl(*this);
  107. // Make sure to emit all elements of a Decl.
  108. for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
  109. Builder->EmitTopLevelDecl(*I);
  110. return true;
  111. }
  112. void EmitDeferredDecls() {
  113. if (DeferredInlineMethodDefinitions.empty())
  114. return;
  115. // Emit any deferred inline method definitions. Note that more deferred
  116. // methods may be added during this loop, since ASTConsumer callbacks
  117. // can be invoked if AST inspection results in declarations being added.
  118. HandlingTopLevelDeclRAII HandlingDecl(*this);
  119. for (unsigned I = 0; I != DeferredInlineMethodDefinitions.size(); ++I)
  120. Builder->EmitTopLevelDecl(DeferredInlineMethodDefinitions[I]);
  121. DeferredInlineMethodDefinitions.clear();
  122. }
  123. void HandleInlineFunctionDefinition(FunctionDecl *D) override {
  124. if (Diags.hasErrorOccurred())
  125. return;
  126. assert(D->doesThisDeclarationHaveABody());
  127. // Handle friend functions.
  128. if (D->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend)) {
  129. if (Ctx->getTargetInfo().getCXXABI().isMicrosoft()
  130. && !D->getLexicalDeclContext()->isDependentContext())
  131. Builder->EmitTopLevelDecl(D);
  132. return;
  133. }
  134. // Otherwise, must be a method.
  135. auto MD = cast<CXXMethodDecl>(D);
  136. // We may want to emit this definition. However, that decision might be
  137. // based on computing the linkage, and we have to defer that in case we
  138. // are inside of something that will change the method's final linkage,
  139. // e.g.
  140. // typedef struct {
  141. // void bar();
  142. // void foo() { bar(); }
  143. // } A;
  144. DeferredInlineMethodDefinitions.push_back(MD);
  145. // Provide some coverage mapping even for methods that aren't emitted.
  146. // Don't do this for templated classes though, as they may not be
  147. // instantiable.
  148. if (!MD->getParent()->getDescribedClassTemplate())
  149. Builder->AddDeferredUnusedCoverageMapping(MD);
  150. }
  151. /// HandleTagDeclDefinition - This callback is invoked each time a TagDecl
  152. /// to (e.g. struct, union, enum, class) is completed. This allows the
  153. /// client hack on the type, which can occur at any point in the file
  154. /// (because these can be defined in declspecs).
  155. void HandleTagDeclDefinition(TagDecl *D) override {
  156. if (Diags.hasErrorOccurred())
  157. return;
  158. Builder->UpdateCompletedType(D);
  159. // For MSVC compatibility, treat declarations of static data members with
  160. // inline initializers as definitions.
  161. if (Ctx->getTargetInfo().getCXXABI().isMicrosoft()) {
  162. for (Decl *Member : D->decls()) {
  163. if (VarDecl *VD = dyn_cast<VarDecl>(Member)) {
  164. if (Ctx->isMSStaticDataMemberInlineDefinition(VD) &&
  165. Ctx->DeclMustBeEmitted(VD)) {
  166. Builder->EmitGlobal(VD);
  167. }
  168. }
  169. }
  170. }
  171. // For OpenMP emit declare reduction functions, if required.
  172. if (Ctx->getLangOpts().OpenMP) {
  173. for (Decl *Member : D->decls()) {
  174. if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Member)) {
  175. if (Ctx->DeclMustBeEmitted(DRD))
  176. Builder->EmitGlobal(DRD);
  177. }
  178. }
  179. }
  180. }
  181. void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
  182. if (Diags.hasErrorOccurred())
  183. return;
  184. if (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo())
  185. if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
  186. DI->completeRequiredType(RD);
  187. }
  188. void HandleTranslationUnit(ASTContext &Ctx) override {
  189. // Release the Builder when there is no error.
  190. if (!Diags.hasErrorOccurred() && Builder)
  191. Builder->Release();
  192. // If there are errors before or when releasing the Builder, reset
  193. // the module to stop here before invoking the backend.
  194. if (Diags.hasErrorOccurred()) {
  195. if (Builder)
  196. Builder->clear();
  197. M.reset();
  198. return;
  199. }
  200. }
  201. void AssignInheritanceModel(CXXRecordDecl *RD) override {
  202. if (Diags.hasErrorOccurred())
  203. return;
  204. Builder->RefreshTypeCacheForClass(RD);
  205. }
  206. void CompleteTentativeDefinition(VarDecl *D) override {
  207. if (Diags.hasErrorOccurred())
  208. return;
  209. Builder->EmitTentativeDefinition(D);
  210. }
  211. void HandleVTable(CXXRecordDecl *RD) override {
  212. if (Diags.hasErrorOccurred())
  213. return;
  214. Builder->EmitVTable(RD);
  215. }
  216. };
  217. }
  218. void CodeGenerator::anchor() { }
  219. CodeGenerator *clang::CreateLLVMCodeGen(
  220. DiagnosticsEngine &Diags, const std::string &ModuleName,
  221. const HeaderSearchOptions &HeaderSearchOpts,
  222. const PreprocessorOptions &PreprocessorOpts, const CodeGenOptions &CGO,
  223. llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo) {
  224. return new CodeGeneratorImpl(Diags, ModuleName, HeaderSearchOpts,
  225. PreprocessorOpts, CGO, C, CoverageInfo);
  226. }