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