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/Basic/Diagnostic.h"
15 #include "clang/Basic/SourceManager.h"
16 #include "clang/Frontend/CompilerInvocation.h"
17 #include "clang/Frontend/Utils.h"
18 #include "clang/Lex/ModuleLoader.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/IntrusiveRefCntPtr.h"
22 #include "llvm/ADT/StringRef.h"
38 class CodeCompleteConsumer;
39 class DiagnosticsEngine;
40 class DiagnosticConsumer;
41 class ExternalASTSource;
51 /// CompilerInstance - Helper class for managing a single instance of the Clang
54 /// The CompilerInstance serves two purposes:
55 /// (1) It manages the various objects which are necessary to run the compiler,
56 /// for example the preprocessor, the target information, and the AST
58 /// (2) It provides utility routines for constructing and manipulating the
59 /// common Clang objects.
61 /// The compiler instance generally owns the instance of all the objects that it
62 /// manages. However, clients can still share objects by manually setting the
63 /// object and retaking ownership prior to destroying the CompilerInstance.
65 /// The compiler instance is intended to simplify clients, but not to lock them
66 /// in to the compiler instance for everything. When possible, utility functions
67 /// come in two forms; a short form that reuses the CompilerInstance objects,
68 /// and a long form that takes explicit instances of any required objects.
69 class CompilerInstance : public ModuleLoader {
70 /// The options used in this compiler instance.
71 IntrusiveRefCntPtr<CompilerInvocation> Invocation;
73 /// The diagnostics engine instance.
74 IntrusiveRefCntPtr<DiagnosticsEngine> Diagnostics;
76 /// The target being compiled for.
77 IntrusiveRefCntPtr<TargetInfo> Target;
79 /// The virtual file system.
80 IntrusiveRefCntPtr<vfs::FileSystem> VirtualFileSystem;
83 IntrusiveRefCntPtr<FileManager> FileMgr;
85 /// The source manager.
86 IntrusiveRefCntPtr<SourceManager> SourceMgr;
89 IntrusiveRefCntPtr<Preprocessor> PP;
92 IntrusiveRefCntPtr<ASTContext> Context;
95 std::unique_ptr<ASTConsumer> Consumer;
97 /// The code completion consumer.
98 std::unique_ptr<CodeCompleteConsumer> CompletionConsumer;
100 /// \brief The semantic analysis object.
101 std::unique_ptr<Sema> TheSema;
103 /// \brief The frontend timer
104 std::unique_ptr<llvm::Timer> FrontendTimer;
106 /// \brief The ASTReader, if one exists.
107 IntrusiveRefCntPtr<ASTReader> ModuleManager;
109 /// \brief The module dependency collector for crashdumps
110 std::shared_ptr<ModuleDependencyCollector> ModuleDepCollector;
112 /// \brief The dependency file generator.
113 std::unique_ptr<DependencyFileGenerator> TheDependencyFileGenerator;
115 std::vector<std::shared_ptr<DependencyCollector>> DependencyCollectors;
117 /// \brief The set of top-level modules that has already been loaded,
118 /// along with the module map
119 llvm::DenseMap<const IdentifierInfo *, Module *> KnownModules;
121 /// \brief Module names that have an override for the target file.
122 llvm::StringMap<std::string> ModuleFileOverrides;
124 /// \brief The location of the module-import keyword for the last module
126 SourceLocation LastModuleImportLoc;
128 /// \brief The result of the last module import.
130 ModuleLoadResult LastModuleImportResult;
132 /// \brief Whether we should (re)build the global module index once we
133 /// have finished with this translation unit.
134 bool BuildGlobalModuleIndex;
136 /// \brief We have a full global module index, with all modules.
137 bool HaveFullGlobalModuleIndex;
139 /// \brief One or more modules failed to build.
140 bool ModuleBuildFailed;
142 /// \brief Holds information about the output file.
144 /// If TempFilename is not empty we must rename it to Filename at the end.
145 /// TempFilename may be empty and Filename non-empty if creating the temporary
148 std::string Filename;
149 std::string TempFilename;
152 OutputFile(const std::string &filename, const std::string &tempFilename,
154 : Filename(filename), TempFilename(tempFilename), OS(os) { }
157 /// The list of active output files.
158 std::list<OutputFile> OutputFiles;
160 CompilerInstance(const CompilerInstance &) LLVM_DELETED_FUNCTION;
161 void operator=(const CompilerInstance &) LLVM_DELETED_FUNCTION;
163 explicit CompilerInstance(bool BuildingModule = false);
166 /// @name High-Level Operations
169 /// ExecuteAction - Execute the provided action against the compiler's
170 /// CompilerInvocation object.
172 /// This function makes the following assumptions:
174 /// - The invocation options should be initialized. This function does not
175 /// handle the '-help' or '-version' options, clients should handle those
178 /// - The diagnostics engine should have already been created by the client.
180 /// - No other CompilerInstance state should have been initialized (this is
181 /// an unchecked error).
183 /// - Clients should have initialized any LLVM target features that may be
186 /// - Clients should eventually call llvm_shutdown() upon the completion of
187 /// this routine to ensure that any managed objects are properly destroyed.
189 /// Note that this routine may write output to 'stderr'.
191 /// \param Act - The action to execute.
192 /// \return - True on success.
194 // FIXME: This function should take the stream to write any debugging /
195 // verbose output to as an argument.
197 // FIXME: Eliminate the llvm_shutdown requirement, that should either be part
198 // of the context or else not CompilerInstance specific.
199 bool ExecuteAction(FrontendAction &Act);
202 /// @name Compiler Invocation and Options
205 bool hasInvocation() const { return Invocation != nullptr; }
207 CompilerInvocation &getInvocation() {
208 assert(Invocation && "Compiler instance has no invocation!");
212 /// setInvocation - Replace the current invocation.
213 void setInvocation(CompilerInvocation *Value);
215 /// \brief Indicates whether we should (re)build the global module index.
216 bool shouldBuildGlobalModuleIndex() const;
218 /// \brief Set the flag indicating whether we should (re)build the global
220 void setBuildGlobalModuleIndex(bool Build) {
221 BuildGlobalModuleIndex = Build;
225 /// @name Forwarding Methods
228 AnalyzerOptionsRef getAnalyzerOpts() {
229 return Invocation->getAnalyzerOpts();
232 CodeGenOptions &getCodeGenOpts() {
233 return Invocation->getCodeGenOpts();
235 const CodeGenOptions &getCodeGenOpts() const {
236 return Invocation->getCodeGenOpts();
239 DependencyOutputOptions &getDependencyOutputOpts() {
240 return Invocation->getDependencyOutputOpts();
242 const DependencyOutputOptions &getDependencyOutputOpts() const {
243 return Invocation->getDependencyOutputOpts();
246 DiagnosticOptions &getDiagnosticOpts() {
247 return Invocation->getDiagnosticOpts();
249 const DiagnosticOptions &getDiagnosticOpts() const {
250 return Invocation->getDiagnosticOpts();
253 FileSystemOptions &getFileSystemOpts() {
254 return Invocation->getFileSystemOpts();
256 const FileSystemOptions &getFileSystemOpts() const {
257 return Invocation->getFileSystemOpts();
260 FrontendOptions &getFrontendOpts() {
261 return Invocation->getFrontendOpts();
263 const FrontendOptions &getFrontendOpts() const {
264 return Invocation->getFrontendOpts();
267 HeaderSearchOptions &getHeaderSearchOpts() {
268 return Invocation->getHeaderSearchOpts();
270 const HeaderSearchOptions &getHeaderSearchOpts() const {
271 return Invocation->getHeaderSearchOpts();
274 LangOptions &getLangOpts() {
275 return *Invocation->getLangOpts();
277 const LangOptions &getLangOpts() const {
278 return *Invocation->getLangOpts();
281 PreprocessorOptions &getPreprocessorOpts() {
282 return Invocation->getPreprocessorOpts();
284 const PreprocessorOptions &getPreprocessorOpts() const {
285 return Invocation->getPreprocessorOpts();
288 PreprocessorOutputOptions &getPreprocessorOutputOpts() {
289 return Invocation->getPreprocessorOutputOpts();
291 const PreprocessorOutputOptions &getPreprocessorOutputOpts() const {
292 return Invocation->getPreprocessorOutputOpts();
295 TargetOptions &getTargetOpts() {
296 return Invocation->getTargetOpts();
298 const TargetOptions &getTargetOpts() const {
299 return Invocation->getTargetOpts();
303 /// @name Diagnostics Engine
306 bool hasDiagnostics() const { return Diagnostics != nullptr; }
308 /// Get the current diagnostics engine.
309 DiagnosticsEngine &getDiagnostics() const {
310 assert(Diagnostics && "Compiler instance has no diagnostics!");
314 /// setDiagnostics - Replace the current diagnostics engine.
315 void setDiagnostics(DiagnosticsEngine *Value);
317 DiagnosticConsumer &getDiagnosticClient() const {
318 assert(Diagnostics && Diagnostics->getClient() &&
319 "Compiler instance has no diagnostic client!");
320 return *Diagnostics->getClient();
324 /// @name Target Info
327 bool hasTarget() const { return Target != nullptr; }
329 TargetInfo &getTarget() const {
330 assert(Target && "Compiler instance has no target!");
334 /// Replace the current diagnostics engine.
335 void setTarget(TargetInfo *Value);
338 /// @name Virtual File System
341 bool hasVirtualFileSystem() const { return VirtualFileSystem != nullptr; }
343 vfs::FileSystem &getVirtualFileSystem() const {
344 assert(hasVirtualFileSystem() &&
345 "Compiler instance has no virtual file system");
346 return *VirtualFileSystem;
349 /// \brief Replace the current virtual file system.
351 /// \note Most clients should use setFileManager, which will implicitly reset
352 /// the virtual file system to the one contained in the file manager.
353 void setVirtualFileSystem(IntrusiveRefCntPtr<vfs::FileSystem> FS) {
354 VirtualFileSystem = FS;
358 /// @name File Manager
361 bool hasFileManager() const { return FileMgr != nullptr; }
363 /// Return the current file manager to the caller.
364 FileManager &getFileManager() const {
365 assert(FileMgr && "Compiler instance has no file manager!");
369 void resetAndLeakFileManager() {
370 BuryPointer(FileMgr.get());
371 FileMgr.resetWithoutRelease();
374 /// \brief Replace the current file manager and virtual file system.
375 void setFileManager(FileManager *Value);
378 /// @name Source Manager
381 bool hasSourceManager() const { return SourceMgr != nullptr; }
383 /// Return the current source manager.
384 SourceManager &getSourceManager() const {
385 assert(SourceMgr && "Compiler instance has no source manager!");
389 void resetAndLeakSourceManager() {
390 BuryPointer(SourceMgr.get());
391 SourceMgr.resetWithoutRelease();
394 /// setSourceManager - Replace the current source manager.
395 void setSourceManager(SourceManager *Value);
398 /// @name Preprocessor
401 bool hasPreprocessor() const { return PP != nullptr; }
403 /// Return the current preprocessor.
404 Preprocessor &getPreprocessor() const {
405 assert(PP && "Compiler instance has no preprocessor!");
409 void resetAndLeakPreprocessor() {
410 BuryPointer(PP.get());
411 PP.resetWithoutRelease();
414 /// Replace the current preprocessor.
415 void setPreprocessor(Preprocessor *Value);
421 bool hasASTContext() const { return Context != nullptr; }
423 ASTContext &getASTContext() const {
424 assert(Context && "Compiler instance has no AST context!");
428 void resetAndLeakASTContext() {
429 BuryPointer(Context.get());
430 Context.resetWithoutRelease();
433 /// setASTContext - Replace the current AST context.
434 void setASTContext(ASTContext *Value);
436 /// \brief Replace the current Sema; the compiler instance takes ownership
438 void setSema(Sema *S);
441 /// @name ASTConsumer
444 bool hasASTConsumer() const { return (bool)Consumer; }
446 ASTConsumer &getASTConsumer() const {
447 assert(Consumer && "Compiler instance has no AST consumer!");
451 /// takeASTConsumer - Remove the current AST consumer and give ownership to
453 std::unique_ptr<ASTConsumer> takeASTConsumer() { return std::move(Consumer); }
455 /// setASTConsumer - Replace the current AST consumer; the compiler instance
456 /// takes ownership of \p Value.
457 void setASTConsumer(std::unique_ptr<ASTConsumer> Value);
460 /// @name Semantic analysis
462 bool hasSema() const { return (bool)TheSema; }
464 Sema &getSema() const {
465 assert(TheSema && "Compiler instance has no Sema object!");
469 std::unique_ptr<Sema> takeSema();
470 void resetAndLeakSema();
473 /// @name Module Management
476 IntrusiveRefCntPtr<ASTReader> getModuleManager() const;
477 void setModuleManager(IntrusiveRefCntPtr<ASTReader> Reader);
479 std::shared_ptr<ModuleDependencyCollector> getModuleDepCollector() const;
480 void setModuleDepCollector(
481 std::shared_ptr<ModuleDependencyCollector> Collector);
484 /// @name Code Completion
487 bool hasCodeCompletionConsumer() const { return (bool)CompletionConsumer; }
489 CodeCompleteConsumer &getCodeCompletionConsumer() const {
490 assert(CompletionConsumer &&
491 "Compiler instance has no code completion consumer!");
492 return *CompletionConsumer;
495 /// setCodeCompletionConsumer - Replace the current code completion consumer;
496 /// the compiler instance takes ownership of \p Value.
497 void setCodeCompletionConsumer(CodeCompleteConsumer *Value);
500 /// @name Frontend timer
503 bool hasFrontendTimer() const { return (bool)FrontendTimer; }
505 llvm::Timer &getFrontendTimer() const {
506 assert(FrontendTimer && "Compiler instance has no frontend timer!");
507 return *FrontendTimer;
511 /// @name Output Files
514 /// addOutputFile - Add an output file onto the list of tracked output files.
516 /// \param OutFile - The output file info.
517 void addOutputFile(const OutputFile &OutFile);
519 /// clearOutputFiles - Clear the output file list, destroying the contained
522 /// \param EraseFiles - If true, attempt to erase the files from disk.
523 void clearOutputFiles(bool EraseFiles);
526 /// @name Construction Utility Methods
529 /// Create the diagnostics engine using the invocation's diagnostic options
530 /// and replace any existing one with it.
532 /// Note that this routine also replaces the diagnostic client,
533 /// allocating one if one is not provided.
535 /// \param Client If non-NULL, a diagnostic client that will be
536 /// attached to (and, then, owned by) the DiagnosticsEngine inside this AST
539 /// \param ShouldOwnClient If Client is non-NULL, specifies whether
540 /// the diagnostic object should take ownership of the client.
541 void createDiagnostics(DiagnosticConsumer *Client = nullptr,
542 bool ShouldOwnClient = true);
544 /// Create a DiagnosticsEngine object with a the TextDiagnosticPrinter.
546 /// If no diagnostic client is provided, this creates a
547 /// DiagnosticConsumer that is owned by the returned diagnostic
548 /// object, if using directly the caller is responsible for
549 /// releasing the returned DiagnosticsEngine's client eventually.
551 /// \param Opts - The diagnostic options; note that the created text
552 /// diagnostic object contains a reference to these options.
554 /// \param Client If non-NULL, a diagnostic client that will be
555 /// attached to (and, then, owned by) the returned DiagnosticsEngine
558 /// \param CodeGenOpts If non-NULL, the code gen options in use, which may be
559 /// used by some diagnostics printers (for logging purposes only).
561 /// \return The new object on success, or null on failure.
562 static IntrusiveRefCntPtr<DiagnosticsEngine>
563 createDiagnostics(DiagnosticOptions *Opts,
564 DiagnosticConsumer *Client = nullptr,
565 bool ShouldOwnClient = true,
566 const CodeGenOptions *CodeGenOpts = nullptr);
568 /// Create the file manager and replace any existing one with it.
569 void createFileManager();
571 /// Create the source manager and replace any existing one with it.
572 void createSourceManager(FileManager &FileMgr);
574 /// Create the preprocessor, using the invocation, file, and source managers,
575 /// and replace any existing one with it.
576 void createPreprocessor(TranslationUnitKind TUKind);
578 /// Create the AST context.
579 void createASTContext();
581 /// Create an external AST source to read a PCH file and attach it to the AST
583 void createPCHExternalASTSource(StringRef Path, bool DisablePCHValidation,
584 bool AllowPCHWithCompilerErrors,
585 void *DeserializationListener,
586 bool OwnDeserializationListener);
588 /// Create an external AST source to read a PCH file.
590 /// \return - The new object on success, or null on failure.
591 static ExternalASTSource *createPCHExternalASTSource(
592 StringRef Path, const std::string &Sysroot, bool DisablePCHValidation,
593 bool AllowPCHWithCompilerErrors, Preprocessor &PP, ASTContext &Context,
594 void *DeserializationListener, bool OwnDeserializationListener,
595 bool Preamble, bool UseGlobalModuleIndex);
597 /// Create a code completion consumer using the invocation; note that this
598 /// will cause the source manager to truncate the input source file at the
599 /// completion point.
600 void createCodeCompletionConsumer();
602 /// Create a code completion consumer to print code completion results, at
603 /// \p Filename, \p Line, and \p Column, to the given output stream \p OS.
604 static CodeCompleteConsumer *
605 createCodeCompletionConsumer(Preprocessor &PP, const std::string &Filename,
606 unsigned Line, unsigned Column,
607 const CodeCompleteOptions &Opts,
610 /// \brief Create the Sema object to be used for parsing.
611 void createSema(TranslationUnitKind TUKind,
612 CodeCompleteConsumer *CompletionConsumer);
614 /// Create the frontend timer and replace any existing one with it.
615 void createFrontendTimer();
617 /// Create the default output file (from the invocation's options) and add it
618 /// to the list of tracked output files.
620 /// The files created by this function always use temporary files to write to
621 /// their result (that is, the data is written to a temporary file which will
622 /// atomically replace the target output on success).
624 /// \return - Null on error.
625 llvm::raw_fd_ostream *
626 createDefaultOutputFile(bool Binary = true, StringRef BaseInput = "",
627 StringRef Extension = "");
629 /// Create a new output file and add it to the list of tracked output files,
630 /// optionally deriving the output path name.
632 /// \return - Null on error.
633 llvm::raw_fd_ostream *
634 createOutputFile(StringRef OutputPath,
635 bool Binary, bool RemoveFileOnSignal,
639 bool CreateMissingDirectories = false);
641 /// Create a new output file, optionally deriving the output path name.
643 /// If \p OutputPath is empty, then createOutputFile will derive an output
644 /// path location as \p BaseInput, with any suffix removed, and \p Extension
645 /// appended. If \p OutputPath is not stdout and \p UseTemporary
646 /// is true, createOutputFile will create a new temporary file that must be
647 /// renamed to \p OutputPath in the end.
649 /// \param OutputPath - If given, the path to the output file.
650 /// \param Error [out] - On failure, the error.
651 /// \param BaseInput - If \p OutputPath is empty, the input path name to use
652 /// for deriving the output path.
653 /// \param Extension - The extension to use for derived output names.
654 /// \param Binary - The mode to open the file in.
655 /// \param RemoveFileOnSignal - Whether the file should be registered with
656 /// llvm::sys::RemoveFileOnSignal. Note that this is not safe for
657 /// multithreaded use, as the underlying signal mechanism is not reentrant
658 /// \param UseTemporary - Create a new temporary file that must be renamed to
659 /// OutputPath in the end.
660 /// \param CreateMissingDirectories - When \p UseTemporary is true, create
661 /// missing directories in the output path.
662 /// \param ResultPathName [out] - If given, the result path name will be
663 /// stored here on success.
664 /// \param TempPathName [out] - If given, the temporary file path name
665 /// will be stored here on success.
666 static llvm::raw_fd_ostream *
667 createOutputFile(StringRef OutputPath, std::error_code &Error, bool Binary,
668 bool RemoveFileOnSignal, StringRef BaseInput,
669 StringRef Extension, bool UseTemporary,
670 bool CreateMissingDirectories, std::string *ResultPathName,
671 std::string *TempPathName);
673 llvm::raw_null_ostream *createNullOutputFile();
676 /// @name Initialization Utility Methods
679 /// InitializeSourceManager - Initialize the source manager to set InputFile
680 /// as the main file.
682 /// \return True on success.
683 bool InitializeSourceManager(const FrontendInputFile &Input);
685 /// InitializeSourceManager - Initialize the source manager to set InputFile
686 /// as the main file.
688 /// \return True on success.
689 static bool InitializeSourceManager(const FrontendInputFile &Input,
690 DiagnosticsEngine &Diags,
691 FileManager &FileMgr,
692 SourceManager &SourceMgr,
693 const FrontendOptions &Opts);
697 // Create module manager.
698 void createModuleManager();
700 bool loadModuleFile(StringRef FileName);
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