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/Frontend/CompilerInvocation.h"
14 #include "clang/Basic/Diagnostic.h"
15 #include "clang/Basic/SourceManager.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/StringRef.h"
21 #include "llvm/ADT/OwningPtr.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 Module *LastModuleImportResult;
116 /// \brief Holds information about the output file.
118 /// If TempFilename is not empty we must rename it to Filename at the end.
119 /// TempFilename may be empty and Filename non empty if creating the temporary
122 std::string Filename;
123 std::string TempFilename;
126 OutputFile(const std::string &filename, const std::string &tempFilename,
128 : Filename(filename), TempFilename(tempFilename), OS(os) { }
131 /// The list of active output files.
132 std::list<OutputFile> OutputFiles;
134 CompilerInstance(const CompilerInstance &) LLVM_DELETED_FUNCTION;
135 void operator=(const CompilerInstance &) LLVM_DELETED_FUNCTION;
140 /// @name High-Level Operations
143 /// ExecuteAction - Execute the provided action against the compiler's
144 /// CompilerInvocation object.
146 /// This function makes the following assumptions:
148 /// - The invocation options should be initialized. This function does not
149 /// handle the '-help' or '-version' options, clients should handle those
152 /// - The diagnostics engine should have already been created by the client.
154 /// - No other CompilerInstance state should have been initialized (this is
155 /// an unchecked error).
157 /// - Clients should have initialized any LLVM target features that may be
160 /// - Clients should eventually call llvm_shutdown() upon the completion of
161 /// this routine to ensure that any managed objects are properly destroyed.
163 /// Note that this routine may write output to 'stderr'.
165 /// \param Act - The action to execute.
166 /// \return - True on success.
168 // FIXME: This function should take the stream to write any debugging /
169 // verbose output to as an argument.
171 // FIXME: Eliminate the llvm_shutdown requirement, that should either be part
172 // of the context or else not CompilerInstance specific.
173 bool ExecuteAction(FrontendAction &Act);
176 /// @name Compiler Invocation and Options
179 bool hasInvocation() const { return Invocation != 0; }
181 CompilerInvocation &getInvocation() {
182 assert(Invocation && "Compiler instance has no invocation!");
186 /// setInvocation - Replace the current invocation.
187 void setInvocation(CompilerInvocation *Value);
190 /// @name Forwarding Methods
193 AnalyzerOptionsRef getAnalyzerOpts() {
194 return Invocation->getAnalyzerOpts();
197 CodeGenOptions &getCodeGenOpts() {
198 return Invocation->getCodeGenOpts();
200 const CodeGenOptions &getCodeGenOpts() const {
201 return Invocation->getCodeGenOpts();
204 DependencyOutputOptions &getDependencyOutputOpts() {
205 return Invocation->getDependencyOutputOpts();
207 const DependencyOutputOptions &getDependencyOutputOpts() const {
208 return Invocation->getDependencyOutputOpts();
211 DiagnosticOptions &getDiagnosticOpts() {
212 return Invocation->getDiagnosticOpts();
214 const DiagnosticOptions &getDiagnosticOpts() const {
215 return Invocation->getDiagnosticOpts();
218 const FileSystemOptions &getFileSystemOpts() const {
219 return Invocation->getFileSystemOpts();
222 FrontendOptions &getFrontendOpts() {
223 return Invocation->getFrontendOpts();
225 const FrontendOptions &getFrontendOpts() const {
226 return Invocation->getFrontendOpts();
229 HeaderSearchOptions &getHeaderSearchOpts() {
230 return Invocation->getHeaderSearchOpts();
232 const HeaderSearchOptions &getHeaderSearchOpts() const {
233 return Invocation->getHeaderSearchOpts();
236 LangOptions &getLangOpts() {
237 return *Invocation->getLangOpts();
239 const LangOptions &getLangOpts() const {
240 return *Invocation->getLangOpts();
243 PreprocessorOptions &getPreprocessorOpts() {
244 return Invocation->getPreprocessorOpts();
246 const PreprocessorOptions &getPreprocessorOpts() const {
247 return Invocation->getPreprocessorOpts();
250 PreprocessorOutputOptions &getPreprocessorOutputOpts() {
251 return Invocation->getPreprocessorOutputOpts();
253 const PreprocessorOutputOptions &getPreprocessorOutputOpts() const {
254 return Invocation->getPreprocessorOutputOpts();
257 TargetOptions &getTargetOpts() {
258 return Invocation->getTargetOpts();
260 const TargetOptions &getTargetOpts() const {
261 return Invocation->getTargetOpts();
265 /// @name Diagnostics Engine
268 bool hasDiagnostics() const { return Diagnostics != 0; }
270 /// Get the current diagnostics engine.
271 DiagnosticsEngine &getDiagnostics() const {
272 assert(Diagnostics && "Compiler instance has no diagnostics!");
276 /// setDiagnostics - Replace the current diagnostics engine.
277 void setDiagnostics(DiagnosticsEngine *Value);
279 DiagnosticConsumer &getDiagnosticClient() const {
280 assert(Diagnostics && Diagnostics->getClient() &&
281 "Compiler instance has no diagnostic client!");
282 return *Diagnostics->getClient();
286 /// @name Target Info
289 bool hasTarget() const { return Target != 0; }
291 TargetInfo &getTarget() const {
292 assert(Target && "Compiler instance has no target!");
296 /// Replace the current diagnostics engine.
297 void setTarget(TargetInfo *Value);
300 /// @name File Manager
303 bool hasFileManager() const { return FileMgr != 0; }
305 /// Return the current file manager to the caller.
306 FileManager &getFileManager() const {
307 assert(FileMgr && "Compiler instance has no file manager!");
311 void resetAndLeakFileManager() {
312 FileMgr.resetWithoutRelease();
315 /// setFileManager - Replace the current file manager.
316 void setFileManager(FileManager *Value);
319 /// @name Source Manager
322 bool hasSourceManager() const { return SourceMgr != 0; }
324 /// Return the current source manager.
325 SourceManager &getSourceManager() const {
326 assert(SourceMgr && "Compiler instance has no source manager!");
330 void resetAndLeakSourceManager() {
331 SourceMgr.resetWithoutRelease();
334 /// setSourceManager - Replace the current source manager.
335 void setSourceManager(SourceManager *Value);
338 /// @name Preprocessor
341 bool hasPreprocessor() const { return PP != 0; }
343 /// Return the current preprocessor.
344 Preprocessor &getPreprocessor() const {
345 assert(PP && "Compiler instance has no preprocessor!");
349 void resetAndLeakPreprocessor() {
350 PP.resetWithoutRelease();
353 /// Replace the current preprocessor.
354 void setPreprocessor(Preprocessor *Value);
360 bool hasASTContext() const { return Context != 0; }
362 ASTContext &getASTContext() const {
363 assert(Context && "Compiler instance has no AST context!");
367 void resetAndLeakASTContext() {
368 Context.resetWithoutRelease();
371 /// setASTContext - Replace the current AST context.
372 void setASTContext(ASTContext *Value);
374 /// \brief Replace the current Sema; the compiler instance takes ownership
376 void setSema(Sema *S);
379 /// @name ASTConsumer
382 bool hasASTConsumer() const { return Consumer != 0; }
384 ASTConsumer &getASTConsumer() const {
385 assert(Consumer && "Compiler instance has no AST consumer!");
389 /// takeASTConsumer - Remove the current AST consumer and give ownership to
391 ASTConsumer *takeASTConsumer() { return Consumer.take(); }
393 /// setASTConsumer - Replace the current AST consumer; the compiler instance
394 /// takes ownership of \p Value.
395 void setASTConsumer(ASTConsumer *Value);
398 /// @name Semantic analysis
400 bool hasSema() const { return TheSema != 0; }
402 Sema &getSema() const {
403 assert(TheSema && "Compiler instance has no Sema object!");
407 Sema *takeSema() { return TheSema.take(); }
410 /// @name Module Management
413 ASTReader *getModuleManager() const { return ModuleManager; }
416 /// @name Code Completion
419 bool hasCodeCompletionConsumer() const { return CompletionConsumer != 0; }
421 CodeCompleteConsumer &getCodeCompletionConsumer() const {
422 assert(CompletionConsumer &&
423 "Compiler instance has no code completion consumer!");
424 return *CompletionConsumer;
427 /// takeCodeCompletionConsumer - Remove the current code completion consumer
428 /// and give ownership to the caller.
429 CodeCompleteConsumer *takeCodeCompletionConsumer() {
430 return CompletionConsumer.take();
433 /// setCodeCompletionConsumer - Replace the current code completion consumer;
434 /// the compiler instance takes ownership of \p Value.
435 void setCodeCompletionConsumer(CodeCompleteConsumer *Value);
438 /// @name Frontend timer
441 bool hasFrontendTimer() const { return FrontendTimer != 0; }
443 llvm::Timer &getFrontendTimer() const {
444 assert(FrontendTimer && "Compiler instance has no frontend timer!");
445 return *FrontendTimer;
449 /// @name Output Files
452 /// addOutputFile - Add an output file onto the list of tracked output files.
454 /// \param OutFile - The output file info.
455 void addOutputFile(const OutputFile &OutFile);
457 /// clearOutputFiles - Clear the output file list, destroying the contained
460 /// \param EraseFiles - If true, attempt to erase the files from disk.
461 void clearOutputFiles(bool EraseFiles);
464 /// @name Construction Utility Methods
467 /// Create the diagnostics engine using the invocation's diagnostic options
468 /// and replace any existing one with it.
470 /// Note that this routine also replaces the diagnostic client,
471 /// allocating one if one is not provided.
473 /// \param Client If non-NULL, a diagnostic client that will be
474 /// attached to (and, then, owned by) the DiagnosticsEngine inside this AST
477 /// \param ShouldOwnClient If Client is non-NULL, specifies whether
478 /// the diagnostic object should take ownership of the client.
480 /// \param ShouldCloneClient If Client is non-NULL, specifies whether that
481 /// client should be cloned.
482 void createDiagnostics(int Argc, const char* const *Argv,
483 DiagnosticConsumer *Client = 0,
484 bool ShouldOwnClient = true,
485 bool ShouldCloneClient = true);
487 /// Create a DiagnosticsEngine object with a the TextDiagnosticPrinter.
489 /// The \p Argc and \p Argv arguments are used only for logging purposes,
490 /// when the diagnostic options indicate that the compiler should output
491 /// logging information.
493 /// If no diagnostic client is provided, this creates a
494 /// DiagnosticConsumer that is owned by the returned diagnostic
495 /// object, if using directly the caller is responsible for
496 /// releasing the returned DiagnosticsEngine's client eventually.
498 /// \param Opts - The diagnostic options; note that the created text
499 /// diagnostic object contains a reference to these options.
501 /// \param Client If non-NULL, a diagnostic client that will be
502 /// attached to (and, then, owned by) the returned DiagnosticsEngine
505 /// \param CodeGenOpts If non-NULL, the code gen options in use, which may be
506 /// used by some diagnostics printers (for logging purposes only).
508 /// \return The new object on success, or null on failure.
509 static IntrusiveRefCntPtr<DiagnosticsEngine>
510 createDiagnostics(DiagnosticOptions *Opts, int Argc,
511 const char* const *Argv,
512 DiagnosticConsumer *Client = 0,
513 bool ShouldOwnClient = true,
514 bool ShouldCloneClient = true,
515 const CodeGenOptions *CodeGenOpts = 0);
517 /// Create the file manager and replace any existing one with it.
518 void createFileManager();
520 /// Create the source manager and replace any existing one with it.
521 void createSourceManager(FileManager &FileMgr);
523 /// Create the preprocessor, using the invocation, file, and source managers,
524 /// and replace any existing one with it.
525 void createPreprocessor();
527 /// Create the AST context.
528 void createASTContext();
530 /// Create an external AST source to read a PCH file and attach it to the AST
532 void createPCHExternalASTSource(StringRef Path,
533 bool DisablePCHValidation,
534 bool AllowPCHWithCompilerErrors,
535 void *DeserializationListener);
537 /// Create an external AST source to read a PCH file.
539 /// \return - The new object on success, or null on failure.
540 static ExternalASTSource *
541 createPCHExternalASTSource(StringRef Path, const std::string &Sysroot,
542 bool DisablePCHValidation,
543 bool AllowPCHWithCompilerErrors,
544 Preprocessor &PP, ASTContext &Context,
545 void *DeserializationListener, bool Preamble);
547 /// Create a code completion consumer using the invocation; note that this
548 /// will cause the source manager to truncate the input source file at the
549 /// completion point.
550 void createCodeCompletionConsumer();
552 /// Create a code completion consumer to print code completion results, at
553 /// \p Filename, \p Line, and \p Column, to the given output stream \p OS.
554 static CodeCompleteConsumer *
555 createCodeCompletionConsumer(Preprocessor &PP, const std::string &Filename,
556 unsigned Line, unsigned Column,
557 const CodeCompleteOptions &Opts,
560 /// \brief Create the Sema object to be used for parsing.
561 void createSema(TranslationUnitKind TUKind,
562 CodeCompleteConsumer *CompletionConsumer);
564 /// Create the frontend timer and replace any existing one with it.
565 void createFrontendTimer();
567 /// Create the default output file (from the invocation's options) and add it
568 /// to the list of tracked output files.
570 /// The files created by this function always use temporary files to write to
571 /// their result (that is, the data is written to a temporary file which will
572 /// atomically replace the target output on success).
574 /// \return - Null on error.
575 llvm::raw_fd_ostream *
576 createDefaultOutputFile(bool Binary = true, StringRef BaseInput = "",
577 StringRef Extension = "");
579 /// Create a new output file and add it to the list of tracked output files,
580 /// optionally deriving the output path name.
582 /// \return - Null on error.
583 llvm::raw_fd_ostream *
584 createOutputFile(StringRef OutputPath,
585 bool Binary = true, bool RemoveFileOnSignal = true,
586 StringRef BaseInput = "",
587 StringRef Extension = "",
588 bool UseTemporary = false,
589 bool CreateMissingDirectories = false);
591 /// Create a new output file, optionally deriving the output path name.
593 /// If \p OutputPath is empty, then createOutputFile will derive an output
594 /// path location as \p BaseInput, with any suffix removed, and \p Extension
595 /// appended. If \p OutputPath is not stdout and \p UseTemporary
596 /// is true, createOutputFile will create a new temporary file that must be
597 /// renamed to \p OutputPath in the end.
599 /// \param OutputPath - If given, the path to the output file.
600 /// \param Error [out] - On failure, the error message.
601 /// \param BaseInput - If \p OutputPath is empty, the input path name to use
602 /// for deriving the output path.
603 /// \param Extension - The extension to use for derived output names.
604 /// \param Binary - The mode to open the file in.
605 /// \param RemoveFileOnSignal - Whether the file should be registered with
606 /// llvm::sys::RemoveFileOnSignal. Note that this is not safe for
607 /// multithreaded use, as the underlying signal mechanism is not reentrant
608 /// \param UseTemporary - Create a new temporary file that must be renamed to
609 /// OutputPath in the end.
610 /// \param CreateMissingDirectories - When \p UseTemporary is true, create
611 /// missing directories in the output path.
612 /// \param ResultPathName [out] - If given, the result path name will be
613 /// stored here on success.
614 /// \param TempPathName [out] - If given, the temporary file path name
615 /// will be stored here on success.
616 static llvm::raw_fd_ostream *
617 createOutputFile(StringRef OutputPath, std::string &Error,
618 bool Binary = true, bool RemoveFileOnSignal = true,
619 StringRef BaseInput = "",
620 StringRef Extension = "",
621 bool UseTemporary = false,
622 bool CreateMissingDirectories = false,
623 std::string *ResultPathName = 0,
624 std::string *TempPathName = 0);
627 /// @name Initialization Utility Methods
630 /// InitializeSourceManager - Initialize the source manager to set InputFile
631 /// as the main file.
633 /// \return True on success.
634 bool InitializeSourceManager(const FrontendInputFile &Input);
636 /// InitializeSourceManager - Initialize the source manager to set InputFile
637 /// as the main file.
639 /// \return True on success.
640 static bool InitializeSourceManager(const FrontendInputFile &Input,
641 DiagnosticsEngine &Diags,
642 FileManager &FileMgr,
643 SourceManager &SourceMgr,
644 const FrontendOptions &Opts);
648 virtual Module *loadModule(SourceLocation ImportLoc, ModuleIdPath Path,
649 Module::NameVisibilityKind Visibility,
650 bool IsInclusionDirective);
653 } // end namespace clang