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/Lex/ModuleLoader.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/IntrusiveRefCntPtr.h"
20 #include "llvm/ADT/OwningPtr.h"
21 #include "llvm/ADT/StringRef.h"
36 class CodeCompleteConsumer;
37 class DiagnosticsEngine;
38 class DiagnosticConsumer;
39 class ExternalASTSource;
49 /// CompilerInstance - Helper class for managing a single instance of the Clang
52 /// The CompilerInstance serves two purposes:
53 /// (1) It manages the various objects which are necessary to run the compiler,
54 /// for example the preprocessor, the target information, and the AST
56 /// (2) It provides utility routines for constructing and manipulating the
57 /// common Clang objects.
59 /// The compiler instance generally owns the instance of all the objects that it
60 /// manages. However, clients can still share objects by manually setting the
61 /// object and retaking ownership prior to destroying the CompilerInstance.
63 /// The compiler instance is intended to simplify clients, but not to lock them
64 /// in to the compiler instance for everything. When possible, utility functions
65 /// come in two forms; a short form that reuses the CompilerInstance objects,
66 /// and a long form that takes explicit instances of any required objects.
67 class CompilerInstance : public ModuleLoader {
68 /// The options used in this compiler instance.
69 IntrusiveRefCntPtr<CompilerInvocation> Invocation;
71 /// The diagnostics engine instance.
72 IntrusiveRefCntPtr<DiagnosticsEngine> Diagnostics;
74 /// The target being compiled for.
75 IntrusiveRefCntPtr<TargetInfo> Target;
78 IntrusiveRefCntPtr<FileManager> FileMgr;
80 /// The source manager.
81 IntrusiveRefCntPtr<SourceManager> SourceMgr;
84 IntrusiveRefCntPtr<Preprocessor> PP;
87 IntrusiveRefCntPtr<ASTContext> Context;
90 OwningPtr<ASTConsumer> Consumer;
92 /// The code completion consumer.
93 OwningPtr<CodeCompleteConsumer> CompletionConsumer;
95 /// \brief The semantic analysis object.
96 OwningPtr<Sema> TheSema;
98 /// \brief The frontend timer
99 OwningPtr<llvm::Timer> FrontendTimer;
101 /// \brief Non-owning reference to the ASTReader, if one exists.
102 ASTReader *ModuleManager;
104 /// \brief The set of top-level modules that has already been loaded,
105 /// along with the module map
106 llvm::DenseMap<const IdentifierInfo *, Module *> KnownModules;
108 /// \brief The location of the module-import keyword for the last module
110 SourceLocation LastModuleImportLoc;
112 /// \brief The result of the last module import.
114 ModuleLoadResult LastModuleImportResult;
116 /// \brief Whether we should (re)build the global module index once we
117 /// have finished with this translation unit.
118 bool BuildGlobalModuleIndex;
120 /// \brief One or more modules failed to build.
121 bool ModuleBuildFailed;
123 /// \brief Holds information about the output file.
125 /// If TempFilename is not empty we must rename it to Filename at the end.
126 /// TempFilename may be empty and Filename non empty if creating the temporary
129 std::string Filename;
130 std::string TempFilename;
133 OutputFile(const std::string &filename, const std::string &tempFilename,
135 : Filename(filename), TempFilename(tempFilename), OS(os) { }
138 /// The list of active output files.
139 std::list<OutputFile> OutputFiles;
141 CompilerInstance(const CompilerInstance &) LLVM_DELETED_FUNCTION;
142 void operator=(const CompilerInstance &) LLVM_DELETED_FUNCTION;
147 /// @name High-Level Operations
150 /// ExecuteAction - Execute the provided action against the compiler's
151 /// CompilerInvocation object.
153 /// This function makes the following assumptions:
155 /// - The invocation options should be initialized. This function does not
156 /// handle the '-help' or '-version' options, clients should handle those
159 /// - The diagnostics engine should have already been created by the client.
161 /// - No other CompilerInstance state should have been initialized (this is
162 /// an unchecked error).
164 /// - Clients should have initialized any LLVM target features that may be
167 /// - Clients should eventually call llvm_shutdown() upon the completion of
168 /// this routine to ensure that any managed objects are properly destroyed.
170 /// Note that this routine may write output to 'stderr'.
172 /// \param Act - The action to execute.
173 /// \return - True on success.
175 // FIXME: This function should take the stream to write any debugging /
176 // verbose output to as an argument.
178 // FIXME: Eliminate the llvm_shutdown requirement, that should either be part
179 // of the context or else not CompilerInstance specific.
180 bool ExecuteAction(FrontendAction &Act);
183 /// @name Compiler Invocation and Options
186 bool hasInvocation() const { return Invocation != 0; }
188 CompilerInvocation &getInvocation() {
189 assert(Invocation && "Compiler instance has no invocation!");
193 /// setInvocation - Replace the current invocation.
194 void setInvocation(CompilerInvocation *Value);
196 /// \brief Indicates whether we should (re)build the global module index.
197 bool shouldBuildGlobalModuleIndex() const;
199 /// \brief Set the flag indicating whether we should (re)build the global
201 void setBuildGlobalModuleIndex(bool Build) {
202 BuildGlobalModuleIndex = Build;
206 /// @name Forwarding Methods
209 AnalyzerOptionsRef getAnalyzerOpts() {
210 return Invocation->getAnalyzerOpts();
213 CodeGenOptions &getCodeGenOpts() {
214 return Invocation->getCodeGenOpts();
216 const CodeGenOptions &getCodeGenOpts() const {
217 return Invocation->getCodeGenOpts();
220 DependencyOutputOptions &getDependencyOutputOpts() {
221 return Invocation->getDependencyOutputOpts();
223 const DependencyOutputOptions &getDependencyOutputOpts() const {
224 return Invocation->getDependencyOutputOpts();
227 DiagnosticOptions &getDiagnosticOpts() {
228 return Invocation->getDiagnosticOpts();
230 const DiagnosticOptions &getDiagnosticOpts() const {
231 return Invocation->getDiagnosticOpts();
234 const FileSystemOptions &getFileSystemOpts() const {
235 return Invocation->getFileSystemOpts();
238 FrontendOptions &getFrontendOpts() {
239 return Invocation->getFrontendOpts();
241 const FrontendOptions &getFrontendOpts() const {
242 return Invocation->getFrontendOpts();
245 HeaderSearchOptions &getHeaderSearchOpts() {
246 return Invocation->getHeaderSearchOpts();
248 const HeaderSearchOptions &getHeaderSearchOpts() const {
249 return Invocation->getHeaderSearchOpts();
252 LangOptions &getLangOpts() {
253 return *Invocation->getLangOpts();
255 const LangOptions &getLangOpts() const {
256 return *Invocation->getLangOpts();
259 PreprocessorOptions &getPreprocessorOpts() {
260 return Invocation->getPreprocessorOpts();
262 const PreprocessorOptions &getPreprocessorOpts() const {
263 return Invocation->getPreprocessorOpts();
266 PreprocessorOutputOptions &getPreprocessorOutputOpts() {
267 return Invocation->getPreprocessorOutputOpts();
269 const PreprocessorOutputOptions &getPreprocessorOutputOpts() const {
270 return Invocation->getPreprocessorOutputOpts();
273 TargetOptions &getTargetOpts() {
274 return Invocation->getTargetOpts();
276 const TargetOptions &getTargetOpts() const {
277 return Invocation->getTargetOpts();
281 /// @name Diagnostics Engine
284 bool hasDiagnostics() const { return Diagnostics != 0; }
286 /// Get the current diagnostics engine.
287 DiagnosticsEngine &getDiagnostics() const {
288 assert(Diagnostics && "Compiler instance has no diagnostics!");
292 /// setDiagnostics - Replace the current diagnostics engine.
293 void setDiagnostics(DiagnosticsEngine *Value);
295 DiagnosticConsumer &getDiagnosticClient() const {
296 assert(Diagnostics && Diagnostics->getClient() &&
297 "Compiler instance has no diagnostic client!");
298 return *Diagnostics->getClient();
302 /// @name Target Info
305 bool hasTarget() const { return Target != 0; }
307 TargetInfo &getTarget() const {
308 assert(Target && "Compiler instance has no target!");
312 /// Replace the current diagnostics engine.
313 void setTarget(TargetInfo *Value);
316 /// @name File Manager
319 bool hasFileManager() const { return FileMgr != 0; }
321 /// Return the current file manager to the caller.
322 FileManager &getFileManager() const {
323 assert(FileMgr && "Compiler instance has no file manager!");
327 void resetAndLeakFileManager() {
328 FileMgr.resetWithoutRelease();
331 /// setFileManager - Replace the current file manager.
332 void setFileManager(FileManager *Value);
335 /// @name Source Manager
338 bool hasSourceManager() const { return SourceMgr != 0; }
340 /// Return the current source manager.
341 SourceManager &getSourceManager() const {
342 assert(SourceMgr && "Compiler instance has no source manager!");
346 void resetAndLeakSourceManager() {
347 SourceMgr.resetWithoutRelease();
350 /// setSourceManager - Replace the current source manager.
351 void setSourceManager(SourceManager *Value);
354 /// @name Preprocessor
357 bool hasPreprocessor() const { return PP != 0; }
359 /// Return the current preprocessor.
360 Preprocessor &getPreprocessor() const {
361 assert(PP && "Compiler instance has no preprocessor!");
365 void resetAndLeakPreprocessor() {
366 PP.resetWithoutRelease();
369 /// Replace the current preprocessor.
370 void setPreprocessor(Preprocessor *Value);
376 bool hasASTContext() const { return Context != 0; }
378 ASTContext &getASTContext() const {
379 assert(Context && "Compiler instance has no AST context!");
383 void resetAndLeakASTContext() {
384 Context.resetWithoutRelease();
387 /// setASTContext - Replace the current AST context.
388 void setASTContext(ASTContext *Value);
390 /// \brief Replace the current Sema; the compiler instance takes ownership
392 void setSema(Sema *S);
395 /// @name ASTConsumer
398 bool hasASTConsumer() const { return Consumer.isValid(); }
400 ASTConsumer &getASTConsumer() const {
401 assert(Consumer && "Compiler instance has no AST consumer!");
405 /// takeASTConsumer - Remove the current AST consumer and give ownership to
407 ASTConsumer *takeASTConsumer() { return Consumer.take(); }
409 /// setASTConsumer - Replace the current AST consumer; the compiler instance
410 /// takes ownership of \p Value.
411 void setASTConsumer(ASTConsumer *Value);
414 /// @name Semantic analysis
416 bool hasSema() const { return TheSema.isValid(); }
418 Sema &getSema() const {
419 assert(TheSema && "Compiler instance has no Sema object!");
423 Sema *takeSema() { return TheSema.take(); }
426 /// @name Module Management
429 ASTReader *getModuleManager() const { return ModuleManager; }
430 void setModuleManager(ASTReader *Reader) { ModuleManager = Reader; }
433 /// @name Code Completion
436 bool hasCodeCompletionConsumer() const {
437 return CompletionConsumer.isValid();
440 CodeCompleteConsumer &getCodeCompletionConsumer() const {
441 assert(CompletionConsumer &&
442 "Compiler instance has no code completion consumer!");
443 return *CompletionConsumer;
446 /// takeCodeCompletionConsumer - Remove the current code completion consumer
447 /// and give ownership to the caller.
448 CodeCompleteConsumer *takeCodeCompletionConsumer() {
449 return CompletionConsumer.take();
452 /// setCodeCompletionConsumer - Replace the current code completion consumer;
453 /// the compiler instance takes ownership of \p Value.
454 void setCodeCompletionConsumer(CodeCompleteConsumer *Value);
457 /// @name Frontend timer
460 bool hasFrontendTimer() const { return FrontendTimer.isValid(); }
462 llvm::Timer &getFrontendTimer() const {
463 assert(FrontendTimer && "Compiler instance has no frontend timer!");
464 return *FrontendTimer;
468 /// @name Output Files
471 /// addOutputFile - Add an output file onto the list of tracked output files.
473 /// \param OutFile - The output file info.
474 void addOutputFile(const OutputFile &OutFile);
476 /// clearOutputFiles - Clear the output file list, destroying the contained
479 /// \param EraseFiles - If true, attempt to erase the files from disk.
480 void clearOutputFiles(bool EraseFiles);
483 /// @name Construction Utility Methods
486 /// Create the diagnostics engine using the invocation's diagnostic options
487 /// and replace any existing one with it.
489 /// Note that this routine also replaces the diagnostic client,
490 /// allocating one if one is not provided.
492 /// \param Client If non-NULL, a diagnostic client that will be
493 /// attached to (and, then, owned by) the DiagnosticsEngine inside this AST
496 /// \param ShouldOwnClient If Client is non-NULL, specifies whether
497 /// the diagnostic object should take ownership of the client.
498 void createDiagnostics(DiagnosticConsumer *Client = 0,
499 bool ShouldOwnClient = true);
501 /// Create a DiagnosticsEngine object with a the TextDiagnosticPrinter.
503 /// If no diagnostic client is provided, this creates a
504 /// DiagnosticConsumer that is owned by the returned diagnostic
505 /// object, if using directly the caller is responsible for
506 /// releasing the returned DiagnosticsEngine's client eventually.
508 /// \param Opts - The diagnostic options; note that the created text
509 /// diagnostic object contains a reference to these options.
511 /// \param Client If non-NULL, a diagnostic client that will be
512 /// attached to (and, then, owned by) the returned DiagnosticsEngine
515 /// \param CodeGenOpts If non-NULL, the code gen options in use, which may be
516 /// used by some diagnostics printers (for logging purposes only).
518 /// \return The new object on success, or null on failure.
519 static IntrusiveRefCntPtr<DiagnosticsEngine>
520 createDiagnostics(DiagnosticOptions *Opts,
521 DiagnosticConsumer *Client = 0,
522 bool ShouldOwnClient = true,
523 const CodeGenOptions *CodeGenOpts = 0);
525 /// Create the file manager and replace any existing one with it.
526 void createFileManager();
528 /// Create the source manager and replace any existing one with it.
529 void createSourceManager(FileManager &FileMgr);
531 /// Create the preprocessor, using the invocation, file, and source managers,
532 /// and replace any existing one with it.
533 void createPreprocessor();
535 /// Create the AST context.
536 void createASTContext();
538 /// Create an external AST source to read a PCH file and attach it to the AST
540 void createPCHExternalASTSource(StringRef Path,
541 bool DisablePCHValidation,
542 bool AllowPCHWithCompilerErrors,
543 void *DeserializationListener);
545 /// Create an external AST source to read a PCH file.
547 /// \return - The new object on success, or null on failure.
548 static ExternalASTSource *
549 createPCHExternalASTSource(StringRef Path, const std::string &Sysroot,
550 bool DisablePCHValidation,
551 bool AllowPCHWithCompilerErrors,
552 Preprocessor &PP, ASTContext &Context,
553 void *DeserializationListener, bool Preamble,
554 bool UseGlobalModuleIndex);
556 /// Create a code completion consumer using the invocation; note that this
557 /// will cause the source manager to truncate the input source file at the
558 /// completion point.
559 void createCodeCompletionConsumer();
561 /// Create a code completion consumer to print code completion results, at
562 /// \p Filename, \p Line, and \p Column, to the given output stream \p OS.
563 static CodeCompleteConsumer *
564 createCodeCompletionConsumer(Preprocessor &PP, const std::string &Filename,
565 unsigned Line, unsigned Column,
566 const CodeCompleteOptions &Opts,
569 /// \brief Create the Sema object to be used for parsing.
570 void createSema(TranslationUnitKind TUKind,
571 CodeCompleteConsumer *CompletionConsumer);
573 /// Create the frontend timer and replace any existing one with it.
574 void createFrontendTimer();
576 /// Create the default output file (from the invocation's options) and add it
577 /// to the list of tracked output files.
579 /// The files created by this function always use temporary files to write to
580 /// their result (that is, the data is written to a temporary file which will
581 /// atomically replace the target output on success).
583 /// \return - Null on error.
584 llvm::raw_fd_ostream *
585 createDefaultOutputFile(bool Binary = true, StringRef BaseInput = "",
586 StringRef Extension = "");
588 /// Create a new output file and add it to the list of tracked output files,
589 /// optionally deriving the output path name.
591 /// \return - Null on error.
592 llvm::raw_fd_ostream *
593 createOutputFile(StringRef OutputPath,
594 bool Binary, bool RemoveFileOnSignal,
598 bool CreateMissingDirectories = false);
600 /// Create a new output file, optionally deriving the output path name.
602 /// If \p OutputPath is empty, then createOutputFile will derive an output
603 /// path location as \p BaseInput, with any suffix removed, and \p Extension
604 /// appended. If \p OutputPath is not stdout and \p UseTemporary
605 /// is true, createOutputFile will create a new temporary file that must be
606 /// renamed to \p OutputPath in the end.
608 /// \param OutputPath - If given, the path to the output file.
609 /// \param Error [out] - On failure, the error message.
610 /// \param BaseInput - If \p OutputPath is empty, the input path name to use
611 /// for deriving the output path.
612 /// \param Extension - The extension to use for derived output names.
613 /// \param Binary - The mode to open the file in.
614 /// \param RemoveFileOnSignal - Whether the file should be registered with
615 /// llvm::sys::RemoveFileOnSignal. Note that this is not safe for
616 /// multithreaded use, as the underlying signal mechanism is not reentrant
617 /// \param UseTemporary - Create a new temporary file that must be renamed to
618 /// OutputPath in the end.
619 /// \param CreateMissingDirectories - When \p UseTemporary is true, create
620 /// missing directories in the output path.
621 /// \param ResultPathName [out] - If given, the result path name will be
622 /// stored here on success.
623 /// \param TempPathName [out] - If given, the temporary file path name
624 /// will be stored here on success.
625 static llvm::raw_fd_ostream *
626 createOutputFile(StringRef OutputPath, std::string &Error,
627 bool Binary, bool RemoveFileOnSignal,
631 bool CreateMissingDirectories,
632 std::string *ResultPathName,
633 std::string *TempPathName);
636 /// @name Initialization Utility Methods
639 /// InitializeSourceManager - Initialize the source manager to set InputFile
640 /// as the main file.
642 /// \return True on success.
643 bool InitializeSourceManager(const FrontendInputFile &Input);
645 /// InitializeSourceManager - Initialize the source manager to set InputFile
646 /// as the main file.
648 /// \return True on success.
649 static bool InitializeSourceManager(const FrontendInputFile &Input,
650 DiagnosticsEngine &Diags,
651 FileManager &FileMgr,
652 SourceManager &SourceMgr,
653 const FrontendOptions &Opts);
657 virtual ModuleLoadResult loadModule(SourceLocation ImportLoc,
659 Module::NameVisibilityKind Visibility,
660 bool IsInclusionDirective);
662 virtual void makeModuleVisible(Module *Mod,
663 Module::NameVisibilityKind Visibility,
664 SourceLocation ImportLoc,
667 bool hadModuleLoaderFatalFailure() const {
668 return ModuleLoader::HadFatalFailure;
673 } // end namespace clang