1 //===--- FrontendActions.cpp ----------------------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "clang/Frontend/FrontendActions.h" 11 #include "clang/AST/ASTConsumer.h" 12 #include "clang/Basic/FileManager.h" 13 #include "clang/Frontend/ASTConsumers.h" 14 #include "clang/Frontend/CompilerInstance.h" 15 #include "clang/Frontend/FrontendDiagnostic.h" 16 #include "clang/Frontend/MultiplexConsumer.h" 17 #include "clang/Frontend/Utils.h" 18 #include "clang/Lex/HeaderSearch.h" 19 #include "clang/Lex/Preprocessor.h" 20 #include "clang/Lex/PreprocessorOptions.h" 21 #include "clang/Serialization/ASTReader.h" 22 #include "clang/Serialization/ASTWriter.h" 23 #include "llvm/Support/FileSystem.h" 24 #include "llvm/Support/MemoryBuffer.h" 25 #include "llvm/Support/Path.h" 26 #include "llvm/Support/raw_ostream.h" 27 #include <memory> 28 #include <system_error> 29 30 using namespace clang; 31 32 //===----------------------------------------------------------------------===// 33 // Custom Actions 34 //===----------------------------------------------------------------------===// 35 36 std::unique_ptr<ASTConsumer> 37 InitOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { 38 return llvm::make_unique<ASTConsumer>(); 39 } 40 41 void InitOnlyAction::ExecuteAction() { 42 } 43 44 //===----------------------------------------------------------------------===// 45 // AST Consumer Actions 46 //===----------------------------------------------------------------------===// 47 48 std::unique_ptr<ASTConsumer> 49 ASTPrintAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { 50 if (std::unique_ptr<raw_ostream> OS = 51 CI.createDefaultOutputFile(false, InFile)) 52 return CreateASTPrinter(std::move(OS), CI.getFrontendOpts().ASTDumpFilter); 53 return nullptr; 54 } 55 56 std::unique_ptr<ASTConsumer> 57 ASTDumpAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { 58 return CreateASTDumper(CI.getFrontendOpts().ASTDumpFilter, 59 CI.getFrontendOpts().ASTDumpDecls, 60 CI.getFrontendOpts().ASTDumpLookups); 61 } 62 63 std::unique_ptr<ASTConsumer> 64 ASTDeclListAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { 65 return CreateASTDeclNodeLister(); 66 } 67 68 std::unique_ptr<ASTConsumer> 69 ASTViewAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { 70 return CreateASTViewer(); 71 } 72 73 std::unique_ptr<ASTConsumer> 74 DeclContextPrintAction::CreateASTConsumer(CompilerInstance &CI, 75 StringRef InFile) { 76 return CreateDeclContextPrinter(); 77 } 78 79 std::unique_ptr<ASTConsumer> 80 GeneratePCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { 81 std::string Sysroot; 82 std::string OutputFile; 83 std::unique_ptr<raw_pwrite_stream> OS = 84 ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile); 85 if (!OS) 86 return nullptr; 87 88 if (!CI.getFrontendOpts().RelocatablePCH) 89 Sysroot.clear(); 90 91 auto Buffer = std::make_shared<PCHBuffer>(); 92 std::vector<std::unique_ptr<ASTConsumer>> Consumers; 93 Consumers.push_back(llvm::make_unique<PCHGenerator>( 94 CI.getPreprocessor(), OutputFile, Sysroot, 95 Buffer, CI.getFrontendOpts().ModuleFileExtensions, 96 /*AllowASTWithErrors*/false, 97 /*IncludeTimestamps*/ 98 +CI.getFrontendOpts().IncludeTimestamps)); 99 Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator( 100 CI, InFile, OutputFile, std::move(OS), Buffer)); 101 102 return llvm::make_unique<MultiplexConsumer>(std::move(Consumers)); 103 } 104 105 std::unique_ptr<raw_pwrite_stream> 106 GeneratePCHAction::ComputeASTConsumerArguments(CompilerInstance &CI, 107 StringRef InFile, 108 std::string &Sysroot, 109 std::string &OutputFile) { 110 Sysroot = CI.getHeaderSearchOpts().Sysroot; 111 if (CI.getFrontendOpts().RelocatablePCH && Sysroot.empty()) { 112 CI.getDiagnostics().Report(diag::err_relocatable_without_isysroot); 113 return nullptr; 114 } 115 116 // We use createOutputFile here because this is exposed via libclang, and we 117 // must disable the RemoveFileOnSignal behavior. 118 // We use a temporary to avoid race conditions. 119 std::unique_ptr<raw_pwrite_stream> OS = 120 CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true, 121 /*RemoveFileOnSignal=*/false, InFile, 122 /*Extension=*/"", /*useTemporary=*/true); 123 if (!OS) 124 return nullptr; 125 126 OutputFile = CI.getFrontendOpts().OutputFile; 127 return OS; 128 } 129 130 bool GeneratePCHAction::BeginSourceFileAction(CompilerInstance &CI, 131 StringRef Filename) { 132 CI.getLangOpts().CompilingPCH = true; 133 return true; 134 } 135 136 std::unique_ptr<ASTConsumer> 137 GenerateModuleAction::CreateASTConsumer(CompilerInstance &CI, 138 StringRef InFile) { 139 std::unique_ptr<raw_pwrite_stream> OS = CreateOutputFile(CI, InFile); 140 if (!OS) 141 return nullptr; 142 143 std::string OutputFile = CI.getFrontendOpts().OutputFile; 144 std::string Sysroot; 145 146 auto Buffer = std::make_shared<PCHBuffer>(); 147 std::vector<std::unique_ptr<ASTConsumer>> Consumers; 148 149 Consumers.push_back(llvm::make_unique<PCHGenerator>( 150 CI.getPreprocessor(), OutputFile, Sysroot, 151 Buffer, CI.getFrontendOpts().ModuleFileExtensions, 152 /*AllowASTWithErrors=*/false, 153 /*IncludeTimestamps=*/ 154 +CI.getFrontendOpts().BuildingImplicitModule)); 155 Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator( 156 CI, InFile, OutputFile, std::move(OS), Buffer)); 157 return llvm::make_unique<MultiplexConsumer>(std::move(Consumers)); 158 } 159 160 bool GenerateModuleAction::BeginSourceFileAction(CompilerInstance &CI, 161 StringRef Filename) { 162 // Set up embedding for any specified files. Do this before we load any 163 // source files, including the primary module map for the compilation. 164 for (const auto &F : CI.getFrontendOpts().ModulesEmbedFiles) { 165 if (const auto *FE = CI.getFileManager().getFile(F, /*openFile*/true)) 166 CI.getSourceManager().setFileIsTransient(FE); 167 else 168 CI.getDiagnostics().Report(diag::err_modules_embed_file_not_found) << F; 169 } 170 if (CI.getFrontendOpts().ModulesEmbedAllFiles) 171 CI.getSourceManager().setAllFilesAreTransient(true); 172 173 return true; 174 } 175 176 177 static SmallVectorImpl<char> & 178 operator+=(SmallVectorImpl<char> &Includes, StringRef RHS) { 179 Includes.append(RHS.begin(), RHS.end()); 180 return Includes; 181 } 182 183 static void addHeaderInclude(StringRef HeaderName, 184 SmallVectorImpl<char> &Includes, 185 const LangOptions &LangOpts, 186 bool IsExternC) { 187 if (IsExternC && LangOpts.CPlusPlus) 188 Includes += "extern \"C\" {\n"; 189 if (LangOpts.ObjC1) 190 Includes += "#import \""; 191 else 192 Includes += "#include \""; 193 194 Includes += HeaderName; 195 196 Includes += "\"\n"; 197 if (IsExternC && LangOpts.CPlusPlus) 198 Includes += "}\n"; 199 } 200 201 /// \brief Collect the set of header includes needed to construct the given 202 /// module and update the TopHeaders file set of the module. 203 /// 204 /// \param Module The module we're collecting includes from. 205 /// 206 /// \param Includes Will be augmented with the set of \#includes or \#imports 207 /// needed to load all of the named headers. 208 static std::error_code 209 collectModuleHeaderIncludes(const LangOptions &LangOpts, FileManager &FileMgr, 210 ModuleMap &ModMap, clang::Module *Module, 211 SmallVectorImpl<char> &Includes) { 212 // Don't collect any headers for unavailable modules. 213 if (!Module->isAvailable()) 214 return std::error_code(); 215 216 // Add includes for each of these headers. 217 for (auto HK : {Module::HK_Normal, Module::HK_Private}) { 218 for (Module::Header &H : Module->Headers[HK]) { 219 Module->addTopHeader(H.Entry); 220 // Use the path as specified in the module map file. We'll look for this 221 // file relative to the module build directory (the directory containing 222 // the module map file) so this will find the same file that we found 223 // while parsing the module map. 224 addHeaderInclude(H.NameAsWritten, Includes, LangOpts, Module->IsExternC); 225 } 226 } 227 // Note that Module->PrivateHeaders will not be a TopHeader. 228 229 if (Module::Header UmbrellaHeader = Module->getUmbrellaHeader()) { 230 Module->addTopHeader(UmbrellaHeader.Entry); 231 if (Module->Parent) 232 // Include the umbrella header for submodules. 233 addHeaderInclude(UmbrellaHeader.NameAsWritten, Includes, LangOpts, 234 Module->IsExternC); 235 } else if (Module::DirectoryName UmbrellaDir = Module->getUmbrellaDir()) { 236 // Add all of the headers we find in this subdirectory. 237 std::error_code EC; 238 SmallString<128> DirNative; 239 llvm::sys::path::native(UmbrellaDir.Entry->getName(), DirNative); 240 241 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem(); 242 for (vfs::recursive_directory_iterator Dir(FS, DirNative, EC), End; 243 Dir != End && !EC; Dir.increment(EC)) { 244 // Check whether this entry has an extension typically associated with 245 // headers. 246 if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->getName())) 247 .Cases(".h", ".H", ".hh", ".hpp", true) 248 .Default(false)) 249 continue; 250 251 const FileEntry *Header = FileMgr.getFile(Dir->getName()); 252 // FIXME: This shouldn't happen unless there is a file system race. Is 253 // that worth diagnosing? 254 if (!Header) 255 continue; 256 257 // If this header is marked 'unavailable' in this module, don't include 258 // it. 259 if (ModMap.isHeaderUnavailableInModule(Header, Module)) 260 continue; 261 262 // Compute the relative path from the directory to this file. 263 SmallVector<StringRef, 16> Components; 264 auto PathIt = llvm::sys::path::rbegin(Dir->getName()); 265 for (int I = 0; I != Dir.level() + 1; ++I, ++PathIt) 266 Components.push_back(*PathIt); 267 SmallString<128> RelativeHeader(UmbrellaDir.NameAsWritten); 268 for (auto It = Components.rbegin(), End = Components.rend(); It != End; 269 ++It) 270 llvm::sys::path::append(RelativeHeader, *It); 271 272 // Include this header as part of the umbrella directory. 273 Module->addTopHeader(Header); 274 addHeaderInclude(RelativeHeader, Includes, LangOpts, Module->IsExternC); 275 } 276 277 if (EC) 278 return EC; 279 } 280 281 // Recurse into submodules. 282 for (clang::Module::submodule_iterator Sub = Module->submodule_begin(), 283 SubEnd = Module->submodule_end(); 284 Sub != SubEnd; ++Sub) 285 if (std::error_code Err = collectModuleHeaderIncludes( 286 LangOpts, FileMgr, ModMap, *Sub, Includes)) 287 return Err; 288 289 return std::error_code(); 290 } 291 292 bool GenerateModuleFromModuleMapAction::BeginSourceFileAction( 293 CompilerInstance &CI, StringRef Filename) { 294 CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleMap); 295 296 if (!GenerateModuleAction::BeginSourceFileAction(CI, Filename)) 297 return false; 298 299 // Find the module map file. 300 const FileEntry *ModuleMap = 301 CI.getFileManager().getFile(Filename, /*openFile*/true); 302 if (!ModuleMap) { 303 CI.getDiagnostics().Report(diag::err_module_map_not_found) 304 << Filename; 305 return false; 306 } 307 308 // Parse the module map file. 309 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo(); 310 if (HS.loadModuleMapFile(ModuleMap, IsSystem)) 311 return false; 312 313 if (CI.getLangOpts().CurrentModule.empty()) { 314 CI.getDiagnostics().Report(diag::err_missing_module_name); 315 316 // FIXME: Eventually, we could consider asking whether there was just 317 // a single module described in the module map, and use that as a 318 // default. Then it would be fairly trivial to just "compile" a module 319 // map with a single module (the common case). 320 return false; 321 } 322 323 // If we're being run from the command-line, the module build stack will not 324 // have been filled in yet, so complete it now in order to allow us to detect 325 // module cycles. 326 SourceManager &SourceMgr = CI.getSourceManager(); 327 if (SourceMgr.getModuleBuildStack().empty()) 328 SourceMgr.pushModuleBuildStack(CI.getLangOpts().CurrentModule, 329 FullSourceLoc(SourceLocation(), SourceMgr)); 330 331 // Dig out the module definition. 332 Module = HS.lookupModule(CI.getLangOpts().CurrentModule, 333 /*AllowSearch=*/false); 334 if (!Module) { 335 CI.getDiagnostics().Report(diag::err_missing_module) 336 << CI.getLangOpts().CurrentModule << Filename; 337 338 return false; 339 } 340 341 // Check whether we can build this module at all. 342 clang::Module::Requirement Requirement; 343 clang::Module::UnresolvedHeaderDirective MissingHeader; 344 if (!Module->isAvailable(CI.getLangOpts(), CI.getTarget(), Requirement, 345 MissingHeader)) { 346 if (MissingHeader.FileNameLoc.isValid()) { 347 CI.getDiagnostics().Report(MissingHeader.FileNameLoc, 348 diag::err_module_header_missing) 349 << MissingHeader.IsUmbrella << MissingHeader.FileName; 350 } else { 351 CI.getDiagnostics().Report(diag::err_module_unavailable) 352 << Module->getFullModuleName() 353 << Requirement.second << Requirement.first; 354 } 355 356 return false; 357 } 358 359 if (ModuleMapForUniquing && ModuleMapForUniquing != ModuleMap) { 360 Module->IsInferred = true; 361 HS.getModuleMap().setInferredModuleAllowedBy(Module, ModuleMapForUniquing); 362 } else { 363 ModuleMapForUniquing = ModuleMap; 364 } 365 366 FileManager &FileMgr = CI.getFileManager(); 367 368 // Collect the set of #includes we need to build the module. 369 SmallString<256> HeaderContents; 370 std::error_code Err = std::error_code(); 371 if (Module::Header UmbrellaHeader = Module->getUmbrellaHeader()) 372 addHeaderInclude(UmbrellaHeader.NameAsWritten, HeaderContents, 373 CI.getLangOpts(), Module->IsExternC); 374 Err = collectModuleHeaderIncludes( 375 CI.getLangOpts(), FileMgr, 376 CI.getPreprocessor().getHeaderSearchInfo().getModuleMap(), Module, 377 HeaderContents); 378 379 if (Err) { 380 CI.getDiagnostics().Report(diag::err_module_cannot_create_includes) 381 << Module->getFullModuleName() << Err.message(); 382 return false; 383 } 384 385 // Inform the preprocessor that includes from within the input buffer should 386 // be resolved relative to the build directory of the module map file. 387 CI.getPreprocessor().setMainFileDir(Module->Directory); 388 389 std::unique_ptr<llvm::MemoryBuffer> InputBuffer = 390 llvm::MemoryBuffer::getMemBufferCopy(HeaderContents, 391 Module::getModuleInputBufferName()); 392 // Ownership of InputBuffer will be transferred to the SourceManager. 393 setCurrentInput(FrontendInputFile(InputBuffer.release(), getCurrentFileKind(), 394 Module->IsSystem)); 395 return true; 396 } 397 398 std::unique_ptr<raw_pwrite_stream> 399 GenerateModuleFromModuleMapAction::CreateOutputFile(CompilerInstance &CI, 400 StringRef InFile) { 401 // If no output file was provided, figure out where this module would go 402 // in the module cache. 403 if (CI.getFrontendOpts().OutputFile.empty()) { 404 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo(); 405 CI.getFrontendOpts().OutputFile = 406 HS.getModuleFileName(CI.getLangOpts().CurrentModule, 407 ModuleMapForUniquing->getName(), 408 /*UsePrebuiltPath=*/false); 409 } 410 411 // We use createOutputFile here because this is exposed via libclang, and we 412 // must disable the RemoveFileOnSignal behavior. 413 // We use a temporary to avoid race conditions. 414 return CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true, 415 /*RemoveFileOnSignal=*/false, InFile, 416 /*Extension=*/"", /*useTemporary=*/true, 417 /*CreateMissingDirectories=*/true); 418 } 419 420 bool GenerateModuleInterfaceAction::BeginSourceFileAction(CompilerInstance &CI, 421 StringRef Filename) { 422 if (!CI.getLangOpts().ModulesTS) { 423 CI.getDiagnostics().Report(diag::err_module_interface_requires_modules_ts); 424 return false; 425 } 426 427 CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleInterface); 428 429 return GenerateModuleAction::BeginSourceFileAction(CI, Filename); 430 } 431 432 std::unique_ptr<raw_pwrite_stream> 433 GenerateModuleInterfaceAction::CreateOutputFile(CompilerInstance &CI, 434 StringRef InFile) { 435 return CI.createDefaultOutputFile(/*Binary=*/true, InFile, "pcm"); 436 } 437 438 SyntaxOnlyAction::~SyntaxOnlyAction() { 439 } 440 441 std::unique_ptr<ASTConsumer> 442 SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { 443 return llvm::make_unique<ASTConsumer>(); 444 } 445 446 std::unique_ptr<ASTConsumer> 447 DumpModuleInfoAction::CreateASTConsumer(CompilerInstance &CI, 448 StringRef InFile) { 449 return llvm::make_unique<ASTConsumer>(); 450 } 451 452 std::unique_ptr<ASTConsumer> 453 VerifyPCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { 454 return llvm::make_unique<ASTConsumer>(); 455 } 456 457 void VerifyPCHAction::ExecuteAction() { 458 CompilerInstance &CI = getCompilerInstance(); 459 bool Preamble = CI.getPreprocessorOpts().PrecompiledPreambleBytes.first != 0; 460 const std::string &Sysroot = CI.getHeaderSearchOpts().Sysroot; 461 std::unique_ptr<ASTReader> Reader(new ASTReader( 462 CI.getPreprocessor(), CI.getASTContext(), CI.getPCHContainerReader(), 463 CI.getFrontendOpts().ModuleFileExtensions, 464 Sysroot.empty() ? "" : Sysroot.c_str(), 465 /*DisableValidation*/ false, 466 /*AllowPCHWithCompilerErrors*/ false, 467 /*AllowConfigurationMismatch*/ true, 468 /*ValidateSystemInputs*/ true)); 469 470 Reader->ReadAST(getCurrentFile(), 471 Preamble ? serialization::MK_Preamble 472 : serialization::MK_PCH, 473 SourceLocation(), 474 ASTReader::ARR_ConfigurationMismatch); 475 } 476 477 namespace { 478 /// \brief AST reader listener that dumps module information for a module 479 /// file. 480 class DumpModuleInfoListener : public ASTReaderListener { 481 llvm::raw_ostream &Out; 482 483 public: 484 DumpModuleInfoListener(llvm::raw_ostream &Out) : Out(Out) { } 485 486 #define DUMP_BOOLEAN(Value, Text) \ 487 Out.indent(4) << Text << ": " << (Value? "Yes" : "No") << "\n" 488 489 bool ReadFullVersionInformation(StringRef FullVersion) override { 490 Out.indent(2) 491 << "Generated by " 492 << (FullVersion == getClangFullRepositoryVersion()? "this" 493 : "a different") 494 << " Clang: " << FullVersion << "\n"; 495 return ASTReaderListener::ReadFullVersionInformation(FullVersion); 496 } 497 498 void ReadModuleName(StringRef ModuleName) override { 499 Out.indent(2) << "Module name: " << ModuleName << "\n"; 500 } 501 void ReadModuleMapFile(StringRef ModuleMapPath) override { 502 Out.indent(2) << "Module map file: " << ModuleMapPath << "\n"; 503 } 504 505 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, 506 bool AllowCompatibleDifferences) override { 507 Out.indent(2) << "Language options:\n"; 508 #define LANGOPT(Name, Bits, Default, Description) \ 509 DUMP_BOOLEAN(LangOpts.Name, Description); 510 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \ 511 Out.indent(4) << Description << ": " \ 512 << static_cast<unsigned>(LangOpts.get##Name()) << "\n"; 513 #define VALUE_LANGOPT(Name, Bits, Default, Description) \ 514 Out.indent(4) << Description << ": " << LangOpts.Name << "\n"; 515 #define BENIGN_LANGOPT(Name, Bits, Default, Description) 516 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description) 517 #include "clang/Basic/LangOptions.def" 518 519 if (!LangOpts.ModuleFeatures.empty()) { 520 Out.indent(4) << "Module features:\n"; 521 for (StringRef Feature : LangOpts.ModuleFeatures) 522 Out.indent(6) << Feature << "\n"; 523 } 524 525 return false; 526 } 527 528 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, 529 bool AllowCompatibleDifferences) override { 530 Out.indent(2) << "Target options:\n"; 531 Out.indent(4) << " Triple: " << TargetOpts.Triple << "\n"; 532 Out.indent(4) << " CPU: " << TargetOpts.CPU << "\n"; 533 Out.indent(4) << " ABI: " << TargetOpts.ABI << "\n"; 534 535 if (!TargetOpts.FeaturesAsWritten.empty()) { 536 Out.indent(4) << "Target features:\n"; 537 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); 538 I != N; ++I) { 539 Out.indent(6) << TargetOpts.FeaturesAsWritten[I] << "\n"; 540 } 541 } 542 543 return false; 544 } 545 546 bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, 547 bool Complain) override { 548 Out.indent(2) << "Diagnostic options:\n"; 549 #define DIAGOPT(Name, Bits, Default) DUMP_BOOLEAN(DiagOpts->Name, #Name); 550 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \ 551 Out.indent(4) << #Name << ": " << DiagOpts->get##Name() << "\n"; 552 #define VALUE_DIAGOPT(Name, Bits, Default) \ 553 Out.indent(4) << #Name << ": " << DiagOpts->Name << "\n"; 554 #include "clang/Basic/DiagnosticOptions.def" 555 556 Out.indent(4) << "Diagnostic flags:\n"; 557 for (const std::string &Warning : DiagOpts->Warnings) 558 Out.indent(6) << "-W" << Warning << "\n"; 559 for (const std::string &Remark : DiagOpts->Remarks) 560 Out.indent(6) << "-R" << Remark << "\n"; 561 562 return false; 563 } 564 565 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, 566 StringRef SpecificModuleCachePath, 567 bool Complain) override { 568 Out.indent(2) << "Header search options:\n"; 569 Out.indent(4) << "System root [-isysroot=]: '" << HSOpts.Sysroot << "'\n"; 570 Out.indent(4) << "Module Cache: '" << SpecificModuleCachePath << "'\n"; 571 DUMP_BOOLEAN(HSOpts.UseBuiltinIncludes, 572 "Use builtin include directories [-nobuiltininc]"); 573 DUMP_BOOLEAN(HSOpts.UseStandardSystemIncludes, 574 "Use standard system include directories [-nostdinc]"); 575 DUMP_BOOLEAN(HSOpts.UseStandardCXXIncludes, 576 "Use standard C++ include directories [-nostdinc++]"); 577 DUMP_BOOLEAN(HSOpts.UseLibcxx, 578 "Use libc++ (rather than libstdc++) [-stdlib=]"); 579 return false; 580 } 581 582 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, 583 bool Complain, 584 std::string &SuggestedPredefines) override { 585 Out.indent(2) << "Preprocessor options:\n"; 586 DUMP_BOOLEAN(PPOpts.UsePredefines, 587 "Uses compiler/target-specific predefines [-undef]"); 588 DUMP_BOOLEAN(PPOpts.DetailedRecord, 589 "Uses detailed preprocessing record (for indexing)"); 590 591 if (!PPOpts.Macros.empty()) { 592 Out.indent(4) << "Predefined macros:\n"; 593 } 594 595 for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator 596 I = PPOpts.Macros.begin(), IEnd = PPOpts.Macros.end(); 597 I != IEnd; ++I) { 598 Out.indent(6); 599 if (I->second) 600 Out << "-U"; 601 else 602 Out << "-D"; 603 Out << I->first << "\n"; 604 } 605 return false; 606 } 607 608 /// Indicates that a particular module file extension has been read. 609 void readModuleFileExtension( 610 const ModuleFileExtensionMetadata &Metadata) override { 611 Out.indent(2) << "Module file extension '" 612 << Metadata.BlockName << "' " << Metadata.MajorVersion 613 << "." << Metadata.MinorVersion; 614 if (!Metadata.UserInfo.empty()) { 615 Out << ": "; 616 Out.write_escaped(Metadata.UserInfo); 617 } 618 619 Out << "\n"; 620 } 621 #undef DUMP_BOOLEAN 622 }; 623 } 624 625 bool DumpModuleInfoAction::BeginInvocation(CompilerInstance &CI) { 626 // The Object file reader also supports raw ast files and there is no point in 627 // being strict about the module file format in -module-file-info mode. 628 CI.getHeaderSearchOpts().ModuleFormat = "obj"; 629 return true; 630 } 631 632 void DumpModuleInfoAction::ExecuteAction() { 633 // Set up the output file. 634 std::unique_ptr<llvm::raw_fd_ostream> OutFile; 635 StringRef OutputFileName = getCompilerInstance().getFrontendOpts().OutputFile; 636 if (!OutputFileName.empty() && OutputFileName != "-") { 637 std::error_code EC; 638 OutFile.reset(new llvm::raw_fd_ostream(OutputFileName.str(), EC, 639 llvm::sys::fs::F_Text)); 640 } 641 llvm::raw_ostream &Out = OutFile.get()? *OutFile.get() : llvm::outs(); 642 643 Out << "Information for module file '" << getCurrentFile() << "':\n"; 644 auto &FileMgr = getCompilerInstance().getFileManager(); 645 auto Buffer = FileMgr.getBufferForFile(getCurrentFile()); 646 StringRef Magic = (*Buffer)->getMemBufferRef().getBuffer(); 647 bool IsRaw = (Magic.size() >= 4 && Magic[0] == 'C' && Magic[1] == 'P' && 648 Magic[2] == 'C' && Magic[3] == 'H'); 649 Out << " Module format: " << (IsRaw ? "raw" : "obj") << "\n"; 650 651 Preprocessor &PP = getCompilerInstance().getPreprocessor(); 652 DumpModuleInfoListener Listener(Out); 653 HeaderSearchOptions &HSOpts = 654 PP.getHeaderSearchInfo().getHeaderSearchOpts(); 655 ASTReader::readASTFileControlBlock( 656 getCurrentFile(), FileMgr, getCompilerInstance().getPCHContainerReader(), 657 /*FindModuleFileExtensions=*/true, Listener, 658 HSOpts.ModulesValidateDiagnosticOptions); 659 } 660 661 //===----------------------------------------------------------------------===// 662 // Preprocessor Actions 663 //===----------------------------------------------------------------------===// 664 665 void DumpRawTokensAction::ExecuteAction() { 666 Preprocessor &PP = getCompilerInstance().getPreprocessor(); 667 SourceManager &SM = PP.getSourceManager(); 668 669 // Start lexing the specified input file. 670 const llvm::MemoryBuffer *FromFile = SM.getBuffer(SM.getMainFileID()); 671 Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts()); 672 RawLex.SetKeepWhitespaceMode(true); 673 674 Token RawTok; 675 RawLex.LexFromRawLexer(RawTok); 676 while (RawTok.isNot(tok::eof)) { 677 PP.DumpToken(RawTok, true); 678 llvm::errs() << "\n"; 679 RawLex.LexFromRawLexer(RawTok); 680 } 681 } 682 683 void DumpTokensAction::ExecuteAction() { 684 Preprocessor &PP = getCompilerInstance().getPreprocessor(); 685 // Start preprocessing the specified input file. 686 Token Tok; 687 PP.EnterMainSourceFile(); 688 do { 689 PP.Lex(Tok); 690 PP.DumpToken(Tok, true); 691 llvm::errs() << "\n"; 692 } while (Tok.isNot(tok::eof)); 693 } 694 695 void GeneratePTHAction::ExecuteAction() { 696 CompilerInstance &CI = getCompilerInstance(); 697 std::unique_ptr<raw_pwrite_stream> OS = 698 CI.createDefaultOutputFile(true, getCurrentFile()); 699 if (!OS) 700 return; 701 702 CacheTokens(CI.getPreprocessor(), OS.get()); 703 } 704 705 void PreprocessOnlyAction::ExecuteAction() { 706 Preprocessor &PP = getCompilerInstance().getPreprocessor(); 707 708 // Ignore unknown pragmas. 709 PP.IgnorePragmas(); 710 711 Token Tok; 712 // Start parsing the specified input file. 713 PP.EnterMainSourceFile(); 714 do { 715 PP.Lex(Tok); 716 } while (Tok.isNot(tok::eof)); 717 } 718 719 void PrintPreprocessedAction::ExecuteAction() { 720 CompilerInstance &CI = getCompilerInstance(); 721 // Output file may need to be set to 'Binary', to avoid converting Unix style 722 // line feeds (<LF>) to Microsoft style line feeds (<CR><LF>). 723 // 724 // Look to see what type of line endings the file uses. If there's a 725 // CRLF, then we won't open the file up in binary mode. If there is 726 // just an LF or CR, then we will open the file up in binary mode. 727 // In this fashion, the output format should match the input format, unless 728 // the input format has inconsistent line endings. 729 // 730 // This should be a relatively fast operation since most files won't have 731 // all of their source code on a single line. However, that is still a 732 // concern, so if we scan for too long, we'll just assume the file should 733 // be opened in binary mode. 734 bool BinaryMode = true; 735 bool InvalidFile = false; 736 const SourceManager& SM = CI.getSourceManager(); 737 const llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getMainFileID(), 738 &InvalidFile); 739 if (!InvalidFile) { 740 const char *cur = Buffer->getBufferStart(); 741 const char *end = Buffer->getBufferEnd(); 742 const char *next = (cur != end) ? cur + 1 : end; 743 744 // Limit ourselves to only scanning 256 characters into the source 745 // file. This is mostly a sanity check in case the file has no 746 // newlines whatsoever. 747 if (end - cur > 256) end = cur + 256; 748 749 while (next < end) { 750 if (*cur == 0x0D) { // CR 751 if (*next == 0x0A) // CRLF 752 BinaryMode = false; 753 754 break; 755 } else if (*cur == 0x0A) // LF 756 break; 757 758 ++cur; 759 ++next; 760 } 761 } 762 763 std::unique_ptr<raw_ostream> OS = 764 CI.createDefaultOutputFile(BinaryMode, getCurrentFile()); 765 if (!OS) return; 766 767 DoPrintPreprocessedInput(CI.getPreprocessor(), OS.get(), 768 CI.getPreprocessorOutputOpts()); 769 } 770 771 void PrintPreambleAction::ExecuteAction() { 772 switch (getCurrentFileKind()) { 773 case IK_C: 774 case IK_CXX: 775 case IK_ObjC: 776 case IK_ObjCXX: 777 case IK_OpenCL: 778 case IK_CUDA: 779 break; 780 781 case IK_None: 782 case IK_Asm: 783 case IK_PreprocessedC: 784 case IK_PreprocessedCuda: 785 case IK_PreprocessedCXX: 786 case IK_PreprocessedObjC: 787 case IK_PreprocessedObjCXX: 788 case IK_AST: 789 case IK_LLVM_IR: 790 case IK_RenderScript: 791 // We can't do anything with these. 792 return; 793 } 794 795 CompilerInstance &CI = getCompilerInstance(); 796 auto Buffer = CI.getFileManager().getBufferForFile(getCurrentFile()); 797 if (Buffer) { 798 unsigned Preamble = 799 Lexer::ComputePreamble((*Buffer)->getBuffer(), CI.getLangOpts()).first; 800 llvm::outs().write((*Buffer)->getBufferStart(), Preamble); 801 } 802 } 803