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