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