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