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