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