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"
40 class CodeCompleteConsumer;
41 class DiagnosticsEngine;
42 class DiagnosticConsumer;
43 class ExternalASTSource;
53 /// CompilerInstance - Helper class for managing a single instance of the Clang
56 /// The CompilerInstance serves two purposes:
57 /// (1) It manages the various objects which are necessary to run the compiler,
58 /// for example the preprocessor, the target information, and the AST
60 /// (2) It provides utility routines for constructing and manipulating the
61 /// common Clang objects.
63 /// The compiler instance generally owns the instance of all the objects that it
64 /// manages. However, clients can still share objects by manually setting the
65 /// object and retaking ownership prior to destroying the CompilerInstance.
67 /// The compiler instance is intended to simplify clients, but not to lock them
68 /// in to the compiler instance for everything. When possible, utility functions
69 /// come in two forms; a short form that reuses the CompilerInstance objects,
70 /// and a long form that takes explicit instances of any required objects.
71 class CompilerInstance : public ModuleLoader {
72 /// The options used in this compiler instance.
73 IntrusiveRefCntPtr<CompilerInvocation> Invocation;
75 /// The diagnostics engine instance.
76 IntrusiveRefCntPtr<DiagnosticsEngine> Diagnostics;
78 /// The target being compiled for.
79 IntrusiveRefCntPtr<TargetInfo> Target;
81 /// The virtual file system.
82 IntrusiveRefCntPtr<vfs::FileSystem> VirtualFileSystem;
85 IntrusiveRefCntPtr<FileManager> FileMgr;
87 /// The source manager.
88 IntrusiveRefCntPtr<SourceManager> SourceMgr;
91 IntrusiveRefCntPtr<Preprocessor> PP;
94 IntrusiveRefCntPtr<ASTContext> Context;
97 std::unique_ptr<ASTConsumer> Consumer;
99 /// The code completion consumer.
100 std::unique_ptr<CodeCompleteConsumer> CompletionConsumer;
102 /// \brief The semantic analysis object.
103 std::unique_ptr<Sema> TheSema;
105 /// \brief The frontend timer group.
106 std::unique_ptr<llvm::TimerGroup> FrontendTimerGroup;
108 /// \brief The frontend timer.
109 std::unique_ptr<llvm::Timer> FrontendTimer;
111 /// \brief The ASTReader, if one exists.
112 IntrusiveRefCntPtr<ASTReader> ModuleManager;
114 /// \brief The module dependency collector for crashdumps
115 std::shared_ptr<ModuleDependencyCollector> ModuleDepCollector;
117 /// \brief The module provider.
118 std::shared_ptr<PCHContainerOperations> ThePCHContainerOperations;
120 /// \brief The dependency file generator.
121 std::unique_ptr<DependencyFileGenerator> TheDependencyFileGenerator;
123 std::vector<std::shared_ptr<DependencyCollector>> DependencyCollectors;
125 /// \brief The set of top-level modules that has already been loaded,
126 /// along with the module map
127 llvm::DenseMap<const IdentifierInfo *, Module *> KnownModules;
129 /// \brief Module names that have an override for the target file.
130 llvm::StringMap<std::string> ModuleFileOverrides;
132 /// \brief Module files that we've explicitly loaded via \ref loadModuleFile,
133 /// and their dependencies.
134 llvm::StringSet<> ExplicitlyLoadedModuleFiles;
136 /// \brief The location of the module-import keyword for the last module
138 SourceLocation LastModuleImportLoc;
140 /// \brief The result of the last module import.
142 ModuleLoadResult LastModuleImportResult;
144 /// \brief Whether we should (re)build the global module index once we
145 /// have finished with this translation unit.
146 bool BuildGlobalModuleIndex;
148 /// \brief We have a full global module index, with all modules.
149 bool HaveFullGlobalModuleIndex;
151 /// \brief One or more modules failed to build.
152 bool ModuleBuildFailed;
154 /// \brief Holds information about the output file.
156 /// If TempFilename is not empty we must rename it to Filename at the end.
157 /// TempFilename may be empty and Filename non-empty if creating the temporary
160 std::string Filename;
161 std::string TempFilename;
162 std::unique_ptr<raw_ostream> OS;
164 OutputFile(std::string filename, std::string tempFilename,
165 std::unique_ptr<raw_ostream> OS)
166 : Filename(std::move(filename)), TempFilename(std::move(tempFilename)),
168 OutputFile(OutputFile &&O)
169 : Filename(std::move(O.Filename)),
170 TempFilename(std::move(O.TempFilename)), OS(std::move(O.OS)) {}
173 /// If the output doesn't support seeking (terminal, pipe). we switch
174 /// the stream to a buffer_ostream. These are the buffer and the original
176 std::unique_ptr<llvm::raw_fd_ostream> NonSeekStream;
178 /// The list of active output files.
179 std::list<OutputFile> OutputFiles;
181 CompilerInstance(const CompilerInstance &) = delete;
182 void operator=(const CompilerInstance &) = delete;
184 explicit CompilerInstance(
185 std::shared_ptr<PCHContainerOperations> PCHContainerOps =
186 std::make_shared<RawPCHContainerOperations>(),
187 bool BuildingModule = false);
188 ~CompilerInstance() override;
190 /// @name High-Level Operations
193 /// ExecuteAction - Execute the provided action against the compiler's
194 /// CompilerInvocation object.
196 /// This function makes the following assumptions:
198 /// - The invocation options should be initialized. This function does not
199 /// handle the '-help' or '-version' options, clients should handle those
202 /// - The diagnostics engine should have already been created by the client.
204 /// - No other CompilerInstance state should have been initialized (this is
205 /// an unchecked error).
207 /// - Clients should have initialized any LLVM target features that may be
210 /// - Clients should eventually call llvm_shutdown() upon the completion of
211 /// this routine to ensure that any managed objects are properly destroyed.
213 /// Note that this routine may write output to 'stderr'.
215 /// \param Act - The action to execute.
216 /// \return - True on success.
218 // FIXME: This function should take the stream to write any debugging /
219 // verbose output to as an argument.
221 // FIXME: Eliminate the llvm_shutdown requirement, that should either be part
222 // of the context or else not CompilerInstance specific.
223 bool ExecuteAction(FrontendAction &Act);
226 /// @name Compiler Invocation and Options
229 bool hasInvocation() const { return Invocation != nullptr; }
231 CompilerInvocation &getInvocation() {
232 assert(Invocation && "Compiler instance has no invocation!");
236 /// setInvocation - Replace the current invocation.
237 void setInvocation(CompilerInvocation *Value);
239 /// \brief Indicates whether we should (re)build the global module index.
240 bool shouldBuildGlobalModuleIndex() const;
242 /// \brief Set the flag indicating whether we should (re)build the global
244 void setBuildGlobalModuleIndex(bool Build) {
245 BuildGlobalModuleIndex = Build;
249 /// @name Forwarding Methods
252 AnalyzerOptionsRef getAnalyzerOpts() {
253 return Invocation->getAnalyzerOpts();
256 CodeGenOptions &getCodeGenOpts() {
257 return Invocation->getCodeGenOpts();
259 const CodeGenOptions &getCodeGenOpts() const {
260 return Invocation->getCodeGenOpts();
263 DependencyOutputOptions &getDependencyOutputOpts() {
264 return Invocation->getDependencyOutputOpts();
266 const DependencyOutputOptions &getDependencyOutputOpts() const {
267 return Invocation->getDependencyOutputOpts();
270 DiagnosticOptions &getDiagnosticOpts() {
271 return Invocation->getDiagnosticOpts();
273 const DiagnosticOptions &getDiagnosticOpts() const {
274 return Invocation->getDiagnosticOpts();
277 FileSystemOptions &getFileSystemOpts() {
278 return Invocation->getFileSystemOpts();
280 const FileSystemOptions &getFileSystemOpts() const {
281 return Invocation->getFileSystemOpts();
284 FrontendOptions &getFrontendOpts() {
285 return Invocation->getFrontendOpts();
287 const FrontendOptions &getFrontendOpts() const {
288 return Invocation->getFrontendOpts();
291 HeaderSearchOptions &getHeaderSearchOpts() {
292 return Invocation->getHeaderSearchOpts();
294 const HeaderSearchOptions &getHeaderSearchOpts() const {
295 return Invocation->getHeaderSearchOpts();
298 LangOptions &getLangOpts() {
299 return *Invocation->getLangOpts();
301 const LangOptions &getLangOpts() const {
302 return *Invocation->getLangOpts();
305 PreprocessorOptions &getPreprocessorOpts() {
306 return Invocation->getPreprocessorOpts();
308 const PreprocessorOptions &getPreprocessorOpts() const {
309 return Invocation->getPreprocessorOpts();
312 PreprocessorOutputOptions &getPreprocessorOutputOpts() {
313 return Invocation->getPreprocessorOutputOpts();
315 const PreprocessorOutputOptions &getPreprocessorOutputOpts() const {
316 return Invocation->getPreprocessorOutputOpts();
319 TargetOptions &getTargetOpts() {
320 return Invocation->getTargetOpts();
322 const TargetOptions &getTargetOpts() const {
323 return Invocation->getTargetOpts();
327 /// @name Diagnostics Engine
330 bool hasDiagnostics() const { return Diagnostics != nullptr; }
332 /// Get the current diagnostics engine.
333 DiagnosticsEngine &getDiagnostics() const {
334 assert(Diagnostics && "Compiler instance has no diagnostics!");
338 /// setDiagnostics - Replace the current diagnostics engine.
339 void setDiagnostics(DiagnosticsEngine *Value);
341 DiagnosticConsumer &getDiagnosticClient() const {
342 assert(Diagnostics && Diagnostics->getClient() &&
343 "Compiler instance has no diagnostic client!");
344 return *Diagnostics->getClient();
348 /// @name Target Info
351 bool hasTarget() const { return Target != nullptr; }
353 TargetInfo &getTarget() const {
354 assert(Target && "Compiler instance has no target!");
358 /// Replace the current diagnostics engine.
359 void setTarget(TargetInfo *Value);
362 /// @name Virtual File System
365 bool hasVirtualFileSystem() const { return VirtualFileSystem != nullptr; }
367 vfs::FileSystem &getVirtualFileSystem() const {
368 assert(hasVirtualFileSystem() &&
369 "Compiler instance has no virtual file system");
370 return *VirtualFileSystem;
373 /// \brief Replace the current virtual file system.
375 /// \note Most clients should use setFileManager, which will implicitly reset
376 /// the virtual file system to the one contained in the file manager.
377 void setVirtualFileSystem(IntrusiveRefCntPtr<vfs::FileSystem> FS) {
378 VirtualFileSystem = FS;
382 /// @name File Manager
385 bool hasFileManager() const { return FileMgr != nullptr; }
387 /// Return the current file manager to the caller.
388 FileManager &getFileManager() const {
389 assert(FileMgr && "Compiler instance has no file manager!");
393 void resetAndLeakFileManager() {
394 BuryPointer(FileMgr.get());
395 FileMgr.resetWithoutRelease();
398 /// \brief Replace the current file manager and virtual file system.
399 void setFileManager(FileManager *Value);
402 /// @name Source Manager
405 bool hasSourceManager() const { return SourceMgr != nullptr; }
407 /// Return the current source manager.
408 SourceManager &getSourceManager() const {
409 assert(SourceMgr && "Compiler instance has no source manager!");
413 void resetAndLeakSourceManager() {
414 BuryPointer(SourceMgr.get());
415 SourceMgr.resetWithoutRelease();
418 /// setSourceManager - Replace the current source manager.
419 void setSourceManager(SourceManager *Value);
422 /// @name Preprocessor
425 bool hasPreprocessor() const { return PP != nullptr; }
427 /// Return the current preprocessor.
428 Preprocessor &getPreprocessor() const {
429 assert(PP && "Compiler instance has no preprocessor!");
433 void resetAndLeakPreprocessor() {
434 BuryPointer(PP.get());
435 PP.resetWithoutRelease();
438 /// Replace the current preprocessor.
439 void setPreprocessor(Preprocessor *Value);
445 bool hasASTContext() const { return Context != nullptr; }
447 ASTContext &getASTContext() const {
448 assert(Context && "Compiler instance has no AST context!");
452 void resetAndLeakASTContext() {
453 BuryPointer(Context.get());
454 Context.resetWithoutRelease();
457 /// setASTContext - Replace the current AST context.
458 void setASTContext(ASTContext *Value);
460 /// \brief Replace the current Sema; the compiler instance takes ownership
462 void setSema(Sema *S);
465 /// @name ASTConsumer
468 bool hasASTConsumer() const { return (bool)Consumer; }
470 ASTConsumer &getASTConsumer() const {
471 assert(Consumer && "Compiler instance has no AST consumer!");
475 /// takeASTConsumer - Remove the current AST consumer and give ownership to
477 std::unique_ptr<ASTConsumer> takeASTConsumer() { return std::move(Consumer); }
479 /// setASTConsumer - Replace the current AST consumer; the compiler instance
480 /// takes ownership of \p Value.
481 void setASTConsumer(std::unique_ptr<ASTConsumer> Value);
484 /// @name Semantic analysis
486 bool hasSema() const { return (bool)TheSema; }
488 Sema &getSema() const {
489 assert(TheSema && "Compiler instance has no Sema object!");
493 std::unique_ptr<Sema> takeSema();
494 void resetAndLeakSema();
497 /// @name Module Management
500 IntrusiveRefCntPtr<ASTReader> getModuleManager() const;
501 void setModuleManager(IntrusiveRefCntPtr<ASTReader> Reader);
503 std::shared_ptr<ModuleDependencyCollector> getModuleDepCollector() const;
504 void setModuleDepCollector(
505 std::shared_ptr<ModuleDependencyCollector> Collector);
507 std::shared_ptr<PCHContainerOperations> getPCHContainerOperations() const {
508 return ThePCHContainerOperations;
512 /// @name Code Completion
515 bool hasCodeCompletionConsumer() const { return (bool)CompletionConsumer; }
517 CodeCompleteConsumer &getCodeCompletionConsumer() const {
518 assert(CompletionConsumer &&
519 "Compiler instance has no code completion consumer!");
520 return *CompletionConsumer;
523 /// setCodeCompletionConsumer - Replace the current code completion consumer;
524 /// the compiler instance takes ownership of \p Value.
525 void setCodeCompletionConsumer(CodeCompleteConsumer *Value);
528 /// @name Frontend timer
531 bool hasFrontendTimer() const { return (bool)FrontendTimer; }
533 llvm::Timer &getFrontendTimer() const {
534 assert(FrontendTimer && "Compiler instance has no frontend timer!");
535 return *FrontendTimer;
539 /// @name Output Files
542 /// addOutputFile - Add an output file onto the list of tracked output files.
544 /// \param OutFile - The output file info.
545 void addOutputFile(OutputFile &&OutFile);
547 /// clearOutputFiles - Clear the output file list, destroying the contained
550 /// \param EraseFiles - If true, attempt to erase the files from disk.
551 void clearOutputFiles(bool EraseFiles);
554 /// @name Construction Utility Methods
557 /// Create the diagnostics engine using the invocation's diagnostic options
558 /// and replace any existing one with it.
560 /// Note that this routine also replaces the diagnostic client,
561 /// allocating one if one is not provided.
563 /// \param Client If non-NULL, a diagnostic client that will be
564 /// attached to (and, then, owned by) the DiagnosticsEngine inside this AST
567 /// \param ShouldOwnClient If Client is non-NULL, specifies whether
568 /// the diagnostic object should take ownership of the client.
569 void createDiagnostics(DiagnosticConsumer *Client = nullptr,
570 bool ShouldOwnClient = true);
572 /// Create a DiagnosticsEngine object with a the TextDiagnosticPrinter.
574 /// If no diagnostic client is provided, this creates a
575 /// DiagnosticConsumer that is owned by the returned diagnostic
576 /// object, if using directly the caller is responsible for
577 /// releasing the returned DiagnosticsEngine's client eventually.
579 /// \param Opts - The diagnostic options; note that the created text
580 /// diagnostic object contains a reference to these options.
582 /// \param Client If non-NULL, a diagnostic client that will be
583 /// attached to (and, then, owned by) the returned DiagnosticsEngine
586 /// \param CodeGenOpts If non-NULL, the code gen options in use, which may be
587 /// used by some diagnostics printers (for logging purposes only).
589 /// \return The new object on success, or null on failure.
590 static IntrusiveRefCntPtr<DiagnosticsEngine>
591 createDiagnostics(DiagnosticOptions *Opts,
592 DiagnosticConsumer *Client = nullptr,
593 bool ShouldOwnClient = true,
594 const CodeGenOptions *CodeGenOpts = nullptr);
596 /// Create the file manager and replace any existing one with it.
597 void createFileManager();
599 /// Create the source manager and replace any existing one with it.
600 void createSourceManager(FileManager &FileMgr);
602 /// Create the preprocessor, using the invocation, file, and source managers,
603 /// and replace any existing one with it.
604 void createPreprocessor(TranslationUnitKind TUKind);
606 std::string getSpecificModuleCachePath();
608 /// Create the AST context.
609 void createASTContext();
611 /// Create an external AST source to read a PCH file and attach it to the AST
613 void createPCHExternalASTSource(StringRef Path, bool DisablePCHValidation,
614 bool AllowPCHWithCompilerErrors,
615 void *DeserializationListener,
616 bool OwnDeserializationListener);
618 /// Create an external AST source to read a PCH file.
620 /// \return - The new object on success, or null on failure.
621 static IntrusiveRefCntPtr<ASTReader> createPCHExternalASTSource(
622 StringRef Path, StringRef Sysroot, bool DisablePCHValidation,
623 bool AllowPCHWithCompilerErrors, Preprocessor &PP, ASTContext &Context,
624 const PCHContainerOperations &PCHContainerOps,
625 void *DeserializationListener, bool OwnDeserializationListener,
626 bool Preamble, bool UseGlobalModuleIndex);
628 /// Create a code completion consumer using the invocation; note that this
629 /// will cause the source manager to truncate the input source file at the
630 /// completion point.
631 void createCodeCompletionConsumer();
633 /// Create a code completion consumer to print code completion results, at
634 /// \p Filename, \p Line, and \p Column, to the given output stream \p OS.
635 static CodeCompleteConsumer *createCodeCompletionConsumer(
636 Preprocessor &PP, StringRef Filename, unsigned Line, unsigned Column,
637 const CodeCompleteOptions &Opts, raw_ostream &OS);
639 /// \brief Create the Sema object to be used for parsing.
640 void createSema(TranslationUnitKind TUKind,
641 CodeCompleteConsumer *CompletionConsumer);
643 /// Create the frontend timer and replace any existing one with it.
644 void createFrontendTimer();
646 /// Create the default output file (from the invocation's options) and add it
647 /// to the list of tracked output files.
649 /// The files created by this function always use temporary files to write to
650 /// their result (that is, the data is written to a temporary file which will
651 /// atomically replace the target output on success).
653 /// \return - Null on error.
654 raw_pwrite_stream *createDefaultOutputFile(bool Binary = true,
655 StringRef BaseInput = "",
656 StringRef Extension = "");
658 /// Create a new output file and add it to the list of tracked output files,
659 /// optionally deriving the output path name.
661 /// \return - Null on error.
662 raw_pwrite_stream *createOutputFile(StringRef OutputPath, bool Binary,
663 bool RemoveFileOnSignal,
664 StringRef BaseInput, StringRef Extension,
666 bool CreateMissingDirectories = false);
668 /// Create a new output file, optionally deriving the output path name.
670 /// If \p OutputPath is empty, then createOutputFile will derive an output
671 /// path location as \p BaseInput, with any suffix removed, and \p Extension
672 /// appended. If \p OutputPath is not stdout and \p UseTemporary
673 /// is true, createOutputFile will create a new temporary file that must be
674 /// renamed to \p OutputPath in the end.
676 /// \param OutputPath - If given, the path to the output file.
677 /// \param Error [out] - On failure, the error.
678 /// \param BaseInput - If \p OutputPath is empty, the input path name to use
679 /// for deriving the output path.
680 /// \param Extension - The extension to use for derived output names.
681 /// \param Binary - The mode to open the file in.
682 /// \param RemoveFileOnSignal - Whether the file should be registered with
683 /// llvm::sys::RemoveFileOnSignal. Note that this is not safe for
684 /// multithreaded use, as the underlying signal mechanism is not reentrant
685 /// \param UseTemporary - Create a new temporary file that must be renamed to
686 /// OutputPath in the end.
687 /// \param CreateMissingDirectories - When \p UseTemporary is true, create
688 /// missing directories in the output path.
689 /// \param ResultPathName [out] - If given, the result path name will be
690 /// stored here on success.
691 /// \param TempPathName [out] - If given, the temporary file path name
692 /// will be stored here on success.
693 std::unique_ptr<raw_pwrite_stream>
694 createOutputFile(StringRef OutputPath, std::error_code &Error, bool Binary,
695 bool RemoveFileOnSignal, StringRef BaseInput,
696 StringRef Extension, bool UseTemporary,
697 bool CreateMissingDirectories, std::string *ResultPathName,
698 std::string *TempPathName);
700 llvm::raw_null_ostream *createNullOutputFile();
703 /// @name Initialization Utility Methods
706 /// InitializeSourceManager - Initialize the source manager to set InputFile
707 /// as the main file.
709 /// \return True on success.
710 bool InitializeSourceManager(const FrontendInputFile &Input);
712 /// InitializeSourceManager - Initialize the source manager to set InputFile
713 /// as the main file.
715 /// \return True on success.
716 static bool InitializeSourceManager(const FrontendInputFile &Input,
717 DiagnosticsEngine &Diags,
718 FileManager &FileMgr,
719 SourceManager &SourceMgr,
720 const FrontendOptions &Opts);
724 // Create module manager.
725 void createModuleManager();
727 bool loadModuleFile(StringRef FileName);
729 ModuleLoadResult loadModule(SourceLocation ImportLoc, ModuleIdPath Path,
730 Module::NameVisibilityKind Visibility,
731 bool IsInclusionDirective) override;
733 void makeModuleVisible(Module *Mod, Module::NameVisibilityKind Visibility,
734 SourceLocation ImportLoc) override;
736 bool hadModuleLoaderFatalFailure() const {
737 return ModuleLoader::HadFatalFailure;
740 GlobalModuleIndex *loadGlobalModuleIndex(SourceLocation TriggerLoc) override;
742 bool lookupMissingImports(StringRef Name, SourceLocation TriggerLoc) override;
744 void addDependencyCollector(std::shared_ptr<DependencyCollector> Listener) {
745 DependencyCollectors.push_back(std::move(Listener));
749 } // end namespace clang