ModuleBuilder.cpp 12 KB

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