1 //===-- CompilerInstance.h - Clang Compiler Instance ------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #ifndef LLVM_CLANG_FRONTEND_COMPILERINSTANCE_H_
11 #define LLVM_CLANG_FRONTEND_COMPILERINSTANCE_H_
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/Frontend/PCHContainerOperations.h"
15 #include "clang/Basic/Diagnostic.h"
16 #include "clang/Basic/SourceManager.h"
17 #include "clang/Frontend/CompilerInvocation.h"
18 #include "clang/Frontend/Utils.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"
39 class CodeCompleteConsumer;
40 class DiagnosticsEngine;
41 class DiagnosticConsumer;
42 class ExternalASTSource;
52 /// CompilerInstance - Helper class for managing a single instance of the Clang
55 /// The CompilerInstance serves two purposes:
56 /// (1) It manages the various objects which are necessary to run the compiler,
57 /// for example the preprocessor, the target information, and the AST
59 /// (2) It provides utility routines for constructing and manipulating the
60 /// common Clang objects.
62 /// The compiler instance generally owns the instance of all the objects that it
63 /// manages. However, clients can still share objects by manually setting the
64 /// object and retaking ownership prior to destroying the CompilerInstance.
66 /// The compiler instance is intended to simplify clients, but not to lock them
67 /// in to the compiler instance for everything. When possible, utility functions
68 /// come in two forms; a short form that reuses the CompilerInstance objects,
69 /// and a long form that takes explicit instances of any required objects.
70 class CompilerInstance : public ModuleLoader {
71 /// The options used in this compiler instance.
72 IntrusiveRefCntPtr<CompilerInvocation> Invocation;
74 /// The diagnostics engine instance.
75 IntrusiveRefCntPtr<DiagnosticsEngine> Diagnostics;
77 /// The target being compiled for.
78 IntrusiveRefCntPtr<TargetInfo> Target;
80 /// The virtual file system.
81 IntrusiveRefCntPtr<vfs::FileSystem> VirtualFileSystem;
84 IntrusiveRefCntPtr<FileManager> FileMgr;
86 /// The source manager.
87 IntrusiveRefCntPtr<SourceManager> SourceMgr;
90 IntrusiveRefCntPtr<Preprocessor> PP;
93 IntrusiveRefCntPtr<ASTContext> Context;
96 std::unique_ptr<ASTConsumer> Consumer;
98 /// The code completion consumer.
99 std::unique_ptr<CodeCompleteConsumer> CompletionConsumer;
101 /// \brief The semantic analysis object.
102 std::unique_ptr<Sema> TheSema;
104 /// \brief The frontend timer
105 std::unique_ptr<llvm::Timer> FrontendTimer;
107 /// \brief The ASTReader, if one exists.
108 IntrusiveRefCntPtr<ASTReader> ModuleManager;
110 /// \brief The module dependency collector for crashdumps
111 std::shared_ptr<ModuleDependencyCollector> ModuleDepCollector;
113 /// \brief The module provider.
114 std::shared_ptr<PCHContainerOperations> ThePCHContainerOperations;
116 /// \brief The dependency file generator.
117 std::unique_ptr<DependencyFileGenerator> TheDependencyFileGenerator;
119 std::vector<std::shared_ptr<DependencyCollector>> DependencyCollectors;
121 /// \brief The set of top-level modules that has already been loaded,
122 /// along with the module map
123 llvm::DenseMap<const IdentifierInfo *, Module *> KnownModules;
125 /// \brief Module names that have an override for the target file.
126 llvm::StringMap<std::string> ModuleFileOverrides;
128 /// \brief Module files that we've explicitly loaded via \ref loadModuleFile,
129 /// and their dependencies.
130 llvm::StringSet<> ExplicitlyLoadedModuleFiles;
132 /// \brief The location of the module-import keyword for the last module
134 SourceLocation LastModuleImportLoc;
136 /// \brief The result of the last module import.
138 ModuleLoadResult LastModuleImportResult;
140 /// \brief Whether we should (re)build the global module index once we
141 /// have finished with this translation unit.
142 bool BuildGlobalModuleIndex;
144 /// \brief We have a full global module index, with all modules.
145 bool HaveFullGlobalModuleIndex;
147 /// \brief One or more modules failed to build.
148 bool ModuleBuildFailed;
150 /// \brief Holds information about the output file.
152 /// If TempFilename is not empty we must rename it to Filename at the end.
153 /// TempFilename may be empty and Filename non-empty if creating the temporary
156 std::string Filename;
157 std::string TempFilename;
158 std::unique_ptr<raw_ostream> OS;
160 OutputFile(const std::string &filename, const std::string &tempFilename,
161 std::unique_ptr<raw_ostream> OS)
162 : Filename(filename), TempFilename(tempFilename), OS(std::move(OS)) {}
163 OutputFile(OutputFile &&O)
164 : Filename(std::move(O.Filename)),
165 TempFilename(std::move(O.TempFilename)), OS(std::move(O.OS)) {}
168 /// If the output doesn't support seeking (terminal, pipe). we switch
169 /// the stream to a buffer_ostream. These are the buffer and the original
171 std::unique_ptr<llvm::raw_fd_ostream> NonSeekStream;
173 /// The list of active output files.
174 std::list<OutputFile> OutputFiles;
176 CompilerInstance(const CompilerInstance &) = delete;
177 void operator=(const CompilerInstance &) = delete;
179 explicit CompilerInstance(
180 std::shared_ptr<PCHContainerOperations> PCHContainerOps =
181 std::make_shared<RawPCHContainerOperations>(),
182 bool BuildingModule = false);
183 ~CompilerInstance() override;
185 /// @name High-Level Operations
188 /// ExecuteAction - Execute the provided action against the compiler's
189 /// CompilerInvocation object.
191 /// This function makes the following assumptions:
193 /// - The invocation options should be initialized. This function does not
194 /// handle the '-help' or '-version' options, clients should handle those
197 /// - The diagnostics engine should have already been created by the client.
199 /// - No other CompilerInstance state should have been initialized (this is
200 /// an unchecked error).
202 /// - Clients should have initialized any LLVM target features that may be
205 /// - Clients should eventually call llvm_shutdown() upon the completion of
206 /// this routine to ensure that any managed objects are properly destroyed.
208 /// Note that this routine may write output to 'stderr'.
210 /// \param Act - The action to execute.
211 /// \return - True on success.
213 // FIXME: This function should take the stream to write any debugging /
214 // verbose output to as an argument.
216 // FIXME: Eliminate the llvm_shutdown requirement, that should either be part
217 // of the context or else not CompilerInstance specific.
218 bool ExecuteAction(FrontendAction &Act);
221 /// @name Compiler Invocation and Options
224 bool hasInvocation() const { return Invocation != nullptr; }
226 CompilerInvocation &getInvocation() {
227 assert(Invocation && "Compiler instance has no invocation!");
231 /// setInvocation - Replace the current invocation.
232 void setInvocation(CompilerInvocation *Value);
234 /// \brief Indicates whether we should (re)build the global module index.
235 bool shouldBuildGlobalModuleIndex() const;
237 /// \brief Set the flag indicating whether we should (re)build the global
239 void setBuildGlobalModuleIndex(bool Build) {
240 BuildGlobalModuleIndex = Build;
244 /// @name Forwarding Methods
247 AnalyzerOptionsRef getAnalyzerOpts() {
248 return Invocation->getAnalyzerOpts();
251 CodeGenOptions &getCodeGenOpts() {
252 return Invocation->getCodeGenOpts();
254 const CodeGenOptions &getCodeGenOpts() const {
255 return Invocation->getCodeGenOpts();
258 DependencyOutputOptions &getDependencyOutputOpts() {
259 return Invocation->getDependencyOutputOpts();
261 const DependencyOutputOptions &getDependencyOutputOpts() const {
262 return Invocation->getDependencyOutputOpts();
265 DiagnosticOptions &getDiagnosticOpts() {
266 return Invocation->getDiagnosticOpts();
268 const DiagnosticOptions &getDiagnosticOpts() const {
269 return Invocation->getDiagnosticOpts();
272 FileSystemOptions &getFileSystemOpts() {
273 return Invocation->getFileSystemOpts();
275 const FileSystemOptions &getFileSystemOpts() const {
276 return Invocation->getFileSystemOpts();
279 FrontendOptions &getFrontendOpts() {
280 return Invocation->getFrontendOpts();
282 const FrontendOptions &getFrontendOpts() const {
283 return Invocation->getFrontendOpts();
286 HeaderSearchOptions &getHeaderSearchOpts() {
287 return Invocation->getHeaderSearchOpts();
289 const HeaderSearchOptions &getHeaderSearchOpts() const {
290 return Invocation->getHeaderSearchOpts();
293 LangOptions &getLangOpts() {
294 return *Invocation->getLangOpts();
296 const LangOptions &getLangOpts() const {
297 return *Invocation->getLangOpts();
300 PreprocessorOptions &getPreprocessorOpts() {
301 return Invocation->getPreprocessorOpts();
303 const PreprocessorOptions &getPreprocessorOpts() const {
304 return Invocation->getPreprocessorOpts();
307 PreprocessorOutputOptions &getPreprocessorOutputOpts() {
308 return Invocation->getPreprocessorOutputOpts();
310 const PreprocessorOutputOptions &getPreprocessorOutputOpts() const {
311 return Invocation->getPreprocessorOutputOpts();
314 TargetOptions &getTargetOpts() {
315 return Invocation->getTargetOpts();
317 const TargetOptions &getTargetOpts() const {
318 return Invocation->getTargetOpts();
322 /// @name Diagnostics Engine
325 bool hasDiagnostics() const { return Diagnostics != nullptr; }
327 /// Get the current diagnostics engine.
328 DiagnosticsEngine &getDiagnostics() const {
329 assert(Diagnostics && "Compiler instance has no diagnostics!");
333 /// setDiagnostics - Replace the current diagnostics engine.
334 void setDiagnostics(DiagnosticsEngine *Value);
336 DiagnosticConsumer &getDiagnosticClient() const {
337 assert(Diagnostics && Diagnostics->getClient() &&
338 "Compiler instance has no diagnostic client!");
339 return *Diagnostics->getClient();
343 /// @name Target Info
346 bool hasTarget() const { return Target != nullptr; }
348 TargetInfo &getTarget() const {
349 assert(Target && "Compiler instance has no target!");
353 /// Replace the current diagnostics engine.
354 void setTarget(TargetInfo *Value);
357 /// @name Virtual File System
360 bool hasVirtualFileSystem() const { return VirtualFileSystem != nullptr; }
362 vfs::FileSystem &getVirtualFileSystem() const {
363 assert(hasVirtualFileSystem() &&
364 "Compiler instance has no virtual file system");
365 return *VirtualFileSystem;
368 /// \brief Replace the current virtual file system.
370 /// \note Most clients should use setFileManager, which will implicitly reset
371 /// the virtual file system to the one contained in the file manager.
372 void setVirtualFileSystem(IntrusiveRefCntPtr<vfs::FileSystem> FS) {
373 VirtualFileSystem = FS;
377 /// @name File Manager
380 bool hasFileManager() const { return FileMgr != nullptr; }
382 /// Return the current file manager to the caller.
383 FileManager &getFileManager() const {
384 assert(FileMgr && "Compiler instance has no file manager!");
388 void resetAndLeakFileManager() {
389 BuryPointer(FileMgr.get());
390 FileMgr.resetWithoutRelease();
393 /// \brief Replace the current file manager and virtual file system.
394 void setFileManager(FileManager *Value);
397 /// @name Source Manager
400 bool hasSourceManager() const { return SourceMgr != nullptr; }
402 /// Return the current source manager.
403 SourceManager &getSourceManager() const {
404 assert(SourceMgr && "Compiler instance has no source manager!");
408 void resetAndLeakSourceManager() {
409 BuryPointer(SourceMgr.get());
410 SourceMgr.resetWithoutRelease();
413 /// setSourceManager - Replace the current source manager.
414 void setSourceManager(SourceManager *Value);
417 /// @name Preprocessor
420 bool hasPreprocessor() const { return PP != nullptr; }
422 /// Return the current preprocessor.
423 Preprocessor &getPreprocessor() const {
424 assert(PP && "Compiler instance has no preprocessor!");
428 void resetAndLeakPreprocessor() {
429 BuryPointer(PP.get());
430 PP.resetWithoutRelease();
433 /// Replace the current preprocessor.
434 void setPreprocessor(Preprocessor *Value);
440 bool hasASTContext() const { return Context != nullptr; }
442 ASTContext &getASTContext() const {
443 assert(Context && "Compiler instance has no AST context!");
447 void resetAndLeakASTContext() {
448 BuryPointer(Context.get());
449 Context.resetWithoutRelease();
452 /// setASTContext - Replace the current AST context.
453 void setASTContext(ASTContext *Value);
455 /// \brief Replace the current Sema; the compiler instance takes ownership
457 void setSema(Sema *S);
460 /// @name ASTConsumer
463 bool hasASTConsumer() const { return (bool)Consumer; }
465 ASTConsumer &getASTConsumer() const {
466 assert(Consumer && "Compiler instance has no AST consumer!");
470 /// takeASTConsumer - Remove the current AST consumer and give ownership to
472 std::unique_ptr<ASTConsumer> takeASTConsumer() { return std::move(Consumer); }
474 /// setASTConsumer - Replace the current AST consumer; the compiler instance
475 /// takes ownership of \p Value.
476 void setASTConsumer(std::unique_ptr<ASTConsumer> Value);
479 /// @name Semantic analysis
481 bool hasSema() const { return (bool)TheSema; }
483 Sema &getSema() const {
484 assert(TheSema && "Compiler instance has no Sema object!");
488 std::unique_ptr<Sema> takeSema();
489 void resetAndLeakSema();
492 /// @name Module Management
495 IntrusiveRefCntPtr<ASTReader> getModuleManager() const;
496 void setModuleManager(IntrusiveRefCntPtr<ASTReader> Reader);
498 std::shared_ptr<ModuleDependencyCollector> getModuleDepCollector() const;
499 void setModuleDepCollector(
500 std::shared_ptr<ModuleDependencyCollector> Collector);
502 std::shared_ptr<PCHContainerOperations> getPCHContainerOperations() const {
503 return ThePCHContainerOperations;
507 /// @name Code Completion
510 bool hasCodeCompletionConsumer() const { return (bool)CompletionConsumer; }
512 CodeCompleteConsumer &getCodeCompletionConsumer() const {
513 assert(CompletionConsumer &&
514 "Compiler instance has no code completion consumer!");
515 return *CompletionConsumer;
518 /// setCodeCompletionConsumer - Replace the current code completion consumer;
519 /// the compiler instance takes ownership of \p Value.
520 void setCodeCompletionConsumer(CodeCompleteConsumer *Value);
523 /// @name Frontend timer
526 bool hasFrontendTimer() const { return (bool)FrontendTimer; }
528 llvm::Timer &getFrontendTimer() const {
529 assert(FrontendTimer && "Compiler instance has no frontend timer!");
530 return *FrontendTimer;
534 /// @name Output Files
537 /// addOutputFile - Add an output file onto the list of tracked output files.
539 /// \param OutFile - The output file info.
540 void addOutputFile(OutputFile &&OutFile);
542 /// clearOutputFiles - Clear the output file list, destroying the contained
545 /// \param EraseFiles - If true, attempt to erase the files from disk.
546 void clearOutputFiles(bool EraseFiles);
549 /// @name Construction Utility Methods
552 /// Create the diagnostics engine using the invocation's diagnostic options
553 /// and replace any existing one with it.
555 /// Note that this routine also replaces the diagnostic client,
556 /// allocating one if one is not provided.
558 /// \param Client If non-NULL, a diagnostic client that will be
559 /// attached to (and, then, owned by) the DiagnosticsEngine inside this AST
562 /// \param ShouldOwnClient If Client is non-NULL, specifies whether
563 /// the diagnostic object should take ownership of the client.
564 void createDiagnostics(DiagnosticConsumer *Client = nullptr,
565 bool ShouldOwnClient = true);
567 /// Create a DiagnosticsEngine object with a the TextDiagnosticPrinter.
569 /// If no diagnostic client is provided, this creates a
570 /// DiagnosticConsumer that is owned by the returned diagnostic
571 /// object, if using directly the caller is responsible for
572 /// releasing the returned DiagnosticsEngine's client eventually.
574 /// \param Opts - The diagnostic options; note that the created text
575 /// diagnostic object contains a reference to these options.
577 /// \param Client If non-NULL, a diagnostic client that will be
578 /// attached to (and, then, owned by) the returned DiagnosticsEngine
581 /// \param CodeGenOpts If non-NULL, the code gen options in use, which may be
582 /// used by some diagnostics printers (for logging purposes only).
584 /// \return The new object on success, or null on failure.
585 static IntrusiveRefCntPtr<DiagnosticsEngine>
586 createDiagnostics(DiagnosticOptions *Opts,
587 DiagnosticConsumer *Client = nullptr,
588 bool ShouldOwnClient = true,
589 const CodeGenOptions *CodeGenOpts = nullptr);
591 /// Create the file manager and replace any existing one with it.
592 void createFileManager();
594 /// Create the source manager and replace any existing one with it.
595 void createSourceManager(FileManager &FileMgr);
597 /// Create the preprocessor, using the invocation, file, and source managers,
598 /// and replace any existing one with it.
599 void createPreprocessor(TranslationUnitKind TUKind);
601 std::string getSpecificModuleCachePath();
603 /// Create the AST context.
604 void createASTContext();
606 /// Create an external AST source to read a PCH file and attach it to the AST
608 void createPCHExternalASTSource(StringRef Path, bool DisablePCHValidation,
609 bool AllowPCHWithCompilerErrors,
610 void *DeserializationListener,
611 bool OwnDeserializationListener);
613 /// Create an external AST source to read a PCH file.
615 /// \return - The new object on success, or null on failure.
616 static IntrusiveRefCntPtr<ASTReader> createPCHExternalASTSource(
617 StringRef Path, const std::string &Sysroot, bool DisablePCHValidation,
618 bool AllowPCHWithCompilerErrors, Preprocessor &PP, ASTContext &Context,
619 const PCHContainerOperations &PCHContainerOps,
620 void *DeserializationListener, bool OwnDeserializationListener,
621 bool Preamble, bool UseGlobalModuleIndex);
623 /// Create a code completion consumer using the invocation; note that this
624 /// will cause the source manager to truncate the input source file at the
625 /// completion point.
626 void createCodeCompletionConsumer();
628 /// Create a code completion consumer to print code completion results, at
629 /// \p Filename, \p Line, and \p Column, to the given output stream \p OS.
630 static CodeCompleteConsumer *
631 createCodeCompletionConsumer(Preprocessor &PP, const std::string &Filename,
632 unsigned Line, unsigned Column,
633 const CodeCompleteOptions &Opts,
636 /// \brief Create the Sema object to be used for parsing.
637 void createSema(TranslationUnitKind TUKind,
638 CodeCompleteConsumer *CompletionConsumer);
640 /// Create the frontend timer and replace any existing one with it.
641 void createFrontendTimer();
643 /// Create the default output file (from the invocation's options) and add it
644 /// to the list of tracked output files.
646 /// The files created by this function always use temporary files to write to
647 /// their result (that is, the data is written to a temporary file which will
648 /// atomically replace the target output on success).
650 /// \return - Null on error.
651 raw_pwrite_stream *createDefaultOutputFile(bool Binary = true,
652 StringRef BaseInput = "",
653 StringRef Extension = "");
655 /// Create a new output file and add it to the list of tracked output files,
656 /// optionally deriving the output path name.
658 /// \return - Null on error.
659 raw_pwrite_stream *createOutputFile(StringRef OutputPath, bool Binary,
660 bool RemoveFileOnSignal,
661 StringRef BaseInput, StringRef Extension,
663 bool CreateMissingDirectories = false);
665 /// Create a new output file, optionally deriving the output path name.
667 /// If \p OutputPath is empty, then createOutputFile will derive an output
668 /// path location as \p BaseInput, with any suffix removed, and \p Extension
669 /// appended. If \p OutputPath is not stdout and \p UseTemporary
670 /// is true, createOutputFile will create a new temporary file that must be
671 /// renamed to \p OutputPath in the end.
673 /// \param OutputPath - If given, the path to the output file.
674 /// \param Error [out] - On failure, the error.
675 /// \param BaseInput - If \p OutputPath is empty, the input path name to use
676 /// for deriving the output path.
677 /// \param Extension - The extension to use for derived output names.
678 /// \param Binary - The mode to open the file in.
679 /// \param RemoveFileOnSignal - Whether the file should be registered with
680 /// llvm::sys::RemoveFileOnSignal. Note that this is not safe for
681 /// multithreaded use, as the underlying signal mechanism is not reentrant
682 /// \param UseTemporary - Create a new temporary file that must be renamed to
683 /// OutputPath in the end.
684 /// \param CreateMissingDirectories - When \p UseTemporary is true, create
685 /// missing directories in the output path.
686 /// \param ResultPathName [out] - If given, the result path name will be
687 /// stored here on success.
688 /// \param TempPathName [out] - If given, the temporary file path name
689 /// will be stored here on success.
690 std::unique_ptr<raw_pwrite_stream>
691 createOutputFile(StringRef OutputPath, std::error_code &Error, bool Binary,
692 bool RemoveFileOnSignal, StringRef BaseInput,
693 StringRef Extension, bool UseTemporary,
694 bool CreateMissingDirectories, std::string *ResultPathName,
695 std::string *TempPathName);
697 llvm::raw_null_ostream *createNullOutputFile();
700 /// @name Initialization Utility Methods
703 /// InitializeSourceManager - Initialize the source manager to set InputFile
704 /// as the main file.
706 /// \return True on success.
707 bool InitializeSourceManager(const FrontendInputFile &Input);
709 /// InitializeSourceManager - Initialize the source manager to set InputFile
710 /// as the main file.
712 /// \return True on success.
713 static bool InitializeSourceManager(const FrontendInputFile &Input,
714 DiagnosticsEngine &Diags,
715 FileManager &FileMgr,
716 SourceManager &SourceMgr,
717 const FrontendOptions &Opts);
721 // Create module manager.
722 void createModuleManager();
724 bool loadModuleFile(StringRef FileName);
726 ModuleLoadResult loadModule(SourceLocation ImportLoc, ModuleIdPath Path,
727 Module::NameVisibilityKind Visibility,
728 bool IsInclusionDirective) override;
730 void makeModuleVisible(Module *Mod, Module::NameVisibilityKind Visibility,
731 SourceLocation ImportLoc) override;
733 bool hadModuleLoaderFatalFailure() const {
734 return ModuleLoader::HadFatalFailure;
737 GlobalModuleIndex *loadGlobalModuleIndex(SourceLocation TriggerLoc) override;
739 bool lookupMissingImports(StringRef Name, SourceLocation TriggerLoc) override;
741 void addDependencyCollector(std::shared_ptr<DependencyCollector> Listener) {
742 DependencyCollectors.push_back(std::move(Listener));
746 } // end namespace clang