Bug Summary

File:build/source/clang/lib/Frontend/FrontendActions.cpp
Warning:line 478, column 11
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

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