| 1 |
//===--- FrontendActions.cpp ----------------------------------------------===// |
| 2 |
// |
| 3 |
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 |
// See https://llvm.org/LICENSE.txt for license information. |
| 5 |
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 |
// |
| 7 |
//===----------------------------------------------------------------------===// |
| 8 |
|
| 9 |
#include "clang/Frontend/FrontendActions.h" |
| 10 |
#include "clang/AST/ASTConsumer.h" |
| 11 |
#include "clang/AST/Decl.h" |
| 12 |
#include "clang/Basic/FileManager.h" |
| 13 |
#include "clang/Basic/LangStandard.h" |
| 14 |
#include "clang/Basic/Module.h" |
| 15 |
#include "clang/Basic/TargetInfo.h" |
| 16 |
#include "clang/Frontend/ASTConsumers.h" |
| 17 |
#include "clang/Frontend/CompilerInstance.h" |
| 18 |
#include "clang/Frontend/FrontendDiagnostic.h" |
| 19 |
#include "clang/Frontend/MultiplexConsumer.h" |
| 20 |
#include "clang/Frontend/Utils.h" |
| 21 |
#include "clang/Lex/DependencyDirectivesScanner.h" |
| 22 |
#include "clang/Lex/HeaderSearch.h" |
| 23 |
#include "clang/Lex/Preprocessor.h" |
| 24 |
#include "clang/Lex/PreprocessorOptions.h" |
| 25 |
#include "clang/Sema/TemplateInstCallback.h" |
| 26 |
#include "clang/Serialization/ASTReader.h" |
| 27 |
#include "clang/Serialization/ASTWriter.h" |
| 28 |
#include "clang/Serialization/ModuleFile.h" |
| 29 |
#include "llvm/Support/ErrorHandling.h" |
| 30 |
#include "llvm/Support/FileSystem.h" |
| 31 |
#include "llvm/Support/MemoryBuffer.h" |
| 32 |
#include "llvm/Support/Path.h" |
| 33 |
#include "llvm/Support/YAMLTraits.h" |
| 34 |
#include "llvm/Support/raw_ostream.h" |
| 35 |
#include <memory> |
| 36 |
#include <optional> |
| 37 |
#include <system_error> |
| 38 |
|
| 39 |
using namespace clang; |
| 40 |
|
| 41 |
namespace { |
| 42 |
CodeCompleteConsumer *GetCodeCompletionConsumer(CompilerInstance &CI) { |
| 43 |
return CI.hasCodeCompletionConsumer() ? &CI.getCodeCompletionConsumer() |
| 44 |
: nullptr; |
| 45 |
} |
| 46 |
|
| 47 |
void EnsureSemaIsCreated(CompilerInstance &CI, FrontendAction &Action) { |
| 48 |
if (Action.hasCodeCompletionSupport() && |
| 49 |
!CI.getFrontendOpts().CodeCompletionAt.FileName.empty()) |
| 50 |
CI.createCodeCompletionConsumer(); |
| 51 |
|
| 52 |
if (!CI.hasSema()) |
| 53 |
CI.createSema(Action.getTranslationUnitKind(), |
| 54 |
GetCodeCompletionConsumer(CI)); |
| 55 |
} |
| 56 |
} // namespace |
| 57 |
|
| 58 |
//===----------------------------------------------------------------------===// |
| 59 |
// Custom Actions |
| 60 |
//===----------------------------------------------------------------------===// |
| 61 |
|
| 62 |
std::unique_ptr<ASTConsumer> |
| 63 |
InitOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { |
| 64 |
return std::make_unique<ASTConsumer>(); |
| 65 |
} |
| 66 |
|
| 67 |
void InitOnlyAction::ExecuteAction() { |
| 68 |
} |
| 69 |
|
| 70 |
// Basically PreprocessOnlyAction::ExecuteAction. |
| 71 |
void ReadPCHAndPreprocessAction::ExecuteAction() { |
| 72 |
Preprocessor &PP = getCompilerInstance().getPreprocessor(); |
| 73 |
|
| 74 |
// Ignore unknown pragmas. |
| 75 |
PP.IgnorePragmas(); |
| 76 |
|
| 77 |
Token Tok; |
| 78 |
// Start parsing the specified input file. |
| 79 |
PP.EnterMainSourceFile(); |
| 80 |
do { |
| 81 |
PP.Lex(Tok); |
| 82 |
} while (Tok.isNot(tok::eof)); |
| 83 |
} |
| 84 |
|
| 85 |
std::unique_ptr<ASTConsumer> |
| 86 |
ReadPCHAndPreprocessAction::CreateASTConsumer(CompilerInstance &CI, |
| 87 |
StringRef InFile) { |
| 88 |
return std::make_unique<ASTConsumer>(); |
| 89 |
} |
| 90 |
|
| 91 |
//===----------------------------------------------------------------------===// |
| 92 |
// AST Consumer Actions |
| 93 |
//===----------------------------------------------------------------------===// |
| 94 |
|
| 95 |
std::unique_ptr<ASTConsumer> |
| 96 |
ASTPrintAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { |
| 97 |
if (std::unique_ptr<raw_ostream> OS = |
| 98 |
CI.createDefaultOutputFile(false, InFile)) |
| 99 |
return CreateASTPrinter(std::move(OS), CI.getFrontendOpts().ASTDumpFilter); |
| 100 |
return nullptr; |
| 101 |
} |
| 102 |
|
| 103 |
std::unique_ptr<ASTConsumer> |
| 104 |
ASTDumpAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { |
| 105 |
const FrontendOptions &Opts = CI.getFrontendOpts(); |
| 106 |
return CreateASTDumper(nullptr /*Dump to stdout.*/, Opts.ASTDumpFilter, |
| 107 |
Opts.ASTDumpDecls, Opts.ASTDumpAll, |
| 108 |
Opts.ASTDumpLookups, Opts.ASTDumpDeclTypes, |
| 109 |
Opts.ASTDumpFormat); |
| 110 |
} |
| 111 |
|
| 112 |
std::unique_ptr<ASTConsumer> |
| 113 |
ASTDeclListAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { |
| 114 |
return CreateASTDeclNodeLister(); |
| 115 |
} |
| 116 |
|
| 117 |
std::unique_ptr<ASTConsumer> |
| 118 |
ASTViewAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { |
| 119 |
return CreateASTViewer(); |
| 120 |
} |
| 121 |
|
| 122 |
std::unique_ptr<ASTConsumer> |
| 123 |
GeneratePCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { |
| 124 |
std::string Sysroot; |
| 125 |
if (!ComputeASTConsumerArguments(CI, /*ref*/ Sysroot)) |
| 126 |
return nullptr; |
| 127 |
|
| 128 |
std::string OutputFile; |
| 129 |
std::unique_ptr<raw_pwrite_stream> OS = |
| 130 |
CreateOutputFile(CI, InFile, /*ref*/ OutputFile); |
| 131 |
if (!OS) |
| 132 |
return nullptr; |
| 133 |
|
| 134 |
if (!CI.getFrontendOpts().RelocatablePCH) |
| 135 |
Sysroot.clear(); |
| 136 |
|
| 137 |
const auto &FrontendOpts = CI.getFrontendOpts(); |
| 138 |
auto Buffer = std::make_shared<PCHBuffer>(); |
| 139 |
std::vector<std::unique_ptr<ASTConsumer>> Consumers; |
| 140 |
Consumers.push_back(std::make_unique<PCHGenerator>( |
| 141 |
CI.getPreprocessor(), CI.getModuleCache(), OutputFile, Sysroot, Buffer, |
| 142 |
FrontendOpts.ModuleFileExtensions, |
| 143 |
CI.getPreprocessorOpts().AllowPCHWithCompilerErrors, |
| 144 |
FrontendOpts.IncludeTimestamps, +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 |
|
| 151 |
bool 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 |
|
| 162 |
std::unique_ptr<llvm::raw_pwrite_stream> |
| 163 |
GeneratePCHAction::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 |
|
| 175 |
bool GeneratePCHAction::shouldEraseOutputFiles() { |
| 176 |
if (getCompilerInstance().getPreprocessorOpts().AllowPCHWithCompilerErrors) |
| 177 |
return false; |
| 178 |
return ASTFrontendAction::shouldEraseOutputFiles(); |
| 179 |
} |
| 180 |
|
| 181 |
bool GeneratePCHAction::BeginSourceFileAction(CompilerInstance &CI) { |
| 182 |
CI.getLangOpts().CompilingPCH = true; |
| 183 |
return true; |
| 184 |
} |
| 185 |
|
| 186 |
std::unique_ptr<ASTConsumer> |
| 187 |
GenerateModuleAction::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 |
/*ShouldCacheASTInMemory=*/ |
| 207 |
+CI.getFrontendOpts().BuildingImplicitModule)); |
| 208 |
Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator( |
| 209 |
CI, std::string(InFile), OutputFile, std::move(OS), Buffer)); |
| 210 |
return std::make_unique<MultiplexConsumer>(std::move(Consumers)); |
| 211 |
} |
| 212 |
|
| 213 |
bool GenerateModuleAction::shouldEraseOutputFiles() { |
| 214 |
return !getCompilerInstance().getFrontendOpts().AllowPCMWithCompilerErrors && |
| 215 |
ASTFrontendAction::shouldEraseOutputFiles(); |
| 216 |
} |
| 217 |
|
| 218 |
bool GenerateModuleFromModuleMapAction::BeginSourceFileAction( |
| 219 |
CompilerInstance &CI) { |
| 220 |
if (!CI.getLangOpts().Modules) { |
| 221 |
CI.getDiagnostics().Report(diag::err_module_build_requires_fmodules); |
| 222 |
return false; |
| 223 |
} |
| 224 |
|
| 225 |
return GenerateModuleAction::BeginSourceFileAction(CI); |
| 226 |
} |
| 227 |
|
| 228 |
std::unique_ptr<raw_pwrite_stream> |
| 229 |
GenerateModuleFromModuleMapAction::CreateOutputFile(CompilerInstance &CI, |
| 230 |
StringRef InFile) { |
| 231 |
// If no output file was provided, figure out where this module would go |
| 232 |
// in the module cache. |
| 233 |
if (CI.getFrontendOpts().OutputFile.empty()) { |
| 234 |
StringRef ModuleMapFile = CI.getFrontendOpts().OriginalModuleMap; |
| 235 |
if (ModuleMapFile.empty()) |
| 236 |
ModuleMapFile = InFile; |
| 237 |
|
| 238 |
HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo(); |
| 239 |
CI.getFrontendOpts().OutputFile = |
| 240 |
HS.getCachedModuleFileName(CI.getLangOpts().CurrentModule, |
| 241 |
ModuleMapFile); |
| 242 |
} |
| 243 |
|
| 244 |
// Because this is exposed via libclang we must disable RemoveFileOnSignal. |
| 245 |
return CI.createDefaultOutputFile(/*Binary=*/true, InFile, /*Extension=*/"", |
| 246 |
/*RemoveFileOnSignal=*/false, |
| 247 |
/*CreateMissingDirectories=*/true, |
| 248 |
/*ForceUseTemporary=*/true); |
| 249 |
} |
| 250 |
|
| 251 |
bool GenerateModuleInterfaceAction::BeginSourceFileAction( |
| 252 |
CompilerInstance &CI) { |
| 253 |
if (!CI.getLangOpts().ModulesTS && !CI.getLangOpts().CPlusPlusModules) { |
| 254 |
CI.getDiagnostics().Report(diag::err_module_interface_requires_cpp_modules); |
| 255 |
return false; |
| 256 |
} |
| 257 |
|
| 258 |
CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleInterface); |
| 259 |
|
| 260 |
return GenerateModuleAction::BeginSourceFileAction(CI); |
| 261 |
} |
| 262 |
|
| 263 |
std::unique_ptr<raw_pwrite_stream> |
| 264 |
GenerateModuleInterfaceAction::CreateOutputFile(CompilerInstance &CI, |
| 265 |
StringRef InFile) { |
| 266 |
return CI.createDefaultOutputFile(/*Binary=*/true, InFile, "pcm"); |
| 267 |
} |
| 268 |
|
| 269 |
bool GenerateHeaderUnitAction::BeginSourceFileAction(CompilerInstance &CI) { |
| 270 |
if (!CI.getLangOpts().CPlusPlusModules) { |
| 271 |
CI.getDiagnostics().Report(diag::err_module_interface_requires_cpp_modules); |
| 272 |
return false; |
| 273 |
} |
| 274 |
CI.getLangOpts().setCompilingModule(LangOptions::CMK_HeaderUnit); |
| 275 |
return GenerateModuleAction::BeginSourceFileAction(CI); |
| 276 |
} |
| 277 |
|
| 278 |
std::unique_ptr<raw_pwrite_stream> |
| 279 |
GenerateHeaderUnitAction::CreateOutputFile(CompilerInstance &CI, |
| 280 |
StringRef InFile) { |
| 281 |
return CI.createDefaultOutputFile(/*Binary=*/true, InFile, "pcm"); |
| 282 |
} |
| 283 |
|
| 284 |
SyntaxOnlyAction::~SyntaxOnlyAction() { |
| 285 |
} |
| 286 |
|
| 287 |
std::unique_ptr<ASTConsumer> |
| 288 |
SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { |
| 289 |
return std::make_unique<ASTConsumer>(); |
| 290 |
} |
| 291 |
|
| 292 |
std::unique_ptr<ASTConsumer> |
| 293 |
DumpModuleInfoAction::CreateASTConsumer(CompilerInstance &CI, |
| 294 |
StringRef InFile) { |
| 295 |
return std::make_unique<ASTConsumer>(); |
| 296 |
} |
| 297 |
|
| 298 |
std::unique_ptr<ASTConsumer> |
| 299 |
VerifyPCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { |
| 300 |
return std::make_unique<ASTConsumer>(); |
| 301 |
} |
| 302 |
|
| 303 |
void VerifyPCHAction::ExecuteAction() { |
| 304 |
CompilerInstance &CI = getCompilerInstance(); |
| 305 |
bool Preamble = CI.getPreprocessorOpts().PrecompiledPreambleBytes.first != 0; |
| 306 |
const std::string &Sysroot = CI.getHeaderSearchOpts().Sysroot; |
| 307 |
std::unique_ptr<ASTReader> Reader(new ASTReader( |
| 308 |
CI.getPreprocessor(), CI.getModuleCache(), &CI.getASTContext(), |
| 309 |
CI.getPCHContainerReader(), CI.getFrontendOpts().ModuleFileExtensions, |
| 310 |
Sysroot.empty() ? "" : Sysroot.c_str(), |
| 311 |
DisableValidationForModuleKind::None, |
| 312 |
/*AllowASTWithCompilerErrors*/ false, |
| 313 |
/*AllowConfigurationMismatch*/ true, |
| 314 |
/*ValidateSystemInputs*/ true)); |
| 315 |
|
| 316 |
Reader->ReadAST(getCurrentFile(), |
| 317 |
Preamble ? serialization::MK_Preamble |
| 318 |
: serialization::MK_PCH, |
| 319 |
SourceLocation(), |
| 320 |
ASTReader::ARR_ConfigurationMismatch); |
| 321 |
} |
| 322 |
|
| 323 |
namespace { |
| 324 |
struct TemplightEntry { |
| 325 |
std::string Name; |
| 326 |
std::string Kind; |
| 327 |
std::string Event; |
| 328 |
std::string DefinitionLocation; |
| 329 |
std::string PointOfInstantiation; |
| 330 |
}; |
| 331 |
} // namespace |
| 332 |
|
| 333 |
namespace llvm { |
| 334 |
namespace yaml { |
| 335 |
template <> struct MappingTraits<TemplightEntry> { |
| 336 |
static void mapping(IO &io, TemplightEntry &fields) { |
| 337 |
io.mapRequired("name", fields.Name); |
| 338 |
io.mapRequired("kind", fields.Kind); |
| 339 |
io.mapRequired("event", fields.Event); |
| 340 |
io.mapRequired("orig", fields.DefinitionLocation); |
| 341 |
io.mapRequired("poi", fields.PointOfInstantiation); |
| 342 |
} |
| 343 |
}; |
| 344 |
} // namespace yaml |
| 345 |
} // namespace llvm |
| 346 |
|
| 347 |
namespace { |
| 348 |
class DefaultTemplateInstCallback : public TemplateInstantiationCallback { |
| 349 |
using CodeSynthesisContext = Sema::CodeSynthesisContext; |
| 350 |
|
| 351 |
public: |
| 352 |
void initialize(const Sema &) override {} |
| 353 |
|
| 354 |
void finalize(const Sema &) override {} |
| 355 |
|
| 356 |
void atTemplateBegin(const Sema &TheSema, |
| 357 |
const CodeSynthesisContext &Inst) override { |
| 358 |
displayTemplightEntry<true>(llvm::outs(), TheSema, Inst); |
| 359 |
} |
| 360 |
|
| 361 |
void atTemplateEnd(const Sema &TheSema, |
| 362 |
const CodeSynthesisContext &Inst) override { |
| 363 |
displayTemplightEntry<false>(llvm::outs(), TheSema, Inst); |
| 364 |
} |
| 365 |
|
| 366 |
private: |
| 367 |
static std::string toString(CodeSynthesisContext::SynthesisKind Kind) { |
| 368 |
switch (Kind) { |
| 369 |
case CodeSynthesisContext::TemplateInstantiation: |
| 370 |
return "TemplateInstantiation"; |
| 371 |
case CodeSynthesisContext::DefaultTemplateArgumentInstantiation: |
| 372 |
return "DefaultTemplateArgumentInstantiation"; |
| 373 |
case CodeSynthesisContext::DefaultFunctionArgumentInstantiation: |
| 374 |
return "DefaultFunctionArgumentInstantiation"; |
| 375 |
case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution: |
| 376 |
return "ExplicitTemplateArgumentSubstitution"; |
| 377 |
case CodeSynthesisContext::DeducedTemplateArgumentSubstitution: |
| 378 |
return "DeducedTemplateArgumentSubstitution"; |
| 379 |
case CodeSynthesisContext::PriorTemplateArgumentSubstitution: |
| 380 |
return "PriorTemplateArgumentSubstitution"; |
| 381 |
case CodeSynthesisContext::DefaultTemplateArgumentChecking: |
| 382 |
return "DefaultTemplateArgumentChecking"; |
| 383 |
case CodeSynthesisContext::ExceptionSpecEvaluation: |
| 384 |
return "ExceptionSpecEvaluation"; |
| 385 |
case CodeSynthesisContext::ExceptionSpecInstantiation: |
| 386 |
return "ExceptionSpecInstantiation"; |
| 387 |
case CodeSynthesisContext::DeclaringSpecialMember: |
| 388 |
return "DeclaringSpecialMember"; |
| 389 |
case CodeSynthesisContext::DeclaringImplicitEqualityComparison: |
| 390 |
return "DeclaringImplicitEqualityComparison"; |
| 391 |
case CodeSynthesisContext::DefiningSynthesizedFunction: |
| 392 |
return "DefiningSynthesizedFunction"; |
| 393 |
case CodeSynthesisContext::RewritingOperatorAsSpaceship: |
| 394 |
return "RewritingOperatorAsSpaceship"; |
| 395 |
case CodeSynthesisContext::Memoization: |
| 396 |
return "Memoization"; |
| 397 |
case CodeSynthesisContext::ConstraintsCheck: |
| 398 |
return "ConstraintsCheck"; |
| 399 |
case CodeSynthesisContext::ConstraintSubstitution: |
| 400 |
return "ConstraintSubstitution"; |
| 401 |
case CodeSynthesisContext::ConstraintNormalization: |
| 402 |
return "ConstraintNormalization"; |
| 403 |
case CodeSynthesisContext::RequirementParameterInstantiation: |
| 404 |
return "RequirementParameterInstantiation"; |
| 405 |
case CodeSynthesisContext::ParameterMappingSubstitution: |
| 406 |
return "ParameterMappingSubstitution"; |
| 407 |
case CodeSynthesisContext::RequirementInstantiation: |
| 408 |
return "RequirementInstantiation"; |
| 409 |
case CodeSynthesisContext::NestedRequirementConstraintsCheck: |
| 410 |
return "NestedRequirementConstraintsCheck"; |
| 411 |
case CodeSynthesisContext::InitializingStructuredBinding: |
| 412 |
return "InitializingStructuredBinding"; |
| 413 |
case CodeSynthesisContext::MarkingClassDllexported: |
| 414 |
return "MarkingClassDllexported"; |
| 415 |
case CodeSynthesisContext::BuildingBuiltinDumpStructCall: |
| 416 |
return "BuildingBuiltinDumpStructCall"; |
| 417 |
} |
| 418 |
return ""; |
| 419 |
} |
| 420 |
|
| 421 |
template <bool BeginInstantiation> |
| 422 |
static void displayTemplightEntry(llvm::raw_ostream &Out, const Sema &TheSema, |
| 423 |
const CodeSynthesisContext &Inst) { |
| 424 |
std::string YAML; |
| 425 |
{ |
| 426 |
llvm::raw_string_ostream OS(YAML); |
| 427 |
llvm::yaml::Output YO(OS); |
| 428 |
TemplightEntry Entry = |
| 429 |
getTemplightEntry<BeginInstantiation>(TheSema, Inst); |
| 430 |
llvm::yaml::EmptyContext Context; |
| 431 |
llvm::yaml::yamlize(YO, Entry, true, Context); |
| 432 |
} |
| 433 |
Out << "---" << YAML << "\n"; |
| 434 |
} |
| 435 |
|
| 436 |
static void printEntryName(const Sema &TheSema, const Decl *Entity, |
| 437 |
llvm::raw_string_ostream &OS) { |
| 438 |
auto *NamedTemplate = cast<NamedDecl>(Entity); |
| 439 |
|
| 440 |
PrintingPolicy Policy = TheSema.Context.getPrintingPolicy(); |
| 441 |
// FIXME: Also ask for FullyQualifiedNames? |
| 442 |
Policy.SuppressDefaultTemplateArgs = false; |
| 443 |
NamedTemplate->getNameForDiagnostic(OS, Policy, true); |
| 444 |
|
| 445 |
if (!OS.str().empty()) |
| 446 |
return; |
| 447 |
|
| 448 |
Decl *Ctx = Decl::castFromDeclContext(NamedTemplate->getDeclContext()); |
| 449 |
NamedDecl *NamedCtx = dyn_cast_or_null<NamedDecl>(Ctx); |
| 450 |
|
| 451 |
if (const auto *Decl = dyn_cast<TagDecl>(NamedTemplate)) { |
| 452 |
if (const auto *R = dyn_cast<RecordDecl>(Decl)) { |
| 453 |
if (R->isLambda()) { |
| 454 |
OS << "lambda at "; |
| 455 |
Decl->getLocation().print(OS, TheSema.getSourceManager()); |
| 456 |
return; |
| 457 |
} |
| 458 |
} |
| 459 |
OS << "unnamed " << Decl->getKindName(); |
| 460 |
return; |
| 461 |
} |
| 462 |
|
| 463 |
if (const auto *Decl = dyn_cast<ParmVarDecl>(NamedTemplate)) { |
| 464 |
OS << "unnamed function parameter " << Decl->getFunctionScopeIndex() |
| 465 |
<< " "; |
| 466 |
if (Decl->getFunctionScopeDepth() > 0) |
| 467 |
OS << "(at depth " << Decl->getFunctionScopeDepth() << ") "; |
| 468 |
OS << "of "; |
| 469 |
NamedCtx->getNameForDiagnostic(OS, TheSema.getLangOpts(), true); |
| 470 |
return; |
| 471 |
} |
| 472 |
|
| 473 |
if (const auto *Decl = dyn_cast<TemplateTypeParmDecl>(NamedTemplate)) { |
| 474 |
if (const Type *Ty = Decl->getTypeForDecl()) { |
| 475 |
if (const auto *TTPT = dyn_cast_or_null<TemplateTypeParmType>(Ty)) { |
| 476 |
OS << "unnamed template type parameter " << TTPT->getIndex() << " "; |
| 477 |
if (TTPT->getDepth() > 0) |
| 478 |
OS << "(at depth " << TTPT->getDepth() << ") "; |
| 479 |
OS << "of "; |
| 480 |
NamedCtx->getNameForDiagnostic(OS, TheSema.getLangOpts(), true); |
| 481 |
return; |
| 482 |
} |
| 483 |
} |
| 484 |
} |
| 485 |
|
| 486 |
if (const auto *Decl = dyn_cast<NonTypeTemplateParmDecl>(NamedTemplate)) { |
| 487 |
OS << "unnamed template non-type parameter " << Decl->getIndex() << " "; |
| 488 |
if (Decl->getDepth() > 0) |
| 489 |
OS << "(at depth " << Decl->getDepth() << ") "; |
| 490 |
OS << "of "; |
| 491 |
NamedCtx->getNameForDiagnostic(OS, TheSema.getLangOpts(), true); |
| 492 |
return; |
| 493 |
} |
| 494 |
|
| 495 |
if (const auto *Decl = dyn_cast<TemplateTemplateParmDecl>(NamedTemplate)) { |
| 496 |
OS << "unnamed template template parameter " << Decl->getIndex() << " "; |
| 497 |
if (Decl->getDepth() > 0) |
| 498 |
OS << "(at depth " << Decl->getDepth() << ") "; |
| 499 |
OS << "of "; |
| 500 |
NamedCtx->getNameForDiagnostic(OS, TheSema.getLangOpts(), true); |
| 501 |
return; |
| 502 |
} |
| 503 |
|
| 504 |
llvm_unreachable("Failed to retrieve a name for this entry!"); |
| 505 |
OS << "unnamed identifier"; |
| 506 |
} |
| 507 |
|
| 508 |
template <bool BeginInstantiation> |
| 509 |
static TemplightEntry getTemplightEntry(const Sema &TheSema, |
| 510 |
const CodeSynthesisContext &Inst) { |
| 511 |
TemplightEntry Entry; |
| 512 |
Entry.Kind = toString(Inst.Kind); |
| 513 |
Entry.Event = BeginInstantiation ? "Begin" : "End"; |
| 514 |
llvm::raw_string_ostream OS(Entry.Name); |
| 515 |
printEntryName(TheSema, Inst.Entity, OS); |
| 516 |
const PresumedLoc DefLoc = |
| 517 |
TheSema.getSourceManager().getPresumedLoc(Inst.Entity->getLocation()); |
| 518 |
if (!DefLoc.isInvalid()) |
| 519 |
Entry.DefinitionLocation = std::string(DefLoc.getFilename()) + ":" + |
| 520 |
std::to_string(DefLoc.getLine()) + ":" + |
| 521 |
std::to_string(DefLoc.getColumn()); |
| 522 |
const PresumedLoc PoiLoc = |
| 523 |
TheSema.getSourceManager().getPresumedLoc(Inst.PointOfInstantiation); |
| 524 |
if (!PoiLoc.isInvalid()) { |
| 525 |
Entry.PointOfInstantiation = std::string(PoiLoc.getFilename()) + ":" + |
| 526 |
std::to_string(PoiLoc.getLine()) + ":" + |
| 527 |
std::to_string(PoiLoc.getColumn()); |
| 528 |
} |
| 529 |
return Entry; |
| 530 |
} |
| 531 |
}; |
| 532 |
} // namespace |
| 533 |
|
| 534 |
std::unique_ptr<ASTConsumer> |
| 535 |
TemplightDumpAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { |
| 536 |
return std::make_unique<ASTConsumer>(); |
| 537 |
} |
| 538 |
|
| 539 |
void TemplightDumpAction::ExecuteAction() { |
| 540 |
CompilerInstance &CI = getCompilerInstance(); |
| 541 |
|
| 542 |
// This part is normally done by ASTFrontEndAction, but needs to happen |
| 543 |
// before Templight observers can be created |
| 544 |
// FIXME: Move the truncation aspect of this into Sema, we delayed this till |
| 545 |
// here so the source manager would be initialized. |
| 546 |
EnsureSemaIsCreated(CI, *this); |
| 547 |
|
| 548 |
CI.getSema().TemplateInstCallbacks.push_back( |
| 549 |
std::make_unique<DefaultTemplateInstCallback>()); |
| 550 |
ASTFrontendAction::ExecuteAction(); |
| 551 |
} |
| 552 |
|
| 553 |
namespace { |
| 554 |
/// AST reader listener that dumps module information for a module |
| 555 |
/// file. |
| 556 |
class DumpModuleInfoListener : public ASTReaderListener { |
| 557 |
llvm::raw_ostream &Out; |
| 558 |
|
| 559 |
public: |
| 560 |
DumpModuleInfoListener(llvm::raw_ostream &Out) : Out(Out) { } |
| 561 |
|
| 562 |
#define DUMP_BOOLEAN(Value, Text) \ |
| 563 |
Out.indent(4) << Text << ": " << (Value? "Yes" : "No") << "\n" |
| 564 |
|
| 565 |
bool ReadFullVersionInformation(StringRef FullVersion) override { |
| 566 |
Out.indent(2) |
| 567 |
<< "Generated by " |
| 568 |
<< (FullVersion == getClangFullRepositoryVersion()? "this" |
| 569 |
: "a different") |
| 570 |
<< " Clang: " << FullVersion << "\n"; |
| 571 |
return ASTReaderListener::ReadFullVersionInformation(FullVersion); |
| 572 |
} |
| 573 |
|
| 574 |
void ReadModuleName(StringRef ModuleName) override { |
| 575 |
Out.indent(2) << "Module name: " << ModuleName << "\n"; |
| 576 |
} |
| 577 |
void ReadModuleMapFile(StringRef ModuleMapPath) override { |
| 578 |
Out.indent(2) << "Module map file: " << ModuleMapPath << "\n"; |
| 579 |
} |
| 580 |
|
| 581 |
bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, |
| 582 |
bool AllowCompatibleDifferences) override { |
| 583 |
Out.indent(2) << "Language options:\n"; |
| 584 |
#define LANGOPT(Name, Bits, Default, Description) \ |
| 585 |
DUMP_BOOLEAN(LangOpts.Name, Description); |
| 586 |
#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \ |
| 587 |
Out.indent(4) << Description << ": " \ |
| 588 |
<< static_cast<unsigned>(LangOpts.get##Name()) << "\n"; |
| 589 |
#define VALUE_LANGOPT(Name, Bits, Default, Description) \ |
| 590 |
Out.indent(4) << Description << ": " << LangOpts.Name << "\n"; |
| 591 |
#define BENIGN_LANGOPT(Name, Bits, Default, Description) |
| 592 |
#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description) |
| 593 |
#include "clang/Basic/LangOptions.def" |
| 594 |
|
| 595 |
if (!LangOpts.ModuleFeatures.empty()) { |
| 596 |
Out.indent(4) << "Module features:\n"; |
| 597 |
for (StringRef Feature : LangOpts.ModuleFeatures) |
| 598 |
Out.indent(6) << Feature << "\n"; |
| 599 |
} |
| 600 |
|
| 601 |
return false; |
| 602 |
} |
| 603 |
|
| 604 |
bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, |
| 605 |
bool AllowCompatibleDifferences) override { |
| 606 |
Out.indent(2) << "Target options:\n"; |
| 607 |
Out.indent(4) << " Triple: " << TargetOpts.Triple << "\n"; |
| 608 |
Out.indent(4) << " CPU: " << TargetOpts.CPU << "\n"; |
| 609 |
Out.indent(4) << " TuneCPU: " << TargetOpts.TuneCPU << "\n"; |
| 610 |
Out.indent(4) << " ABI: " << TargetOpts.ABI << "\n"; |
| 611 |
|
| 612 |
if (!TargetOpts.FeaturesAsWritten.empty()) { |
| 613 |
Out.indent(4) << "Target features:\n"; |
| 614 |
for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); |
| 615 |
I != N; ++I) { |
| 616 |
Out.indent(6) << TargetOpts.FeaturesAsWritten[I] << "\n"; |
| 617 |
} |
| 618 |
} |
| 619 |
|
| 620 |
return false; |
| 621 |
} |
| 622 |
|
| 623 |
bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, |
| 624 |
bool Complain) override { |
| 625 |
Out.indent(2) << "Diagnostic options:\n"; |
| 626 |
#define DIAGOPT(Name, Bits, Default) DUMP_BOOLEAN(DiagOpts->Name, #Name); |
| 627 |
#define ENUM_DIAGOPT(Name, Type, Bits, Default) \ |
| 628 |
Out.indent(4) << #Name << ": " << DiagOpts->get##Name() << "\n"; |
| 629 |
#define VALUE_DIAGOPT(Name, Bits, Default) \ |
| 630 |
Out.indent(4) << #Name << ": " << DiagOpts->Name << "\n"; |
| 631 |
#include "clang/Basic/DiagnosticOptions.def" |
| 632 |
|
| 633 |
Out.indent(4) << "Diagnostic flags:\n"; |
| 634 |
for (const std::string &Warning : DiagOpts->Warnings) |
| 635 |
Out.indent(6) << "-W" << Warning << "\n"; |
| 636 |
for (const std::string &Remark : DiagOpts->Remarks) |
| 637 |
Out.indent(6) << "-R" << Remark << "\n"; |
| 638 |
|
| 639 |
return false; |
| 640 |
} |
| 641 |
|
| 642 |
bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, |
| 643 |
StringRef SpecificModuleCachePath, |
| 644 |
bool Complain) override { |
| 645 |
Out.indent(2) << "Header search options:\n"; |
| 646 |
Out.indent(4) << "System root [-isysroot=]: '" << HSOpts.Sysroot << "'\n"; |
| 647 |
Out.indent(4) << "Resource dir [ -resource-dir=]: '" << HSOpts.ResourceDir << "'\n"; |
| 648 |
Out.indent(4) << "Module Cache: '" << SpecificModuleCachePath << "'\n"; |
| 649 |
DUMP_BOOLEAN(HSOpts.UseBuiltinIncludes, |
| 650 |
"Use builtin include directories [-nobuiltininc]"); |
| 651 |
DUMP_BOOLEAN(HSOpts.UseStandardSystemIncludes, |
| 652 |
"Use standard system include directories [-nostdinc]"); |
| 653 |
DUMP_BOOLEAN(HSOpts.UseStandardCXXIncludes, |
| 654 |
"Use standard C++ include directories [-nostdinc++]"); |
| 655 |
DUMP_BOOLEAN(HSOpts.UseLibcxx, |
| 656 |
"Use libc++ (rather than libstdc++) [-stdlib=]"); |
| 657 |
return false; |
| 658 |
} |
| 659 |
|
| 660 |
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, |
| 661 |
bool Complain, |
| 662 |
std::string &SuggestedPredefines) override { |
| 663 |
Out.indent(2) << "Preprocessor options:\n"; |
| 664 |
DUMP_BOOLEAN(PPOpts.UsePredefines, |
| 665 |
"Uses compiler/target-specific predefines [-undef]"); |
| 666 |
DUMP_BOOLEAN(PPOpts.DetailedRecord, |
| 667 |
"Uses detailed preprocessing record (for indexing)"); |
| 668 |
|
| 669 |
if (!PPOpts.Macros.empty()) { |
| 670 |
Out.indent(4) << "Predefined macros:\n"; |
| 671 |
} |
| 672 |
|
| 673 |
for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator |
| 674 |
I = PPOpts.Macros.begin(), IEnd = PPOpts.Macros.end(); |
| 675 |
I != IEnd; ++I) { |
| 676 |
Out.indent(6); |
| 677 |
if (I->second) |
| 678 |
Out << "-U"; |
| 679 |
else |
| 680 |
Out << "-D"; |
| 681 |
Out << I->first << "\n"; |
| 682 |
} |
| 683 |
return false; |
| 684 |
} |
| 685 |
|
| 686 |
/// Indicates that a particular module file extension has been read. |
| 687 |
void readModuleFileExtension( |
| 688 |
const ModuleFileExtensionMetadata &Metadata) override { |
| 689 |
Out.indent(2) << "Module file extension '" |
| 690 |
<< Metadata.BlockName << "' " << Metadata.MajorVersion |
| 691 |
<< "." << Metadata.MinorVersion; |
| 692 |
if (!Metadata.UserInfo.empty()) { |
| 693 |
Out << ": "; |
| 694 |
Out.write_escaped(Metadata.UserInfo); |
| 695 |
} |
| 696 |
|
| 697 |
Out << "\n"; |
| 698 |
} |
| 699 |
|
| 700 |
/// Tells the \c ASTReaderListener that we want to receive the |
| 701 |
/// input files of the AST file via \c visitInputFile. |
| 702 |
bool needsInputFileVisitation() override { return true; } |
| 703 |
|
| 704 |
/// Tells the \c ASTReaderListener that we want to receive the |
| 705 |
/// input files of the AST file via \c visitInputFile. |
| 706 |
bool needsSystemInputFileVisitation() override { return true; } |
| 707 |
|
| 708 |
/// Indicates that the AST file contains particular input file. |
| 709 |
/// |
| 710 |
/// \returns true to continue receiving the next input file, false to stop. |
| 711 |
bool visitInputFile(StringRef Filename, bool isSystem, |
| 712 |
bool isOverridden, bool isExplicitModule) override { |
| 713 |
|
| 714 |
Out.indent(2) << "Input file: " << Filename; |
| 715 |
|
| 716 |
if (isSystem || isOverridden || isExplicitModule) { |
| 717 |
Out << " ["; |
| 718 |
if (isSystem) { |
| 719 |
Out << "System"; |
| 720 |
if (isOverridden || isExplicitModule) |
| 721 |
Out << ", "; |
| 722 |
} |
| 723 |
if (isOverridden) { |
| 724 |
Out << "Overridden"; |
| 725 |
if (isExplicitModule) |
| 726 |
Out << ", "; |
| 727 |
} |
| 728 |
if (isExplicitModule) |
| 729 |
Out << "ExplicitModule"; |
| 730 |
|
| 731 |
Out << "]"; |
| 732 |
} |
| 733 |
|
| 734 |
Out << "\n"; |
| 735 |
|
| 736 |
return true; |
| 737 |
} |
| 738 |
|
| 739 |
/// Returns true if this \c ASTReaderListener wants to receive the |
| 740 |
/// imports of the AST file via \c visitImport, false otherwise. |
| 741 |
bool needsImportVisitation() const override { return true; } |
| 742 |
|
| 743 |
/// If needsImportVisitation returns \c true, this is called for each |
| 744 |
/// AST file imported by this AST file. |
| 745 |
void visitImport(StringRef ModuleName, StringRef Filename) override { |
| 746 |
Out.indent(2) << "Imports module '" << ModuleName |
| 747 |
<< "': " << Filename.str() << "\n"; |
| 748 |
} |
| 749 |
#undef DUMP_BOOLEAN |
| 750 |
}; |
| 751 |
} |
| 752 |
|
| 753 |
bool DumpModuleInfoAction::BeginInvocation(CompilerInstance &CI) { |
| 754 |
// The Object file reader also supports raw ast files and there is no point in |
| 755 |
// being strict about the module file format in -module-file-info mode. |
| 756 |
CI.getHeaderSearchOpts().ModuleFormat = "obj"; |
| 757 |
return true; |
| 758 |
} |
| 759 |
|
| 760 |
static StringRef ModuleKindName(Module::ModuleKind MK) { |
| 761 |
switch (MK) { |
| 762 |
case Module::ModuleMapModule: |
| 763 |
return "Module Map Module"; |
| 764 |
case Module::ModuleInterfaceUnit: |
| 765 |
return "Interface 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::GlobalModuleFragment: |
| 773 |
return "Global Module Fragment"; |
| 774 |
case Module::PrivateModuleFragment: |
| 775 |
return "Private Module Fragment"; |
| 776 |
} |
| 777 |
llvm_unreachable("unknown module kind!"); |
| 778 |
} |
| 779 |
|
| 780 |
void DumpModuleInfoAction::ExecuteAction() { |
| 781 |
assert(isCurrentFileAST() && "dumping non-AST?"); |
| 782 |
// Set up the output file. |
| 783 |
std::unique_ptr<llvm::raw_fd_ostream> OutFile; |
| 784 |
CompilerInstance &CI = getCompilerInstance(); |
| 785 |
StringRef OutputFileName = CI.getFrontendOpts().OutputFile; |
| 786 |
if (!OutputFileName.empty() && OutputFileName != "-") { |
| 787 |
std::error_code EC; |
| 788 |
OutFile.reset(new llvm::raw_fd_ostream(OutputFileName.str(), EC, |
| 789 |
llvm::sys::fs::OF_TextWithCRLF)); |
| 790 |
OutputStream = OutFile.get(); |
| 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 (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 |
|
| 910 |
void 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 |
|
| 928 |
void 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 |
|
| 940 |
void 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 |
|
| 954 |
void 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).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 |
|
| 1022 |
void 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 |
|
| 1056 |
void 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 |
|
| 1104 |
void 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() && |
| 1115 |
"no errors reported for failure"); |
| 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 |
|
| 1135 |
void 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 |
} |