FrontendActions.cpp 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147
  1. //===--- FrontendActions.cpp ----------------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "clang/Frontend/FrontendActions.h"
  9. #include "clang/AST/ASTConsumer.h"
  10. #include "clang/AST/Decl.h"
  11. #include "clang/Basic/FileManager.h"
  12. #include "clang/Basic/LangStandard.h"
  13. #include "clang/Basic/Module.h"
  14. #include "clang/Basic/TargetInfo.h"
  15. #include "clang/Frontend/ASTConsumers.h"
  16. #include "clang/Frontend/CompilerInstance.h"
  17. #include "clang/Frontend/FrontendDiagnostic.h"
  18. #include "clang/Frontend/MultiplexConsumer.h"
  19. #include "clang/Frontend/Utils.h"
  20. #include "clang/Lex/DependencyDirectivesScanner.h"
  21. #include "clang/Lex/HeaderSearch.h"
  22. #include "clang/Lex/Preprocessor.h"
  23. #include "clang/Lex/PreprocessorOptions.h"
  24. #include "clang/Sema/TemplateInstCallback.h"
  25. #include "clang/Serialization/ASTReader.h"
  26. #include "clang/Serialization/ASTWriter.h"
  27. #include "clang/Serialization/ModuleFile.h"
  28. #include "llvm/Support/ErrorHandling.h"
  29. #include "llvm/Support/FileSystem.h"
  30. #include "llvm/Support/MemoryBuffer.h"
  31. #include "llvm/Support/Path.h"
  32. #include "llvm/Support/YAMLTraits.h"
  33. #include "llvm/Support/raw_ostream.h"
  34. #include <memory>
  35. #include <optional>
  36. #include <system_error>
  37. using namespace clang;
  38. namespace {
  39. CodeCompleteConsumer *GetCodeCompletionConsumer(CompilerInstance &CI) {
  40. return CI.hasCodeCompletionConsumer() ? &CI.getCodeCompletionConsumer()
  41. : nullptr;
  42. }
  43. void EnsureSemaIsCreated(CompilerInstance &CI, FrontendAction &Action) {
  44. if (Action.hasCodeCompletionSupport() &&
  45. !CI.getFrontendOpts().CodeCompletionAt.FileName.empty())
  46. CI.createCodeCompletionConsumer();
  47. if (!CI.hasSema())
  48. CI.createSema(Action.getTranslationUnitKind(),
  49. GetCodeCompletionConsumer(CI));
  50. }
  51. } // namespace
  52. //===----------------------------------------------------------------------===//
  53. // Custom Actions
  54. //===----------------------------------------------------------------------===//
  55. std::unique_ptr<ASTConsumer>
  56. InitOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  57. return std::make_unique<ASTConsumer>();
  58. }
  59. void InitOnlyAction::ExecuteAction() {
  60. }
  61. // Basically PreprocessOnlyAction::ExecuteAction.
  62. void ReadPCHAndPreprocessAction::ExecuteAction() {
  63. Preprocessor &PP = getCompilerInstance().getPreprocessor();
  64. // Ignore unknown pragmas.
  65. PP.IgnorePragmas();
  66. Token Tok;
  67. // Start parsing the specified input file.
  68. PP.EnterMainSourceFile();
  69. do {
  70. PP.Lex(Tok);
  71. } while (Tok.isNot(tok::eof));
  72. }
  73. std::unique_ptr<ASTConsumer>
  74. ReadPCHAndPreprocessAction::CreateASTConsumer(CompilerInstance &CI,
  75. StringRef InFile) {
  76. return std::make_unique<ASTConsumer>();
  77. }
  78. //===----------------------------------------------------------------------===//
  79. // AST Consumer Actions
  80. //===----------------------------------------------------------------------===//
  81. std::unique_ptr<ASTConsumer>
  82. ASTPrintAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  83. if (std::unique_ptr<raw_ostream> OS =
  84. CI.createDefaultOutputFile(false, InFile))
  85. return CreateASTPrinter(std::move(OS), CI.getFrontendOpts().ASTDumpFilter);
  86. return nullptr;
  87. }
  88. std::unique_ptr<ASTConsumer>
  89. ASTDumpAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  90. const FrontendOptions &Opts = CI.getFrontendOpts();
  91. return CreateASTDumper(nullptr /*Dump to stdout.*/, Opts.ASTDumpFilter,
  92. Opts.ASTDumpDecls, Opts.ASTDumpAll,
  93. Opts.ASTDumpLookups, Opts.ASTDumpDeclTypes,
  94. Opts.ASTDumpFormat);
  95. }
  96. std::unique_ptr<ASTConsumer>
  97. ASTDeclListAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  98. return CreateASTDeclNodeLister();
  99. }
  100. std::unique_ptr<ASTConsumer>
  101. ASTViewAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  102. return CreateASTViewer();
  103. }
  104. std::unique_ptr<ASTConsumer>
  105. GeneratePCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  106. std::string Sysroot;
  107. if (!ComputeASTConsumerArguments(CI, /*ref*/ Sysroot))
  108. return nullptr;
  109. std::string OutputFile;
  110. std::unique_ptr<raw_pwrite_stream> OS =
  111. CreateOutputFile(CI, InFile, /*ref*/ OutputFile);
  112. if (!OS)
  113. return nullptr;
  114. if (!CI.getFrontendOpts().RelocatablePCH)
  115. Sysroot.clear();
  116. const auto &FrontendOpts = CI.getFrontendOpts();
  117. auto Buffer = std::make_shared<PCHBuffer>();
  118. std::vector<std::unique_ptr<ASTConsumer>> Consumers;
  119. Consumers.push_back(std::make_unique<PCHGenerator>(
  120. CI.getPreprocessor(), CI.getModuleCache(), OutputFile, Sysroot, Buffer,
  121. FrontendOpts.ModuleFileExtensions,
  122. CI.getPreprocessorOpts().AllowPCHWithCompilerErrors,
  123. FrontendOpts.IncludeTimestamps, +CI.getLangOpts().CacheGeneratedPCH));
  124. Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator(
  125. CI, std::string(InFile), OutputFile, std::move(OS), Buffer));
  126. return std::make_unique<MultiplexConsumer>(std::move(Consumers));
  127. }
  128. bool GeneratePCHAction::ComputeASTConsumerArguments(CompilerInstance &CI,
  129. std::string &Sysroot) {
  130. Sysroot = CI.getHeaderSearchOpts().Sysroot;
  131. if (CI.getFrontendOpts().RelocatablePCH && Sysroot.empty()) {
  132. CI.getDiagnostics().Report(diag::err_relocatable_without_isysroot);
  133. return false;
  134. }
  135. return true;
  136. }
  137. std::unique_ptr<llvm::raw_pwrite_stream>
  138. GeneratePCHAction::CreateOutputFile(CompilerInstance &CI, StringRef InFile,
  139. std::string &OutputFile) {
  140. // Because this is exposed via libclang we must disable RemoveFileOnSignal.
  141. std::unique_ptr<raw_pwrite_stream> OS = CI.createDefaultOutputFile(
  142. /*Binary=*/true, InFile, /*Extension=*/"", /*RemoveFileOnSignal=*/false);
  143. if (!OS)
  144. return nullptr;
  145. OutputFile = CI.getFrontendOpts().OutputFile;
  146. return OS;
  147. }
  148. bool GeneratePCHAction::shouldEraseOutputFiles() {
  149. if (getCompilerInstance().getPreprocessorOpts().AllowPCHWithCompilerErrors)
  150. return false;
  151. return ASTFrontendAction::shouldEraseOutputFiles();
  152. }
  153. bool GeneratePCHAction::BeginSourceFileAction(CompilerInstance &CI) {
  154. CI.getLangOpts().CompilingPCH = true;
  155. return true;
  156. }
  157. std::unique_ptr<ASTConsumer>
  158. GenerateModuleAction::CreateASTConsumer(CompilerInstance &CI,
  159. StringRef InFile) {
  160. std::unique_ptr<raw_pwrite_stream> OS = CreateOutputFile(CI, InFile);
  161. if (!OS)
  162. return nullptr;
  163. std::string OutputFile = CI.getFrontendOpts().OutputFile;
  164. std::string Sysroot;
  165. auto Buffer = std::make_shared<PCHBuffer>();
  166. std::vector<std::unique_ptr<ASTConsumer>> Consumers;
  167. Consumers.push_back(std::make_unique<PCHGenerator>(
  168. CI.getPreprocessor(), CI.getModuleCache(), OutputFile, Sysroot, Buffer,
  169. CI.getFrontendOpts().ModuleFileExtensions,
  170. /*AllowASTWithErrors=*/
  171. +CI.getFrontendOpts().AllowPCMWithCompilerErrors,
  172. /*IncludeTimestamps=*/
  173. +CI.getFrontendOpts().BuildingImplicitModule,
  174. /*ShouldCacheASTInMemory=*/
  175. +CI.getFrontendOpts().BuildingImplicitModule));
  176. Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator(
  177. CI, std::string(InFile), OutputFile, std::move(OS), Buffer));
  178. return std::make_unique<MultiplexConsumer>(std::move(Consumers));
  179. }
  180. bool GenerateModuleAction::shouldEraseOutputFiles() {
  181. return !getCompilerInstance().getFrontendOpts().AllowPCMWithCompilerErrors &&
  182. ASTFrontendAction::shouldEraseOutputFiles();
  183. }
  184. bool GenerateModuleFromModuleMapAction::BeginSourceFileAction(
  185. CompilerInstance &CI) {
  186. if (!CI.getLangOpts().Modules) {
  187. CI.getDiagnostics().Report(diag::err_module_build_requires_fmodules);
  188. return false;
  189. }
  190. return GenerateModuleAction::BeginSourceFileAction(CI);
  191. }
  192. std::unique_ptr<raw_pwrite_stream>
  193. GenerateModuleFromModuleMapAction::CreateOutputFile(CompilerInstance &CI,
  194. StringRef InFile) {
  195. // If no output file was provided, figure out where this module would go
  196. // in the module cache.
  197. if (CI.getFrontendOpts().OutputFile.empty()) {
  198. StringRef ModuleMapFile = CI.getFrontendOpts().OriginalModuleMap;
  199. if (ModuleMapFile.empty())
  200. ModuleMapFile = InFile;
  201. HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
  202. CI.getFrontendOpts().OutputFile =
  203. HS.getCachedModuleFileName(CI.getLangOpts().CurrentModule,
  204. ModuleMapFile);
  205. }
  206. // Because this is exposed via libclang we must disable RemoveFileOnSignal.
  207. return CI.createDefaultOutputFile(/*Binary=*/true, InFile, /*Extension=*/"",
  208. /*RemoveFileOnSignal=*/false,
  209. /*CreateMissingDirectories=*/true,
  210. /*ForceUseTemporary=*/true);
  211. }
  212. bool GenerateModuleInterfaceAction::BeginSourceFileAction(
  213. CompilerInstance &CI) {
  214. if (!CI.getLangOpts().ModulesTS && !CI.getLangOpts().CPlusPlusModules) {
  215. CI.getDiagnostics().Report(diag::err_module_interface_requires_cpp_modules);
  216. return false;
  217. }
  218. CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleInterface);
  219. return GenerateModuleAction::BeginSourceFileAction(CI);
  220. }
  221. std::unique_ptr<raw_pwrite_stream>
  222. GenerateModuleInterfaceAction::CreateOutputFile(CompilerInstance &CI,
  223. StringRef InFile) {
  224. return CI.createDefaultOutputFile(/*Binary=*/true, InFile, "pcm");
  225. }
  226. bool GenerateHeaderUnitAction::BeginSourceFileAction(CompilerInstance &CI) {
  227. if (!CI.getLangOpts().CPlusPlusModules) {
  228. CI.getDiagnostics().Report(diag::err_module_interface_requires_cpp_modules);
  229. return false;
  230. }
  231. CI.getLangOpts().setCompilingModule(LangOptions::CMK_HeaderUnit);
  232. return GenerateModuleAction::BeginSourceFileAction(CI);
  233. }
  234. std::unique_ptr<raw_pwrite_stream>
  235. GenerateHeaderUnitAction::CreateOutputFile(CompilerInstance &CI,
  236. StringRef InFile) {
  237. return CI.createDefaultOutputFile(/*Binary=*/true, InFile, "pcm");
  238. }
  239. SyntaxOnlyAction::~SyntaxOnlyAction() {
  240. }
  241. std::unique_ptr<ASTConsumer>
  242. SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  243. return std::make_unique<ASTConsumer>();
  244. }
  245. std::unique_ptr<ASTConsumer>
  246. DumpModuleInfoAction::CreateASTConsumer(CompilerInstance &CI,
  247. StringRef InFile) {
  248. return std::make_unique<ASTConsumer>();
  249. }
  250. std::unique_ptr<ASTConsumer>
  251. VerifyPCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  252. return std::make_unique<ASTConsumer>();
  253. }
  254. void VerifyPCHAction::ExecuteAction() {
  255. CompilerInstance &CI = getCompilerInstance();
  256. bool Preamble = CI.getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
  257. const std::string &Sysroot = CI.getHeaderSearchOpts().Sysroot;
  258. std::unique_ptr<ASTReader> Reader(new ASTReader(
  259. CI.getPreprocessor(), CI.getModuleCache(), &CI.getASTContext(),
  260. CI.getPCHContainerReader(), CI.getFrontendOpts().ModuleFileExtensions,
  261. Sysroot.empty() ? "" : Sysroot.c_str(),
  262. DisableValidationForModuleKind::None,
  263. /*AllowASTWithCompilerErrors*/ false,
  264. /*AllowConfigurationMismatch*/ true,
  265. /*ValidateSystemInputs*/ true));
  266. Reader->ReadAST(getCurrentFile(),
  267. Preamble ? serialization::MK_Preamble
  268. : serialization::MK_PCH,
  269. SourceLocation(),
  270. ASTReader::ARR_ConfigurationMismatch);
  271. }
  272. namespace {
  273. struct TemplightEntry {
  274. std::string Name;
  275. std::string Kind;
  276. std::string Event;
  277. std::string DefinitionLocation;
  278. std::string PointOfInstantiation;
  279. };
  280. } // namespace
  281. namespace llvm {
  282. namespace yaml {
  283. template <> struct MappingTraits<TemplightEntry> {
  284. static void mapping(IO &io, TemplightEntry &fields) {
  285. io.mapRequired("name", fields.Name);
  286. io.mapRequired("kind", fields.Kind);
  287. io.mapRequired("event", fields.Event);
  288. io.mapRequired("orig", fields.DefinitionLocation);
  289. io.mapRequired("poi", fields.PointOfInstantiation);
  290. }
  291. };
  292. } // namespace yaml
  293. } // namespace llvm
  294. namespace {
  295. class DefaultTemplateInstCallback : public TemplateInstantiationCallback {
  296. using CodeSynthesisContext = Sema::CodeSynthesisContext;
  297. public:
  298. void initialize(const Sema &) override {}
  299. void finalize(const Sema &) override {}
  300. void atTemplateBegin(const Sema &TheSema,
  301. const CodeSynthesisContext &Inst) override {
  302. displayTemplightEntry<true>(llvm::outs(), TheSema, Inst);
  303. }
  304. void atTemplateEnd(const Sema &TheSema,
  305. const CodeSynthesisContext &Inst) override {
  306. displayTemplightEntry<false>(llvm::outs(), TheSema, Inst);
  307. }
  308. private:
  309. static std::string toString(CodeSynthesisContext::SynthesisKind Kind) {
  310. switch (Kind) {
  311. case CodeSynthesisContext::TemplateInstantiation:
  312. return "TemplateInstantiation";
  313. case CodeSynthesisContext::DefaultTemplateArgumentInstantiation:
  314. return "DefaultTemplateArgumentInstantiation";
  315. case CodeSynthesisContext::DefaultFunctionArgumentInstantiation:
  316. return "DefaultFunctionArgumentInstantiation";
  317. case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution:
  318. return "ExplicitTemplateArgumentSubstitution";
  319. case CodeSynthesisContext::DeducedTemplateArgumentSubstitution:
  320. return "DeducedTemplateArgumentSubstitution";
  321. case CodeSynthesisContext::PriorTemplateArgumentSubstitution:
  322. return "PriorTemplateArgumentSubstitution";
  323. case CodeSynthesisContext::DefaultTemplateArgumentChecking:
  324. return "DefaultTemplateArgumentChecking";
  325. case CodeSynthesisContext::ExceptionSpecEvaluation:
  326. return "ExceptionSpecEvaluation";
  327. case CodeSynthesisContext::ExceptionSpecInstantiation:
  328. return "ExceptionSpecInstantiation";
  329. case CodeSynthesisContext::DeclaringSpecialMember:
  330. return "DeclaringSpecialMember";
  331. case CodeSynthesisContext::DeclaringImplicitEqualityComparison:
  332. return "DeclaringImplicitEqualityComparison";
  333. case CodeSynthesisContext::DefiningSynthesizedFunction:
  334. return "DefiningSynthesizedFunction";
  335. case CodeSynthesisContext::RewritingOperatorAsSpaceship:
  336. return "RewritingOperatorAsSpaceship";
  337. case CodeSynthesisContext::Memoization:
  338. return "Memoization";
  339. case CodeSynthesisContext::ConstraintsCheck:
  340. return "ConstraintsCheck";
  341. case CodeSynthesisContext::ConstraintSubstitution:
  342. return "ConstraintSubstitution";
  343. case CodeSynthesisContext::ConstraintNormalization:
  344. return "ConstraintNormalization";
  345. case CodeSynthesisContext::RequirementParameterInstantiation:
  346. return "RequirementParameterInstantiation";
  347. case CodeSynthesisContext::ParameterMappingSubstitution:
  348. return "ParameterMappingSubstitution";
  349. case CodeSynthesisContext::RequirementInstantiation:
  350. return "RequirementInstantiation";
  351. case CodeSynthesisContext::NestedRequirementConstraintsCheck:
  352. return "NestedRequirementConstraintsCheck";
  353. case CodeSynthesisContext::InitializingStructuredBinding:
  354. return "InitializingStructuredBinding";
  355. case CodeSynthesisContext::MarkingClassDllexported:
  356. return "MarkingClassDllexported";
  357. case CodeSynthesisContext::BuildingBuiltinDumpStructCall:
  358. return "BuildingBuiltinDumpStructCall";
  359. }
  360. return "";
  361. }
  362. template <bool BeginInstantiation>
  363. static void displayTemplightEntry(llvm::raw_ostream &Out, const Sema &TheSema,
  364. const CodeSynthesisContext &Inst) {
  365. std::string YAML;
  366. {
  367. llvm::raw_string_ostream OS(YAML);
  368. llvm::yaml::Output YO(OS);
  369. TemplightEntry Entry =
  370. getTemplightEntry<BeginInstantiation>(TheSema, Inst);
  371. llvm::yaml::EmptyContext Context;
  372. llvm::yaml::yamlize(YO, Entry, true, Context);
  373. }
  374. Out << "---" << YAML << "\n";
  375. }
  376. static void printEntryName(const Sema &TheSema, const Decl *Entity,
  377. llvm::raw_string_ostream &OS) {
  378. auto *NamedTemplate = cast<NamedDecl>(Entity);
  379. PrintingPolicy Policy = TheSema.Context.getPrintingPolicy();
  380. // FIXME: Also ask for FullyQualifiedNames?
  381. Policy.SuppressDefaultTemplateArgs = false;
  382. NamedTemplate->getNameForDiagnostic(OS, Policy, true);
  383. if (!OS.str().empty())
  384. return;
  385. Decl *Ctx = Decl::castFromDeclContext(NamedTemplate->getDeclContext());
  386. NamedDecl *NamedCtx = dyn_cast_or_null<NamedDecl>(Ctx);
  387. if (const auto *Decl = dyn_cast<TagDecl>(NamedTemplate)) {
  388. if (const auto *R = dyn_cast<RecordDecl>(Decl)) {
  389. if (R->isLambda()) {
  390. OS << "lambda at ";
  391. Decl->getLocation().print(OS, TheSema.getSourceManager());
  392. return;
  393. }
  394. }
  395. OS << "unnamed " << Decl->getKindName();
  396. return;
  397. }
  398. if (const auto *Decl = dyn_cast<ParmVarDecl>(NamedTemplate)) {
  399. OS << "unnamed function parameter " << Decl->getFunctionScopeIndex()
  400. << " ";
  401. if (Decl->getFunctionScopeDepth() > 0)
  402. OS << "(at depth " << Decl->getFunctionScopeDepth() << ") ";
  403. OS << "of ";
  404. NamedCtx->getNameForDiagnostic(OS, TheSema.getLangOpts(), true);
  405. return;
  406. }
  407. if (const auto *Decl = dyn_cast<TemplateTypeParmDecl>(NamedTemplate)) {
  408. if (const Type *Ty = Decl->getTypeForDecl()) {
  409. if (const auto *TTPT = dyn_cast_or_null<TemplateTypeParmType>(Ty)) {
  410. OS << "unnamed template type parameter " << TTPT->getIndex() << " ";
  411. if (TTPT->getDepth() > 0)
  412. OS << "(at depth " << TTPT->getDepth() << ") ";
  413. OS << "of ";
  414. NamedCtx->getNameForDiagnostic(OS, TheSema.getLangOpts(), true);
  415. return;
  416. }
  417. }
  418. }
  419. if (const auto *Decl = dyn_cast<NonTypeTemplateParmDecl>(NamedTemplate)) {
  420. OS << "unnamed template non-type parameter " << Decl->getIndex() << " ";
  421. if (Decl->getDepth() > 0)
  422. OS << "(at depth " << Decl->getDepth() << ") ";
  423. OS << "of ";
  424. NamedCtx->getNameForDiagnostic(OS, TheSema.getLangOpts(), true);
  425. return;
  426. }
  427. if (const auto *Decl = dyn_cast<TemplateTemplateParmDecl>(NamedTemplate)) {
  428. OS << "unnamed template template parameter " << Decl->getIndex() << " ";
  429. if (Decl->getDepth() > 0)
  430. OS << "(at depth " << Decl->getDepth() << ") ";
  431. OS << "of ";
  432. NamedCtx->getNameForDiagnostic(OS, TheSema.getLangOpts(), true);
  433. return;
  434. }
  435. llvm_unreachable("Failed to retrieve a name for this entry!");
  436. OS << "unnamed identifier";
  437. }
  438. template <bool BeginInstantiation>
  439. static TemplightEntry getTemplightEntry(const Sema &TheSema,
  440. const CodeSynthesisContext &Inst) {
  441. TemplightEntry Entry;
  442. Entry.Kind = toString(Inst.Kind);
  443. Entry.Event = BeginInstantiation ? "Begin" : "End";
  444. llvm::raw_string_ostream OS(Entry.Name);
  445. printEntryName(TheSema, Inst.Entity, OS);
  446. const PresumedLoc DefLoc =
  447. TheSema.getSourceManager().getPresumedLoc(Inst.Entity->getLocation());
  448. if (!DefLoc.isInvalid())
  449. Entry.DefinitionLocation = std::string(DefLoc.getFilename()) + ":" +
  450. std::to_string(DefLoc.getLine()) + ":" +
  451. std::to_string(DefLoc.getColumn());
  452. const PresumedLoc PoiLoc =
  453. TheSema.getSourceManager().getPresumedLoc(Inst.PointOfInstantiation);
  454. if (!PoiLoc.isInvalid()) {
  455. Entry.PointOfInstantiation = std::string(PoiLoc.getFilename()) + ":" +
  456. std::to_string(PoiLoc.getLine()) + ":" +
  457. std::to_string(PoiLoc.getColumn());
  458. }
  459. return Entry;
  460. }
  461. };
  462. } // namespace
  463. std::unique_ptr<ASTConsumer>
  464. TemplightDumpAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
  465. return std::make_unique<ASTConsumer>();
  466. }
  467. void TemplightDumpAction::ExecuteAction() {
  468. CompilerInstance &CI = getCompilerInstance();
  469. // This part is normally done by ASTFrontEndAction, but needs to happen
  470. // before Templight observers can be created
  471. // FIXME: Move the truncation aspect of this into Sema, we delayed this till
  472. // here so the source manager would be initialized.
  473. EnsureSemaIsCreated(CI, *this);
  474. CI.getSema().TemplateInstCallbacks.push_back(
  475. std::make_unique<DefaultTemplateInstCallback>());
  476. ASTFrontendAction::ExecuteAction();
  477. }
  478. namespace {
  479. /// AST reader listener that dumps module information for a module
  480. /// file.
  481. class DumpModuleInfoListener : public ASTReaderListener {
  482. llvm::raw_ostream &Out;
  483. public:
  484. DumpModuleInfoListener(llvm::raw_ostream &Out) : Out(Out) { }
  485. #define DUMP_BOOLEAN(Value, Text) \
  486. Out.indent(4) << Text << ": " << (Value? "Yes" : "No") << "\n"
  487. bool ReadFullVersionInformation(StringRef FullVersion) override {
  488. Out.indent(2)
  489. << "Generated by "
  490. << (FullVersion == getClangFullRepositoryVersion()? "this"
  491. : "a different")
  492. << " Clang: " << FullVersion << "\n";
  493. return ASTReaderListener::ReadFullVersionInformation(FullVersion);
  494. }
  495. void ReadModuleName(StringRef ModuleName) override {
  496. Out.indent(2) << "Module name: " << ModuleName << "\n";
  497. }
  498. void ReadModuleMapFile(StringRef ModuleMapPath) override {
  499. Out.indent(2) << "Module map file: " << ModuleMapPath << "\n";
  500. }
  501. bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
  502. bool AllowCompatibleDifferences) override {
  503. Out.indent(2) << "Language options:\n";
  504. #define LANGOPT(Name, Bits, Default, Description) \
  505. DUMP_BOOLEAN(LangOpts.Name, Description);
  506. #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
  507. Out.indent(4) << Description << ": " \
  508. << static_cast<unsigned>(LangOpts.get##Name()) << "\n";
  509. #define VALUE_LANGOPT(Name, Bits, Default, Description) \
  510. Out.indent(4) << Description << ": " << LangOpts.Name << "\n";
  511. #define BENIGN_LANGOPT(Name, Bits, Default, Description)
  512. #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
  513. #include "clang/Basic/LangOptions.def"
  514. if (!LangOpts.ModuleFeatures.empty()) {
  515. Out.indent(4) << "Module features:\n";
  516. for (StringRef Feature : LangOpts.ModuleFeatures)
  517. Out.indent(6) << Feature << "\n";
  518. }
  519. return false;
  520. }
  521. bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
  522. bool AllowCompatibleDifferences) override {
  523. Out.indent(2) << "Target options:\n";
  524. Out.indent(4) << " Triple: " << TargetOpts.Triple << "\n";
  525. Out.indent(4) << " CPU: " << TargetOpts.CPU << "\n";
  526. Out.indent(4) << " TuneCPU: " << TargetOpts.TuneCPU << "\n";
  527. Out.indent(4) << " ABI: " << TargetOpts.ABI << "\n";
  528. if (!TargetOpts.FeaturesAsWritten.empty()) {
  529. Out.indent(4) << "Target features:\n";
  530. for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size();
  531. I != N; ++I) {
  532. Out.indent(6) << TargetOpts.FeaturesAsWritten[I] << "\n";
  533. }
  534. }
  535. return false;
  536. }
  537. bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
  538. bool Complain) override {
  539. Out.indent(2) << "Diagnostic options:\n";
  540. #define DIAGOPT(Name, Bits, Default) DUMP_BOOLEAN(DiagOpts->Name, #Name);
  541. #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
  542. Out.indent(4) << #Name << ": " << DiagOpts->get##Name() << "\n";
  543. #define VALUE_DIAGOPT(Name, Bits, Default) \
  544. Out.indent(4) << #Name << ": " << DiagOpts->Name << "\n";
  545. #include "clang/Basic/DiagnosticOptions.def"
  546. Out.indent(4) << "Diagnostic flags:\n";
  547. for (const std::string &Warning : DiagOpts->Warnings)
  548. Out.indent(6) << "-W" << Warning << "\n";
  549. for (const std::string &Remark : DiagOpts->Remarks)
  550. Out.indent(6) << "-R" << Remark << "\n";
  551. return false;
  552. }
  553. bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
  554. StringRef SpecificModuleCachePath,
  555. bool Complain) override {
  556. Out.indent(2) << "Header search options:\n";
  557. Out.indent(4) << "System root [-isysroot=]: '" << HSOpts.Sysroot << "'\n";
  558. Out.indent(4) << "Resource dir [ -resource-dir=]: '" << HSOpts.ResourceDir << "'\n";
  559. Out.indent(4) << "Module Cache: '" << SpecificModuleCachePath << "'\n";
  560. DUMP_BOOLEAN(HSOpts.UseBuiltinIncludes,
  561. "Use builtin include directories [-nobuiltininc]");
  562. DUMP_BOOLEAN(HSOpts.UseStandardSystemIncludes,
  563. "Use standard system include directories [-nostdinc]");
  564. DUMP_BOOLEAN(HSOpts.UseStandardCXXIncludes,
  565. "Use standard C++ include directories [-nostdinc++]");
  566. DUMP_BOOLEAN(HSOpts.UseLibcxx,
  567. "Use libc++ (rather than libstdc++) [-stdlib=]");
  568. return false;
  569. }
  570. bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
  571. bool Complain,
  572. std::string &SuggestedPredefines) override {
  573. Out.indent(2) << "Preprocessor options:\n";
  574. DUMP_BOOLEAN(PPOpts.UsePredefines,
  575. "Uses compiler/target-specific predefines [-undef]");
  576. DUMP_BOOLEAN(PPOpts.DetailedRecord,
  577. "Uses detailed preprocessing record (for indexing)");
  578. if (!PPOpts.Macros.empty()) {
  579. Out.indent(4) << "Predefined macros:\n";
  580. }
  581. for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator
  582. I = PPOpts.Macros.begin(), IEnd = PPOpts.Macros.end();
  583. I != IEnd; ++I) {
  584. Out.indent(6);
  585. if (I->second)
  586. Out << "-U";
  587. else
  588. Out << "-D";
  589. Out << I->first << "\n";
  590. }
  591. return false;
  592. }
  593. /// Indicates that a particular module file extension has been read.
  594. void readModuleFileExtension(
  595. const ModuleFileExtensionMetadata &Metadata) override {
  596. Out.indent(2) << "Module file extension '"
  597. << Metadata.BlockName << "' " << Metadata.MajorVersion
  598. << "." << Metadata.MinorVersion;
  599. if (!Metadata.UserInfo.empty()) {
  600. Out << ": ";
  601. Out.write_escaped(Metadata.UserInfo);
  602. }
  603. Out << "\n";
  604. }
  605. /// Tells the \c ASTReaderListener that we want to receive the
  606. /// input files of the AST file via \c visitInputFile.
  607. bool needsInputFileVisitation() override { return true; }
  608. /// Tells the \c ASTReaderListener that we want to receive the
  609. /// input files of the AST file via \c visitInputFile.
  610. bool needsSystemInputFileVisitation() override { return true; }
  611. /// Indicates that the AST file contains particular input file.
  612. ///
  613. /// \returns true to continue receiving the next input file, false to stop.
  614. bool visitInputFile(StringRef Filename, bool isSystem,
  615. bool isOverridden, bool isExplicitModule) override {
  616. Out.indent(2) << "Input file: " << Filename;
  617. if (isSystem || isOverridden || isExplicitModule) {
  618. Out << " [";
  619. if (isSystem) {
  620. Out << "System";
  621. if (isOverridden || isExplicitModule)
  622. Out << ", ";
  623. }
  624. if (isOverridden) {
  625. Out << "Overridden";
  626. if (isExplicitModule)
  627. Out << ", ";
  628. }
  629. if (isExplicitModule)
  630. Out << "ExplicitModule";
  631. Out << "]";
  632. }
  633. Out << "\n";
  634. return true;
  635. }
  636. /// Returns true if this \c ASTReaderListener wants to receive the
  637. /// imports of the AST file via \c visitImport, false otherwise.
  638. bool needsImportVisitation() const override { return true; }
  639. /// If needsImportVisitation returns \c true, this is called for each
  640. /// AST file imported by this AST file.
  641. void visitImport(StringRef ModuleName, StringRef Filename) override {
  642. Out.indent(2) << "Imports module '" << ModuleName
  643. << "': " << Filename.str() << "\n";
  644. }
  645. #undef DUMP_BOOLEAN
  646. };
  647. }
  648. bool DumpModuleInfoAction::BeginInvocation(CompilerInstance &CI) {
  649. // The Object file reader also supports raw ast files and there is no point in
  650. // being strict about the module file format in -module-file-info mode.
  651. CI.getHeaderSearchOpts().ModuleFormat = "obj";
  652. return true;
  653. }
  654. static StringRef ModuleKindName(Module::ModuleKind MK) {
  655. switch (MK) {
  656. case Module::ModuleMapModule:
  657. return "Module Map Module";
  658. case Module::ModuleInterfaceUnit:
  659. return "Interface Unit";
  660. case Module::ModulePartitionInterface:
  661. return "Partition Interface";
  662. case Module::ModulePartitionImplementation:
  663. return "Partition Implementation";
  664. case Module::ModuleHeaderUnit:
  665. return "Header Unit";
  666. case Module::GlobalModuleFragment:
  667. return "Global Module Fragment";
  668. case Module::PrivateModuleFragment:
  669. return "Private Module Fragment";
  670. }
  671. llvm_unreachable("unknown module kind!");
  672. }
  673. void DumpModuleInfoAction::ExecuteAction() {
  674. assert(isCurrentFileAST() && "dumping non-AST?");
  675. // Set up the output file.
  676. std::unique_ptr<llvm::raw_fd_ostream> OutFile;
  677. CompilerInstance &CI = getCompilerInstance();
  678. StringRef OutputFileName = CI.getFrontendOpts().OutputFile;
  679. if (!OutputFileName.empty() && OutputFileName != "-") {
  680. std::error_code EC;
  681. OutFile.reset(new llvm::raw_fd_ostream(OutputFileName.str(), EC,
  682. llvm::sys::fs::OF_TextWithCRLF));
  683. OutputStream = OutFile.get();
  684. }
  685. llvm::raw_ostream &Out = OutputStream ? *OutputStream : llvm::outs();
  686. Out << "Information for module file '" << getCurrentFile() << "':\n";
  687. auto &FileMgr = CI.getFileManager();
  688. auto Buffer = FileMgr.getBufferForFile(getCurrentFile());
  689. StringRef Magic = (*Buffer)->getMemBufferRef().getBuffer();
  690. bool IsRaw = (Magic.size() >= 4 && Magic[0] == 'C' && Magic[1] == 'P' &&
  691. Magic[2] == 'C' && Magic[3] == 'H');
  692. Out << " Module format: " << (IsRaw ? "raw" : "obj") << "\n";
  693. Preprocessor &PP = CI.getPreprocessor();
  694. DumpModuleInfoListener Listener(Out);
  695. HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
  696. // The FrontendAction::BeginSourceFile () method loads the AST so that much
  697. // of the information is already available and modules should have been
  698. // loaded.
  699. const LangOptions &LO = getCurrentASTUnit().getLangOpts();
  700. if (LO.CPlusPlusModules && !LO.CurrentModule.empty()) {
  701. ASTReader *R = getCurrentASTUnit().getASTReader().get();
  702. unsigned SubModuleCount = R->getTotalNumSubmodules();
  703. serialization::ModuleFile &MF = R->getModuleManager().getPrimaryModule();
  704. Out << " ====== C++20 Module structure ======\n";
  705. if (MF.ModuleName != LO.CurrentModule)
  706. Out << " Mismatched module names : " << MF.ModuleName << " and "
  707. << LO.CurrentModule << "\n";
  708. struct SubModInfo {
  709. unsigned Idx;
  710. Module *Mod;
  711. Module::ModuleKind Kind;
  712. std::string &Name;
  713. bool Seen;
  714. };
  715. std::map<std::string, SubModInfo> SubModMap;
  716. auto PrintSubMapEntry = [&](std::string Name, Module::ModuleKind Kind) {
  717. Out << " " << ModuleKindName(Kind) << " '" << Name << "'";
  718. auto I = SubModMap.find(Name);
  719. if (I == SubModMap.end())
  720. Out << " was not found in the sub modules!\n";
  721. else {
  722. I->second.Seen = true;
  723. Out << " is at index #" << I->second.Idx << "\n";
  724. }
  725. };
  726. Module *Primary = nullptr;
  727. for (unsigned Idx = 0; Idx <= SubModuleCount; ++Idx) {
  728. Module *M = R->getModule(Idx);
  729. if (!M)
  730. continue;
  731. if (M->Name == LO.CurrentModule) {
  732. Primary = M;
  733. Out << " " << ModuleKindName(M->Kind) << " '" << LO.CurrentModule
  734. << "' is the Primary Module at index #" << Idx << "\n";
  735. SubModMap.insert({M->Name, {Idx, M, M->Kind, M->Name, true}});
  736. } else
  737. SubModMap.insert({M->Name, {Idx, M, M->Kind, M->Name, false}});
  738. }
  739. if (Primary) {
  740. if (!Primary->submodules().empty())
  741. Out << " Sub Modules:\n";
  742. for (auto *MI : Primary->submodules()) {
  743. PrintSubMapEntry(MI->Name, MI->Kind);
  744. }
  745. if (!Primary->Imports.empty())
  746. Out << " Imports:\n";
  747. for (auto *IMP : Primary->Imports) {
  748. PrintSubMapEntry(IMP->Name, IMP->Kind);
  749. }
  750. if (!Primary->Exports.empty())
  751. Out << " Exports:\n";
  752. for (unsigned MN = 0, N = Primary->Exports.size(); MN != N; ++MN) {
  753. if (Module *M = Primary->Exports[MN].getPointer()) {
  754. PrintSubMapEntry(M->Name, M->Kind);
  755. }
  756. }
  757. }
  758. // Emit the macro definitions in the module file so that we can know how
  759. // much definitions in the module file quickly.
  760. // TODO: Emit the macro definition bodies completely.
  761. if (auto FilteredMacros = llvm::make_filter_range(
  762. R->getPreprocessor().macros(),
  763. [](const auto &Macro) { return Macro.first->isFromAST(); });
  764. !FilteredMacros.empty()) {
  765. Out << " Macro Definitions:\n";
  766. for (/*<IdentifierInfo *, MacroState> pair*/ const auto &Macro :
  767. FilteredMacros)
  768. Out << " " << Macro.first->getName() << "\n";
  769. }
  770. // Now let's print out any modules we did not see as part of the Primary.
  771. for (auto SM : SubModMap) {
  772. if (!SM.second.Seen && SM.second.Mod) {
  773. Out << " " << ModuleKindName(SM.second.Kind) << " '" << SM.first
  774. << "' at index #" << SM.second.Idx
  775. << " has no direct reference in the Primary\n";
  776. }
  777. }
  778. Out << " ====== ======\n";
  779. }
  780. // The reminder of the output is produced from the listener as the AST
  781. // FileCcontrolBlock is (re-)parsed.
  782. ASTReader::readASTFileControlBlock(
  783. getCurrentFile(), FileMgr, CI.getModuleCache(),
  784. CI.getPCHContainerReader(),
  785. /*FindModuleFileExtensions=*/true, Listener,
  786. HSOpts.ModulesValidateDiagnosticOptions);
  787. }
  788. //===----------------------------------------------------------------------===//
  789. // Preprocessor Actions
  790. //===----------------------------------------------------------------------===//
  791. void DumpRawTokensAction::ExecuteAction() {
  792. Preprocessor &PP = getCompilerInstance().getPreprocessor();
  793. SourceManager &SM = PP.getSourceManager();
  794. // Start lexing the specified input file.
  795. llvm::MemoryBufferRef FromFile = SM.getBufferOrFake(SM.getMainFileID());
  796. Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts());
  797. RawLex.SetKeepWhitespaceMode(true);
  798. Token RawTok;
  799. RawLex.LexFromRawLexer(RawTok);
  800. while (RawTok.isNot(tok::eof)) {
  801. PP.DumpToken(RawTok, true);
  802. llvm::errs() << "\n";
  803. RawLex.LexFromRawLexer(RawTok);
  804. }
  805. }
  806. void DumpTokensAction::ExecuteAction() {
  807. Preprocessor &PP = getCompilerInstance().getPreprocessor();
  808. // Start preprocessing the specified input file.
  809. Token Tok;
  810. PP.EnterMainSourceFile();
  811. do {
  812. PP.Lex(Tok);
  813. PP.DumpToken(Tok, true);
  814. llvm::errs() << "\n";
  815. } while (Tok.isNot(tok::eof));
  816. }
  817. void PreprocessOnlyAction::ExecuteAction() {
  818. Preprocessor &PP = getCompilerInstance().getPreprocessor();
  819. // Ignore unknown pragmas.
  820. PP.IgnorePragmas();
  821. Token Tok;
  822. // Start parsing the specified input file.
  823. PP.EnterMainSourceFile();
  824. do {
  825. PP.Lex(Tok);
  826. } while (Tok.isNot(tok::eof));
  827. }
  828. void PrintPreprocessedAction::ExecuteAction() {
  829. CompilerInstance &CI = getCompilerInstance();
  830. // Output file may need to be set to 'Binary', to avoid converting Unix style
  831. // line feeds (<LF>) to Microsoft style line feeds (<CR><LF>) on Windows.
  832. //
  833. // Look to see what type of line endings the file uses. If there's a
  834. // CRLF, then we won't open the file up in binary mode. If there is
  835. // just an LF or CR, then we will open the file up in binary mode.
  836. // In this fashion, the output format should match the input format, unless
  837. // the input format has inconsistent line endings.
  838. //
  839. // This should be a relatively fast operation since most files won't have
  840. // all of their source code on a single line. However, that is still a
  841. // concern, so if we scan for too long, we'll just assume the file should
  842. // be opened in binary mode.
  843. bool BinaryMode = false;
  844. if (llvm::Triple(LLVM_HOST_TRIPLE).isOSWindows()) {
  845. BinaryMode = true;
  846. const SourceManager &SM = CI.getSourceManager();
  847. if (std::optional<llvm::MemoryBufferRef> Buffer =
  848. SM.getBufferOrNone(SM.getMainFileID())) {
  849. const char *cur = Buffer->getBufferStart();
  850. const char *end = Buffer->getBufferEnd();
  851. const char *next = (cur != end) ? cur + 1 : end;
  852. // Limit ourselves to only scanning 256 characters into the source
  853. // file. This is mostly a check in case the file has no
  854. // newlines whatsoever.
  855. if (end - cur > 256)
  856. end = cur + 256;
  857. while (next < end) {
  858. if (*cur == 0x0D) { // CR
  859. if (*next == 0x0A) // CRLF
  860. BinaryMode = false;
  861. break;
  862. } else if (*cur == 0x0A) // LF
  863. break;
  864. ++cur;
  865. ++next;
  866. }
  867. }
  868. }
  869. std::unique_ptr<raw_ostream> OS =
  870. CI.createDefaultOutputFile(BinaryMode, getCurrentFileOrBufferName());
  871. if (!OS) return;
  872. // If we're preprocessing a module map, start by dumping the contents of the
  873. // module itself before switching to the input buffer.
  874. auto &Input = getCurrentInput();
  875. if (Input.getKind().getFormat() == InputKind::ModuleMap) {
  876. if (Input.isFile()) {
  877. (*OS) << "# 1 \"";
  878. OS->write_escaped(Input.getFile());
  879. (*OS) << "\"\n";
  880. }
  881. getCurrentModule()->print(*OS);
  882. (*OS) << "#pragma clang module contents\n";
  883. }
  884. DoPrintPreprocessedInput(CI.getPreprocessor(), OS.get(),
  885. CI.getPreprocessorOutputOpts());
  886. }
  887. void PrintPreambleAction::ExecuteAction() {
  888. switch (getCurrentFileKind().getLanguage()) {
  889. case Language::C:
  890. case Language::CXX:
  891. case Language::ObjC:
  892. case Language::ObjCXX:
  893. case Language::OpenCL:
  894. case Language::OpenCLCXX:
  895. case Language::CUDA:
  896. case Language::HIP:
  897. case Language::HLSL:
  898. break;
  899. case Language::Unknown:
  900. case Language::Asm:
  901. case Language::LLVM_IR:
  902. case Language::RenderScript:
  903. // We can't do anything with these.
  904. return;
  905. }
  906. // We don't expect to find any #include directives in a preprocessed input.
  907. if (getCurrentFileKind().isPreprocessed())
  908. return;
  909. CompilerInstance &CI = getCompilerInstance();
  910. auto Buffer = CI.getFileManager().getBufferForFile(getCurrentFile());
  911. if (Buffer) {
  912. unsigned Preamble =
  913. Lexer::ComputePreamble((*Buffer)->getBuffer(), CI.getLangOpts()).Size;
  914. llvm::outs().write((*Buffer)->getBufferStart(), Preamble);
  915. }
  916. }
  917. void DumpCompilerOptionsAction::ExecuteAction() {
  918. CompilerInstance &CI = getCompilerInstance();
  919. std::unique_ptr<raw_ostream> OSP =
  920. CI.createDefaultOutputFile(false, getCurrentFile());
  921. if (!OSP)
  922. return;
  923. raw_ostream &OS = *OSP;
  924. const Preprocessor &PP = CI.getPreprocessor();
  925. const LangOptions &LangOpts = PP.getLangOpts();
  926. // FIXME: Rather than manually format the JSON (which is awkward due to
  927. // needing to remove trailing commas), this should make use of a JSON library.
  928. // FIXME: Instead of printing enums as an integral value and specifying the
  929. // type as a separate field, use introspection to print the enumerator.
  930. OS << "{\n";
  931. OS << "\n\"features\" : [\n";
  932. {
  933. llvm::SmallString<128> Str;
  934. #define FEATURE(Name, Predicate) \
  935. ("\t{\"" #Name "\" : " + llvm::Twine(Predicate ? "true" : "false") + "},\n") \
  936. .toVector(Str);
  937. #include "clang/Basic/Features.def"
  938. #undef FEATURE
  939. // Remove the newline and comma from the last entry to ensure this remains
  940. // valid JSON.
  941. OS << Str.substr(0, Str.size() - 2);
  942. }
  943. OS << "\n],\n";
  944. OS << "\n\"extensions\" : [\n";
  945. {
  946. llvm::SmallString<128> Str;
  947. #define EXTENSION(Name, Predicate) \
  948. ("\t{\"" #Name "\" : " + llvm::Twine(Predicate ? "true" : "false") + "},\n") \
  949. .toVector(Str);
  950. #include "clang/Basic/Features.def"
  951. #undef EXTENSION
  952. // Remove the newline and comma from the last entry to ensure this remains
  953. // valid JSON.
  954. OS << Str.substr(0, Str.size() - 2);
  955. }
  956. OS << "\n]\n";
  957. OS << "}";
  958. }
  959. void PrintDependencyDirectivesSourceMinimizerAction::ExecuteAction() {
  960. CompilerInstance &CI = getCompilerInstance();
  961. SourceManager &SM = CI.getPreprocessor().getSourceManager();
  962. llvm::MemoryBufferRef FromFile = SM.getBufferOrFake(SM.getMainFileID());
  963. llvm::SmallVector<dependency_directives_scan::Token, 16> Tokens;
  964. llvm::SmallVector<dependency_directives_scan::Directive, 32> Directives;
  965. if (scanSourceForDependencyDirectives(
  966. FromFile.getBuffer(), Tokens, Directives, &CI.getDiagnostics(),
  967. SM.getLocForStartOfFile(SM.getMainFileID()))) {
  968. assert(CI.getDiagnostics().hasErrorOccurred() &&
  969. "no errors reported for failure");
  970. // Preprocess the source when verifying the diagnostics to capture the
  971. // 'expected' comments.
  972. if (CI.getDiagnosticOpts().VerifyDiagnostics) {
  973. // Make sure we don't emit new diagnostics!
  974. CI.getDiagnostics().setSuppressAllDiagnostics(true);
  975. Preprocessor &PP = getCompilerInstance().getPreprocessor();
  976. PP.EnterMainSourceFile();
  977. Token Tok;
  978. do {
  979. PP.Lex(Tok);
  980. } while (Tok.isNot(tok::eof));
  981. }
  982. return;
  983. }
  984. printDependencyDirectivesAsSource(FromFile.getBuffer(), Directives,
  985. llvm::outs());
  986. }
  987. void GetDependenciesByModuleNameAction::ExecuteAction() {
  988. CompilerInstance &CI = getCompilerInstance();
  989. Preprocessor &PP = CI.getPreprocessor();
  990. SourceManager &SM = PP.getSourceManager();
  991. FileID MainFileID = SM.getMainFileID();
  992. SourceLocation FileStart = SM.getLocForStartOfFile(MainFileID);
  993. SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
  994. IdentifierInfo *ModuleID = PP.getIdentifierInfo(ModuleName);
  995. Path.push_back(std::make_pair(ModuleID, FileStart));
  996. auto ModResult = CI.loadModule(FileStart, Path, Module::Hidden, false);
  997. PPCallbacks *CB = PP.getPPCallbacks();
  998. CB->moduleImport(SourceLocation(), Path, ModResult);
  999. }