ModuleBuilder.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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. #include "dxc/DXIL/DxilMetadataHelper.h" // HLSL Change - dx source info
  28. using namespace clang;
  29. namespace {
  30. class CodeGeneratorImpl : public CodeGenerator {
  31. DiagnosticsEngine &Diags;
  32. std::unique_ptr<const llvm::DataLayout> TD;
  33. ASTContext *Ctx;
  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. struct HandlingTopLevelDeclRAII {
  39. CodeGeneratorImpl &Self;
  40. HandlingTopLevelDeclRAII(CodeGeneratorImpl &Self) : Self(Self) {
  41. ++Self.HandlingTopLevelDecls;
  42. }
  43. ~HandlingTopLevelDeclRAII() {
  44. if (--Self.HandlingTopLevelDecls == 0)
  45. Self.EmitDeferredDecls();
  46. }
  47. };
  48. CoverageSourceInfo *CoverageInfo;
  49. protected:
  50. std::unique_ptr<llvm::Module> M;
  51. std::unique_ptr<CodeGen::CodeGenModule> Builder;
  52. private:
  53. SmallVector<CXXMethodDecl *, 8> DeferredInlineMethodDefinitions;
  54. public:
  55. CodeGeneratorImpl(DiagnosticsEngine &diags, const std::string &ModuleName,
  56. const HeaderSearchOptions &HSO,
  57. const PreprocessorOptions &PPO, const CodeGenOptions &CGO,
  58. llvm::LLVMContext &C,
  59. CoverageSourceInfo *CoverageInfo = nullptr)
  60. : Diags(diags), Ctx(nullptr), HeaderSearchOpts(HSO),
  61. PreprocessorOpts(PPO), CodeGenOpts(CGO), HandlingTopLevelDecls(0),
  62. CoverageInfo(CoverageInfo),
  63. M(new llvm::Module(ModuleName, C)) {}
  64. ~CodeGeneratorImpl() override {
  65. // There should normally not be any leftover inline method definitions.
  66. assert(DeferredInlineMethodDefinitions.empty() ||
  67. Diags.hasErrorOccurred());
  68. }
  69. llvm::Module* GetModule() override {
  70. return M.get();
  71. }
  72. const Decl *GetDeclForMangledName(StringRef MangledName) override {
  73. GlobalDecl Result;
  74. if (!Builder->lookupRepresentativeDecl(MangledName, Result))
  75. return nullptr;
  76. const Decl *D = Result.getCanonicalDecl().getDecl();
  77. if (auto FD = dyn_cast<FunctionDecl>(D)) {
  78. if (FD->hasBody(FD))
  79. return FD;
  80. } else if (auto TD = dyn_cast<TagDecl>(D)) {
  81. if (auto Def = TD->getDefinition())
  82. return Def;
  83. }
  84. return D;
  85. }
  86. llvm::Module *ReleaseModule() override { return M.release(); }
  87. void Initialize(ASTContext &Context) override {
  88. Ctx = &Context;
  89. M->setTargetTriple(Ctx->getTargetInfo().getTriple().getTriple());
  90. M->setDataLayout(Ctx->getTargetInfo().getTargetDescription());
  91. TD.reset(
  92. new llvm::DataLayout(Ctx->getTargetInfo().getTargetDescription()));
  93. Builder.reset(new CodeGen::CodeGenModule(Context,
  94. HeaderSearchOpts,
  95. PreprocessorOpts,
  96. CodeGenOpts, *M, *TD,
  97. Diags, CoverageInfo));
  98. for (size_t i = 0, e = CodeGenOpts.DependentLibraries.size(); i < e; ++i)
  99. HandleDependentLibrary(CodeGenOpts.DependentLibraries[i]);
  100. }
  101. void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
  102. if (Diags.hasErrorOccurred())
  103. return;
  104. Builder->HandleCXXStaticMemberVarInstantiation(VD);
  105. }
  106. bool HandleTopLevelDecl(DeclGroupRef DG) override {
  107. if (Diags.hasErrorOccurred())
  108. return true;
  109. HandlingTopLevelDeclRAII HandlingDecl(*this);
  110. // Make sure to emit all elements of a Decl.
  111. for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
  112. Builder->EmitTopLevelDecl(*I);
  113. return true;
  114. }
  115. void EmitDeferredDecls() {
  116. if (DeferredInlineMethodDefinitions.empty())
  117. return;
  118. // Emit any deferred inline method definitions. Note that more deferred
  119. // methods may be added during this loop, since ASTConsumer callbacks
  120. // can be invoked if AST inspection results in declarations being added.
  121. HandlingTopLevelDeclRAII HandlingDecl(*this);
  122. for (unsigned I = 0; I != DeferredInlineMethodDefinitions.size(); ++I)
  123. Builder->EmitTopLevelDecl(DeferredInlineMethodDefinitions[I]);
  124. DeferredInlineMethodDefinitions.clear();
  125. }
  126. void HandleInlineMethodDefinition(CXXMethodDecl *D) override {
  127. if (Diags.hasErrorOccurred())
  128. return;
  129. assert(D->doesThisDeclarationHaveABody());
  130. // We may want to emit this definition. However, that decision might be
  131. // based on computing the linkage, and we have to defer that in case we
  132. // are inside of something that will change the method's final linkage,
  133. // e.g.
  134. // typedef struct {
  135. // void bar();
  136. // void foo() { bar(); }
  137. // } A;
  138. DeferredInlineMethodDefinitions.push_back(D);
  139. // Provide some coverage mapping even for methods that aren't emitted.
  140. // Don't do this for templated classes though, as they may not be
  141. // instantiable.
  142. if (!D->getParent()->getDescribedClassTemplate())
  143. Builder->AddDeferredUnusedCoverageMapping(D);
  144. }
  145. /// HandleTagDeclDefinition - This callback is invoked each time a TagDecl
  146. /// to (e.g. struct, union, enum, class) is completed. This allows the
  147. /// client hack on the type, which can occur at any point in the file
  148. /// (because these can be defined in declspecs).
  149. void HandleTagDeclDefinition(TagDecl *D) override {
  150. if (Diags.hasErrorOccurred())
  151. return;
  152. Builder->UpdateCompletedType(D);
  153. // For MSVC compatibility, treat declarations of static data members with
  154. // inline initializers as definitions.
  155. if (Ctx->getLangOpts().MSVCCompat) {
  156. for (Decl *Member : D->decls()) {
  157. if (VarDecl *VD = dyn_cast<VarDecl>(Member)) {
  158. if (Ctx->isMSStaticDataMemberInlineDefinition(VD) &&
  159. Ctx->DeclMustBeEmitted(VD)) {
  160. Builder->EmitGlobal(VD);
  161. }
  162. }
  163. }
  164. }
  165. }
  166. void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
  167. if (Diags.hasErrorOccurred())
  168. return;
  169. if (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo())
  170. if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
  171. DI->completeRequiredType(RD);
  172. }
  173. void HandleTranslationUnit(ASTContext &Ctx) override {
  174. if (Diags.hasErrorOccurred()) {
  175. if (Builder)
  176. Builder->clear();
  177. M.reset();
  178. return;
  179. }
  180. if (Builder)
  181. Builder->Release();
  182. // HLSL Change Begins
  183. // Error may happen in Builder->Release for HLSL
  184. if (CodeGenOpts.getDebugInfo() == CodeGenOptions::DebugInfoKind::FullDebugInfo) {
  185. // Add all file contents in a list of filename/content pairs.
  186. llvm::NamedMDNode *pContents = nullptr;
  187. llvm::LLVMContext &LLVMCtx = M->getContext();
  188. auto AddFile = [&](StringRef name, StringRef content) {
  189. if (pContents == nullptr) {
  190. pContents = M->getOrInsertNamedMetadata(
  191. hlsl::DxilMDHelper::kDxilSourceContentsMDName);
  192. }
  193. llvm::MDTuple *pFileInfo = llvm::MDNode::get(
  194. LLVMCtx,
  195. { llvm::MDString::get(LLVMCtx, name),
  196. llvm::MDString::get(LLVMCtx, content) });
  197. pContents->addOperand(pFileInfo);
  198. };
  199. std::map<StringRef, StringRef> filesMap;
  200. bool bFoundMainFile = false;
  201. for (SourceManager::fileinfo_iterator
  202. it = Ctx.getSourceManager().fileinfo_begin(),
  203. end = Ctx.getSourceManager().fileinfo_end();
  204. it != end; ++it) {
  205. if (it->first->isValid() && !it->second->IsSystemFile) {
  206. // If main file, write that to metadata first.
  207. // Add the rest to filesMap to sort by name.
  208. if (CodeGenOpts.MainFileName.compare(it->first->getName()) == 0) {
  209. assert(!bFoundMainFile && "otherwise, more than one file matches main filename");
  210. AddFile(it->first->getName(), it->second->getRawBuffer()->getBuffer());
  211. bFoundMainFile = true;
  212. } else {
  213. filesMap[it->first->getName()] = it->second->getRawBuffer()->getBuffer();
  214. }
  215. }
  216. }
  217. assert(bFoundMainFile && "otherwise, no file found matches main filename");
  218. // Emit the rest of the files in sorted order.
  219. for (auto it : filesMap) {
  220. AddFile(it.first, it.second);
  221. }
  222. // Add Defines to Debug Info
  223. llvm::NamedMDNode *pDefines = M->getOrInsertNamedMetadata(
  224. hlsl::DxilMDHelper::kDxilSourceDefinesMDName);
  225. std::vector<llvm::Metadata *> vecDefines;
  226. vecDefines.resize(CodeGenOpts.HLSLDefines.size());
  227. std::transform(CodeGenOpts.HLSLDefines.begin(), CodeGenOpts.HLSLDefines.end(),
  228. vecDefines.begin(), [&LLVMCtx](const std::string &str) { return llvm::MDString::get(LLVMCtx, str); });
  229. llvm::MDTuple *pDefinesInfo = llvm::MDNode::get(LLVMCtx, vecDefines);
  230. pDefines->addOperand(pDefinesInfo);
  231. // Add main file name to debug info
  232. llvm::NamedMDNode *pSourceFilename = M->getOrInsertNamedMetadata(
  233. hlsl::DxilMDHelper::kDxilSourceMainFileNameMDName);
  234. llvm::MDTuple *pFileName = llvm::MDNode::get(
  235. LLVMCtx, llvm::MDString::get(LLVMCtx, CodeGenOpts.MainFileName));
  236. pSourceFilename->addOperand(pFileName);
  237. // Pass in any other arguments to debug info
  238. llvm::NamedMDNode *pArgs = M->getOrInsertNamedMetadata(
  239. hlsl::DxilMDHelper::kDxilSourceArgsMDName);
  240. std::vector<llvm::Metadata *> vecArguments;
  241. vecArguments.resize(CodeGenOpts.HLSLArguments.size());
  242. std::transform(CodeGenOpts.HLSLArguments.begin(), CodeGenOpts.HLSLArguments.end(),
  243. vecArguments.begin(), [&LLVMCtx](const std::string &str) { return llvm::MDString::get(LLVMCtx, str); });
  244. llvm::MDTuple *pArgumentsInfo = llvm::MDNode::get(LLVMCtx, vecArguments);
  245. pArgs->addOperand(pArgumentsInfo);
  246. }
  247. if (Diags.hasErrorOccurred())
  248. M.reset();
  249. // HLSL Change Ends
  250. }
  251. void CompleteTentativeDefinition(VarDecl *D) override {
  252. if (Diags.hasErrorOccurred())
  253. return;
  254. Builder->EmitTentativeDefinition(D);
  255. }
  256. void HandleVTable(CXXRecordDecl *RD) override {
  257. if (Diags.hasErrorOccurred())
  258. return;
  259. Builder->EmitVTable(RD);
  260. }
  261. void HandleLinkerOptionPragma(llvm::StringRef Opts) override {
  262. Builder->AppendLinkerOptions(Opts);
  263. }
  264. void HandleDetectMismatch(llvm::StringRef Name,
  265. llvm::StringRef Value) override {
  266. Builder->AddDetectMismatch(Name, Value);
  267. }
  268. void HandleDependentLibrary(llvm::StringRef Lib) override {
  269. Builder->AddDependentLib(Lib);
  270. }
  271. };
  272. }
  273. void CodeGenerator::anchor() { }
  274. CodeGenerator *clang::CreateLLVMCodeGen(
  275. DiagnosticsEngine &Diags, const std::string &ModuleName,
  276. const HeaderSearchOptions &HeaderSearchOpts,
  277. const PreprocessorOptions &PreprocessorOpts, const CodeGenOptions &CGO,
  278. llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo) {
  279. return new CodeGeneratorImpl(Diags, ModuleName, HeaderSearchOpts,
  280. PreprocessorOpts, CGO, C, CoverageInfo);
  281. }