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