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/Basic/FileManager.h" 12 #include "clang/Basic/TargetInfo.h" 13 #include "clang/Basic/LangStandard.h" 14 #include "clang/Frontend/ASTConsumers.h" 15 #include "clang/Frontend/CompilerInstance.h" 16 #include "clang/Frontend/FrontendDiagnostic.h" 17 #include "clang/Frontend/MultiplexConsumer.h" 18 #include "clang/Frontend/Utils.h" 19 #include "clang/Lex/DependencyDirectivesSourceMinimizer.h" 20 #include "clang/Lex/HeaderSearch.h" 21 #include "clang/Lex/Preprocessor.h" 22 #include "clang/Lex/PreprocessorOptions.h" 23 #include "clang/Sema/TemplateInstCallback.h" 24 #include "clang/Serialization/ASTReader.h" 25 #include "clang/Serialization/ASTWriter.h" 26 #include "llvm/Support/FileSystem.h" 27 #include "llvm/Support/MemoryBuffer.h" 28 #include "llvm/Support/Path.h" 29 #include "llvm/Support/YAMLTraits.h" 30 #include "llvm/Support/raw_ostream.h" 31 #include <memory> 32 #include <system_error> 33 34 using namespace clang; 35 36 namespace { 37 CodeCompleteConsumer *GetCodeCompletionConsumer(CompilerInstance &CI) { 38 return CI.hasCodeCompletionConsumer() ? &CI.getCodeCompletionConsumer() 39 : nullptr; 40 } 41 42 void EnsureSemaIsCreated(CompilerInstance &CI, FrontendAction &Action) { 43 if (Action.hasCodeCompletionSupport() && 44 !CI.getFrontendOpts().CodeCompletionAt.FileName.empty()) 45 CI.createCodeCompletionConsumer(); 46 47 if (!CI.hasSema()) 48 CI.createSema(Action.getTranslationUnitKind(), 49 GetCodeCompletionConsumer(CI)); 50 } 51 } // namespace 52 53 //===----------------------------------------------------------------------===// 54 // Custom Actions 55 //===----------------------------------------------------------------------===// 56 57 std::unique_ptr<ASTConsumer> 58 InitOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { 59 return std::make_unique<ASTConsumer>(); 60 } 61 62 void InitOnlyAction::ExecuteAction() { 63 } 64 65 //===----------------------------------------------------------------------===// 66 // AST Consumer Actions 67 //===----------------------------------------------------------------------===// 68 69 std::unique_ptr<ASTConsumer> 70 ASTPrintAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { 71 if (std::unique_ptr<raw_ostream> OS = 72 CI.createDefaultOutputFile(false, InFile)) 73 return CreateASTPrinter(std::move(OS), CI.getFrontendOpts().ASTDumpFilter); 74 return nullptr; 75 } 76 77 std::unique_ptr<ASTConsumer> 78 ASTDumpAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { 79 const FrontendOptions &Opts = CI.getFrontendOpts(); 80 return CreateASTDumper(nullptr /*Dump to stdout.*/, Opts.ASTDumpFilter, 81 Opts.ASTDumpDecls, Opts.ASTDumpAll, 82 Opts.ASTDumpLookups, Opts.ASTDumpDeclTypes, 83 Opts.ASTDumpFormat); 84 } 85 86 std::unique_ptr<ASTConsumer> 87 ASTDeclListAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { 88 return CreateASTDeclNodeLister(); 89 } 90 91 std::unique_ptr<ASTConsumer> 92 ASTViewAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { 93 return CreateASTViewer(); 94 } 95 96 std::unique_ptr<ASTConsumer> 97 GeneratePCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { 98 std::string Sysroot; 99 if (!ComputeASTConsumerArguments(CI, /*ref*/ Sysroot)) 100 return nullptr; 101 102 std::string OutputFile; 103 std::unique_ptr<raw_pwrite_stream> OS = 104 CreateOutputFile(CI, InFile, /*ref*/ OutputFile); 105 if (!OS) 106 return nullptr; 107 108 if (!CI.getFrontendOpts().RelocatablePCH) 109 Sysroot.clear(); 110 111 const auto &FrontendOpts = CI.getFrontendOpts(); 112 auto Buffer = std::make_shared<PCHBuffer>(); 113 std::vector<std::unique_ptr<ASTConsumer>> Consumers; 114 Consumers.push_back(std::make_unique<PCHGenerator>( 115 CI.getPreprocessor(), CI.getModuleCache(), OutputFile, Sysroot, Buffer, 116 FrontendOpts.ModuleFileExtensions, 117 CI.getPreprocessorOpts().AllowPCHWithCompilerErrors, 118 FrontendOpts.IncludeTimestamps, +CI.getLangOpts().CacheGeneratedPCH)); 119 Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator( 120 CI, std::string(InFile), OutputFile, std::move(OS), Buffer)); 121 122 return std::make_unique<MultiplexConsumer>(std::move(Consumers)); 123 } 124 125 bool GeneratePCHAction::ComputeASTConsumerArguments(CompilerInstance &CI, 126 std::string &Sysroot) { 127 Sysroot = CI.getHeaderSearchOpts().Sysroot; 128 if (CI.getFrontendOpts().RelocatablePCH && Sysroot.empty()) { 129 CI.getDiagnostics().Report(diag::err_relocatable_without_isysroot); 130 return false; 131 } 132 133 return true; 134 } 135 136 std::unique_ptr<llvm::raw_pwrite_stream> 137 GeneratePCHAction::CreateOutputFile(CompilerInstance &CI, StringRef InFile, 138 std::string &OutputFile) { 139 // We use createOutputFile here because this is exposed via libclang, and we 140 // must disable the RemoveFileOnSignal behavior. 141 // We use a temporary to avoid race conditions. 142 std::unique_ptr<raw_pwrite_stream> OS = 143 CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true, 144 /*RemoveFileOnSignal=*/false, InFile, 145 /*Extension=*/"", CI.getFrontendOpts().UseTemporary); 146 if (!OS) 147 return nullptr; 148 149 OutputFile = CI.getFrontendOpts().OutputFile; 150 return OS; 151 } 152 153 bool GeneratePCHAction::shouldEraseOutputFiles() { 154 if (getCompilerInstance().getPreprocessorOpts().AllowPCHWithCompilerErrors) 155 return false; 156 return ASTFrontendAction::shouldEraseOutputFiles(); 157 } 158 159 bool GeneratePCHAction::BeginSourceFileAction(CompilerInstance &CI) { 160 CI.getLangOpts().CompilingPCH = true; 161 return true; 162 } 163 164 std::unique_ptr<ASTConsumer> 165 GenerateModuleAction::CreateASTConsumer(CompilerInstance &CI, 166 StringRef InFile) { 167 std::unique_ptr<raw_pwrite_stream> OS = CreateOutputFile(CI, InFile); 168 if (!OS) 169 return nullptr; 170 171 std::string OutputFile = CI.getFrontendOpts().OutputFile; 172 std::string Sysroot; 173 174 auto Buffer = std::make_shared<PCHBuffer>(); 175 std::vector<std::unique_ptr<ASTConsumer>> Consumers; 176 177 Consumers.push_back(std::make_unique<PCHGenerator>( 178 CI.getPreprocessor(), CI.getModuleCache(), OutputFile, Sysroot, Buffer, 179 CI.getFrontendOpts().ModuleFileExtensions, 180 /*AllowASTWithErrors=*/false, 181 /*IncludeTimestamps=*/ 182 +CI.getFrontendOpts().BuildingImplicitModule, 183 /*ShouldCacheASTInMemory=*/ 184 +CI.getFrontendOpts().BuildingImplicitModule)); 185 Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator( 186 CI, std::string(InFile), OutputFile, std::move(OS), Buffer)); 187 return std::make_unique<MultiplexConsumer>(std::move(Consumers)); 188 } 189 190 bool GenerateModuleFromModuleMapAction::BeginSourceFileAction( 191 CompilerInstance &CI) { 192 if (!CI.getLangOpts().Modules) { 193 CI.getDiagnostics().Report(diag::err_module_build_requires_fmodules); 194 return false; 195 } 196 197 return GenerateModuleAction::BeginSourceFileAction(CI); 198 } 199 200 std::unique_ptr<raw_pwrite_stream> 201 GenerateModuleFromModuleMapAction::CreateOutputFile(CompilerInstance &CI, 202 StringRef InFile) { 203 // If no output file was provided, figure out where this module would go 204 // in the module cache. 205 if (CI.getFrontendOpts().OutputFile.empty()) { 206 StringRef ModuleMapFile = CI.getFrontendOpts().OriginalModuleMap; 207 if (ModuleMapFile.empty()) 208 ModuleMapFile = InFile; 209 210 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo(); 211 CI.getFrontendOpts().OutputFile = 212 HS.getCachedModuleFileName(CI.getLangOpts().CurrentModule, 213 ModuleMapFile); 214 } 215 216 // We use createOutputFile here because this is exposed via libclang, and we 217 // must disable the RemoveFileOnSignal behavior. 218 // We use a temporary to avoid race conditions. 219 return CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true, 220 /*RemoveFileOnSignal=*/false, InFile, 221 /*Extension=*/"", /*UseTemporary=*/true, 222 /*CreateMissingDirectories=*/true); 223 } 224 225 bool GenerateModuleInterfaceAction::BeginSourceFileAction( 226 CompilerInstance &CI) { 227 if (!CI.getLangOpts().ModulesTS && !CI.getLangOpts().CPlusPlusModules) { 228 CI.getDiagnostics().Report(diag::err_module_interface_requires_cpp_modules); 229 return false; 230 } 231 232 CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleInterface); 233 234 return GenerateModuleAction::BeginSourceFileAction(CI); 235 } 236 237 std::unique_ptr<raw_pwrite_stream> 238 GenerateModuleInterfaceAction::CreateOutputFile(CompilerInstance &CI, 239 StringRef InFile) { 240 return CI.createDefaultOutputFile(/*Binary=*/true, InFile, "pcm"); 241 } 242 243 bool GenerateHeaderModuleAction::PrepareToExecuteAction( 244 CompilerInstance &CI) { 245 if (!CI.getLangOpts().Modules) { 246 CI.getDiagnostics().Report(diag::err_header_module_requires_modules); 247 return false; 248 } 249 250 auto &Inputs = CI.getFrontendOpts().Inputs; 251 if (Inputs.empty()) 252 return GenerateModuleAction::BeginInvocation(CI); 253 254 auto Kind = Inputs[0].getKind(); 255 256 // Convert the header file inputs into a single module input buffer. 257 SmallString<256> HeaderContents; 258 ModuleHeaders.reserve(Inputs.size()); 259 for (const FrontendInputFile &FIF : Inputs) { 260 // FIXME: We should support re-compiling from an AST file. 261 if (FIF.getKind().getFormat() != InputKind::Source || !FIF.isFile()) { 262 CI.getDiagnostics().Report(diag::err_module_header_file_not_found) 263 << (FIF.isFile() ? FIF.getFile() 264 : FIF.getBuffer().getBufferIdentifier()); 265 return true; 266 } 267 268 HeaderContents += "#include \""; 269 HeaderContents += FIF.getFile(); 270 HeaderContents += "\"\n"; 271 ModuleHeaders.push_back(std::string(FIF.getFile())); 272 } 273 Buffer = llvm::MemoryBuffer::getMemBufferCopy( 274 HeaderContents, Module::getModuleInputBufferName()); 275 276 // Set that buffer up as our "real" input. 277 Inputs.clear(); 278 Inputs.push_back( 279 FrontendInputFile(Buffer->getMemBufferRef(), Kind, /*IsSystem*/ false)); 280 281 return GenerateModuleAction::PrepareToExecuteAction(CI); 282 } 283 284 bool GenerateHeaderModuleAction::BeginSourceFileAction( 285 CompilerInstance &CI) { 286 CI.getLangOpts().setCompilingModule(LangOptions::CMK_HeaderModule); 287 288 // Synthesize a Module object for the given headers. 289 auto &HS = CI.getPreprocessor().getHeaderSearchInfo(); 290 SmallVector<Module::Header, 16> Headers; 291 for (StringRef Name : ModuleHeaders) { 292 const DirectoryLookup *CurDir = nullptr; 293 Optional<FileEntryRef> FE = HS.LookupFile( 294 Name, SourceLocation(), /*Angled*/ false, nullptr, CurDir, None, 295 nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); 296 if (!FE) { 297 CI.getDiagnostics().Report(diag::err_module_header_file_not_found) 298 << Name; 299 continue; 300 } 301 Headers.push_back({std::string(Name), &FE->getFileEntry()}); 302 } 303 HS.getModuleMap().createHeaderModule(CI.getLangOpts().CurrentModule, Headers); 304 305 return GenerateModuleAction::BeginSourceFileAction(CI); 306 } 307 308 std::unique_ptr<raw_pwrite_stream> 309 GenerateHeaderModuleAction::CreateOutputFile(CompilerInstance &CI, 310 StringRef InFile) { 311 return CI.createDefaultOutputFile(/*Binary=*/true, InFile, "pcm"); 312 } 313 314 SyntaxOnlyAction::~SyntaxOnlyAction() { 315 } 316 317 std::unique_ptr<ASTConsumer> 318 SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { 319 return std::make_unique<ASTConsumer>(); 320 } 321 322 std::unique_ptr<ASTConsumer> 323 DumpModuleInfoAction::CreateASTConsumer(CompilerInstance &CI, 324 StringRef InFile) { 325 return std::make_unique<ASTConsumer>(); 326 } 327 328 std::unique_ptr<ASTConsumer> 329 VerifyPCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { 330 return std::make_unique<ASTConsumer>(); 331 } 332 333 void VerifyPCHAction::ExecuteAction() { 334 CompilerInstance &CI = getCompilerInstance(); 335 bool Preamble = CI.getPreprocessorOpts().PrecompiledPreambleBytes.first != 0; 336 const std::string &Sysroot = CI.getHeaderSearchOpts().Sysroot; 337 std::unique_ptr<ASTReader> Reader(new ASTReader( 338 CI.getPreprocessor(), CI.getModuleCache(), &CI.getASTContext(), 339 CI.getPCHContainerReader(), CI.getFrontendOpts().ModuleFileExtensions, 340 Sysroot.empty() ? "" : Sysroot.c_str(), 341 /*DisableValidation*/ false, 342 /*AllowPCHWithCompilerErrors*/ false, 343 /*AllowConfigurationMismatch*/ true, 344 /*ValidateSystemInputs*/ true)); 345 346 Reader->ReadAST(getCurrentFile(), 347 Preamble ? serialization::MK_Preamble 348 : serialization::MK_PCH, 349 SourceLocation(), 350 ASTReader::ARR_ConfigurationMismatch); 351 } 352 353 namespace { 354 struct TemplightEntry { 355 std::string Name; 356 std::string Kind; 357 std::string Event; 358 std::string DefinitionLocation; 359 std::string PointOfInstantiation; 360 }; 361 } // namespace 362 363 namespace llvm { 364 namespace yaml { 365 template <> struct MappingTraits<TemplightEntry> { 366 static void mapping(IO &io, TemplightEntry &fields) { 367 io.mapRequired("name", fields.Name); 368 io.mapRequired("kind", fields.Kind); 369 io.mapRequired("event", fields.Event); 370 io.mapRequired("orig", fields.DefinitionLocation); 371 io.mapRequired("poi", fields.PointOfInstantiation); 372 } 373 }; 374 } // namespace yaml 375 } // namespace llvm 376 377 namespace { 378 class DefaultTemplateInstCallback : public TemplateInstantiationCallback { 379 using CodeSynthesisContext = Sema::CodeSynthesisContext; 380 381 public: 382 void initialize(const Sema &) override {} 383 384 void finalize(const Sema &) override {} 385 386 void atTemplateBegin(const Sema &TheSema, 387 const CodeSynthesisContext &Inst) override { 388 displayTemplightEntry<true>(llvm::outs(), TheSema, Inst); 389 } 390 391 void atTemplateEnd(const Sema &TheSema, 392 const CodeSynthesisContext &Inst) override { 393 displayTemplightEntry<false>(llvm::outs(), TheSema, Inst); 394 } 395 396 private: 397 static std::string toString(CodeSynthesisContext::SynthesisKind Kind) { 398 switch (Kind) { 399 case CodeSynthesisContext::TemplateInstantiation: 400 return "TemplateInstantiation"; 401 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation: 402 return "DefaultTemplateArgumentInstantiation"; 403 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation: 404 return "DefaultFunctionArgumentInstantiation"; 405 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution: 406 return "ExplicitTemplateArgumentSubstitution"; 407 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution: 408 return "DeducedTemplateArgumentSubstitution"; 409 case CodeSynthesisContext::PriorTemplateArgumentSubstitution: 410 return "PriorTemplateArgumentSubstitution"; 411 case CodeSynthesisContext::DefaultTemplateArgumentChecking: 412 return "DefaultTemplateArgumentChecking"; 413 case CodeSynthesisContext::ExceptionSpecEvaluation: 414 return "ExceptionSpecEvaluation"; 415 case CodeSynthesisContext::ExceptionSpecInstantiation: 416 return "ExceptionSpecInstantiation"; 417 case CodeSynthesisContext::DeclaringSpecialMember: 418 return "DeclaringSpecialMember"; 419 case CodeSynthesisContext::DeclaringImplicitEqualityComparison: 420 return "DeclaringImplicitEqualityComparison"; 421 case CodeSynthesisContext::DefiningSynthesizedFunction: 422 return "DefiningSynthesizedFunction"; 423 case CodeSynthesisContext::RewritingOperatorAsSpaceship: 424 return "RewritingOperatorAsSpaceship"; 425 case CodeSynthesisContext::Memoization: 426 return "Memoization"; 427 case CodeSynthesisContext::ConstraintsCheck: 428 return "ConstraintsCheck"; 429 case CodeSynthesisContext::ConstraintSubstitution: 430 return "ConstraintSubstitution"; 431 case CodeSynthesisContext::ConstraintNormalization: 432 return "ConstraintNormalization"; 433 case CodeSynthesisContext::ParameterMappingSubstitution: 434 return "ParameterMappingSubstitution"; 435 case CodeSynthesisContext::RequirementInstantiation: 436 return "RequirementInstantiation"; 437 case CodeSynthesisContext::NestedRequirementConstraintsCheck: 438 return "NestedRequirementConstraintsCheck"; 439 case CodeSynthesisContext::InitializingStructuredBinding: 440 return "InitializingStructuredBinding"; 441 case CodeSynthesisContext::MarkingClassDllexported: 442 return "MarkingClassDllexported"; 443 } 444 return ""; 445 } 446 447 template <bool BeginInstantiation> 448 static void displayTemplightEntry(llvm::raw_ostream &Out, const Sema &TheSema, 449 const CodeSynthesisContext &Inst) { 450 std::string YAML; 451 { 452 llvm::raw_string_ostream OS(YAML); 453 llvm::yaml::Output YO(OS); 454 TemplightEntry Entry = 455 getTemplightEntry<BeginInstantiation>(TheSema, Inst); 456 llvm::yaml::EmptyContext Context; 457 llvm::yaml::yamlize(YO, Entry, true, Context); 458 } 459 Out << "---" << YAML << "\n"; 460 } 461 462 template <bool BeginInstantiation> 463 static TemplightEntry getTemplightEntry(const Sema &TheSema, 464 const CodeSynthesisContext &Inst) { 465 TemplightEntry Entry; 466 Entry.Kind = toString(Inst.Kind); 467 Entry.Event = BeginInstantiation ? "Begin" : "End"; 468 if (auto *NamedTemplate = dyn_cast_or_null<NamedDecl>(Inst.Entity)) { 469 llvm::raw_string_ostream OS(Entry.Name); 470 PrintingPolicy Policy = TheSema.Context.getPrintingPolicy(); 471 // FIXME: Also ask for FullyQualifiedNames? 472 Policy.SuppressDefaultTemplateArgs = false; 473 NamedTemplate->getNameForDiagnostic(OS, Policy, true); 474 const PresumedLoc DefLoc = 475 TheSema.getSourceManager().getPresumedLoc(Inst.Entity->getLocation()); 476 if(!DefLoc.isInvalid()) 477 Entry.DefinitionLocation = std::string(DefLoc.getFilename()) + ":" + 478 std::to_string(DefLoc.getLine()) + ":" + 479 std::to_string(DefLoc.getColumn()); 480 } 481 const PresumedLoc PoiLoc = 482 TheSema.getSourceManager().getPresumedLoc(Inst.PointOfInstantiation); 483 if (!PoiLoc.isInvalid()) { 484 Entry.PointOfInstantiation = std::string(PoiLoc.getFilename()) + ":" + 485 std::to_string(PoiLoc.getLine()) + ":" + 486 std::to_string(PoiLoc.getColumn()); 487 } 488 return Entry; 489 } 490 }; 491 } // namespace 492 493 std::unique_ptr<ASTConsumer> 494 TemplightDumpAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { 495 return std::make_unique<ASTConsumer>(); 496 } 497 498 void TemplightDumpAction::ExecuteAction() { 499 CompilerInstance &CI = getCompilerInstance(); 500 501 // This part is normally done by ASTFrontEndAction, but needs to happen 502 // before Templight observers can be created 503 // FIXME: Move the truncation aspect of this into Sema, we delayed this till 504 // here so the source manager would be initialized. 505 EnsureSemaIsCreated(CI, *this); 506 507 CI.getSema().TemplateInstCallbacks.push_back( 508 std::make_unique<DefaultTemplateInstCallback>()); 509 ASTFrontendAction::ExecuteAction(); 510 } 511 512 namespace { 513 /// AST reader listener that dumps module information for a module 514 /// file. 515 class DumpModuleInfoListener : public ASTReaderListener { 516 llvm::raw_ostream &Out; 517 518 public: 519 DumpModuleInfoListener(llvm::raw_ostream &Out) : Out(Out) { } 520 521 #define DUMP_BOOLEAN(Value, Text) \ 522 Out.indent(4) << Text << ": " << (Value? "Yes" : "No") << "\n" 523 524 bool ReadFullVersionInformation(StringRef FullVersion) override { 525 Out.indent(2) 526 << "Generated by " 527 << (FullVersion == getClangFullRepositoryVersion()? "this" 528 : "a different") 529 << " Clang: " << FullVersion << "\n"; 530 return ASTReaderListener::ReadFullVersionInformation(FullVersion); 531 } 532 533 void ReadModuleName(StringRef ModuleName) override { 534 Out.indent(2) << "Module name: " << ModuleName << "\n"; 535 } 536 void ReadModuleMapFile(StringRef ModuleMapPath) override { 537 Out.indent(2) << "Module map file: " << ModuleMapPath << "\n"; 538 } 539 540 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, 541 bool AllowCompatibleDifferences) override { 542 Out.indent(2) << "Language options:\n"; 543 #define LANGOPT(Name, Bits, Default, Description) \ 544 DUMP_BOOLEAN(LangOpts.Name, Description); 545 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \ 546 Out.indent(4) << Description << ": " \ 547 << static_cast<unsigned>(LangOpts.get##Name()) << "\n"; 548 #define VALUE_LANGOPT(Name, Bits, Default, Description) \ 549 Out.indent(4) << Description << ": " << LangOpts.Name << "\n"; 550 #define BENIGN_LANGOPT(Name, Bits, Default, Description) 551 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description) 552 #include "clang/Basic/LangOptions.def" 553 554 if (!LangOpts.ModuleFeatures.empty()) { 555 Out.indent(4) << "Module features:\n"; 556 for (StringRef Feature : LangOpts.ModuleFeatures) 557 Out.indent(6) << Feature << "\n"; 558 } 559 560 return false; 561 } 562 563 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, 564 bool AllowCompatibleDifferences) override { 565 Out.indent(2) << "Target options:\n"; 566 Out.indent(4) << " Triple: " << TargetOpts.Triple << "\n"; 567 Out.indent(4) << " CPU: " << TargetOpts.CPU << "\n"; 568 Out.indent(4) << " TuneCPU: " << TargetOpts.TuneCPU << "\n"; 569 Out.indent(4) << " ABI: " << TargetOpts.ABI << "\n"; 570 571 if (!TargetOpts.FeaturesAsWritten.empty()) { 572 Out.indent(4) << "Target features:\n"; 573 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); 574 I != N; ++I) { 575 Out.indent(6) << TargetOpts.FeaturesAsWritten[I] << "\n"; 576 } 577 } 578 579 return false; 580 } 581 582 bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, 583 bool Complain) override { 584 Out.indent(2) << "Diagnostic options:\n"; 585 #define DIAGOPT(Name, Bits, Default) DUMP_BOOLEAN(DiagOpts->Name, #Name); 586 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \ 587 Out.indent(4) << #Name << ": " << DiagOpts->get##Name() << "\n"; 588 #define VALUE_DIAGOPT(Name, Bits, Default) \ 589 Out.indent(4) << #Name << ": " << DiagOpts->Name << "\n"; 590 #include "clang/Basic/DiagnosticOptions.def" 591 592 Out.indent(4) << "Diagnostic flags:\n"; 593 for (const std::string &Warning : DiagOpts->Warnings) 594 Out.indent(6) << "-W" << Warning << "\n"; 595 for (const std::string &Remark : DiagOpts->Remarks) 596 Out.indent(6) << "-R" << Remark << "\n"; 597 598 return false; 599 } 600 601 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, 602 StringRef SpecificModuleCachePath, 603 bool Complain) override { 604 Out.indent(2) << "Header search options:\n"; 605 Out.indent(4) << "System root [-isysroot=]: '" << HSOpts.Sysroot << "'\n"; 606 Out.indent(4) << "Resource dir [ -resource-dir=]: '" << HSOpts.ResourceDir << "'\n"; 607 Out.indent(4) << "Module Cache: '" << SpecificModuleCachePath << "'\n"; 608 DUMP_BOOLEAN(HSOpts.UseBuiltinIncludes, 609 "Use builtin include directories [-nobuiltininc]"); 610 DUMP_BOOLEAN(HSOpts.UseStandardSystemIncludes, 611 "Use standard system include directories [-nostdinc]"); 612 DUMP_BOOLEAN(HSOpts.UseStandardCXXIncludes, 613 "Use standard C++ include directories [-nostdinc++]"); 614 DUMP_BOOLEAN(HSOpts.UseLibcxx, 615 "Use libc++ (rather than libstdc++) [-stdlib=]"); 616 return false; 617 } 618 619 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, 620 bool Complain, 621 std::string &SuggestedPredefines) override { 622 Out.indent(2) << "Preprocessor options:\n"; 623 DUMP_BOOLEAN(PPOpts.UsePredefines, 624 "Uses compiler/target-specific predefines [-undef]"); 625 DUMP_BOOLEAN(PPOpts.DetailedRecord, 626 "Uses detailed preprocessing record (for indexing)"); 627 628 if (!PPOpts.Macros.empty()) { 629 Out.indent(4) << "Predefined macros:\n"; 630 } 631 632 for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator 633 I = PPOpts.Macros.begin(), IEnd = PPOpts.Macros.end(); 634 I != IEnd; ++I) { 635 Out.indent(6); 636 if (I->second) 637 Out << "-U"; 638 else 639 Out << "-D"; 640 Out << I->first << "\n"; 641 } 642 return false; 643 } 644 645 /// Indicates that a particular module file extension has been read. 646 void readModuleFileExtension( 647 const ModuleFileExtensionMetadata &Metadata) override { 648 Out.indent(2) << "Module file extension '" 649 << Metadata.BlockName << "' " << Metadata.MajorVersion 650 << "." << Metadata.MinorVersion; 651 if (!Metadata.UserInfo.empty()) { 652 Out << ": "; 653 Out.write_escaped(Metadata.UserInfo); 654 } 655 656 Out << "\n"; 657 } 658 659 /// Tells the \c ASTReaderListener that we want to receive the 660 /// input files of the AST file via \c visitInputFile. 661 bool needsInputFileVisitation() override { return true; } 662 663 /// Tells the \c ASTReaderListener that we want to receive the 664 /// input files of the AST file via \c visitInputFile. 665 bool needsSystemInputFileVisitation() override { return true; } 666 667 /// Indicates that the AST file contains particular input file. 668 /// 669 /// \returns true to continue receiving the next input file, false to stop. 670 bool visitInputFile(StringRef Filename, bool isSystem, 671 bool isOverridden, bool isExplicitModule) override { 672 673 Out.indent(2) << "Input file: " << Filename; 674 675 if (isSystem || isOverridden || isExplicitModule) { 676 Out << " ["; 677 if (isSystem) { 678 Out << "System"; 679 if (isOverridden || isExplicitModule) 680 Out << ", "; 681 } 682 if (isOverridden) { 683 Out << "Overridden"; 684 if (isExplicitModule) 685 Out << ", "; 686 } 687 if (isExplicitModule) 688 Out << "ExplicitModule"; 689 690 Out << "]"; 691 } 692 693 Out << "\n"; 694 695 return true; 696 } 697 698 /// Returns true if this \c ASTReaderListener wants to receive the 699 /// imports of the AST file via \c visitImport, false otherwise. 700 bool needsImportVisitation() const override { return true; } 701 702 /// If needsImportVisitation returns \c true, this is called for each 703 /// AST file imported by this AST file. 704 void visitImport(StringRef ModuleName, StringRef Filename) override { 705 Out.indent(2) << "Imports module '" << ModuleName 706 << "': " << Filename.str() << "\n"; 707 } 708 #undef DUMP_BOOLEAN 709 }; 710 } 711 712 bool DumpModuleInfoAction::BeginInvocation(CompilerInstance &CI) { 713 // The Object file reader also supports raw ast files and there is no point in 714 // being strict about the module file format in -module-file-info mode. 715 CI.getHeaderSearchOpts().ModuleFormat = "obj"; 716 return true; 717 } 718 719 void DumpModuleInfoAction::ExecuteAction() { 720 // Set up the output file. 721 std::unique_ptr<llvm::raw_fd_ostream> OutFile; 722 StringRef OutputFileName = getCompilerInstance().getFrontendOpts().OutputFile; 723 if (!OutputFileName.empty() && OutputFileName != "-") { 724 std::error_code EC; 725 OutFile.reset(new llvm::raw_fd_ostream(OutputFileName.str(), EC, 726 llvm::sys::fs::OF_Text)); 727 } 728 llvm::raw_ostream &Out = OutFile.get()? *OutFile.get() : llvm::outs(); 729 730 Out << "Information for module file '" << getCurrentFile() << "':\n"; 731 auto &FileMgr = getCompilerInstance().getFileManager(); 732 auto Buffer = FileMgr.getBufferForFile(getCurrentFile()); 733 StringRef Magic = (*Buffer)->getMemBufferRef().getBuffer(); 734 bool IsRaw = (Magic.size() >= 4 && Magic[0] == 'C' && Magic[1] == 'P' && 735 Magic[2] == 'C' && Magic[3] == 'H'); 736 Out << " Module format: " << (IsRaw ? "raw" : "obj") << "\n"; 737 738 Preprocessor &PP = getCompilerInstance().getPreprocessor(); 739 DumpModuleInfoListener Listener(Out); 740 HeaderSearchOptions &HSOpts = 741 PP.getHeaderSearchInfo().getHeaderSearchOpts(); 742 ASTReader::readASTFileControlBlock( 743 getCurrentFile(), FileMgr, getCompilerInstance().getPCHContainerReader(), 744 /*FindModuleFileExtensions=*/true, Listener, 745 HSOpts.ModulesValidateDiagnosticOptions); 746 } 747 748 //===----------------------------------------------------------------------===// 749 // Preprocessor Actions 750 //===----------------------------------------------------------------------===// 751 752 void DumpRawTokensAction::ExecuteAction() { 753 Preprocessor &PP = getCompilerInstance().getPreprocessor(); 754 SourceManager &SM = PP.getSourceManager(); 755 756 // Start lexing the specified input file. 757 llvm::MemoryBufferRef FromFile = SM.getBufferOrFake(SM.getMainFileID()); 758 Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts()); 759 RawLex.SetKeepWhitespaceMode(true); 760 761 Token RawTok; 762 RawLex.LexFromRawLexer(RawTok); 763 while (RawTok.isNot(tok::eof)) { 764 PP.DumpToken(RawTok, true); 765 llvm::errs() << "\n"; 766 RawLex.LexFromRawLexer(RawTok); 767 } 768 } 769 770 void DumpTokensAction::ExecuteAction() { 771 Preprocessor &PP = getCompilerInstance().getPreprocessor(); 772 // Start preprocessing the specified input file. 773 Token Tok; 774 PP.EnterMainSourceFile(); 775 do { 776 PP.Lex(Tok); 777 PP.DumpToken(Tok, true); 778 llvm::errs() << "\n"; 779 } while (Tok.isNot(tok::eof)); 780 } 781 782 void PreprocessOnlyAction::ExecuteAction() { 783 Preprocessor &PP = getCompilerInstance().getPreprocessor(); 784 785 // Ignore unknown pragmas. 786 PP.IgnorePragmas(); 787 788 Token Tok; 789 // Start parsing the specified input file. 790 PP.EnterMainSourceFile(); 791 do { 792 PP.Lex(Tok); 793 } while (Tok.isNot(tok::eof)); 794 } 795 796 void PrintPreprocessedAction::ExecuteAction() { 797 CompilerInstance &CI = getCompilerInstance(); 798 // Output file may need to be set to 'Binary', to avoid converting Unix style 799 // line feeds (<LF>) to Microsoft style line feeds (<CR><LF>). 800 // 801 // Look to see what type of line endings the file uses. If there's a 802 // CRLF, then we won't open the file up in binary mode. If there is 803 // just an LF or CR, then we will open the file up in binary mode. 804 // In this fashion, the output format should match the input format, unless 805 // the input format has inconsistent line endings. 806 // 807 // This should be a relatively fast operation since most files won't have 808 // all of their source code on a single line. However, that is still a 809 // concern, so if we scan for too long, we'll just assume the file should 810 // be opened in binary mode. 811 bool BinaryMode = true; 812 const SourceManager& SM = CI.getSourceManager(); 813 if (llvm::Optional<llvm::MemoryBufferRef> Buffer = 814 SM.getBufferOrNone(SM.getMainFileID())) { 815 const char *cur = Buffer->getBufferStart(); 816 const char *end = Buffer->getBufferEnd(); 817 const char *next = (cur != end) ? cur + 1 : end; 818 819 // Limit ourselves to only scanning 256 characters into the source 820 // file. This is mostly a sanity check in case the file has no 821 // newlines whatsoever. 822 if (end - cur > 256) end = cur + 256; 823 824 while (next < end) { 825 if (*cur == 0x0D) { // CR 826 if (*next == 0x0A) // CRLF 827 BinaryMode = false; 828 829 break; 830 } else if (*cur == 0x0A) // LF 831 break; 832 833 ++cur; 834 ++next; 835 } 836 } 837 838 std::unique_ptr<raw_ostream> OS = 839 CI.createDefaultOutputFile(BinaryMode, getCurrentFileOrBufferName()); 840 if (!OS) return; 841 842 // If we're preprocessing a module map, start by dumping the contents of the 843 // module itself before switching to the input buffer. 844 auto &Input = getCurrentInput(); 845 if (Input.getKind().getFormat() == InputKind::ModuleMap) { 846 if (Input.isFile()) { 847 (*OS) << "# 1 \""; 848 OS->write_escaped(Input.getFile()); 849 (*OS) << "\"\n"; 850 } 851 getCurrentModule()->print(*OS); 852 (*OS) << "#pragma clang module contents\n"; 853 } 854 855 DoPrintPreprocessedInput(CI.getPreprocessor(), OS.get(), 856 CI.getPreprocessorOutputOpts()); 857 } 858 859 void PrintPreambleAction::ExecuteAction() { 860 switch (getCurrentFileKind().getLanguage()) { 861 case Language::C: 862 case Language::CXX: 863 case Language::ObjC: 864 case Language::ObjCXX: 865 case Language::OpenCL: 866 case Language::CUDA: 867 case Language::HIP: 868 break; 869 870 case Language::Unknown: 871 case Language::Asm: 872 case Language::LLVM_IR: 873 case Language::RenderScript: 874 // We can't do anything with these. 875 return; 876 } 877 878 // We don't expect to find any #include directives in a preprocessed input. 879 if (getCurrentFileKind().isPreprocessed()) 880 return; 881 882 CompilerInstance &CI = getCompilerInstance(); 883 auto Buffer = CI.getFileManager().getBufferForFile(getCurrentFile()); 884 if (Buffer) { 885 unsigned Preamble = 886 Lexer::ComputePreamble((*Buffer)->getBuffer(), CI.getLangOpts()).Size; 887 llvm::outs().write((*Buffer)->getBufferStart(), Preamble); 888 } 889 } 890 891 void DumpCompilerOptionsAction::ExecuteAction() { 892 CompilerInstance &CI = getCompilerInstance(); 893 std::unique_ptr<raw_ostream> OSP = 894 CI.createDefaultOutputFile(false, getCurrentFile()); 895 if (!OSP) 896 return; 897 898 raw_ostream &OS = *OSP; 899 const Preprocessor &PP = CI.getPreprocessor(); 900 const LangOptions &LangOpts = PP.getLangOpts(); 901 902 // FIXME: Rather than manually format the JSON (which is awkward due to 903 // needing to remove trailing commas), this should make use of a JSON library. 904 // FIXME: Instead of printing enums as an integral value and specifying the 905 // type as a separate field, use introspection to print the enumerator. 906 907 OS << "{\n"; 908 OS << "\n\"features\" : [\n"; 909 { 910 llvm::SmallString<128> Str; 911 #define FEATURE(Name, Predicate) \ 912 ("\t{\"" #Name "\" : " + llvm::Twine(Predicate ? "true" : "false") + "},\n") \ 913 .toVector(Str); 914 #include "clang/Basic/Features.def" 915 #undef FEATURE 916 // Remove the newline and comma from the last entry to ensure this remains 917 // valid JSON. 918 OS << Str.substr(0, Str.size() - 2); 919 } 920 OS << "\n],\n"; 921 922 OS << "\n\"extensions\" : [\n"; 923 { 924 llvm::SmallString<128> Str; 925 #define EXTENSION(Name, Predicate) \ 926 ("\t{\"" #Name "\" : " + llvm::Twine(Predicate ? "true" : "false") + "},\n") \ 927 .toVector(Str); 928 #include "clang/Basic/Features.def" 929 #undef EXTENSION 930 // Remove the newline and comma from the last entry to ensure this remains 931 // valid JSON. 932 OS << Str.substr(0, Str.size() - 2); 933 } 934 OS << "\n]\n"; 935 936 OS << "}"; 937 } 938 939 void PrintDependencyDirectivesSourceMinimizerAction::ExecuteAction() { 940 CompilerInstance &CI = getCompilerInstance(); 941 SourceManager &SM = CI.getPreprocessor().getSourceManager(); 942 llvm::MemoryBufferRef FromFile = SM.getBufferOrFake(SM.getMainFileID()); 943 944 llvm::SmallString<1024> Output; 945 llvm::SmallVector<minimize_source_to_dependency_directives::Token, 32> Toks; 946 if (minimizeSourceToDependencyDirectives( 947 FromFile.getBuffer(), Output, Toks, &CI.getDiagnostics(), 948 SM.getLocForStartOfFile(SM.getMainFileID()))) { 949 assert(CI.getDiagnostics().hasErrorOccurred() && 950 "no errors reported for failure"); 951 952 // Preprocess the source when verifying the diagnostics to capture the 953 // 'expected' comments. 954 if (CI.getDiagnosticOpts().VerifyDiagnostics) { 955 // Make sure we don't emit new diagnostics! 956 CI.getDiagnostics().setSuppressAllDiagnostics(true); 957 Preprocessor &PP = getCompilerInstance().getPreprocessor(); 958 PP.EnterMainSourceFile(); 959 Token Tok; 960 do { 961 PP.Lex(Tok); 962 } while (Tok.isNot(tok::eof)); 963 } 964 return; 965 } 966 llvm::outs() << Output; 967 } 968