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