FrontendActions.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  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/CompilerInstance.h"
  14. #include "clang/Frontend/FrontendDiagnostic.h"
  15. #include "clang/Frontend/MultiplexConsumer.h"
  16. #include "clang/Frontend/Utils.h"
  17. #include "clang/Lex/HeaderSearch.h"
  18. #include "clang/Lex/Preprocessor.h"
  19. #include "clang/Lex/PreprocessorOptions.h"
  20. #include "clang/Sema/TemplateInstCallback.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/Path.h"
  26. #include "llvm/Support/raw_ostream.h"
  27. #include "llvm/Support/YAMLTraits.h"
  28. #include <memory>
  29. #include <system_error>
  30. using namespace clang;
  31. namespace {
  32. CodeCompleteConsumer *GetCodeCompletionConsumer(CompilerInstance &CI) {
  33. return CI.hasCodeCompletionConsumer() ? &CI.getCodeCompletionConsumer()
  34. : nullptr;
  35. }
  36. void EnsureSemaIsCreated(CompilerInstance &CI, FrontendAction &Action) {
  37. if (Action.hasCodeCompletionSupport() &&
  38. !CI.getFrontendOpts().CodeCompletionAt.FileName.empty())
  39. CI.createCodeCompletionConsumer();
  40. if (!CI.hasSema())
  41. CI.createSema(Action.getTranslationUnitKind(),
  42. GetCodeCompletionConsumer(CI));
  43. }
  44. } // namespace
  45. //===----------------------------------------------------------------------===//
  46. // Custom Actions
  47. //===----------------------------------------------------------------------===//
  48. std::unique_ptr<ASTConsumer>
  49. InitOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  50. return llvm::make_unique<ASTConsumer>();
  51. }
  52. void InitOnlyAction::ExecuteAction() {
  53. }
  54. //===----------------------------------------------------------------------===//
  55. // AST Consumer Actions
  56. //===----------------------------------------------------------------------===//
  57. std::unique_ptr<ASTConsumer>
  58. ASTPrintAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  59. if (std::unique_ptr<raw_ostream> OS =
  60. CI.createDefaultOutputFile(false, InFile))
  61. return CreateASTPrinter(std::move(OS), CI.getFrontendOpts().ASTDumpFilter);
  62. return nullptr;
  63. }
  64. std::unique_ptr<ASTConsumer>
  65. ASTDumpAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  66. return CreateASTDumper(CI.getFrontendOpts().ASTDumpFilter,
  67. CI.getFrontendOpts().ASTDumpDecls,
  68. CI.getFrontendOpts().ASTDumpAll,
  69. CI.getFrontendOpts().ASTDumpLookups);
  70. }
  71. std::unique_ptr<ASTConsumer>
  72. ASTDeclListAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  73. return CreateASTDeclNodeLister();
  74. }
  75. std::unique_ptr<ASTConsumer>
  76. ASTViewAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  77. return CreateASTViewer();
  78. }
  79. std::unique_ptr<ASTConsumer>
  80. DeclContextPrintAction::CreateASTConsumer(CompilerInstance &CI,
  81. StringRef InFile) {
  82. return CreateDeclContextPrinter();
  83. }
  84. std::unique_ptr<ASTConsumer>
  85. GeneratePCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  86. std::string Sysroot;
  87. if (!ComputeASTConsumerArguments(CI, /*ref*/ Sysroot))
  88. return nullptr;
  89. std::string OutputFile;
  90. std::unique_ptr<raw_pwrite_stream> OS =
  91. CreateOutputFile(CI, InFile, /*ref*/ OutputFile);
  92. if (!OS)
  93. return nullptr;
  94. if (!CI.getFrontendOpts().RelocatablePCH)
  95. Sysroot.clear();
  96. auto Buffer = std::make_shared<PCHBuffer>();
  97. std::vector<std::unique_ptr<ASTConsumer>> Consumers;
  98. Consumers.push_back(llvm::make_unique<PCHGenerator>(
  99. CI.getPreprocessor(), OutputFile, Sysroot,
  100. Buffer, CI.getFrontendOpts().ModuleFileExtensions,
  101. /*AllowASTWithErrors*/CI.getPreprocessorOpts().AllowPCHWithCompilerErrors,
  102. /*IncludeTimestamps*/
  103. +CI.getFrontendOpts().IncludeTimestamps));
  104. Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator(
  105. CI, InFile, OutputFile, std::move(OS), Buffer));
  106. return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
  107. }
  108. bool GeneratePCHAction::ComputeASTConsumerArguments(CompilerInstance &CI,
  109. std::string &Sysroot) {
  110. Sysroot = CI.getHeaderSearchOpts().Sysroot;
  111. if (CI.getFrontendOpts().RelocatablePCH && Sysroot.empty()) {
  112. CI.getDiagnostics().Report(diag::err_relocatable_without_isysroot);
  113. return false;
  114. }
  115. return true;
  116. }
  117. std::unique_ptr<llvm::raw_pwrite_stream>
  118. GeneratePCHAction::CreateOutputFile(CompilerInstance &CI, StringRef InFile,
  119. std::string &OutputFile) {
  120. // We use createOutputFile here because this is exposed via libclang, and we
  121. // must disable the RemoveFileOnSignal behavior.
  122. // We use a temporary to avoid race conditions.
  123. std::unique_ptr<raw_pwrite_stream> OS =
  124. CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
  125. /*RemoveFileOnSignal=*/false, InFile,
  126. /*Extension=*/"", /*useTemporary=*/true);
  127. if (!OS)
  128. return nullptr;
  129. OutputFile = CI.getFrontendOpts().OutputFile;
  130. return OS;
  131. }
  132. bool GeneratePCHAction::shouldEraseOutputFiles() {
  133. if (getCompilerInstance().getPreprocessorOpts().AllowPCHWithCompilerErrors)
  134. return false;
  135. return ASTFrontendAction::shouldEraseOutputFiles();
  136. }
  137. bool GeneratePCHAction::BeginSourceFileAction(CompilerInstance &CI) {
  138. CI.getLangOpts().CompilingPCH = true;
  139. return true;
  140. }
  141. std::unique_ptr<ASTConsumer>
  142. GenerateModuleAction::CreateASTConsumer(CompilerInstance &CI,
  143. StringRef InFile) {
  144. std::unique_ptr<raw_pwrite_stream> OS = CreateOutputFile(CI, InFile);
  145. if (!OS)
  146. return nullptr;
  147. std::string OutputFile = CI.getFrontendOpts().OutputFile;
  148. std::string Sysroot;
  149. auto Buffer = std::make_shared<PCHBuffer>();
  150. std::vector<std::unique_ptr<ASTConsumer>> Consumers;
  151. Consumers.push_back(llvm::make_unique<PCHGenerator>(
  152. CI.getPreprocessor(), OutputFile, Sysroot,
  153. Buffer, CI.getFrontendOpts().ModuleFileExtensions,
  154. /*AllowASTWithErrors=*/false,
  155. /*IncludeTimestamps=*/
  156. +CI.getFrontendOpts().BuildingImplicitModule));
  157. Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator(
  158. CI, InFile, OutputFile, std::move(OS), Buffer));
  159. return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
  160. }
  161. bool GenerateModuleFromModuleMapAction::BeginSourceFileAction(
  162. CompilerInstance &CI) {
  163. if (!CI.getLangOpts().Modules) {
  164. CI.getDiagnostics().Report(diag::err_module_build_requires_fmodules);
  165. return false;
  166. }
  167. return GenerateModuleAction::BeginSourceFileAction(CI);
  168. }
  169. std::unique_ptr<raw_pwrite_stream>
  170. GenerateModuleFromModuleMapAction::CreateOutputFile(CompilerInstance &CI,
  171. StringRef InFile) {
  172. // If no output file was provided, figure out where this module would go
  173. // in the module cache.
  174. if (CI.getFrontendOpts().OutputFile.empty()) {
  175. StringRef ModuleMapFile = CI.getFrontendOpts().OriginalModuleMap;
  176. if (ModuleMapFile.empty())
  177. ModuleMapFile = InFile;
  178. HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
  179. CI.getFrontendOpts().OutputFile =
  180. HS.getCachedModuleFileName(CI.getLangOpts().CurrentModule,
  181. ModuleMapFile);
  182. }
  183. // We use createOutputFile here because this is exposed via libclang, and we
  184. // must disable the RemoveFileOnSignal behavior.
  185. // We use a temporary to avoid race conditions.
  186. return CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
  187. /*RemoveFileOnSignal=*/false, InFile,
  188. /*Extension=*/"", /*useTemporary=*/true,
  189. /*CreateMissingDirectories=*/true);
  190. }
  191. bool GenerateModuleInterfaceAction::BeginSourceFileAction(
  192. CompilerInstance &CI) {
  193. if (!CI.getLangOpts().ModulesTS) {
  194. CI.getDiagnostics().Report(diag::err_module_interface_requires_modules_ts);
  195. return false;
  196. }
  197. CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleInterface);
  198. return GenerateModuleAction::BeginSourceFileAction(CI);
  199. }
  200. std::unique_ptr<raw_pwrite_stream>
  201. GenerateModuleInterfaceAction::CreateOutputFile(CompilerInstance &CI,
  202. StringRef InFile) {
  203. return CI.createDefaultOutputFile(/*Binary=*/true, InFile, "pcm");
  204. }
  205. SyntaxOnlyAction::~SyntaxOnlyAction() {
  206. }
  207. std::unique_ptr<ASTConsumer>
  208. SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  209. return llvm::make_unique<ASTConsumer>();
  210. }
  211. std::unique_ptr<ASTConsumer>
  212. DumpModuleInfoAction::CreateASTConsumer(CompilerInstance &CI,
  213. StringRef InFile) {
  214. return llvm::make_unique<ASTConsumer>();
  215. }
  216. std::unique_ptr<ASTConsumer>
  217. VerifyPCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  218. return llvm::make_unique<ASTConsumer>();
  219. }
  220. void VerifyPCHAction::ExecuteAction() {
  221. CompilerInstance &CI = getCompilerInstance();
  222. bool Preamble = CI.getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
  223. const std::string &Sysroot = CI.getHeaderSearchOpts().Sysroot;
  224. std::unique_ptr<ASTReader> Reader(new ASTReader(
  225. CI.getPreprocessor(), &CI.getASTContext(), CI.getPCHContainerReader(),
  226. CI.getFrontendOpts().ModuleFileExtensions,
  227. Sysroot.empty() ? "" : Sysroot.c_str(),
  228. /*DisableValidation*/ false,
  229. /*AllowPCHWithCompilerErrors*/ false,
  230. /*AllowConfigurationMismatch*/ true,
  231. /*ValidateSystemInputs*/ true));
  232. Reader->ReadAST(getCurrentFile(),
  233. Preamble ? serialization::MK_Preamble
  234. : serialization::MK_PCH,
  235. SourceLocation(),
  236. ASTReader::ARR_ConfigurationMismatch);
  237. }
  238. namespace {
  239. struct TemplightEntry {
  240. std::string Name;
  241. std::string Kind;
  242. std::string Event;
  243. std::string DefinitionLocation;
  244. std::string PointOfInstantiation;
  245. };
  246. } // namespace
  247. namespace llvm {
  248. namespace yaml {
  249. template <> struct MappingTraits<TemplightEntry> {
  250. static void mapping(IO &io, TemplightEntry &fields) {
  251. io.mapRequired("name", fields.Name);
  252. io.mapRequired("kind", fields.Kind);
  253. io.mapRequired("event", fields.Event);
  254. io.mapRequired("orig", fields.DefinitionLocation);
  255. io.mapRequired("poi", fields.PointOfInstantiation);
  256. }
  257. };
  258. } // namespace yaml
  259. } // namespace llvm
  260. namespace {
  261. class DefaultTemplateInstCallback : public TemplateInstantiationCallback {
  262. using CodeSynthesisContext = Sema::CodeSynthesisContext;
  263. public:
  264. virtual void initialize(const Sema &) {}
  265. virtual void finalize(const Sema &) {}
  266. virtual void atTemplateBegin(const Sema &TheSema,
  267. const CodeSynthesisContext &Inst) override {
  268. displayTemplightEntry<true>(llvm::outs(), TheSema, Inst);
  269. }
  270. virtual void atTemplateEnd(const Sema &TheSema,
  271. const CodeSynthesisContext &Inst) override {
  272. displayTemplightEntry<false>(llvm::outs(), TheSema, Inst);
  273. }
  274. private:
  275. static std::string toString(CodeSynthesisContext::SynthesisKind Kind) {
  276. switch (Kind) {
  277. case CodeSynthesisContext::TemplateInstantiation:
  278. return "TemplateInstantiation";
  279. case CodeSynthesisContext::DefaultTemplateArgumentInstantiation:
  280. return "DefaultTemplateArgumentInstantiation";
  281. case CodeSynthesisContext::DefaultFunctionArgumentInstantiation:
  282. return "DefaultFunctionArgumentInstantiation";
  283. case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution:
  284. return "ExplicitTemplateArgumentSubstitution";
  285. case CodeSynthesisContext::DeducedTemplateArgumentSubstitution:
  286. return "DeducedTemplateArgumentSubstitution";
  287. case CodeSynthesisContext::PriorTemplateArgumentSubstitution:
  288. return "PriorTemplateArgumentSubstitution";
  289. case CodeSynthesisContext::DefaultTemplateArgumentChecking:
  290. return "DefaultTemplateArgumentChecking";
  291. case CodeSynthesisContext::ExceptionSpecInstantiation:
  292. return "ExceptionSpecInstantiation";
  293. case CodeSynthesisContext::DeclaringSpecialMember:
  294. return "DeclaringSpecialMember";
  295. case CodeSynthesisContext::DefiningSynthesizedFunction:
  296. return "DefiningSynthesizedFunction";
  297. case CodeSynthesisContext::Memoization:
  298. return "Memoization";
  299. }
  300. return "";
  301. }
  302. template <bool BeginInstantiation>
  303. static void displayTemplightEntry(llvm::raw_ostream &Out, const Sema &TheSema,
  304. const CodeSynthesisContext &Inst) {
  305. std::string YAML;
  306. {
  307. llvm::raw_string_ostream OS(YAML);
  308. llvm::yaml::Output YO(OS);
  309. TemplightEntry Entry =
  310. getTemplightEntry<BeginInstantiation>(TheSema, Inst);
  311. llvm::yaml::EmptyContext Context;
  312. llvm::yaml::yamlize(YO, Entry, true, Context);
  313. }
  314. Out << "---" << YAML << "\n";
  315. }
  316. template <bool BeginInstantiation>
  317. static TemplightEntry getTemplightEntry(const Sema &TheSema,
  318. const CodeSynthesisContext &Inst) {
  319. TemplightEntry Entry;
  320. Entry.Kind = toString(Inst.Kind);
  321. Entry.Event = BeginInstantiation ? "Begin" : "End";
  322. if (auto *NamedTemplate = dyn_cast_or_null<NamedDecl>(Inst.Entity)) {
  323. llvm::raw_string_ostream OS(Entry.Name);
  324. NamedTemplate->getNameForDiagnostic(OS, TheSema.getLangOpts(), true);
  325. const PresumedLoc DefLoc =
  326. TheSema.getSourceManager().getPresumedLoc(Inst.Entity->getLocation());
  327. if(!DefLoc.isInvalid())
  328. Entry.DefinitionLocation = std::string(DefLoc.getFilename()) + ":" +
  329. std::to_string(DefLoc.getLine()) + ":" +
  330. std::to_string(DefLoc.getColumn());
  331. }
  332. const PresumedLoc PoiLoc =
  333. TheSema.getSourceManager().getPresumedLoc(Inst.PointOfInstantiation);
  334. if (!PoiLoc.isInvalid()) {
  335. Entry.PointOfInstantiation = std::string(PoiLoc.getFilename()) + ":" +
  336. std::to_string(PoiLoc.getLine()) + ":" +
  337. std::to_string(PoiLoc.getColumn());
  338. }
  339. return Entry;
  340. }
  341. };
  342. } // namespace
  343. std::unique_ptr<ASTConsumer>
  344. TemplightDumpAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  345. return llvm::make_unique<ASTConsumer>();
  346. }
  347. void TemplightDumpAction::ExecuteAction() {
  348. CompilerInstance &CI = getCompilerInstance();
  349. // This part is normally done by ASTFrontEndAction, but needs to happen
  350. // before Templight observers can be created
  351. // FIXME: Move the truncation aspect of this into Sema, we delayed this till
  352. // here so the source manager would be initialized.
  353. EnsureSemaIsCreated(CI, *this);
  354. CI.getSema().TemplateInstCallbacks.push_back(
  355. llvm::make_unique<DefaultTemplateInstCallback>());
  356. ASTFrontendAction::ExecuteAction();
  357. }
  358. namespace {
  359. /// \brief AST reader listener that dumps module information for a module
  360. /// file.
  361. class DumpModuleInfoListener : public ASTReaderListener {
  362. llvm::raw_ostream &Out;
  363. public:
  364. DumpModuleInfoListener(llvm::raw_ostream &Out) : Out(Out) { }
  365. #define DUMP_BOOLEAN(Value, Text) \
  366. Out.indent(4) << Text << ": " << (Value? "Yes" : "No") << "\n"
  367. bool ReadFullVersionInformation(StringRef FullVersion) override {
  368. Out.indent(2)
  369. << "Generated by "
  370. << (FullVersion == getClangFullRepositoryVersion()? "this"
  371. : "a different")
  372. << " Clang: " << FullVersion << "\n";
  373. return ASTReaderListener::ReadFullVersionInformation(FullVersion);
  374. }
  375. void ReadModuleName(StringRef ModuleName) override {
  376. Out.indent(2) << "Module name: " << ModuleName << "\n";
  377. }
  378. void ReadModuleMapFile(StringRef ModuleMapPath) override {
  379. Out.indent(2) << "Module map file: " << ModuleMapPath << "\n";
  380. }
  381. bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
  382. bool AllowCompatibleDifferences) override {
  383. Out.indent(2) << "Language options:\n";
  384. #define LANGOPT(Name, Bits, Default, Description) \
  385. DUMP_BOOLEAN(LangOpts.Name, Description);
  386. #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
  387. Out.indent(4) << Description << ": " \
  388. << static_cast<unsigned>(LangOpts.get##Name()) << "\n";
  389. #define VALUE_LANGOPT(Name, Bits, Default, Description) \
  390. Out.indent(4) << Description << ": " << LangOpts.Name << "\n";
  391. #define BENIGN_LANGOPT(Name, Bits, Default, Description)
  392. #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
  393. #include "clang/Basic/LangOptions.def"
  394. if (!LangOpts.ModuleFeatures.empty()) {
  395. Out.indent(4) << "Module features:\n";
  396. for (StringRef Feature : LangOpts.ModuleFeatures)
  397. Out.indent(6) << Feature << "\n";
  398. }
  399. return false;
  400. }
  401. bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
  402. bool AllowCompatibleDifferences) override {
  403. Out.indent(2) << "Target options:\n";
  404. Out.indent(4) << " Triple: " << TargetOpts.Triple << "\n";
  405. Out.indent(4) << " CPU: " << TargetOpts.CPU << "\n";
  406. Out.indent(4) << " ABI: " << TargetOpts.ABI << "\n";
  407. if (!TargetOpts.FeaturesAsWritten.empty()) {
  408. Out.indent(4) << "Target features:\n";
  409. for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size();
  410. I != N; ++I) {
  411. Out.indent(6) << TargetOpts.FeaturesAsWritten[I] << "\n";
  412. }
  413. }
  414. return false;
  415. }
  416. bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
  417. bool Complain) override {
  418. Out.indent(2) << "Diagnostic options:\n";
  419. #define DIAGOPT(Name, Bits, Default) DUMP_BOOLEAN(DiagOpts->Name, #Name);
  420. #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
  421. Out.indent(4) << #Name << ": " << DiagOpts->get##Name() << "\n";
  422. #define VALUE_DIAGOPT(Name, Bits, Default) \
  423. Out.indent(4) << #Name << ": " << DiagOpts->Name << "\n";
  424. #include "clang/Basic/DiagnosticOptions.def"
  425. Out.indent(4) << "Diagnostic flags:\n";
  426. for (const std::string &Warning : DiagOpts->Warnings)
  427. Out.indent(6) << "-W" << Warning << "\n";
  428. for (const std::string &Remark : DiagOpts->Remarks)
  429. Out.indent(6) << "-R" << Remark << "\n";
  430. return false;
  431. }
  432. bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
  433. StringRef SpecificModuleCachePath,
  434. bool Complain) override {
  435. Out.indent(2) << "Header search options:\n";
  436. Out.indent(4) << "System root [-isysroot=]: '" << HSOpts.Sysroot << "'\n";
  437. Out.indent(4) << "Resource dir [ -resource-dir=]: '" << HSOpts.ResourceDir << "'\n";
  438. Out.indent(4) << "Module Cache: '" << SpecificModuleCachePath << "'\n";
  439. DUMP_BOOLEAN(HSOpts.UseBuiltinIncludes,
  440. "Use builtin include directories [-nobuiltininc]");
  441. DUMP_BOOLEAN(HSOpts.UseStandardSystemIncludes,
  442. "Use standard system include directories [-nostdinc]");
  443. DUMP_BOOLEAN(HSOpts.UseStandardCXXIncludes,
  444. "Use standard C++ include directories [-nostdinc++]");
  445. DUMP_BOOLEAN(HSOpts.UseLibcxx,
  446. "Use libc++ (rather than libstdc++) [-stdlib=]");
  447. return false;
  448. }
  449. bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
  450. bool Complain,
  451. std::string &SuggestedPredefines) override {
  452. Out.indent(2) << "Preprocessor options:\n";
  453. DUMP_BOOLEAN(PPOpts.UsePredefines,
  454. "Uses compiler/target-specific predefines [-undef]");
  455. DUMP_BOOLEAN(PPOpts.DetailedRecord,
  456. "Uses detailed preprocessing record (for indexing)");
  457. if (!PPOpts.Macros.empty()) {
  458. Out.indent(4) << "Predefined macros:\n";
  459. }
  460. for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator
  461. I = PPOpts.Macros.begin(), IEnd = PPOpts.Macros.end();
  462. I != IEnd; ++I) {
  463. Out.indent(6);
  464. if (I->second)
  465. Out << "-U";
  466. else
  467. Out << "-D";
  468. Out << I->first << "\n";
  469. }
  470. return false;
  471. }
  472. /// Indicates that a particular module file extension has been read.
  473. void readModuleFileExtension(
  474. const ModuleFileExtensionMetadata &Metadata) override {
  475. Out.indent(2) << "Module file extension '"
  476. << Metadata.BlockName << "' " << Metadata.MajorVersion
  477. << "." << Metadata.MinorVersion;
  478. if (!Metadata.UserInfo.empty()) {
  479. Out << ": ";
  480. Out.write_escaped(Metadata.UserInfo);
  481. }
  482. Out << "\n";
  483. }
  484. #undef DUMP_BOOLEAN
  485. };
  486. }
  487. bool DumpModuleInfoAction::BeginInvocation(CompilerInstance &CI) {
  488. // The Object file reader also supports raw ast files and there is no point in
  489. // being strict about the module file format in -module-file-info mode.
  490. CI.getHeaderSearchOpts().ModuleFormat = "obj";
  491. return true;
  492. }
  493. void DumpModuleInfoAction::ExecuteAction() {
  494. // Set up the output file.
  495. std::unique_ptr<llvm::raw_fd_ostream> OutFile;
  496. StringRef OutputFileName = getCompilerInstance().getFrontendOpts().OutputFile;
  497. if (!OutputFileName.empty() && OutputFileName != "-") {
  498. std::error_code EC;
  499. OutFile.reset(new llvm::raw_fd_ostream(OutputFileName.str(), EC,
  500. llvm::sys::fs::F_Text));
  501. }
  502. llvm::raw_ostream &Out = OutFile.get()? *OutFile.get() : llvm::outs();
  503. Out << "Information for module file '" << getCurrentFile() << "':\n";
  504. auto &FileMgr = getCompilerInstance().getFileManager();
  505. auto Buffer = FileMgr.getBufferForFile(getCurrentFile());
  506. StringRef Magic = (*Buffer)->getMemBufferRef().getBuffer();
  507. bool IsRaw = (Magic.size() >= 4 && Magic[0] == 'C' && Magic[1] == 'P' &&
  508. Magic[2] == 'C' && Magic[3] == 'H');
  509. Out << " Module format: " << (IsRaw ? "raw" : "obj") << "\n";
  510. Preprocessor &PP = getCompilerInstance().getPreprocessor();
  511. DumpModuleInfoListener Listener(Out);
  512. HeaderSearchOptions &HSOpts =
  513. PP.getHeaderSearchInfo().getHeaderSearchOpts();
  514. ASTReader::readASTFileControlBlock(
  515. getCurrentFile(), FileMgr, getCompilerInstance().getPCHContainerReader(),
  516. /*FindModuleFileExtensions=*/true, Listener,
  517. HSOpts.ModulesValidateDiagnosticOptions);
  518. }
  519. //===----------------------------------------------------------------------===//
  520. // Preprocessor Actions
  521. //===----------------------------------------------------------------------===//
  522. void DumpRawTokensAction::ExecuteAction() {
  523. Preprocessor &PP = getCompilerInstance().getPreprocessor();
  524. SourceManager &SM = PP.getSourceManager();
  525. // Start lexing the specified input file.
  526. const llvm::MemoryBuffer *FromFile = SM.getBuffer(SM.getMainFileID());
  527. Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts());
  528. RawLex.SetKeepWhitespaceMode(true);
  529. Token RawTok;
  530. RawLex.LexFromRawLexer(RawTok);
  531. while (RawTok.isNot(tok::eof)) {
  532. PP.DumpToken(RawTok, true);
  533. llvm::errs() << "\n";
  534. RawLex.LexFromRawLexer(RawTok);
  535. }
  536. }
  537. void DumpTokensAction::ExecuteAction() {
  538. Preprocessor &PP = getCompilerInstance().getPreprocessor();
  539. // Start preprocessing the specified input file.
  540. Token Tok;
  541. PP.EnterMainSourceFile();
  542. do {
  543. PP.Lex(Tok);
  544. PP.DumpToken(Tok, true);
  545. llvm::errs() << "\n";
  546. } while (Tok.isNot(tok::eof));
  547. }
  548. void GeneratePTHAction::ExecuteAction() {
  549. CompilerInstance &CI = getCompilerInstance();
  550. std::unique_ptr<raw_pwrite_stream> OS =
  551. CI.createDefaultOutputFile(true, getCurrentFile());
  552. if (!OS)
  553. return;
  554. CacheTokens(CI.getPreprocessor(), OS.get());
  555. }
  556. void PreprocessOnlyAction::ExecuteAction() {
  557. Preprocessor &PP = getCompilerInstance().getPreprocessor();
  558. // Ignore unknown pragmas.
  559. PP.IgnorePragmas();
  560. Token Tok;
  561. // Start parsing the specified input file.
  562. PP.EnterMainSourceFile();
  563. do {
  564. PP.Lex(Tok);
  565. } while (Tok.isNot(tok::eof));
  566. }
  567. void PrintPreprocessedAction::ExecuteAction() {
  568. CompilerInstance &CI = getCompilerInstance();
  569. // Output file may need to be set to 'Binary', to avoid converting Unix style
  570. // line feeds (<LF>) to Microsoft style line feeds (<CR><LF>).
  571. //
  572. // Look to see what type of line endings the file uses. If there's a
  573. // CRLF, then we won't open the file up in binary mode. If there is
  574. // just an LF or CR, then we will open the file up in binary mode.
  575. // In this fashion, the output format should match the input format, unless
  576. // the input format has inconsistent line endings.
  577. //
  578. // This should be a relatively fast operation since most files won't have
  579. // all of their source code on a single line. However, that is still a
  580. // concern, so if we scan for too long, we'll just assume the file should
  581. // be opened in binary mode.
  582. bool BinaryMode = true;
  583. bool InvalidFile = false;
  584. const SourceManager& SM = CI.getSourceManager();
  585. const llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getMainFileID(),
  586. &InvalidFile);
  587. if (!InvalidFile) {
  588. const char *cur = Buffer->getBufferStart();
  589. const char *end = Buffer->getBufferEnd();
  590. const char *next = (cur != end) ? cur + 1 : end;
  591. // Limit ourselves to only scanning 256 characters into the source
  592. // file. This is mostly a sanity check in case the file has no
  593. // newlines whatsoever.
  594. if (end - cur > 256) end = cur + 256;
  595. while (next < end) {
  596. if (*cur == 0x0D) { // CR
  597. if (*next == 0x0A) // CRLF
  598. BinaryMode = false;
  599. break;
  600. } else if (*cur == 0x0A) // LF
  601. break;
  602. ++cur;
  603. ++next;
  604. }
  605. }
  606. std::unique_ptr<raw_ostream> OS =
  607. CI.createDefaultOutputFile(BinaryMode, getCurrentFile());
  608. if (!OS) return;
  609. // If we're preprocessing a module map, start by dumping the contents of the
  610. // module itself before switching to the input buffer.
  611. auto &Input = getCurrentInput();
  612. if (Input.getKind().getFormat() == InputKind::ModuleMap) {
  613. if (Input.isFile()) {
  614. (*OS) << "# 1 \"";
  615. OS->write_escaped(Input.getFile());
  616. (*OS) << "\"\n";
  617. }
  618. // FIXME: Include additional information here so that we don't need the
  619. // original source files to exist on disk.
  620. getCurrentModule()->print(*OS);
  621. (*OS) << "#pragma clang module contents\n";
  622. }
  623. DoPrintPreprocessedInput(CI.getPreprocessor(), OS.get(),
  624. CI.getPreprocessorOutputOpts());
  625. }
  626. void PrintPreambleAction::ExecuteAction() {
  627. switch (getCurrentFileKind().getLanguage()) {
  628. case InputKind::C:
  629. case InputKind::CXX:
  630. case InputKind::ObjC:
  631. case InputKind::ObjCXX:
  632. case InputKind::OpenCL:
  633. case InputKind::CUDA:
  634. break;
  635. case InputKind::Unknown:
  636. case InputKind::Asm:
  637. case InputKind::LLVM_IR:
  638. case InputKind::RenderScript:
  639. // We can't do anything with these.
  640. return;
  641. }
  642. // We don't expect to find any #include directives in a preprocessed input.
  643. if (getCurrentFileKind().isPreprocessed())
  644. return;
  645. CompilerInstance &CI = getCompilerInstance();
  646. auto Buffer = CI.getFileManager().getBufferForFile(getCurrentFile());
  647. if (Buffer) {
  648. unsigned Preamble =
  649. Lexer::ComputePreamble((*Buffer)->getBuffer(), CI.getLangOpts()).Size;
  650. llvm::outs().write((*Buffer)->getBufferStart(), Preamble);
  651. }
  652. }