FrontendActions.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  1. //===--- FrontendActions.cpp ----------------------------------------------===//
  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. #include "clang/Frontend/FrontendActions.h"
  10. #include "clang/AST/ASTConsumer.h"
  11. #include "clang/Basic/FileManager.h"
  12. #include "clang/Frontend/ASTConsumers.h"
  13. #include "clang/Frontend/ASTUnit.h"
  14. #include "clang/Frontend/CompilerInstance.h"
  15. #include "clang/Frontend/FrontendDiagnostic.h"
  16. #include "clang/Frontend/MultiplexConsumer.h"
  17. #include "clang/Frontend/Utils.h"
  18. #include "clang/Lex/HeaderSearch.h"
  19. #include "clang/Lex/HLSLMacroExpander.h"
  20. #include "clang/Lex/Pragma.h"
  21. #include "clang/Lex/Preprocessor.h"
  22. #include "clang/Parse/Parser.h"
  23. #include "clang/Serialization/ASTReader.h"
  24. #include "clang/Serialization/ASTWriter.h"
  25. #include "llvm/Support/FileSystem.h"
  26. #include "llvm/Support/MemoryBuffer.h"
  27. #include "llvm/Support/raw_ostream.h"
  28. #include <memory>
  29. #include <system_error>
  30. // HLSL Change Begin.
  31. #include "dxc/DxilRootSignature/DxilRootSignature.h"
  32. #include "clang/Parse/ParseHLSL.h"
  33. // HLSL Change End.
  34. using namespace clang;
  35. //===----------------------------------------------------------------------===//
  36. // Custom Actions
  37. //===----------------------------------------------------------------------===//
  38. std::unique_ptr<ASTConsumer>
  39. InitOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  40. return llvm::make_unique<ASTConsumer>();
  41. }
  42. void InitOnlyAction::ExecuteAction() {
  43. }
  44. //===----------------------------------------------------------------------===//
  45. // AST Consumer Actions
  46. //===----------------------------------------------------------------------===//
  47. std::unique_ptr<ASTConsumer>
  48. ASTPrintAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  49. if (raw_ostream *OS = CI.createDefaultOutputFile(false, InFile))
  50. return CreateASTPrinter(OS, CI.getFrontendOpts().ASTDumpFilter);
  51. return nullptr;
  52. }
  53. std::unique_ptr<ASTConsumer>
  54. ASTDumpAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  55. return CreateASTDumper(CI.getOutStream(), // HLSL Change - explicit out stream
  56. CI.getFrontendOpts().ASTDumpFilter,
  57. CI.getFrontendOpts().ASTDumpDecls,
  58. CI.getFrontendOpts().ASTDumpLookups);
  59. }
  60. std::unique_ptr<ASTConsumer>
  61. ASTDeclListAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  62. return CreateASTDeclNodeLister();
  63. }
  64. std::unique_ptr<ASTConsumer>
  65. ASTViewAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  66. return CreateASTViewer();
  67. }
  68. std::unique_ptr<ASTConsumer>
  69. DeclContextPrintAction::CreateASTConsumer(CompilerInstance &CI,
  70. StringRef InFile) {
  71. return CreateDeclContextPrinter();
  72. }
  73. #if 0 // HLSL Change Starts - no support for modules or PCH
  74. std::unique_ptr<ASTConsumer>
  75. GeneratePCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  76. std::string Sysroot;
  77. std::string OutputFile;
  78. raw_pwrite_stream *OS =
  79. ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile);
  80. if (!OS)
  81. return nullptr;
  82. if (!CI.getFrontendOpts().RelocatablePCH)
  83. Sysroot.clear();
  84. auto Buffer = std::make_shared<PCHBuffer>();
  85. std::vector<std::unique_ptr<ASTConsumer>> Consumers;
  86. Consumers.push_back(llvm::make_unique<PCHGenerator>(
  87. CI.getPreprocessor(), OutputFile, nullptr, Sysroot, Buffer));
  88. Consumers.push_back(
  89. CI.getPCHContainerWriter().CreatePCHContainerGenerator(
  90. CI.getDiagnostics(), CI.getHeaderSearchOpts(),
  91. CI.getPreprocessorOpts(), CI.getTargetOpts(), CI.getLangOpts(),
  92. InFile, OutputFile, OS, Buffer));
  93. return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
  94. }
  95. raw_pwrite_stream *GeneratePCHAction::ComputeASTConsumerArguments(
  96. CompilerInstance &CI, StringRef InFile, std::string &Sysroot,
  97. std::string &OutputFile) {
  98. Sysroot = CI.getHeaderSearchOpts().Sysroot;
  99. if (CI.getFrontendOpts().RelocatablePCH && Sysroot.empty()) {
  100. CI.getDiagnostics().Report(diag::err_relocatable_without_isysroot);
  101. return nullptr;
  102. }
  103. // We use createOutputFile here because this is exposed via libclang, and we
  104. // must disable the RemoveFileOnSignal behavior.
  105. // We use a temporary to avoid race conditions.
  106. raw_pwrite_stream *OS =
  107. CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
  108. /*RemoveFileOnSignal=*/false, InFile,
  109. /*Extension=*/"", /*useTemporary=*/true);
  110. if (!OS)
  111. return nullptr;
  112. OutputFile = CI.getFrontendOpts().OutputFile;
  113. return OS;
  114. }
  115. std::unique_ptr<ASTConsumer>
  116. GenerateModuleAction::CreateASTConsumer(CompilerInstance &CI,
  117. StringRef InFile) {
  118. std::string Sysroot;
  119. std::string OutputFile;
  120. raw_pwrite_stream *OS =
  121. ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile);
  122. if (!OS)
  123. return nullptr;
  124. auto Buffer = std::make_shared<PCHBuffer>();
  125. std::vector<std::unique_ptr<ASTConsumer>> Consumers;
  126. Consumers.push_back(llvm::make_unique<PCHGenerator>(
  127. CI.getPreprocessor(), OutputFile, Module, Sysroot, Buffer));
  128. Consumers.push_back(
  129. CI.getPCHContainerWriter().CreatePCHContainerGenerator(
  130. CI.getDiagnostics(), CI.getHeaderSearchOpts(),
  131. CI.getPreprocessorOpts(), CI.getTargetOpts(), CI.getLangOpts(),
  132. InFile, OutputFile, OS, Buffer));
  133. return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
  134. }
  135. static SmallVectorImpl<char> &
  136. operator+=(SmallVectorImpl<char> &Includes, StringRef RHS) {
  137. Includes.append(RHS.begin(), RHS.end());
  138. return Includes;
  139. }
  140. static std::error_code addHeaderInclude(StringRef HeaderName,
  141. SmallVectorImpl<char> &Includes,
  142. const LangOptions &LangOpts,
  143. bool IsExternC) {
  144. if (IsExternC && LangOpts.CPlusPlus)
  145. Includes += "extern \"C\" {\n";
  146. if (LangOpts.ObjC1)
  147. Includes += "#import \"";
  148. else
  149. Includes += "#include \"";
  150. Includes += HeaderName;
  151. Includes += "\"\n";
  152. if (IsExternC && LangOpts.CPlusPlus)
  153. Includes += "}\n";
  154. return std::error_code();
  155. }
  156. /// \brief Collect the set of header includes needed to construct the given
  157. /// module and update the TopHeaders file set of the module.
  158. ///
  159. /// \param Module The module we're collecting includes from.
  160. ///
  161. /// \param Includes Will be augmented with the set of \#includes or \#imports
  162. /// needed to load all of the named headers.
  163. static std::error_code
  164. collectModuleHeaderIncludes(const LangOptions &LangOpts, FileManager &FileMgr,
  165. ModuleMap &ModMap, clang::Module *Module,
  166. SmallVectorImpl<char> &Includes) {
  167. // Don't collect any headers for unavailable modules.
  168. if (!Module->isAvailable())
  169. return std::error_code();
  170. // Add includes for each of these headers.
  171. for (Module::Header &H : Module->Headers[Module::HK_Normal]) {
  172. Module->addTopHeader(H.Entry);
  173. // Use the path as specified in the module map file. We'll look for this
  174. // file relative to the module build directory (the directory containing
  175. // the module map file) so this will find the same file that we found
  176. // while parsing the module map.
  177. if (std::error_code Err = addHeaderInclude(H.NameAsWritten, Includes,
  178. LangOpts, Module->IsExternC))
  179. return Err;
  180. }
  181. // Note that Module->PrivateHeaders will not be a TopHeader.
  182. if (Module::Header UmbrellaHeader = Module->getUmbrellaHeader()) {
  183. Module->addTopHeader(UmbrellaHeader.Entry);
  184. if (Module->Parent) {
  185. // Include the umbrella header for submodules.
  186. if (std::error_code Err = addHeaderInclude(UmbrellaHeader.NameAsWritten,
  187. Includes, LangOpts,
  188. Module->IsExternC))
  189. return Err;
  190. }
  191. } else if (Module::DirectoryName UmbrellaDir = Module->getUmbrellaDir()) {
  192. // Add all of the headers we find in this subdirectory.
  193. std::error_code EC;
  194. SmallString<128> DirNative;
  195. llvm::sys::path::native(UmbrellaDir.Entry->getName(), DirNative);
  196. for (llvm::sys::fs::recursive_directory_iterator Dir(DirNative, EC),
  197. DirEnd;
  198. Dir != DirEnd && !EC; Dir.increment(EC)) {
  199. // Check whether this entry has an extension typically associated with
  200. // headers.
  201. if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->path()))
  202. .Cases(".h", ".H", ".hh", ".hpp", true)
  203. .Default(false))
  204. continue;
  205. const FileEntry *Header = FileMgr.getFile(Dir->path());
  206. // FIXME: This shouldn't happen unless there is a file system race. Is
  207. // that worth diagnosing?
  208. if (!Header)
  209. continue;
  210. // If this header is marked 'unavailable' in this module, don't include
  211. // it.
  212. if (ModMap.isHeaderUnavailableInModule(Header, Module))
  213. continue;
  214. // Compute the relative path from the directory to this file.
  215. SmallVector<StringRef, 16> Components;
  216. auto PathIt = llvm::sys::path::rbegin(Dir->path());
  217. for (int I = 0; I != Dir.level() + 1; ++I, ++PathIt)
  218. Components.push_back(*PathIt);
  219. SmallString<128> RelativeHeader(UmbrellaDir.NameAsWritten);
  220. for (auto It = Components.rbegin(), End = Components.rend(); It != End;
  221. ++It)
  222. llvm::sys::path::append(RelativeHeader, *It);
  223. // Include this header as part of the umbrella directory.
  224. Module->addTopHeader(Header);
  225. if (std::error_code Err = addHeaderInclude(RelativeHeader, Includes,
  226. LangOpts, Module->IsExternC))
  227. return Err;
  228. }
  229. if (EC)
  230. return EC;
  231. }
  232. // Recurse into submodules.
  233. for (clang::Module::submodule_iterator Sub = Module->submodule_begin(),
  234. SubEnd = Module->submodule_end();
  235. Sub != SubEnd; ++Sub)
  236. if (std::error_code Err = collectModuleHeaderIncludes(
  237. LangOpts, FileMgr, ModMap, *Sub, Includes))
  238. return Err;
  239. return std::error_code();
  240. }
  241. bool GenerateModuleAction::BeginSourceFileAction(CompilerInstance &CI,
  242. StringRef Filename) {
  243. // Find the module map file.
  244. const FileEntry *ModuleMap = CI.getFileManager().getFile(Filename);
  245. if (!ModuleMap) {
  246. CI.getDiagnostics().Report(diag::err_module_map_not_found)
  247. << Filename;
  248. return false;
  249. }
  250. // Parse the module map file.
  251. HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
  252. if (HS.loadModuleMapFile(ModuleMap, IsSystem))
  253. return false;
  254. if (CI.getLangOpts().CurrentModule.empty()) {
  255. CI.getDiagnostics().Report(diag::err_missing_module_name);
  256. // FIXME: Eventually, we could consider asking whether there was just
  257. // a single module described in the module map, and use that as a
  258. // default. Then it would be fairly trivial to just "compile" a module
  259. // map with a single module (the common case).
  260. return false;
  261. }
  262. // If we're being run from the command-line, the module build stack will not
  263. // have been filled in yet, so complete it now in order to allow us to detect
  264. // module cycles.
  265. SourceManager &SourceMgr = CI.getSourceManager();
  266. if (SourceMgr.getModuleBuildStack().empty())
  267. SourceMgr.pushModuleBuildStack(CI.getLangOpts().CurrentModule,
  268. FullSourceLoc(SourceLocation(), SourceMgr));
  269. // Dig out the module definition.
  270. Module = HS.lookupModule(CI.getLangOpts().CurrentModule,
  271. /*AllowSearch=*/false);
  272. if (!Module) {
  273. CI.getDiagnostics().Report(diag::err_missing_module)
  274. << CI.getLangOpts().CurrentModule << Filename;
  275. return false;
  276. }
  277. // Check whether we can build this module at all.
  278. clang::Module::Requirement Requirement;
  279. clang::Module::UnresolvedHeaderDirective MissingHeader;
  280. if (!Module->isAvailable(CI.getLangOpts(), CI.getTarget(), Requirement,
  281. MissingHeader)) {
  282. if (MissingHeader.FileNameLoc.isValid()) {
  283. CI.getDiagnostics().Report(MissingHeader.FileNameLoc,
  284. diag::err_module_header_missing)
  285. << MissingHeader.IsUmbrella << MissingHeader.FileName;
  286. } else {
  287. CI.getDiagnostics().Report(diag::err_module_unavailable)
  288. << Module->getFullModuleName()
  289. << Requirement.second << Requirement.first;
  290. }
  291. return false;
  292. }
  293. if (ModuleMapForUniquing && ModuleMapForUniquing != ModuleMap) {
  294. Module->IsInferred = true;
  295. HS.getModuleMap().setInferredModuleAllowedBy(Module, ModuleMapForUniquing);
  296. } else {
  297. ModuleMapForUniquing = ModuleMap;
  298. }
  299. FileManager &FileMgr = CI.getFileManager();
  300. // Collect the set of #includes we need to build the module.
  301. SmallString<256> HeaderContents;
  302. std::error_code Err = std::error_code();
  303. if (Module::Header UmbrellaHeader = Module->getUmbrellaHeader())
  304. Err = addHeaderInclude(UmbrellaHeader.NameAsWritten, HeaderContents,
  305. CI.getLangOpts(), Module->IsExternC);
  306. if (!Err)
  307. Err = collectModuleHeaderIncludes(
  308. CI.getLangOpts(), FileMgr,
  309. CI.getPreprocessor().getHeaderSearchInfo().getModuleMap(), Module,
  310. HeaderContents);
  311. if (Err) {
  312. CI.getDiagnostics().Report(diag::err_module_cannot_create_includes)
  313. << Module->getFullModuleName() << Err.message();
  314. return false;
  315. }
  316. // Inform the preprocessor that includes from within the input buffer should
  317. // be resolved relative to the build directory of the module map file.
  318. CI.getPreprocessor().setMainFileDir(Module->Directory);
  319. std::unique_ptr<llvm::MemoryBuffer> InputBuffer =
  320. llvm::MemoryBuffer::getMemBufferCopy(HeaderContents,
  321. Module::getModuleInputBufferName());
  322. // Ownership of InputBuffer will be transferred to the SourceManager.
  323. setCurrentInput(FrontendInputFile(InputBuffer.release(), getCurrentFileKind(),
  324. Module->IsSystem));
  325. return true;
  326. }
  327. raw_pwrite_stream *GenerateModuleAction::ComputeASTConsumerArguments(
  328. CompilerInstance &CI, StringRef InFile, std::string &Sysroot,
  329. std::string &OutputFile) {
  330. // If no output file was provided, figure out where this module would go
  331. // in the module cache.
  332. if (CI.getFrontendOpts().OutputFile.empty()) {
  333. HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
  334. CI.getFrontendOpts().OutputFile =
  335. HS.getModuleFileName(CI.getLangOpts().CurrentModule,
  336. ModuleMapForUniquing->getName());
  337. }
  338. // We use createOutputFile here because this is exposed via libclang, and we
  339. // must disable the RemoveFileOnSignal behavior.
  340. // We use a temporary to avoid race conditions.
  341. raw_pwrite_stream *OS =
  342. CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
  343. /*RemoveFileOnSignal=*/false, InFile,
  344. /*Extension=*/"", /*useTemporary=*/true,
  345. /*CreateMissingDirectories=*/true);
  346. if (!OS)
  347. return nullptr;
  348. OutputFile = CI.getFrontendOpts().OutputFile;
  349. return OS;
  350. }
  351. #endif // HLSL Change Ends - no support for modules or PCH
  352. std::unique_ptr<ASTConsumer>
  353. SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  354. return llvm::make_unique<ASTConsumer>();
  355. }
  356. #if 0 // HLSL Change Starts - no support for modules or PCH
  357. std::unique_ptr<ASTConsumer>
  358. DumpModuleInfoAction::CreateASTConsumer(CompilerInstance &CI,
  359. StringRef InFile) {
  360. return llvm::make_unique<ASTConsumer>();
  361. }
  362. std::unique_ptr<ASTConsumer>
  363. VerifyPCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  364. return llvm::make_unique<ASTConsumer>();
  365. }
  366. void VerifyPCHAction::ExecuteAction() {
  367. CompilerInstance &CI = getCompilerInstance();
  368. bool Preamble = CI.getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
  369. const std::string &Sysroot = CI.getHeaderSearchOpts().Sysroot;
  370. std::unique_ptr<ASTReader> Reader(new ASTReader(
  371. CI.getPreprocessor(), CI.getASTContext(), CI.getPCHContainerReader(),
  372. Sysroot.empty() ? "" : Sysroot.c_str(),
  373. /*DisableValidation*/ false,
  374. /*AllowPCHWithCompilerErrors*/ false,
  375. /*AllowConfigurationMismatch*/ true,
  376. /*ValidateSystemInputs*/ true));
  377. Reader->ReadAST(getCurrentFile(),
  378. Preamble ? serialization::MK_Preamble
  379. : serialization::MK_PCH,
  380. SourceLocation(),
  381. ASTReader::ARR_ConfigurationMismatch);
  382. }
  383. namespace {
  384. /// \brief AST reader listener that dumps module information for a module
  385. /// file.
  386. class DumpModuleInfoListener : public ASTReaderListener {
  387. llvm::raw_ostream &Out;
  388. public:
  389. DumpModuleInfoListener(llvm::raw_ostream &Out) : Out(Out) { }
  390. #define DUMP_BOOLEAN(Value, Text) \
  391. Out.indent(4) << Text << ": " << (Value? "Yes" : "No") << "\n"
  392. bool ReadFullVersionInformation(StringRef FullVersion) override {
  393. Out.indent(2)
  394. << "Generated by "
  395. << (FullVersion == getClangFullRepositoryVersion()? "this"
  396. : "a different")
  397. << " Clang: " << FullVersion << "\n";
  398. return ASTReaderListener::ReadFullVersionInformation(FullVersion);
  399. }
  400. void ReadModuleName(StringRef ModuleName) override {
  401. Out.indent(2) << "Module name: " << ModuleName << "\n";
  402. }
  403. void ReadModuleMapFile(StringRef ModuleMapPath) override {
  404. Out.indent(2) << "Module map file: " << ModuleMapPath << "\n";
  405. }
  406. bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
  407. bool AllowCompatibleDifferences) override {
  408. Out.indent(2) << "Language options:\n";
  409. #define LANGOPT(Name, Bits, Default, Description) \
  410. DUMP_BOOLEAN(LangOpts.Name, Description);
  411. #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
  412. Out.indent(4) << Description << ": " \
  413. << static_cast<unsigned>(LangOpts.get##Name()) << "\n";
  414. #define VALUE_LANGOPT(Name, Bits, Default, Description) \
  415. Out.indent(4) << Description << ": " << LangOpts.Name << "\n";
  416. #define BENIGN_LANGOPT(Name, Bits, Default, Description)
  417. #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
  418. #include "clang/Basic/LangOptions.fixed.def" // HLSL Change
  419. if (!LangOpts.ModuleFeatures.empty()) {
  420. Out.indent(4) << "Module features:\n";
  421. for (StringRef Feature : LangOpts.ModuleFeatures)
  422. Out.indent(6) << Feature << "\n";
  423. }
  424. return false;
  425. }
  426. bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
  427. bool AllowCompatibleDifferences) override {
  428. Out.indent(2) << "Target options:\n";
  429. Out.indent(4) << " Triple: " << TargetOpts.Triple << "\n";
  430. Out.indent(4) << " CPU: " << TargetOpts.CPU << "\n";
  431. Out.indent(4) << " ABI: " << TargetOpts.ABI << "\n";
  432. if (!TargetOpts.FeaturesAsWritten.empty()) {
  433. Out.indent(4) << "Target features:\n";
  434. for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size();
  435. I != N; ++I) {
  436. Out.indent(6) << TargetOpts.FeaturesAsWritten[I] << "\n";
  437. }
  438. }
  439. return false;
  440. }
  441. bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
  442. bool Complain) override {
  443. Out.indent(2) << "Diagnostic options:\n";
  444. #define DIAGOPT(Name, Bits, Default) DUMP_BOOLEAN(DiagOpts->Name, #Name);
  445. #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
  446. Out.indent(4) << #Name << ": " << DiagOpts->get##Name() << "\n";
  447. #define VALUE_DIAGOPT(Name, Bits, Default) \
  448. Out.indent(4) << #Name << ": " << DiagOpts->Name << "\n";
  449. #include "clang/Basic/DiagnosticOptions.def"
  450. Out.indent(4) << "Diagnostic flags:\n";
  451. for (const std::string &Warning : DiagOpts->Warnings)
  452. Out.indent(6) << "-W" << Warning << "\n";
  453. for (const std::string &Remark : DiagOpts->Remarks)
  454. Out.indent(6) << "-R" << Remark << "\n";
  455. return false;
  456. }
  457. bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
  458. StringRef SpecificModuleCachePath,
  459. bool Complain) override {
  460. Out.indent(2) << "Header search options:\n";
  461. Out.indent(4) << "System root [-isysroot=]: '" << HSOpts.Sysroot << "'\n";
  462. Out.indent(4) << "Module Cache: '" << SpecificModuleCachePath << "'\n";
  463. DUMP_BOOLEAN(HSOpts.UseBuiltinIncludes,
  464. "Use builtin include directories [-nobuiltininc]");
  465. DUMP_BOOLEAN(HSOpts.UseStandardSystemIncludes,
  466. "Use standard system include directories [-nostdinc]");
  467. DUMP_BOOLEAN(HSOpts.UseStandardCXXIncludes,
  468. "Use standard C++ include directories [-nostdinc++]");
  469. DUMP_BOOLEAN(HSOpts.UseLibcxx,
  470. "Use libc++ (rather than libstdc++) [-stdlib=]");
  471. return false;
  472. }
  473. bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
  474. bool Complain,
  475. std::string &SuggestedPredefines) override {
  476. Out.indent(2) << "Preprocessor options:\n";
  477. DUMP_BOOLEAN(PPOpts.UsePredefines,
  478. "Uses compiler/target-specific predefines [-undef]");
  479. DUMP_BOOLEAN(PPOpts.DetailedRecord,
  480. "Uses detailed preprocessing record (for indexing)");
  481. if (!PPOpts.Macros.empty()) {
  482. Out.indent(4) << "Predefined macros:\n";
  483. }
  484. for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator
  485. I = PPOpts.Macros.begin(), IEnd = PPOpts.Macros.end();
  486. I != IEnd; ++I) {
  487. Out.indent(6);
  488. if (I->second)
  489. Out << "-U";
  490. else
  491. Out << "-D";
  492. Out << I->first << "\n";
  493. }
  494. return false;
  495. }
  496. #undef DUMP_BOOLEAN
  497. };
  498. }
  499. void DumpModuleInfoAction::ExecuteAction() {
  500. // Set up the output file.
  501. std::unique_ptr<llvm::raw_fd_ostream> OutFile;
  502. StringRef OutputFileName = getCompilerInstance().getFrontendOpts().OutputFile;
  503. if (!OutputFileName.empty() && OutputFileName != "-") {
  504. std::error_code EC;
  505. OutFile.reset(new llvm::raw_fd_ostream(OutputFileName.str(), EC,
  506. llvm::sys::fs::F_Text));
  507. }
  508. llvm::raw_ostream &Out = OutFile.get()? *OutFile.get() : llvm::outs();
  509. Out << "Information for module file '" << getCurrentFile() << "':\n";
  510. DumpModuleInfoListener Listener(Out);
  511. ASTReader::readASTFileControlBlock(
  512. getCurrentFile(), getCompilerInstance().getFileManager(),
  513. getCompilerInstance().getPCHContainerReader(), Listener);
  514. }
  515. #endif // HLSL Change Ends - no support for modules or PCH
  516. //===----------------------------------------------------------------------===//
  517. // Preprocessor Actions
  518. //===----------------------------------------------------------------------===//
  519. void DumpRawTokensAction::ExecuteAction() {
  520. Preprocessor &PP = getCompilerInstance().getPreprocessor();
  521. SourceManager &SM = PP.getSourceManager();
  522. // Start lexing the specified input file.
  523. const llvm::MemoryBuffer *FromFile = SM.getBuffer(SM.getMainFileID());
  524. Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts());
  525. RawLex.SetKeepWhitespaceMode(true);
  526. Token RawTok;
  527. RawLex.LexFromRawLexer(RawTok);
  528. while (RawTok.isNot(tok::eof)) {
  529. PP.DumpToken(RawTok, true);
  530. llvm::errs() << "\n";
  531. RawLex.LexFromRawLexer(RawTok);
  532. }
  533. }
  534. void DumpTokensAction::ExecuteAction() {
  535. Preprocessor &PP = getCompilerInstance().getPreprocessor();
  536. // Start preprocessing the specified input file.
  537. Token Tok;
  538. PP.EnterMainSourceFile();
  539. do {
  540. PP.Lex(Tok);
  541. PP.DumpToken(Tok, true);
  542. llvm::errs() << "\n";
  543. } while (Tok.isNot(tok::eof));
  544. }
  545. void GeneratePTHAction::ExecuteAction() {
  546. CompilerInstance &CI = getCompilerInstance();
  547. raw_pwrite_stream *OS = CI.createDefaultOutputFile(true, getCurrentFile());
  548. if (!OS)
  549. return;
  550. CacheTokens(CI.getPreprocessor(), OS);
  551. }
  552. void PreprocessOnlyAction::ExecuteAction() {
  553. Preprocessor &PP = getCompilerInstance().getPreprocessor();
  554. // Ignore unknown pragmas.
  555. PP.IgnorePragmas();
  556. Token Tok;
  557. // Start parsing the specified input file.
  558. PP.EnterMainSourceFile();
  559. do {
  560. PP.Lex(Tok);
  561. } while (Tok.isNot(tok::eof));
  562. }
  563. void PrintPreprocessedAction::ExecuteAction() {
  564. CompilerInstance &CI = getCompilerInstance();
  565. // Output file may need to be set to 'Binary', to avoid converting Unix style
  566. // line feeds (<LF>) to Microsoft style line feeds (<CR><LF>).
  567. //
  568. // Look to see what type of line endings the file uses. If there's a
  569. // CRLF, then we won't open the file up in binary mode. If there is
  570. // just an LF or CR, then we will open the file up in binary mode.
  571. // In this fashion, the output format should match the input format, unless
  572. // the input format has inconsistent line endings.
  573. //
  574. // This should be a relatively fast operation since most files won't have
  575. // all of their source code on a single line. However, that is still a
  576. // concern, so if we scan for too long, we'll just assume the file should
  577. // be opened in binary mode.
  578. bool BinaryMode = true;
  579. bool InvalidFile = false;
  580. const SourceManager& SM = CI.getSourceManager();
  581. const llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getMainFileID(),
  582. &InvalidFile);
  583. if (!InvalidFile) {
  584. const char *cur = Buffer->getBufferStart();
  585. const char *end = Buffer->getBufferEnd();
  586. const char *next = (cur != end) ? cur + 1 : end;
  587. // Limit ourselves to only scanning 256 characters into the source
  588. // file. This is mostly a sanity check in case the file has no
  589. // newlines whatsoever.
  590. if (end - cur > 256) end = cur + 256;
  591. while (next < end) {
  592. if (*cur == 0x0D) { // CR
  593. if (*next == 0x0A) // CRLF
  594. BinaryMode = false;
  595. break;
  596. } else if (*cur == 0x0A) // LF
  597. break;
  598. ++cur, ++next;
  599. }
  600. }
  601. raw_ostream *OS = CI.createDefaultOutputFile(BinaryMode, getCurrentFile());
  602. if (!OS) return;
  603. DoPrintPreprocessedInput(CI.getPreprocessor(), OS,
  604. CI.getPreprocessorOutputOpts());
  605. }
  606. // HLSL Change Begin.
  607. HLSLRootSignatureAction::HLSLRootSignatureAction(StringRef rootSigMacro,
  608. unsigned major, unsigned minor)
  609. : HLSLRootSignatureMacro(rootSigMacro), rootSigMajor(major),
  610. rootSigMinor(minor) {
  611. rootSigHandle = llvm::make_unique<hlsl::RootSignatureHandle>();
  612. }
  613. void HLSLRootSignatureAction::ExecuteAction() {
  614. CompilerInstance &CI = getCompilerInstance();
  615. Preprocessor &PP = CI.getPreprocessor();
  616. // Ignore unknown pragmas.
  617. PP.IgnorePragmas();
  618. // Scans and ignores all tokens in the files.
  619. PP.EnterMainSourceFile();
  620. Token Tok;
  621. do PP.Lex(Tok);
  622. while (Tok.isNot(tok::eof));
  623. hlsl::DxilRootSignatureVersion rootSigVer;
  624. if (rootSigMinor == 0) {
  625. rootSigVer = hlsl::DxilRootSignatureVersion::Version_1_0;
  626. }
  627. else {
  628. assert(rootSigMinor == 1 &&
  629. "else HLSLRootSignatureAction Constructor needs to be updated");
  630. rootSigVer = hlsl::DxilRootSignatureVersion::Version_1_1;
  631. }
  632. assert(rootSigMajor == 1 &&
  633. "else HLSLRootSignatureAction Constructor needs to be updated");
  634. (void)rootSigMajor;
  635. // Try to find HLSLRootSignatureMacro in macros.
  636. MacroInfo *rootSigMacro = hlsl::MacroExpander::FindMacroInfo(PP, HLSLRootSignatureMacro);
  637. DiagnosticsEngine &Diags = CI.getDiagnostics();
  638. if (!rootSigMacro) {
  639. std::string cannotFindMacro =
  640. "undeclared identifier " + HLSLRootSignatureMacro;
  641. SourceLocation SLoc = Tok.getLocation();
  642. ReportHLSLRootSigError(Diags, SLoc, cannotFindMacro.c_str(),
  643. cannotFindMacro.size());
  644. return;
  645. }
  646. // Expand HLSLRootSignatureMacro.
  647. SourceLocation SLoc = rootSigMacro->getDefinitionLoc();
  648. std::string rootSigString;
  649. hlsl::MacroExpander expander(PP, hlsl::MacroExpander::STRIP_QUOTES);
  650. if (!expander.ExpandMacro(rootSigMacro, &rootSigString)) {
  651. StringRef error("error expanding root signature macro");
  652. ReportHLSLRootSigError(Diags, SLoc, error.data(), error.size());
  653. return;
  654. }
  655. // Compile the expanded root signature.
  656. clang::CompileRootSignature(rootSigString, Diags, SLoc, rootSigVer,
  657. hlsl::DxilRootSignatureCompilationFlags::None, rootSigHandle.get());
  658. }
  659. std::unique_ptr<hlsl::RootSignatureHandle> HLSLRootSignatureAction::takeRootSigHandle() {
  660. return std::move(rootSigHandle);
  661. }
  662. // HLSL Change End.
  663. void PrintPreambleAction::ExecuteAction() {
  664. switch (getCurrentFileKind()) {
  665. case IK_C:
  666. case IK_CXX:
  667. case IK_ObjC:
  668. case IK_ObjCXX:
  669. case IK_OpenCL:
  670. case IK_CUDA:
  671. break;
  672. case IK_None:
  673. case IK_Asm:
  674. case IK_PreprocessedC:
  675. case IK_PreprocessedCuda:
  676. case IK_PreprocessedCXX:
  677. case IK_PreprocessedObjC:
  678. case IK_PreprocessedObjCXX:
  679. case IK_AST:
  680. case IK_LLVM_IR:
  681. case IK_HLSL: // HLSL Change
  682. // We can't do anything with these.
  683. return;
  684. }
  685. CompilerInstance &CI = getCompilerInstance();
  686. auto Buffer = CI.getFileManager().getBufferForFile(getCurrentFile());
  687. if (Buffer) {
  688. unsigned Preamble =
  689. Lexer::ComputePreamble((*Buffer)->getBuffer(), CI.getLangOpts()).first;
  690. llvm::outs().write((*Buffer)->getBufferStart(), Preamble);
  691. }
  692. }