ModuleBuilder.cpp 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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. std::unique_ptr<const llvm::DataLayout> TD;
  32. ASTContext *Ctx;
  33. const CodeGenOptions CodeGenOpts; // Intentionally copied in.
  34. unsigned HandlingTopLevelDecls;
  35. struct HandlingTopLevelDeclRAII {
  36. CodeGeneratorImpl &Self;
  37. HandlingTopLevelDeclRAII(CodeGeneratorImpl &Self) : Self(Self) {
  38. ++Self.HandlingTopLevelDecls;
  39. }
  40. ~HandlingTopLevelDeclRAII() {
  41. if (--Self.HandlingTopLevelDecls == 0)
  42. Self.EmitDeferredDecls();
  43. }
  44. };
  45. CoverageSourceInfo *CoverageInfo;
  46. protected:
  47. std::unique_ptr<llvm::Module> M;
  48. std::unique_ptr<CodeGen::CodeGenModule> Builder;
  49. private:
  50. SmallVector<CXXMethodDecl *, 8> DeferredInlineMethodDefinitions;
  51. public:
  52. CodeGeneratorImpl(DiagnosticsEngine &diags, const std::string& ModuleName,
  53. const CodeGenOptions &CGO, llvm::LLVMContext& C,
  54. CoverageSourceInfo *CoverageInfo = nullptr)
  55. : Diags(diags), Ctx(nullptr), CodeGenOpts(CGO), HandlingTopLevelDecls(0),
  56. CoverageInfo(CoverageInfo),
  57. M(new llvm::Module(ModuleName, C)) {}
  58. ~CodeGeneratorImpl() override {
  59. // There should normally not be any leftover inline method definitions.
  60. assert(DeferredInlineMethodDefinitions.empty() ||
  61. Diags.hasErrorOccurred());
  62. }
  63. llvm::Module* GetModule() override {
  64. return M.get();
  65. }
  66. const Decl *GetDeclForMangledName(StringRef MangledName) override {
  67. GlobalDecl Result;
  68. if (!Builder->lookupRepresentativeDecl(MangledName, Result))
  69. return nullptr;
  70. const Decl *D = Result.getCanonicalDecl().getDecl();
  71. if (auto FD = dyn_cast<FunctionDecl>(D)) {
  72. if (FD->hasBody(FD))
  73. return FD;
  74. } else if (auto TD = dyn_cast<TagDecl>(D)) {
  75. if (auto Def = TD->getDefinition())
  76. return Def;
  77. }
  78. return D;
  79. }
  80. llvm::Module *ReleaseModule() override { return M.release(); }
  81. void Initialize(ASTContext &Context) override {
  82. Ctx = &Context;
  83. M->setTargetTriple(Ctx->getTargetInfo().getTriple().getTriple());
  84. M->setDataLayout(Ctx->getTargetInfo().getTargetDescription());
  85. TD.reset(
  86. new llvm::DataLayout(Ctx->getTargetInfo().getTargetDescription()));
  87. Builder.reset(new CodeGen::CodeGenModule(Context, CodeGenOpts, *M, *TD,
  88. Diags, CoverageInfo));
  89. for (size_t i = 0, e = CodeGenOpts.DependentLibraries.size(); i < e; ++i)
  90. HandleDependentLibrary(CodeGenOpts.DependentLibraries[i]);
  91. }
  92. void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
  93. if (Diags.hasErrorOccurred())
  94. return;
  95. Builder->HandleCXXStaticMemberVarInstantiation(VD);
  96. }
  97. bool HandleTopLevelDecl(DeclGroupRef DG) override {
  98. if (Diags.hasErrorOccurred())
  99. return true;
  100. HandlingTopLevelDeclRAII HandlingDecl(*this);
  101. // Make sure to emit all elements of a Decl.
  102. for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
  103. Builder->EmitTopLevelDecl(*I);
  104. return true;
  105. }
  106. void EmitDeferredDecls() {
  107. if (DeferredInlineMethodDefinitions.empty())
  108. return;
  109. // Emit any deferred inline method definitions. Note that more deferred
  110. // methods may be added during this loop, since ASTConsumer callbacks
  111. // can be invoked if AST inspection results in declarations being added.
  112. HandlingTopLevelDeclRAII HandlingDecl(*this);
  113. for (unsigned I = 0; I != DeferredInlineMethodDefinitions.size(); ++I)
  114. Builder->EmitTopLevelDecl(DeferredInlineMethodDefinitions[I]);
  115. DeferredInlineMethodDefinitions.clear();
  116. }
  117. void HandleInlineMethodDefinition(CXXMethodDecl *D) override {
  118. if (Diags.hasErrorOccurred())
  119. return;
  120. assert(D->doesThisDeclarationHaveABody());
  121. // We may want to emit this definition. However, that decision might be
  122. // based on computing the linkage, and we have to defer that in case we
  123. // are inside of something that will change the method's final linkage,
  124. // e.g.
  125. // typedef struct {
  126. // void bar();
  127. // void foo() { bar(); }
  128. // } A;
  129. DeferredInlineMethodDefinitions.push_back(D);
  130. // Provide some coverage mapping even for methods that aren't emitted.
  131. // Don't do this for templated classes though, as they may not be
  132. // instantiable.
  133. if (!D->getParent()->getDescribedClassTemplate())
  134. Builder->AddDeferredUnusedCoverageMapping(D);
  135. }
  136. /// HandleTagDeclDefinition - This callback is invoked each time a TagDecl
  137. /// to (e.g. struct, union, enum, class) is completed. This allows the
  138. /// client hack on the type, which can occur at any point in the file
  139. /// (because these can be defined in declspecs).
  140. void HandleTagDeclDefinition(TagDecl *D) override {
  141. if (Diags.hasErrorOccurred())
  142. return;
  143. Builder->UpdateCompletedType(D);
  144. // For MSVC compatibility, treat declarations of static data members with
  145. // inline initializers as definitions.
  146. if (Ctx->getLangOpts().MSVCCompat) {
  147. for (Decl *Member : D->decls()) {
  148. if (VarDecl *VD = dyn_cast<VarDecl>(Member)) {
  149. if (Ctx->isMSStaticDataMemberInlineDefinition(VD) &&
  150. Ctx->DeclMustBeEmitted(VD)) {
  151. Builder->EmitGlobal(VD);
  152. }
  153. }
  154. }
  155. }
  156. }
  157. void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
  158. if (Diags.hasErrorOccurred())
  159. return;
  160. if (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo())
  161. if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
  162. DI->completeRequiredType(RD);
  163. }
  164. void HandleTranslationUnit(ASTContext &Ctx) override {
  165. if (Diags.hasErrorOccurred()) {
  166. if (Builder)
  167. Builder->clear();
  168. M.reset();
  169. return;
  170. }
  171. if (Builder)
  172. Builder->Release();
  173. }
  174. void CompleteTentativeDefinition(VarDecl *D) override {
  175. if (Diags.hasErrorOccurred())
  176. return;
  177. Builder->EmitTentativeDefinition(D);
  178. }
  179. void HandleVTable(CXXRecordDecl *RD) override {
  180. if (Diags.hasErrorOccurred())
  181. return;
  182. Builder->EmitVTable(RD);
  183. }
  184. void HandleLinkerOptionPragma(llvm::StringRef Opts) override {
  185. Builder->AppendLinkerOptions(Opts);
  186. }
  187. void HandleDetectMismatch(llvm::StringRef Name,
  188. llvm::StringRef Value) override {
  189. Builder->AddDetectMismatch(Name, Value);
  190. }
  191. void HandleDependentLibrary(llvm::StringRef Lib) override {
  192. Builder->AddDependentLib(Lib);
  193. }
  194. };
  195. }
  196. void CodeGenerator::anchor() { }
  197. CodeGenerator *clang::CreateLLVMCodeGen(DiagnosticsEngine &Diags,
  198. const std::string& ModuleName,
  199. const CodeGenOptions &CGO,
  200. llvm::LLVMContext& C,
  201. CoverageSourceInfo *CoverageInfo) {
  202. return new CodeGeneratorImpl(Diags, ModuleName, CGO, C, CoverageInfo);
  203. }