1 //===-- CompilerInstance.h - Clang Compiler Instance ------------*- C++ -*-===// 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 #ifndef LLVM_CLANG_FRONTEND_COMPILERINSTANCE_H_ 10 #define LLVM_CLANG_FRONTEND_COMPILERINSTANCE_H_ 11 12 #include "clang/AST/ASTConsumer.h" 13 #include "clang/Basic/Diagnostic.h" 14 #include "clang/Basic/SourceManager.h" 15 #include "clang/Basic/TargetInfo.h" 16 #include "clang/Frontend/CompilerInvocation.h" 17 #include "clang/Frontend/PCHContainerOperations.h" 18 #include "clang/Frontend/Utils.h" 19 #include "clang/Lex/HeaderSearchOptions.h" 20 #include "clang/Lex/ModuleLoader.h" 21 #include "llvm/ADT/ArrayRef.h" 22 #include "llvm/ADT/DenseMap.h" 23 #include "llvm/ADT/IntrusiveRefCntPtr.h" 24 #include "llvm/ADT/StringRef.h" 25 #include "llvm/Support/BuryPointer.h" 26 #include "llvm/Support/FileSystem.h" 27 #include "llvm/Support/VirtualFileSystem.h" 28 #include <cassert> 29 #include <list> 30 #include <memory> 31 #include <optional> 32 #include <string> 33 #include <utility> 34 35 namespace llvm { 36 class raw_fd_ostream; 37 class Timer; 38 class TimerGroup; 39 } 40 41 namespace clang { 42 class ASTContext; 43 class ASTReader; 44 45 namespace serialization { 46 class ModuleFile; 47 } 48 49 class CodeCompleteConsumer; 50 class DiagnosticsEngine; 51 class DiagnosticConsumer; 52 class FileManager; 53 class FrontendAction; 54 class InMemoryModuleCache; 55 class Module; 56 class Preprocessor; 57 class Sema; 58 class SourceManager; 59 class TargetInfo; 60 enum class DisableValidationForModuleKind; 61 62 /// CompilerInstance - Helper class for managing a single instance of the Clang 63 /// compiler. 64 /// 65 /// The CompilerInstance serves two purposes: 66 /// (1) It manages the various objects which are necessary to run the compiler, 67 /// for example the preprocessor, the target information, and the AST 68 /// context. 69 /// (2) It provides utility routines for constructing and manipulating the 70 /// common Clang objects. 71 /// 72 /// The compiler instance generally owns the instance of all the objects that it 73 /// manages. However, clients can still share objects by manually setting the 74 /// object and retaking ownership prior to destroying the CompilerInstance. 75 /// 76 /// The compiler instance is intended to simplify clients, but not to lock them 77 /// in to the compiler instance for everything. When possible, utility functions 78 /// come in two forms; a short form that reuses the CompilerInstance objects, 79 /// and a long form that takes explicit instances of any required objects. 80 class CompilerInstance : public ModuleLoader { 81 /// The options used in this compiler instance. 82 std::shared_ptr<CompilerInvocation> Invocation; 83 84 /// The diagnostics engine instance. 85 IntrusiveRefCntPtr<DiagnosticsEngine> Diagnostics; 86 87 /// The target being compiled for. 88 IntrusiveRefCntPtr<TargetInfo> Target; 89 90 /// Auxiliary Target info. 91 IntrusiveRefCntPtr<TargetInfo> AuxTarget; 92 93 /// The file manager. 94 IntrusiveRefCntPtr<FileManager> FileMgr; 95 96 /// The source manager. 97 IntrusiveRefCntPtr<SourceManager> SourceMgr; 98 99 /// The cache of PCM files. 100 IntrusiveRefCntPtr<InMemoryModuleCache> ModuleCache; 101 102 /// The preprocessor. 103 std::shared_ptr<Preprocessor> PP; 104 105 /// The AST context. 106 IntrusiveRefCntPtr<ASTContext> Context; 107 108 /// An optional sema source that will be attached to sema. 109 IntrusiveRefCntPtr<ExternalSemaSource> ExternalSemaSrc; 110 111 /// The AST consumer. 112 std::unique_ptr<ASTConsumer> Consumer; 113 114 /// The code completion consumer. 115 std::unique_ptr<CodeCompleteConsumer> CompletionConsumer; 116 117 /// The semantic analysis object. 118 std::unique_ptr<Sema> TheSema; 119 120 /// The frontend timer group. 121 std::unique_ptr<llvm::TimerGroup> timerGroup; 122 123 /// The frontend timer. 124 std::unique_ptr<llvm::Timer> FrontendTimer; 125 126 /// The ASTReader, if one exists. 127 IntrusiveRefCntPtr<ASTReader> TheASTReader; 128 129 /// The module dependency collector for crashdumps 130 std::shared_ptr<ModuleDependencyCollector> ModuleDepCollector; 131 132 /// The module provider. 133 std::shared_ptr<PCHContainerOperations> ThePCHContainerOperations; 134 135 std::vector<std::shared_ptr<DependencyCollector>> DependencyCollectors; 136 137 /// Records the set of modules 138 class FailedModulesSet { 139 llvm::StringSet<> Failed; 140 141 public: 142 bool hasAlreadyFailed(StringRef module) { return Failed.count(module) > 0; } 143 144 void addFailed(StringRef module) { Failed.insert(module); } 145 }; 146 147 /// The set of modules that failed to build. 148 /// 149 /// This pointer will be shared among all of the compiler instances created 150 /// to (re)build modules, so that once a module fails to build anywhere, 151 /// other instances will see that the module has failed and won't try to 152 /// build it again. 153 std::shared_ptr<FailedModulesSet> FailedModules; 154 155 /// The set of top-level modules that has already been built on the 156 /// fly as part of this overall compilation action. 157 std::map<std::string, std::string, std::less<>> BuiltModules; 158 159 /// Should we delete the BuiltModules when we're done? 160 bool DeleteBuiltModules = true; 161 162 /// The location of the module-import keyword for the last module 163 /// import. 164 SourceLocation LastModuleImportLoc; 165 166 /// The result of the last module import. 167 /// 168 ModuleLoadResult LastModuleImportResult; 169 170 /// Whether we should (re)build the global module index once we 171 /// have finished with this translation unit. 172 bool BuildGlobalModuleIndex = false; 173 174 /// We have a full global module index, with all modules. 175 bool HaveFullGlobalModuleIndex = false; 176 177 /// One or more modules failed to build. 178 bool DisableGeneratingGlobalModuleIndex = false; 179 180 /// The stream for verbose output if owned, otherwise nullptr. 181 std::unique_ptr<raw_ostream> OwnedVerboseOutputStream; 182 183 /// The stream for verbose output. 184 raw_ostream *VerboseOutputStream = &llvm::errs(); 185 186 /// Holds information about the output file. 187 /// 188 /// If TempFilename is not empty we must rename it to Filename at the end. 189 /// TempFilename may be empty and Filename non-empty if creating the temporary 190 /// failed. 191 struct OutputFile { 192 std::string Filename; 193 std::optional<llvm::sys::fs::TempFile> File; 194 195 OutputFile(std::string filename, 196 std::optional<llvm::sys::fs::TempFile> file) 197 : Filename(std::move(filename)), File(std::move(file)) {} 198 }; 199 200 /// The list of active output files. 201 std::list<OutputFile> OutputFiles; 202 203 /// Force an output buffer. 204 std::unique_ptr<llvm::raw_pwrite_stream> OutputStream; 205 206 CompilerInstance(const CompilerInstance &) = delete; 207 void operator=(const CompilerInstance &) = delete; 208 public: 209 explicit CompilerInstance( 210 std::shared_ptr<PCHContainerOperations> PCHContainerOps = 211 std::make_shared<PCHContainerOperations>(), 212 InMemoryModuleCache *SharedModuleCache = nullptr); 213 ~CompilerInstance() override; 214 215 /// @name High-Level Operations 216 /// @{ 217 218 /// ExecuteAction - Execute the provided action against the compiler's 219 /// CompilerInvocation object. 220 /// 221 /// This function makes the following assumptions: 222 /// 223 /// - The invocation options should be initialized. This function does not 224 /// handle the '-help' or '-version' options, clients should handle those 225 /// directly. 226 /// 227 /// - The diagnostics engine should have already been created by the client. 228 /// 229 /// - No other CompilerInstance state should have been initialized (this is 230 /// an unchecked error). 231 /// 232 /// - Clients should have initialized any LLVM target features that may be 233 /// required. 234 /// 235 /// - Clients should eventually call llvm_shutdown() upon the completion of 236 /// this routine to ensure that any managed objects are properly destroyed. 237 /// 238 /// Note that this routine may write output to 'stderr'. 239 /// 240 /// \param Act - The action to execute. 241 /// \return - True on success. 242 // 243 // FIXME: Eliminate the llvm_shutdown requirement, that should either be part 244 // of the context or else not CompilerInstance specific. 245 bool ExecuteAction(FrontendAction &Act); 246 247 /// At the end of a compilation, print the number of warnings/errors. 248 void printDiagnosticStats(); 249 250 /// Load the list of plugins requested in the \c FrontendOptions. 251 void LoadRequestedPlugins(); 252 253 /// @} 254 /// @name Compiler Invocation and Options 255 /// @{ 256 257 bool hasInvocation() const { return Invocation != nullptr; } 258 259 CompilerInvocation &getInvocation() { 260 assert(Invocation && "Compiler instance has no invocation!"); 261 return *Invocation; 262 } 263 264 std::shared_ptr<CompilerInvocation> getInvocationPtr() { return Invocation; } 265 266 /// setInvocation - Replace the current invocation. 267 void setInvocation(std::shared_ptr<CompilerInvocation> Value); 268 269 /// Indicates whether we should (re)build the global module index. 270 bool shouldBuildGlobalModuleIndex() const; 271 272 /// Set the flag indicating whether we should (re)build the global 273 /// module index. 274 void setBuildGlobalModuleIndex(bool Build) { 275 BuildGlobalModuleIndex = Build; 276 } 277 278 /// @} 279 /// @name Forwarding Methods 280 /// @{ 281 282 AnalyzerOptions &getAnalyzerOpts() { return Invocation->getAnalyzerOpts(); } 283 284 CodeGenOptions &getCodeGenOpts() { 285 return Invocation->getCodeGenOpts(); 286 } 287 const CodeGenOptions &getCodeGenOpts() const { 288 return Invocation->getCodeGenOpts(); 289 } 290 291 DependencyOutputOptions &getDependencyOutputOpts() { 292 return Invocation->getDependencyOutputOpts(); 293 } 294 const DependencyOutputOptions &getDependencyOutputOpts() const { 295 return Invocation->getDependencyOutputOpts(); 296 } 297 298 DiagnosticOptions &getDiagnosticOpts() { 299 return Invocation->getDiagnosticOpts(); 300 } 301 const DiagnosticOptions &getDiagnosticOpts() const { 302 return Invocation->getDiagnosticOpts(); 303 } 304 305 FileSystemOptions &getFileSystemOpts() { 306 return Invocation->getFileSystemOpts(); 307 } 308 const FileSystemOptions &getFileSystemOpts() const { 309 return Invocation->getFileSystemOpts(); 310 } 311 312 FrontendOptions &getFrontendOpts() { 313 return Invocation->getFrontendOpts(); 314 } 315 const FrontendOptions &getFrontendOpts() const { 316 return Invocation->getFrontendOpts(); 317 } 318 319 HeaderSearchOptions &getHeaderSearchOpts() { 320 return Invocation->getHeaderSearchOpts(); 321 } 322 const HeaderSearchOptions &getHeaderSearchOpts() const { 323 return Invocation->getHeaderSearchOpts(); 324 } 325 std::shared_ptr<HeaderSearchOptions> getHeaderSearchOptsPtr() const { 326 return Invocation->getHeaderSearchOptsPtr(); 327 } 328 329 APINotesOptions &getAPINotesOpts() { return Invocation->getAPINotesOpts(); } 330 const APINotesOptions &getAPINotesOpts() const { 331 return Invocation->getAPINotesOpts(); 332 } 333 334 LangOptions &getLangOpts() { return Invocation->getLangOpts(); } 335 const LangOptions &getLangOpts() const { return Invocation->getLangOpts(); } 336 std::shared_ptr<LangOptions> getLangOptsPtr() const { 337 return Invocation->getLangOptsPtr(); 338 } 339 340 PreprocessorOptions &getPreprocessorOpts() { 341 return Invocation->getPreprocessorOpts(); 342 } 343 const PreprocessorOptions &getPreprocessorOpts() const { 344 return Invocation->getPreprocessorOpts(); 345 } 346 347 PreprocessorOutputOptions &getPreprocessorOutputOpts() { 348 return Invocation->getPreprocessorOutputOpts(); 349 } 350 const PreprocessorOutputOptions &getPreprocessorOutputOpts() const { 351 return Invocation->getPreprocessorOutputOpts(); 352 } 353 354 TargetOptions &getTargetOpts() { 355 return Invocation->getTargetOpts(); 356 } 357 const TargetOptions &getTargetOpts() const { 358 return Invocation->getTargetOpts(); 359 } 360 361 /// @} 362 /// @name Diagnostics Engine 363 /// @{ 364 365 bool hasDiagnostics() const { return Diagnostics != nullptr; } 366 367 /// Get the current diagnostics engine. 368 DiagnosticsEngine &getDiagnostics() const { 369 assert(Diagnostics && "Compiler instance has no diagnostics!"); 370 return *Diagnostics; 371 } 372 373 IntrusiveRefCntPtr<DiagnosticsEngine> getDiagnosticsPtr() const { 374 assert(Diagnostics && "Compiler instance has no diagnostics!"); 375 return Diagnostics; 376 } 377 378 /// setDiagnostics - Replace the current diagnostics engine. 379 void setDiagnostics(DiagnosticsEngine *Value); 380 381 DiagnosticConsumer &getDiagnosticClient() const { 382 assert(Diagnostics && Diagnostics->getClient() && 383 "Compiler instance has no diagnostic client!"); 384 return *Diagnostics->getClient(); 385 } 386 387 /// @} 388 /// @name VerboseOutputStream 389 /// @{ 390 391 /// Replace the current stream for verbose output. 392 void setVerboseOutputStream(raw_ostream &Value); 393 394 /// Replace the current stream for verbose output. 395 void setVerboseOutputStream(std::unique_ptr<raw_ostream> Value); 396 397 /// Get the current stream for verbose output. 398 raw_ostream &getVerboseOutputStream() { 399 return *VerboseOutputStream; 400 } 401 402 /// @} 403 /// @name Target Info 404 /// @{ 405 406 bool hasTarget() const { return Target != nullptr; } 407 408 TargetInfo &getTarget() const { 409 assert(Target && "Compiler instance has no target!"); 410 return *Target; 411 } 412 413 IntrusiveRefCntPtr<TargetInfo> getTargetPtr() const { 414 assert(Target && "Compiler instance has no target!"); 415 return Target; 416 } 417 418 /// Replace the current Target. 419 void setTarget(TargetInfo *Value); 420 421 /// @} 422 /// @name AuxTarget Info 423 /// @{ 424 425 TargetInfo *getAuxTarget() const { return AuxTarget.get(); } 426 427 /// Replace the current AuxTarget. 428 void setAuxTarget(TargetInfo *Value); 429 430 // Create Target and AuxTarget based on current options 431 bool createTarget(); 432 433 /// @} 434 /// @name Virtual File System 435 /// @{ 436 437 llvm::vfs::FileSystem &getVirtualFileSystem() const; 438 439 /// @} 440 /// @name File Manager 441 /// @{ 442 443 bool hasFileManager() const { return FileMgr != nullptr; } 444 445 /// Return the current file manager to the caller. 446 FileManager &getFileManager() const { 447 assert(FileMgr && "Compiler instance has no file manager!"); 448 return *FileMgr; 449 } 450 451 IntrusiveRefCntPtr<FileManager> getFileManagerPtr() const { 452 assert(FileMgr && "Compiler instance has no file manager!"); 453 return FileMgr; 454 } 455 456 void resetAndLeakFileManager() { 457 llvm::BuryPointer(FileMgr.get()); 458 FileMgr.resetWithoutRelease(); 459 } 460 461 /// Replace the current file manager and virtual file system. 462 void setFileManager(FileManager *Value); 463 464 /// @} 465 /// @name Source Manager 466 /// @{ 467 468 bool hasSourceManager() const { return SourceMgr != nullptr; } 469 470 /// Return the current source manager. 471 SourceManager &getSourceManager() const { 472 assert(SourceMgr && "Compiler instance has no source manager!"); 473 return *SourceMgr; 474 } 475 476 IntrusiveRefCntPtr<SourceManager> getSourceManagerPtr() const { 477 assert(SourceMgr && "Compiler instance has no source manager!"); 478 return SourceMgr; 479 } 480 481 void resetAndLeakSourceManager() { 482 llvm::BuryPointer(SourceMgr.get()); 483 SourceMgr.resetWithoutRelease(); 484 } 485 486 /// setSourceManager - Replace the current source manager. 487 void setSourceManager(SourceManager *Value); 488 489 /// @} 490 /// @name Preprocessor 491 /// @{ 492 493 bool hasPreprocessor() const { return PP != nullptr; } 494 495 /// Return the current preprocessor. 496 Preprocessor &getPreprocessor() const { 497 assert(PP && "Compiler instance has no preprocessor!"); 498 return *PP; 499 } 500 501 std::shared_ptr<Preprocessor> getPreprocessorPtr() { return PP; } 502 503 void resetAndLeakPreprocessor() { 504 llvm::BuryPointer(new std::shared_ptr<Preprocessor>(PP)); 505 } 506 507 /// Replace the current preprocessor. 508 void setPreprocessor(std::shared_ptr<Preprocessor> Value); 509 510 /// @} 511 /// @name ASTContext 512 /// @{ 513 514 bool hasASTContext() const { return Context != nullptr; } 515 516 ASTContext &getASTContext() const { 517 assert(Context && "Compiler instance has no AST context!"); 518 return *Context; 519 } 520 521 IntrusiveRefCntPtr<ASTContext> getASTContextPtr() const { 522 assert(Context && "Compiler instance has no AST context!"); 523 return Context; 524 } 525 526 void resetAndLeakASTContext() { 527 llvm::BuryPointer(Context.get()); 528 Context.resetWithoutRelease(); 529 } 530 531 /// setASTContext - Replace the current AST context. 532 void setASTContext(ASTContext *Value); 533 534 /// Replace the current Sema; the compiler instance takes ownership 535 /// of S. 536 void setSema(Sema *S); 537 538 /// @} 539 /// @name ASTConsumer 540 /// @{ 541 542 bool hasASTConsumer() const { return (bool)Consumer; } 543 544 ASTConsumer &getASTConsumer() const { 545 assert(Consumer && "Compiler instance has no AST consumer!"); 546 return *Consumer; 547 } 548 549 /// takeASTConsumer - Remove the current AST consumer and give ownership to 550 /// the caller. 551 std::unique_ptr<ASTConsumer> takeASTConsumer() { return std::move(Consumer); } 552 553 /// setASTConsumer - Replace the current AST consumer; the compiler instance 554 /// takes ownership of \p Value. 555 void setASTConsumer(std::unique_ptr<ASTConsumer> Value); 556 557 /// @} 558 /// @name Semantic analysis 559 /// @{ 560 bool hasSema() const { return (bool)TheSema; } 561 562 Sema &getSema() const { 563 assert(TheSema && "Compiler instance has no Sema object!"); 564 return *TheSema; 565 } 566 567 std::unique_ptr<Sema> takeSema(); 568 void resetAndLeakSema(); 569 570 /// @} 571 /// @name Module Management 572 /// @{ 573 574 IntrusiveRefCntPtr<ASTReader> getASTReader() const; 575 void setASTReader(IntrusiveRefCntPtr<ASTReader> Reader); 576 577 std::shared_ptr<ModuleDependencyCollector> getModuleDepCollector() const; 578 void setModuleDepCollector( 579 std::shared_ptr<ModuleDependencyCollector> Collector); 580 581 std::shared_ptr<PCHContainerOperations> getPCHContainerOperations() const { 582 return ThePCHContainerOperations; 583 } 584 585 /// Return the appropriate PCHContainerWriter depending on the 586 /// current CodeGenOptions. 587 const PCHContainerWriter &getPCHContainerWriter() const { 588 assert(Invocation && "cannot determine module format without invocation"); 589 StringRef Format = getHeaderSearchOpts().ModuleFormat; 590 auto *Writer = ThePCHContainerOperations->getWriterOrNull(Format); 591 if (!Writer) { 592 if (Diagnostics) 593 Diagnostics->Report(diag::err_module_format_unhandled) << Format; 594 llvm::report_fatal_error("unknown module format"); 595 } 596 return *Writer; 597 } 598 599 /// Return the appropriate PCHContainerReader depending on the 600 /// current CodeGenOptions. 601 const PCHContainerReader &getPCHContainerReader() const { 602 assert(Invocation && "cannot determine module format without invocation"); 603 StringRef Format = getHeaderSearchOpts().ModuleFormat; 604 auto *Reader = ThePCHContainerOperations->getReaderOrNull(Format); 605 if (!Reader) { 606 if (Diagnostics) 607 Diagnostics->Report(diag::err_module_format_unhandled) << Format; 608 llvm::report_fatal_error("unknown module format"); 609 } 610 return *Reader; 611 } 612 613 /// @} 614 /// @name Code Completion 615 /// @{ 616 617 bool hasCodeCompletionConsumer() const { return (bool)CompletionConsumer; } 618 619 CodeCompleteConsumer &getCodeCompletionConsumer() const { 620 assert(CompletionConsumer && 621 "Compiler instance has no code completion consumer!"); 622 return *CompletionConsumer; 623 } 624 625 /// setCodeCompletionConsumer - Replace the current code completion consumer; 626 /// the compiler instance takes ownership of \p Value. 627 void setCodeCompletionConsumer(CodeCompleteConsumer *Value); 628 629 /// @} 630 /// @name Frontend timer 631 /// @{ 632 633 llvm::TimerGroup &getTimerGroup() const { return *timerGroup; } 634 635 llvm::Timer &getFrontendTimer() const { 636 assert(FrontendTimer && "Compiler instance has no frontend timer!"); 637 return *FrontendTimer; 638 } 639 640 /// @} 641 /// @name Failed modules set 642 /// @{ 643 644 bool hasFailedModulesSet() const { return (bool)FailedModules; } 645 646 void createFailedModulesSet() { 647 FailedModules = std::make_shared<FailedModulesSet>(); 648 } 649 650 std::shared_ptr<FailedModulesSet> getFailedModulesSetPtr() const { 651 return FailedModules; 652 } 653 654 void setFailedModulesSet(std::shared_ptr<FailedModulesSet> FMS) { 655 FailedModules = FMS; 656 } 657 658 /// } 659 /// @name Output Files 660 /// @{ 661 662 /// clearOutputFiles - Clear the output file list. The underlying output 663 /// streams must have been closed beforehand. 664 /// 665 /// \param EraseFiles - If true, attempt to erase the files from disk. 666 void clearOutputFiles(bool EraseFiles); 667 668 /// @} 669 /// @name Construction Utility Methods 670 /// @{ 671 672 /// Create the diagnostics engine using the invocation's diagnostic options 673 /// and replace any existing one with it. 674 /// 675 /// Note that this routine also replaces the diagnostic client, 676 /// allocating one if one is not provided. 677 /// 678 /// \param VFS is used for any IO needed when creating DiagnosticsEngine. It 679 /// doesn't replace VFS in the CompilerInstance (if any). 680 /// 681 /// \param Client If non-NULL, a diagnostic client that will be 682 /// attached to (and, then, owned by) the DiagnosticsEngine inside this AST 683 /// unit. 684 /// 685 /// \param ShouldOwnClient If Client is non-NULL, specifies whether 686 /// the diagnostic object should take ownership of the client. 687 void createDiagnostics(llvm::vfs::FileSystem &VFS, 688 DiagnosticConsumer *Client = nullptr, 689 bool ShouldOwnClient = true); 690 691 /// Create a DiagnosticsEngine object with a the TextDiagnosticPrinter. 692 /// 693 /// If no diagnostic client is provided, this creates a 694 /// DiagnosticConsumer that is owned by the returned diagnostic 695 /// object, if using directly the caller is responsible for 696 /// releasing the returned DiagnosticsEngine's client eventually. 697 /// 698 /// \param Opts - The diagnostic options; note that the created text 699 /// diagnostic object contains a reference to these options. 700 /// 701 /// \param Client If non-NULL, a diagnostic client that will be 702 /// attached to (and, then, owned by) the returned DiagnosticsEngine 703 /// object. 704 /// 705 /// \param CodeGenOpts If non-NULL, the code gen options in use, which may be 706 /// used by some diagnostics printers (for logging purposes only). 707 /// 708 /// \return The new object on success, or null on failure. 709 static IntrusiveRefCntPtr<DiagnosticsEngine> 710 createDiagnostics(llvm::vfs::FileSystem &VFS, DiagnosticOptions *Opts, 711 DiagnosticConsumer *Client = nullptr, 712 bool ShouldOwnClient = true, 713 const CodeGenOptions *CodeGenOpts = nullptr); 714 715 /// Create the file manager and replace any existing one with it. 716 /// 717 /// \return The new file manager on success, or null on failure. 718 FileManager * 719 createFileManager(IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS = nullptr); 720 721 /// Create the source manager and replace any existing one with it. 722 void createSourceManager(FileManager &FileMgr); 723 724 /// Create the preprocessor, using the invocation, file, and source managers, 725 /// and replace any existing one with it. 726 void createPreprocessor(TranslationUnitKind TUKind); 727 728 std::string getSpecificModuleCachePath(StringRef ModuleHash); 729 std::string getSpecificModuleCachePath() { 730 return getSpecificModuleCachePath(getInvocation().getModuleHash()); 731 } 732 733 /// Create the AST context. 734 void createASTContext(); 735 736 /// Create an external AST source to read a PCH file and attach it to the AST 737 /// context. 738 void createPCHExternalASTSource( 739 StringRef Path, DisableValidationForModuleKind DisableValidation, 740 bool AllowPCHWithCompilerErrors, void *DeserializationListener, 741 bool OwnDeserializationListener); 742 743 /// Create an external AST source to read a PCH file. 744 /// 745 /// \return - The new object on success, or null on failure. 746 static IntrusiveRefCntPtr<ASTReader> createPCHExternalASTSource( 747 StringRef Path, StringRef Sysroot, 748 DisableValidationForModuleKind DisableValidation, 749 bool AllowPCHWithCompilerErrors, Preprocessor &PP, 750 InMemoryModuleCache &ModuleCache, ASTContext &Context, 751 const PCHContainerReader &PCHContainerRdr, 752 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions, 753 ArrayRef<std::shared_ptr<DependencyCollector>> DependencyCollectors, 754 void *DeserializationListener, bool OwnDeserializationListener, 755 bool Preamble, bool UseGlobalModuleIndex); 756 757 /// Create a code completion consumer using the invocation; note that this 758 /// will cause the source manager to truncate the input source file at the 759 /// completion point. 760 void createCodeCompletionConsumer(); 761 762 /// Create a code completion consumer to print code completion results, at 763 /// \p Filename, \p Line, and \p Column, to the given output stream \p OS. 764 static CodeCompleteConsumer *createCodeCompletionConsumer( 765 Preprocessor &PP, StringRef Filename, unsigned Line, unsigned Column, 766 const CodeCompleteOptions &Opts, raw_ostream &OS); 767 768 /// Create the Sema object to be used for parsing. 769 void createSema(TranslationUnitKind TUKind, 770 CodeCompleteConsumer *CompletionConsumer); 771 772 /// Create the frontend timer and replace any existing one with it. 773 void createFrontendTimer(); 774 775 /// Create the default output file (from the invocation's options) and add it 776 /// to the list of tracked output files. 777 /// 778 /// The files created by this are usually removed on signal, and, depending 779 /// on FrontendOptions, may also use a temporary file (that is, the data is 780 /// written to a temporary file which will atomically replace the target 781 /// output on success). 782 /// 783 /// \return - Null on error. 784 std::unique_ptr<raw_pwrite_stream> createDefaultOutputFile( 785 bool Binary = true, StringRef BaseInput = "", StringRef Extension = "", 786 bool RemoveFileOnSignal = true, bool CreateMissingDirectories = false, 787 bool ForceUseTemporary = false); 788 789 /// Create a new output file, optionally deriving the output path name, and 790 /// add it to the list of tracked output files. 791 /// 792 /// \return - Null on error. 793 std::unique_ptr<raw_pwrite_stream> 794 createOutputFile(StringRef OutputPath, bool Binary, bool RemoveFileOnSignal, 795 bool UseTemporary, bool CreateMissingDirectories = false); 796 797 private: 798 /// Create a new output file and add it to the list of tracked output files. 799 /// 800 /// If \p OutputPath is empty, then createOutputFile will derive an output 801 /// path location as \p BaseInput, with any suffix removed, and \p Extension 802 /// appended. If \p OutputPath is not stdout and \p UseTemporary 803 /// is true, createOutputFile will create a new temporary file that must be 804 /// renamed to \p OutputPath in the end. 805 /// 806 /// \param OutputPath - If given, the path to the output file. 807 /// \param Binary - The mode to open the file in. 808 /// \param RemoveFileOnSignal - Whether the file should be registered with 809 /// llvm::sys::RemoveFileOnSignal. Note that this is not safe for 810 /// multithreaded use, as the underlying signal mechanism is not reentrant 811 /// \param UseTemporary - Create a new temporary file that must be renamed to 812 /// OutputPath in the end. 813 /// \param CreateMissingDirectories - When \p UseTemporary is true, create 814 /// missing directories in the output path. 815 Expected<std::unique_ptr<raw_pwrite_stream>> 816 createOutputFileImpl(StringRef OutputPath, bool Binary, 817 bool RemoveFileOnSignal, bool UseTemporary, 818 bool CreateMissingDirectories); 819 820 public: 821 std::unique_ptr<raw_pwrite_stream> createNullOutputFile(); 822 823 /// @} 824 /// @name Initialization Utility Methods 825 /// @{ 826 827 /// InitializeSourceManager - Initialize the source manager to set InputFile 828 /// as the main file. 829 /// 830 /// \return True on success. 831 bool InitializeSourceManager(const FrontendInputFile &Input); 832 833 /// InitializeSourceManager - Initialize the source manager to set InputFile 834 /// as the main file. 835 /// 836 /// \return True on success. 837 static bool InitializeSourceManager(const FrontendInputFile &Input, 838 DiagnosticsEngine &Diags, 839 FileManager &FileMgr, 840 SourceManager &SourceMgr); 841 842 /// @} 843 844 void setOutputStream(std::unique_ptr<llvm::raw_pwrite_stream> OutStream) { 845 OutputStream = std::move(OutStream); 846 } 847 848 std::unique_ptr<llvm::raw_pwrite_stream> takeOutputStream() { 849 return std::move(OutputStream); 850 } 851 852 void createASTReader(); 853 854 bool loadModuleFile(StringRef FileName, 855 serialization::ModuleFile *&LoadedModuleFile); 856 857 private: 858 /// Find a module, potentially compiling it, before reading its AST. This is 859 /// the guts of loadModule. 860 /// 861 /// For prebuilt modules, the Module is not expected to exist in 862 /// HeaderSearch's ModuleMap. If a ModuleFile by that name is in the 863 /// ModuleManager, then it will be loaded and looked up. 864 /// 865 /// For implicit modules, the Module is expected to already be in the 866 /// ModuleMap. First attempt to load it from the given path on disk. If that 867 /// fails, defer to compileModuleAndReadAST, which will first build and then 868 /// load it. 869 ModuleLoadResult findOrCompileModuleAndReadAST(StringRef ModuleName, 870 SourceLocation ImportLoc, 871 SourceLocation ModuleNameLoc, 872 bool IsInclusionDirective); 873 874 public: 875 ModuleLoadResult loadModule(SourceLocation ImportLoc, ModuleIdPath Path, 876 Module::NameVisibilityKind Visibility, 877 bool IsInclusionDirective) override; 878 879 void createModuleFromSource(SourceLocation ImportLoc, StringRef ModuleName, 880 StringRef Source) override; 881 882 void makeModuleVisible(Module *Mod, Module::NameVisibilityKind Visibility, 883 SourceLocation ImportLoc) override; 884 885 bool hadModuleLoaderFatalFailure() const { 886 return ModuleLoader::HadFatalFailure; 887 } 888 889 GlobalModuleIndex *loadGlobalModuleIndex(SourceLocation TriggerLoc) override; 890 891 bool lookupMissingImports(StringRef Name, SourceLocation TriggerLoc) override; 892 893 void addDependencyCollector(std::shared_ptr<DependencyCollector> Listener) { 894 DependencyCollectors.push_back(std::move(Listener)); 895 } 896 897 void setExternalSemaSource(IntrusiveRefCntPtr<ExternalSemaSource> ESS); 898 899 InMemoryModuleCache &getModuleCache() const { return *ModuleCache; } 900 }; 901 902 } // end namespace clang 903 904 #endif 905