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/Basic/Diagnostic.h"
14 #include "clang/Basic/SourceManager.h"
15 #include "clang/Frontend/CompilerInvocation.h"
16 #include "clang/Frontend/Utils.h"
17 #include "clang/Lex/ModuleLoader.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/IntrusiveRefCntPtr.h"
21 #include "llvm/ADT/StringRef.h"
37 class CodeCompleteConsumer;
38 class DiagnosticsEngine;
39 class DiagnosticConsumer;
40 class ExternalASTSource;
50 /// CompilerInstance - Helper class for managing a single instance of the Clang
53 /// The CompilerInstance serves two purposes:
54 /// (1) It manages the various objects which are necessary to run the compiler,
55 /// for example the preprocessor, the target information, and the AST
57 /// (2) It provides utility routines for constructing and manipulating the
58 /// common Clang objects.
60 /// The compiler instance generally owns the instance of all the objects that it
61 /// manages. However, clients can still share objects by manually setting the
62 /// object and retaking ownership prior to destroying the CompilerInstance.
64 /// The compiler instance is intended to simplify clients, but not to lock them
65 /// in to the compiler instance for everything. When possible, utility functions
66 /// come in two forms; a short form that reuses the CompilerInstance objects,
67 /// and a long form that takes explicit instances of any required objects.
68 class CompilerInstance : public ModuleLoader {
69 /// The options used in this compiler instance.
70 IntrusiveRefCntPtr<CompilerInvocation> Invocation;
72 /// The diagnostics engine instance.
73 IntrusiveRefCntPtr<DiagnosticsEngine> Diagnostics;
75 /// The target being compiled for.
76 IntrusiveRefCntPtr<TargetInfo> Target;
78 /// The virtual file system.
79 IntrusiveRefCntPtr<vfs::FileSystem> VirtualFileSystem;
82 IntrusiveRefCntPtr<FileManager> FileMgr;
84 /// The source manager.
85 IntrusiveRefCntPtr<SourceManager> SourceMgr;
88 IntrusiveRefCntPtr<Preprocessor> PP;
91 IntrusiveRefCntPtr<ASTContext> Context;
94 std::unique_ptr<ASTConsumer> Consumer;
96 /// The code completion consumer.
97 std::unique_ptr<CodeCompleteConsumer> CompletionConsumer;
99 /// \brief The semantic analysis object.
100 std::unique_ptr<Sema> TheSema;
102 /// \brief The frontend timer
103 std::unique_ptr<llvm::Timer> FrontendTimer;
105 /// \brief The ASTReader, if one exists.
106 IntrusiveRefCntPtr<ASTReader> ModuleManager;
108 /// \brief The module dependency collector for crashdumps
109 std::shared_ptr<ModuleDependencyCollector> ModuleDepCollector;
111 /// \brief The dependency file generator.
112 std::unique_ptr<DependencyFileGenerator> TheDependencyFileGenerator;
114 std::vector<std::shared_ptr<DependencyCollector>> DependencyCollectors;
116 /// \brief The set of top-level modules that has already been loaded,
117 /// along with the module map
118 llvm::DenseMap<const IdentifierInfo *, Module *> KnownModules;
120 /// \brief The location of the module-import keyword for the last module
122 SourceLocation LastModuleImportLoc;
124 /// \brief The result of the last module import.
126 ModuleLoadResult LastModuleImportResult;
128 /// \brief Whether we should (re)build the global module index once we
129 /// have finished with this translation unit.
130 bool BuildGlobalModuleIndex;
132 /// \brief We have a full global module index, with all modules.
133 bool HaveFullGlobalModuleIndex;
135 /// \brief One or more modules failed to build.
136 bool ModuleBuildFailed;
138 /// \brief Holds information about the output file.
140 /// If TempFilename is not empty we must rename it to Filename at the end.
141 /// TempFilename may be empty and Filename non-empty if creating the temporary
144 std::string Filename;
145 std::string TempFilename;
148 OutputFile(const std::string &filename, const std::string &tempFilename,
150 : Filename(filename), TempFilename(tempFilename), OS(os) { }
153 /// The list of active output files.
154 std::list<OutputFile> OutputFiles;
156 CompilerInstance(const CompilerInstance &) LLVM_DELETED_FUNCTION;
157 void operator=(const CompilerInstance &) LLVM_DELETED_FUNCTION;
159 explicit CompilerInstance(bool BuildingModule = false);
162 /// @name High-Level Operations
165 /// ExecuteAction - Execute the provided action against the compiler's
166 /// CompilerInvocation object.
168 /// This function makes the following assumptions:
170 /// - The invocation options should be initialized. This function does not
171 /// handle the '-help' or '-version' options, clients should handle those
174 /// - The diagnostics engine should have already been created by the client.
176 /// - No other CompilerInstance state should have been initialized (this is
177 /// an unchecked error).
179 /// - Clients should have initialized any LLVM target features that may be
182 /// - Clients should eventually call llvm_shutdown() upon the completion of
183 /// this routine to ensure that any managed objects are properly destroyed.
185 /// Note that this routine may write output to 'stderr'.
187 /// \param Act - The action to execute.
188 /// \return - True on success.
190 // FIXME: This function should take the stream to write any debugging /
191 // verbose output to as an argument.
193 // FIXME: Eliminate the llvm_shutdown requirement, that should either be part
194 // of the context or else not CompilerInstance specific.
195 bool ExecuteAction(FrontendAction &Act);
198 /// @name Compiler Invocation and Options
201 bool hasInvocation() const { return Invocation != nullptr; }
203 CompilerInvocation &getInvocation() {
204 assert(Invocation && "Compiler instance has no invocation!");
208 /// setInvocation - Replace the current invocation.
209 void setInvocation(CompilerInvocation *Value);
211 /// \brief Indicates whether we should (re)build the global module index.
212 bool shouldBuildGlobalModuleIndex() const;
214 /// \brief Set the flag indicating whether we should (re)build the global
216 void setBuildGlobalModuleIndex(bool Build) {
217 BuildGlobalModuleIndex = Build;
221 /// @name Forwarding Methods
224 AnalyzerOptionsRef getAnalyzerOpts() {
225 return Invocation->getAnalyzerOpts();
228 CodeGenOptions &getCodeGenOpts() {
229 return Invocation->getCodeGenOpts();
231 const CodeGenOptions &getCodeGenOpts() const {
232 return Invocation->getCodeGenOpts();
235 DependencyOutputOptions &getDependencyOutputOpts() {
236 return Invocation->getDependencyOutputOpts();
238 const DependencyOutputOptions &getDependencyOutputOpts() const {
239 return Invocation->getDependencyOutputOpts();
242 DiagnosticOptions &getDiagnosticOpts() {
243 return Invocation->getDiagnosticOpts();
245 const DiagnosticOptions &getDiagnosticOpts() const {
246 return Invocation->getDiagnosticOpts();
249 const FileSystemOptions &getFileSystemOpts() const {
250 return Invocation->getFileSystemOpts();
253 FrontendOptions &getFrontendOpts() {
254 return Invocation->getFrontendOpts();
256 const FrontendOptions &getFrontendOpts() const {
257 return Invocation->getFrontendOpts();
260 HeaderSearchOptions &getHeaderSearchOpts() {
261 return Invocation->getHeaderSearchOpts();
263 const HeaderSearchOptions &getHeaderSearchOpts() const {
264 return Invocation->getHeaderSearchOpts();
267 LangOptions &getLangOpts() {
268 return *Invocation->getLangOpts();
270 const LangOptions &getLangOpts() const {
271 return *Invocation->getLangOpts();
274 PreprocessorOptions &getPreprocessorOpts() {
275 return Invocation->getPreprocessorOpts();
277 const PreprocessorOptions &getPreprocessorOpts() const {
278 return Invocation->getPreprocessorOpts();
281 PreprocessorOutputOptions &getPreprocessorOutputOpts() {
282 return Invocation->getPreprocessorOutputOpts();
284 const PreprocessorOutputOptions &getPreprocessorOutputOpts() const {
285 return Invocation->getPreprocessorOutputOpts();
288 TargetOptions &getTargetOpts() {
289 return Invocation->getTargetOpts();
291 const TargetOptions &getTargetOpts() const {
292 return Invocation->getTargetOpts();
296 /// @name Diagnostics Engine
299 bool hasDiagnostics() const { return Diagnostics != nullptr; }
301 /// Get the current diagnostics engine.
302 DiagnosticsEngine &getDiagnostics() const {
303 assert(Diagnostics && "Compiler instance has no diagnostics!");
307 /// setDiagnostics - Replace the current diagnostics engine.
308 void setDiagnostics(DiagnosticsEngine *Value);
310 DiagnosticConsumer &getDiagnosticClient() const {
311 assert(Diagnostics && Diagnostics->getClient() &&
312 "Compiler instance has no diagnostic client!");
313 return *Diagnostics->getClient();
317 /// @name Target Info
320 bool hasTarget() const { return Target != nullptr; }
322 TargetInfo &getTarget() const {
323 assert(Target && "Compiler instance has no target!");
327 /// Replace the current diagnostics engine.
328 void setTarget(TargetInfo *Value);
331 /// @name Virtual File System
334 bool hasVirtualFileSystem() const { return VirtualFileSystem != nullptr; }
336 vfs::FileSystem &getVirtualFileSystem() const {
337 assert(hasVirtualFileSystem() &&
338 "Compiler instance has no virtual file system");
339 return *VirtualFileSystem;
342 /// \brief Replace the current virtual file system.
344 /// \note Most clients should use setFileManager, which will implicitly reset
345 /// the virtual file system to the one contained in the file manager.
346 void setVirtualFileSystem(IntrusiveRefCntPtr<vfs::FileSystem> FS) {
347 VirtualFileSystem = FS;
351 /// @name File Manager
354 bool hasFileManager() const { return FileMgr != nullptr; }
356 /// Return the current file manager to the caller.
357 FileManager &getFileManager() const {
358 assert(FileMgr && "Compiler instance has no file manager!");
362 void resetAndLeakFileManager() {
363 BuryPointer(FileMgr.get());
364 FileMgr.resetWithoutRelease();
367 /// \brief Replace the current file manager and virtual file system.
368 void setFileManager(FileManager *Value);
371 /// @name Source Manager
374 bool hasSourceManager() const { return SourceMgr != nullptr; }
376 /// Return the current source manager.
377 SourceManager &getSourceManager() const {
378 assert(SourceMgr && "Compiler instance has no source manager!");
382 void resetAndLeakSourceManager() {
383 BuryPointer(SourceMgr.get());
384 SourceMgr.resetWithoutRelease();
387 /// setSourceManager - Replace the current source manager.
388 void setSourceManager(SourceManager *Value);
391 /// @name Preprocessor
394 bool hasPreprocessor() const { return PP != nullptr; }
396 /// Return the current preprocessor.
397 Preprocessor &getPreprocessor() const {
398 assert(PP && "Compiler instance has no preprocessor!");
402 void resetAndLeakPreprocessor() {
403 BuryPointer(PP.get());
404 PP.resetWithoutRelease();
407 /// Replace the current preprocessor.
408 void setPreprocessor(Preprocessor *Value);
414 bool hasASTContext() const { return Context != nullptr; }
416 ASTContext &getASTContext() const {
417 assert(Context && "Compiler instance has no AST context!");
421 void resetAndLeakASTContext() {
422 BuryPointer(Context.get());
423 Context.resetWithoutRelease();
426 /// setASTContext - Replace the current AST context.
427 void setASTContext(ASTContext *Value);
429 /// \brief Replace the current Sema; the compiler instance takes ownership
431 void setSema(Sema *S);
434 /// @name ASTConsumer
437 bool hasASTConsumer() const { return (bool)Consumer; }
439 ASTConsumer &getASTConsumer() const {
440 assert(Consumer && "Compiler instance has no AST consumer!");
444 /// takeASTConsumer - Remove the current AST consumer and give ownership to
446 ASTConsumer *takeASTConsumer() { return Consumer.release(); }
448 /// setASTConsumer - Replace the current AST consumer; the compiler instance
449 /// takes ownership of \p Value.
450 void setASTConsumer(ASTConsumer *Value);
453 /// @name Semantic analysis
455 bool hasSema() const { return (bool)TheSema; }
457 Sema &getSema() const {
458 assert(TheSema && "Compiler instance has no Sema object!");
462 Sema *takeSema() { return TheSema.release(); }
463 void resetAndLeakSema() { BuryPointer(TheSema.release()); }
466 /// @name Module Management
469 IntrusiveRefCntPtr<ASTReader> getModuleManager() const;
470 void setModuleManager(IntrusiveRefCntPtr<ASTReader> Reader);
472 std::shared_ptr<ModuleDependencyCollector> getModuleDepCollector() const;
473 void setModuleDepCollector(
474 std::shared_ptr<ModuleDependencyCollector> Collector);
477 /// @name Code Completion
480 bool hasCodeCompletionConsumer() const { return (bool)CompletionConsumer; }
482 CodeCompleteConsumer &getCodeCompletionConsumer() const {
483 assert(CompletionConsumer &&
484 "Compiler instance has no code completion consumer!");
485 return *CompletionConsumer;
488 /// takeCodeCompletionConsumer - Remove the current code completion consumer
489 /// and give ownership to the caller.
490 CodeCompleteConsumer *takeCodeCompletionConsumer() {
491 return CompletionConsumer.release();
494 /// setCodeCompletionConsumer - Replace the current code completion consumer;
495 /// the compiler instance takes ownership of \p Value.
496 void setCodeCompletionConsumer(CodeCompleteConsumer *Value);
499 /// @name Frontend timer
502 bool hasFrontendTimer() const { return (bool)FrontendTimer; }
504 llvm::Timer &getFrontendTimer() const {
505 assert(FrontendTimer && "Compiler instance has no frontend timer!");
506 return *FrontendTimer;
510 /// @name Output Files
513 /// addOutputFile - Add an output file onto the list of tracked output files.
515 /// \param OutFile - The output file info.
516 void addOutputFile(const OutputFile &OutFile);
518 /// clearOutputFiles - Clear the output file list, destroying the contained
521 /// \param EraseFiles - If true, attempt to erase the files from disk.
522 void clearOutputFiles(bool EraseFiles);
525 /// @name Construction Utility Methods
528 /// Create the diagnostics engine using the invocation's diagnostic options
529 /// and replace any existing one with it.
531 /// Note that this routine also replaces the diagnostic client,
532 /// allocating one if one is not provided.
534 /// \param Client If non-NULL, a diagnostic client that will be
535 /// attached to (and, then, owned by) the DiagnosticsEngine inside this AST
538 /// \param ShouldOwnClient If Client is non-NULL, specifies whether
539 /// the diagnostic object should take ownership of the client.
540 void createDiagnostics(DiagnosticConsumer *Client = nullptr,
541 bool ShouldOwnClient = true);
543 /// Create a DiagnosticsEngine object with a the TextDiagnosticPrinter.
545 /// If no diagnostic client is provided, this creates a
546 /// DiagnosticConsumer that is owned by the returned diagnostic
547 /// object, if using directly the caller is responsible for
548 /// releasing the returned DiagnosticsEngine's client eventually.
550 /// \param Opts - The diagnostic options; note that the created text
551 /// diagnostic object contains a reference to these options.
553 /// \param Client If non-NULL, a diagnostic client that will be
554 /// attached to (and, then, owned by) the returned DiagnosticsEngine
557 /// \param CodeGenOpts If non-NULL, the code gen options in use, which may be
558 /// used by some diagnostics printers (for logging purposes only).
560 /// \return The new object on success, or null on failure.
561 static IntrusiveRefCntPtr<DiagnosticsEngine>
562 createDiagnostics(DiagnosticOptions *Opts,
563 DiagnosticConsumer *Client = nullptr,
564 bool ShouldOwnClient = true,
565 const CodeGenOptions *CodeGenOpts = nullptr);
567 /// Create the file manager and replace any existing one with it.
568 void createFileManager();
570 /// Create the source manager and replace any existing one with it.
571 void createSourceManager(FileManager &FileMgr);
573 /// Create the preprocessor, using the invocation, file, and source managers,
574 /// and replace any existing one with it.
575 void createPreprocessor(TranslationUnitKind TUKind);
577 /// Create the AST context.
578 void createASTContext();
580 /// Create an external AST source to read a PCH file and attach it to the AST
582 void createPCHExternalASTSource(StringRef Path, bool DisablePCHValidation,
583 bool AllowPCHWithCompilerErrors,
584 void *DeserializationListener,
585 bool OwnDeserializationListener);
587 /// Create an external AST source to read a PCH file.
589 /// \return - The new object on success, or null on failure.
590 static ExternalASTSource *createPCHExternalASTSource(
591 StringRef Path, const std::string &Sysroot, bool DisablePCHValidation,
592 bool AllowPCHWithCompilerErrors, Preprocessor &PP, ASTContext &Context,
593 void *DeserializationListener, bool OwnDeserializationListener,
594 bool Preamble, bool UseGlobalModuleIndex);
596 /// Create a code completion consumer using the invocation; note that this
597 /// will cause the source manager to truncate the input source file at the
598 /// completion point.
599 void createCodeCompletionConsumer();
601 /// Create a code completion consumer to print code completion results, at
602 /// \p Filename, \p Line, and \p Column, to the given output stream \p OS.
603 static CodeCompleteConsumer *
604 createCodeCompletionConsumer(Preprocessor &PP, const std::string &Filename,
605 unsigned Line, unsigned Column,
606 const CodeCompleteOptions &Opts,
609 /// \brief Create the Sema object to be used for parsing.
610 void createSema(TranslationUnitKind TUKind,
611 CodeCompleteConsumer *CompletionConsumer);
613 /// Create the frontend timer and replace any existing one with it.
614 void createFrontendTimer();
616 /// Create the default output file (from the invocation's options) and add it
617 /// to the list of tracked output files.
619 /// The files created by this function always use temporary files to write to
620 /// their result (that is, the data is written to a temporary file which will
621 /// atomically replace the target output on success).
623 /// \return - Null on error.
624 llvm::raw_fd_ostream *
625 createDefaultOutputFile(bool Binary = true, StringRef BaseInput = "",
626 StringRef Extension = "");
628 /// Create a new output file and add it to the list of tracked output files,
629 /// optionally deriving the output path name.
631 /// \return - Null on error.
632 llvm::raw_fd_ostream *
633 createOutputFile(StringRef OutputPath,
634 bool Binary, bool RemoveFileOnSignal,
638 bool CreateMissingDirectories = false);
640 /// Create a new output file, optionally deriving the output path name.
642 /// If \p OutputPath is empty, then createOutputFile will derive an output
643 /// path location as \p BaseInput, with any suffix removed, and \p Extension
644 /// appended. If \p OutputPath is not stdout and \p UseTemporary
645 /// is true, createOutputFile will create a new temporary file that must be
646 /// renamed to \p OutputPath in the end.
648 /// \param OutputPath - If given, the path to the output file.
649 /// \param Error [out] - On failure, the error message.
650 /// \param BaseInput - If \p OutputPath is empty, the input path name to use
651 /// for deriving the output path.
652 /// \param Extension - The extension to use for derived output names.
653 /// \param Binary - The mode to open the file in.
654 /// \param RemoveFileOnSignal - Whether the file should be registered with
655 /// llvm::sys::RemoveFileOnSignal. Note that this is not safe for
656 /// multithreaded use, as the underlying signal mechanism is not reentrant
657 /// \param UseTemporary - Create a new temporary file that must be renamed to
658 /// OutputPath in the end.
659 /// \param CreateMissingDirectories - When \p UseTemporary is true, create
660 /// missing directories in the output path.
661 /// \param ResultPathName [out] - If given, the result path name will be
662 /// stored here on success.
663 /// \param TempPathName [out] - If given, the temporary file path name
664 /// will be stored here on success.
665 static llvm::raw_fd_ostream *
666 createOutputFile(StringRef OutputPath, std::string &Error,
667 bool Binary, bool RemoveFileOnSignal,
671 bool CreateMissingDirectories,
672 std::string *ResultPathName,
673 std::string *TempPathName);
675 llvm::raw_null_ostream *createNullOutputFile();
678 /// @name Initialization Utility Methods
681 /// InitializeSourceManager - Initialize the source manager to set InputFile
682 /// as the main file.
684 /// \return True on success.
685 bool InitializeSourceManager(const FrontendInputFile &Input);
687 /// InitializeSourceManager - Initialize the source manager to set InputFile
688 /// as the main file.
690 /// \return True on success.
691 static bool InitializeSourceManager(const FrontendInputFile &Input,
692 DiagnosticsEngine &Diags,
693 FileManager &FileMgr,
694 SourceManager &SourceMgr,
695 const FrontendOptions &Opts);
699 // Create module manager.
700 void createModuleManager();
702 ModuleLoadResult loadModule(SourceLocation ImportLoc, ModuleIdPath Path,
703 Module::NameVisibilityKind Visibility,
704 bool IsInclusionDirective) override;
706 void makeModuleVisible(Module *Mod, Module::NameVisibilityKind Visibility,
707 SourceLocation ImportLoc, bool Complain) override;
709 bool hadModuleLoaderFatalFailure() const {
710 return ModuleLoader::HadFatalFailure;
713 GlobalModuleIndex *loadGlobalModuleIndex(SourceLocation TriggerLoc) override;
715 bool lookupMissingImports(StringRef Name, SourceLocation TriggerLoc) override;
717 void addDependencyCollector(std::shared_ptr<DependencyCollector> Listener) {
718 DependencyCollectors.push_back(std::move(Listener));
722 } // end namespace clang