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