FrontendActions.cpp 25 KB

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