clang API Documentation
00001 //===-- CompilerInstance.h - Clang Compiler Instance ------------*- C++ -*-===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 00010 #ifndef LLVM_CLANG_FRONTEND_COMPILERINSTANCE_H_ 00011 #define LLVM_CLANG_FRONTEND_COMPILERINSTANCE_H_ 00012 00013 #include "clang/Frontend/CompilerInvocation.h" 00014 #include "clang/Basic/SourceManager.h" 00015 #include "clang/Lex/ModuleLoader.h" 00016 #include "llvm/ADT/ArrayRef.h" 00017 #include "llvm/ADT/DenseMap.h" 00018 #include "llvm/ADT/IntrusiveRefCntPtr.h" 00019 #include "llvm/ADT/StringRef.h" 00020 #include "llvm/ADT/OwningPtr.h" 00021 #include <cassert> 00022 #include <list> 00023 #include <string> 00024 #include <utility> 00025 00026 namespace llvm { 00027 class raw_fd_ostream; 00028 class Timer; 00029 } 00030 00031 namespace clang { 00032 class ASTContext; 00033 class ASTConsumer; 00034 class ASTReader; 00035 class CodeCompleteConsumer; 00036 class DiagnosticsEngine; 00037 class DiagnosticConsumer; 00038 class ExternalASTSource; 00039 class FileEntry; 00040 class FileManager; 00041 class FrontendAction; 00042 class Module; 00043 class Preprocessor; 00044 class Sema; 00045 class SourceManager; 00046 class TargetInfo; 00047 00048 /// CompilerInstance - Helper class for managing a single instance of the Clang 00049 /// compiler. 00050 /// 00051 /// The CompilerInstance serves two purposes: 00052 /// (1) It manages the various objects which are necessary to run the compiler, 00053 /// for example the preprocessor, the target information, and the AST 00054 /// context. 00055 /// (2) It provides utility routines for constructing and manipulating the 00056 /// common Clang objects. 00057 /// 00058 /// The compiler instance generally owns the instance of all the objects that it 00059 /// manages. However, clients can still share objects by manually setting the 00060 /// object and retaking ownership prior to destroying the CompilerInstance. 00061 /// 00062 /// The compiler instance is intended to simplify clients, but not to lock them 00063 /// in to the compiler instance for everything. When possible, utility functions 00064 /// come in two forms; a short form that reuses the CompilerInstance objects, 00065 /// and a long form that takes explicit instances of any required objects. 00066 class CompilerInstance : public ModuleLoader { 00067 /// The options used in this compiler instance. 00068 IntrusiveRefCntPtr<CompilerInvocation> Invocation; 00069 00070 /// The diagnostics engine instance. 00071 IntrusiveRefCntPtr<DiagnosticsEngine> Diagnostics; 00072 00073 /// The target being compiled for. 00074 IntrusiveRefCntPtr<TargetInfo> Target; 00075 00076 /// The file manager. 00077 IntrusiveRefCntPtr<FileManager> FileMgr; 00078 00079 /// The source manager. 00080 IntrusiveRefCntPtr<SourceManager> SourceMgr; 00081 00082 /// The preprocessor. 00083 IntrusiveRefCntPtr<Preprocessor> PP; 00084 00085 /// The AST context. 00086 IntrusiveRefCntPtr<ASTContext> Context; 00087 00088 /// The AST consumer. 00089 OwningPtr<ASTConsumer> Consumer; 00090 00091 /// The code completion consumer. 00092 OwningPtr<CodeCompleteConsumer> CompletionConsumer; 00093 00094 /// \brief The semantic analysis object. 00095 OwningPtr<Sema> TheSema; 00096 00097 /// \brief The frontend timer 00098 OwningPtr<llvm::Timer> FrontendTimer; 00099 00100 /// \brief Non-owning reference to the ASTReader, if one exists. 00101 ASTReader *ModuleManager; 00102 00103 /// \brief The set of top-level modules that has already been loaded, 00104 /// along with the module map 00105 llvm::DenseMap<const IdentifierInfo *, Module *> KnownModules; 00106 00107 /// \brief The location of the module-import keyword for the last module 00108 /// import. 00109 SourceLocation LastModuleImportLoc; 00110 00111 /// \brief The result of the last module import. 00112 /// 00113 Module *LastModuleImportResult; 00114 00115 /// \brief Holds information about the output file. 00116 /// 00117 /// If TempFilename is not empty we must rename it to Filename at the end. 00118 /// TempFilename may be empty and Filename non empty if creating the temporary 00119 /// failed. 00120 struct OutputFile { 00121 std::string Filename; 00122 std::string TempFilename; 00123 raw_ostream *OS; 00124 00125 OutputFile(const std::string &filename, const std::string &tempFilename, 00126 raw_ostream *os) 00127 : Filename(filename), TempFilename(tempFilename), OS(os) { } 00128 }; 00129 00130 /// The list of active output files. 00131 std::list<OutputFile> OutputFiles; 00132 00133 void operator=(const CompilerInstance &); // DO NOT IMPLEMENT 00134 CompilerInstance(const CompilerInstance&); // DO NOT IMPLEMENT 00135 public: 00136 CompilerInstance(); 00137 ~CompilerInstance(); 00138 00139 /// @name High-Level Operations 00140 /// { 00141 00142 /// ExecuteAction - Execute the provided action against the compiler's 00143 /// CompilerInvocation object. 00144 /// 00145 /// This function makes the following assumptions: 00146 /// 00147 /// - The invocation options should be initialized. This function does not 00148 /// handle the '-help' or '-version' options, clients should handle those 00149 /// directly. 00150 /// 00151 /// - The diagnostics engine should have already been created by the client. 00152 /// 00153 /// - No other CompilerInstance state should have been initialized (this is 00154 /// an unchecked error). 00155 /// 00156 /// - Clients should have initialized any LLVM target features that may be 00157 /// required. 00158 /// 00159 /// - Clients should eventually call llvm_shutdown() upon the completion of 00160 /// this routine to ensure that any managed objects are properly destroyed. 00161 /// 00162 /// Note that this routine may write output to 'stderr'. 00163 /// 00164 /// \param Act - The action to execute. 00165 /// \return - True on success. 00166 // 00167 // FIXME: This function should take the stream to write any debugging / 00168 // verbose output to as an argument. 00169 // 00170 // FIXME: Eliminate the llvm_shutdown requirement, that should either be part 00171 // of the context or else not CompilerInstance specific. 00172 bool ExecuteAction(FrontendAction &Act); 00173 00174 /// } 00175 /// @name Compiler Invocation and Options 00176 /// { 00177 00178 bool hasInvocation() const { return Invocation != 0; } 00179 00180 CompilerInvocation &getInvocation() { 00181 assert(Invocation && "Compiler instance has no invocation!"); 00182 return *Invocation; 00183 } 00184 00185 /// setInvocation - Replace the current invocation. 00186 void setInvocation(CompilerInvocation *Value); 00187 00188 /// } 00189 /// @name Forwarding Methods 00190 /// { 00191 00192 AnalyzerOptions &getAnalyzerOpts() { 00193 return Invocation->getAnalyzerOpts(); 00194 } 00195 const AnalyzerOptions &getAnalyzerOpts() const { 00196 return Invocation->getAnalyzerOpts(); 00197 } 00198 00199 CodeGenOptions &getCodeGenOpts() { 00200 return Invocation->getCodeGenOpts(); 00201 } 00202 const CodeGenOptions &getCodeGenOpts() const { 00203 return Invocation->getCodeGenOpts(); 00204 } 00205 00206 DependencyOutputOptions &getDependencyOutputOpts() { 00207 return Invocation->getDependencyOutputOpts(); 00208 } 00209 const DependencyOutputOptions &getDependencyOutputOpts() const { 00210 return Invocation->getDependencyOutputOpts(); 00211 } 00212 00213 DiagnosticOptions &getDiagnosticOpts() { 00214 return Invocation->getDiagnosticOpts(); 00215 } 00216 const DiagnosticOptions &getDiagnosticOpts() const { 00217 return Invocation->getDiagnosticOpts(); 00218 } 00219 00220 const FileSystemOptions &getFileSystemOpts() const { 00221 return Invocation->getFileSystemOpts(); 00222 } 00223 00224 FrontendOptions &getFrontendOpts() { 00225 return Invocation->getFrontendOpts(); 00226 } 00227 const FrontendOptions &getFrontendOpts() const { 00228 return Invocation->getFrontendOpts(); 00229 } 00230 00231 HeaderSearchOptions &getHeaderSearchOpts() { 00232 return Invocation->getHeaderSearchOpts(); 00233 } 00234 const HeaderSearchOptions &getHeaderSearchOpts() const { 00235 return Invocation->getHeaderSearchOpts(); 00236 } 00237 00238 LangOptions &getLangOpts() { 00239 return *Invocation->getLangOpts(); 00240 } 00241 const LangOptions &getLangOpts() const { 00242 return *Invocation->getLangOpts(); 00243 } 00244 00245 PreprocessorOptions &getPreprocessorOpts() { 00246 return Invocation->getPreprocessorOpts(); 00247 } 00248 const PreprocessorOptions &getPreprocessorOpts() const { 00249 return Invocation->getPreprocessorOpts(); 00250 } 00251 00252 PreprocessorOutputOptions &getPreprocessorOutputOpts() { 00253 return Invocation->getPreprocessorOutputOpts(); 00254 } 00255 const PreprocessorOutputOptions &getPreprocessorOutputOpts() const { 00256 return Invocation->getPreprocessorOutputOpts(); 00257 } 00258 00259 TargetOptions &getTargetOpts() { 00260 return Invocation->getTargetOpts(); 00261 } 00262 const TargetOptions &getTargetOpts() const { 00263 return Invocation->getTargetOpts(); 00264 } 00265 00266 /// } 00267 /// @name Diagnostics Engine 00268 /// { 00269 00270 bool hasDiagnostics() const { return Diagnostics != 0; } 00271 00272 /// Get the current diagnostics engine. 00273 DiagnosticsEngine &getDiagnostics() const { 00274 assert(Diagnostics && "Compiler instance has no diagnostics!"); 00275 return *Diagnostics; 00276 } 00277 00278 /// setDiagnostics - Replace the current diagnostics engine. 00279 void setDiagnostics(DiagnosticsEngine *Value); 00280 00281 DiagnosticConsumer &getDiagnosticClient() const { 00282 assert(Diagnostics && Diagnostics->getClient() && 00283 "Compiler instance has no diagnostic client!"); 00284 return *Diagnostics->getClient(); 00285 } 00286 00287 /// } 00288 /// @name Target Info 00289 /// { 00290 00291 bool hasTarget() const { return Target != 0; } 00292 00293 TargetInfo &getTarget() const { 00294 assert(Target && "Compiler instance has no target!"); 00295 return *Target; 00296 } 00297 00298 /// Replace the current diagnostics engine. 00299 void setTarget(TargetInfo *Value); 00300 00301 /// } 00302 /// @name File Manager 00303 /// { 00304 00305 bool hasFileManager() const { return FileMgr != 0; } 00306 00307 /// Return the current file manager to the caller. 00308 FileManager &getFileManager() const { 00309 assert(FileMgr && "Compiler instance has no file manager!"); 00310 return *FileMgr; 00311 } 00312 00313 void resetAndLeakFileManager() { 00314 FileMgr.resetWithoutRelease(); 00315 } 00316 00317 /// setFileManager - Replace the current file manager. 00318 void setFileManager(FileManager *Value); 00319 00320 /// } 00321 /// @name Source Manager 00322 /// { 00323 00324 bool hasSourceManager() const { return SourceMgr != 0; } 00325 00326 /// Return the current source manager. 00327 SourceManager &getSourceManager() const { 00328 assert(SourceMgr && "Compiler instance has no source manager!"); 00329 return *SourceMgr; 00330 } 00331 00332 void resetAndLeakSourceManager() { 00333 SourceMgr.resetWithoutRelease(); 00334 } 00335 00336 /// setSourceManager - Replace the current source manager. 00337 void setSourceManager(SourceManager *Value); 00338 00339 /// } 00340 /// @name Preprocessor 00341 /// { 00342 00343 bool hasPreprocessor() const { return PP != 0; } 00344 00345 /// Return the current preprocessor. 00346 Preprocessor &getPreprocessor() const { 00347 assert(PP && "Compiler instance has no preprocessor!"); 00348 return *PP; 00349 } 00350 00351 void resetAndLeakPreprocessor() { 00352 PP.resetWithoutRelease(); 00353 } 00354 00355 /// Replace the current preprocessor. 00356 void setPreprocessor(Preprocessor *Value); 00357 00358 /// } 00359 /// @name ASTContext 00360 /// { 00361 00362 bool hasASTContext() const { return Context != 0; } 00363 00364 ASTContext &getASTContext() const { 00365 assert(Context && "Compiler instance has no AST context!"); 00366 return *Context; 00367 } 00368 00369 void resetAndLeakASTContext() { 00370 Context.resetWithoutRelease(); 00371 } 00372 00373 /// setASTContext - Replace the current AST context. 00374 void setASTContext(ASTContext *Value); 00375 00376 /// \brief Replace the current Sema; the compiler instance takes ownership 00377 /// of S. 00378 void setSema(Sema *S); 00379 00380 /// } 00381 /// @name ASTConsumer 00382 /// { 00383 00384 bool hasASTConsumer() const { return Consumer != 0; } 00385 00386 ASTConsumer &getASTConsumer() const { 00387 assert(Consumer && "Compiler instance has no AST consumer!"); 00388 return *Consumer; 00389 } 00390 00391 /// takeASTConsumer - Remove the current AST consumer and give ownership to 00392 /// the caller. 00393 ASTConsumer *takeASTConsumer() { return Consumer.take(); } 00394 00395 /// setASTConsumer - Replace the current AST consumer; the compiler instance 00396 /// takes ownership of \arg Value. 00397 void setASTConsumer(ASTConsumer *Value); 00398 00399 /// } 00400 /// @name Semantic analysis 00401 /// { 00402 bool hasSema() const { return TheSema != 0; } 00403 00404 Sema &getSema() const { 00405 assert(TheSema && "Compiler instance has no Sema object!"); 00406 return *TheSema; 00407 } 00408 00409 Sema *takeSema() { return TheSema.take(); } 00410 00411 /// } 00412 /// @name Module Management 00413 /// { 00414 00415 ASTReader *getModuleManager() const { return ModuleManager; } 00416 00417 /// } 00418 /// @name Code Completion 00419 /// { 00420 00421 bool hasCodeCompletionConsumer() const { return CompletionConsumer != 0; } 00422 00423 CodeCompleteConsumer &getCodeCompletionConsumer() const { 00424 assert(CompletionConsumer && 00425 "Compiler instance has no code completion consumer!"); 00426 return *CompletionConsumer; 00427 } 00428 00429 /// takeCodeCompletionConsumer - Remove the current code completion consumer 00430 /// and give ownership to the caller. 00431 CodeCompleteConsumer *takeCodeCompletionConsumer() { 00432 return CompletionConsumer.take(); 00433 } 00434 00435 /// setCodeCompletionConsumer - Replace the current code completion consumer; 00436 /// the compiler instance takes ownership of \arg Value. 00437 void setCodeCompletionConsumer(CodeCompleteConsumer *Value); 00438 00439 /// } 00440 /// @name Frontend timer 00441 /// { 00442 00443 bool hasFrontendTimer() const { return FrontendTimer != 0; } 00444 00445 llvm::Timer &getFrontendTimer() const { 00446 assert(FrontendTimer && "Compiler instance has no frontend timer!"); 00447 return *FrontendTimer; 00448 } 00449 00450 /// } 00451 /// @name Output Files 00452 /// { 00453 00454 /// addOutputFile - Add an output file onto the list of tracked output files. 00455 /// 00456 /// \param OutFile - The output file info. 00457 void addOutputFile(const OutputFile &OutFile); 00458 00459 /// clearOutputFiles - Clear the output file list, destroying the contained 00460 /// output streams. 00461 /// 00462 /// \param EraseFiles - If true, attempt to erase the files from disk. 00463 void clearOutputFiles(bool EraseFiles); 00464 00465 /// } 00466 /// @name Construction Utility Methods 00467 /// { 00468 00469 /// Create the diagnostics engine using the invocation's diagnostic options 00470 /// and replace any existing one with it. 00471 /// 00472 /// Note that this routine also replaces the diagnostic client, 00473 /// allocating one if one is not provided. 00474 /// 00475 /// \param Client If non-NULL, a diagnostic client that will be 00476 /// attached to (and, then, owned by) the DiagnosticsEngine inside this AST 00477 /// unit. 00478 /// 00479 /// \param ShouldOwnClient If Client is non-NULL, specifies whether 00480 /// the diagnostic object should take ownership of the client. 00481 /// 00482 /// \param ShouldCloneClient If Client is non-NULL, specifies whether that 00483 /// client should be cloned. 00484 void createDiagnostics(int Argc, const char* const *Argv, 00485 DiagnosticConsumer *Client = 0, 00486 bool ShouldOwnClient = true, 00487 bool ShouldCloneClient = true); 00488 00489 /// Create a DiagnosticsEngine object with a the TextDiagnosticPrinter. 00490 /// 00491 /// The \arg Argc and \arg Argv arguments are used only for logging purposes, 00492 /// when the diagnostic options indicate that the compiler should output 00493 /// logging information. 00494 /// 00495 /// If no diagnostic client is provided, this creates a 00496 /// DiagnosticConsumer that is owned by the returned diagnostic 00497 /// object, if using directly the caller is responsible for 00498 /// releasing the returned DiagnosticsEngine's client eventually. 00499 /// 00500 /// \param Opts - The diagnostic options; note that the created text 00501 /// diagnostic object contains a reference to these options and its lifetime 00502 /// must extend past that of the diagnostic engine. 00503 /// 00504 /// \param Client If non-NULL, a diagnostic client that will be 00505 /// attached to (and, then, owned by) the returned DiagnosticsEngine 00506 /// object. 00507 /// 00508 /// \param CodeGenOpts If non-NULL, the code gen options in use, which may be 00509 /// used by some diagnostics printers (for logging purposes only). 00510 /// 00511 /// \return The new object on success, or null on failure. 00512 static IntrusiveRefCntPtr<DiagnosticsEngine> 00513 createDiagnostics(const DiagnosticOptions &Opts, int Argc, 00514 const char* const *Argv, 00515 DiagnosticConsumer *Client = 0, 00516 bool ShouldOwnClient = true, 00517 bool ShouldCloneClient = true, 00518 const CodeGenOptions *CodeGenOpts = 0); 00519 00520 /// Create the file manager and replace any existing one with it. 00521 void createFileManager(); 00522 00523 /// Create the source manager and replace any existing one with it. 00524 void createSourceManager(FileManager &FileMgr); 00525 00526 /// Create the preprocessor, using the invocation, file, and source managers, 00527 /// and replace any existing one with it. 00528 void createPreprocessor(); 00529 00530 /// Create the AST context. 00531 void createASTContext(); 00532 00533 /// Create an external AST source to read a PCH file and attach it to the AST 00534 /// context. 00535 void createPCHExternalASTSource(StringRef Path, 00536 bool DisablePCHValidation, 00537 bool DisableStatCache, 00538 bool AllowPCHWithCompilerErrors, 00539 void *DeserializationListener); 00540 00541 /// Create an external AST source to read a PCH file. 00542 /// 00543 /// \return - The new object on success, or null on failure. 00544 static ExternalASTSource * 00545 createPCHExternalASTSource(StringRef Path, const std::string &Sysroot, 00546 bool DisablePCHValidation, 00547 bool DisableStatCache, 00548 bool AllowPCHWithCompilerErrors, 00549 Preprocessor &PP, ASTContext &Context, 00550 void *DeserializationListener, bool Preamble); 00551 00552 /// Create a code completion consumer using the invocation; note that this 00553 /// will cause the source manager to truncate the input source file at the 00554 /// completion point. 00555 void createCodeCompletionConsumer(); 00556 00557 /// Create a code completion consumer to print code completion results, at 00558 /// \arg Filename, \arg Line, and \arg Column, to the given output stream \arg 00559 /// OS. 00560 static CodeCompleteConsumer * 00561 createCodeCompletionConsumer(Preprocessor &PP, const std::string &Filename, 00562 unsigned Line, unsigned Column, 00563 bool ShowMacros, 00564 bool ShowCodePatterns, bool ShowGlobals, 00565 raw_ostream &OS); 00566 00567 /// \brief Create the Sema object to be used for parsing. 00568 void createSema(TranslationUnitKind TUKind, 00569 CodeCompleteConsumer *CompletionConsumer); 00570 00571 /// Create the frontend timer and replace any existing one with it. 00572 void createFrontendTimer(); 00573 00574 /// Create the default output file (from the invocation's options) and add it 00575 /// to the list of tracked output files. 00576 /// 00577 /// The files created by this function always use temporary files to write to 00578 /// their result (that is, the data is written to a temporary file which will 00579 /// atomically replace the target output on success). 00580 /// 00581 /// \return - Null on error. 00582 llvm::raw_fd_ostream * 00583 createDefaultOutputFile(bool Binary = true, StringRef BaseInput = "", 00584 StringRef Extension = ""); 00585 00586 /// Create a new output file and add it to the list of tracked output files, 00587 /// optionally deriving the output path name. 00588 /// 00589 /// \return - Null on error. 00590 llvm::raw_fd_ostream * 00591 createOutputFile(StringRef OutputPath, 00592 bool Binary = true, bool RemoveFileOnSignal = true, 00593 StringRef BaseInput = "", 00594 StringRef Extension = "", 00595 bool UseTemporary = false, 00596 bool CreateMissingDirectories = false); 00597 00598 /// Create a new output file, optionally deriving the output path name. 00599 /// 00600 /// If \arg OutputPath is empty, then createOutputFile will derive an output 00601 /// path location as \arg BaseInput, with any suffix removed, and \arg 00602 /// Extension appended. If OutputPath is not stdout and \arg UseTemporary 00603 /// is true, createOutputFile will create a new temporary file that must be 00604 /// renamed to OutputPath in the end. 00605 /// 00606 /// \param OutputPath - If given, the path to the output file. 00607 /// \param Error [out] - On failure, the error message. 00608 /// \param BaseInput - If \arg OutputPath is empty, the input path name to use 00609 /// for deriving the output path. 00610 /// \param Extension - The extension to use for derived output names. 00611 /// \param Binary - The mode to open the file in. 00612 /// \param RemoveFileOnSignal - Whether the file should be registered with 00613 /// llvm::sys::RemoveFileOnSignal. Note that this is not safe for 00614 /// multithreaded use, as the underlying signal mechanism is not reentrant 00615 /// \param UseTemporary - Create a new temporary file that must be renamed to 00616 /// OutputPath in the end. 00617 /// \param CreateMissingDirectories - When \arg UseTemporary is true, create 00618 /// missing directories in the output path. 00619 /// \param ResultPathName [out] - If given, the result path name will be 00620 /// stored here on success. 00621 /// \param TempPathName [out] - If given, the temporary file path name 00622 /// will be stored here on success. 00623 static llvm::raw_fd_ostream * 00624 createOutputFile(StringRef OutputPath, std::string &Error, 00625 bool Binary = true, bool RemoveFileOnSignal = true, 00626 StringRef BaseInput = "", 00627 StringRef Extension = "", 00628 bool UseTemporary = false, 00629 bool CreateMissingDirectories = false, 00630 std::string *ResultPathName = 0, 00631 std::string *TempPathName = 0); 00632 00633 /// } 00634 /// @name Initialization Utility Methods 00635 /// { 00636 00637 /// InitializeSourceManager - Initialize the source manager to set InputFile 00638 /// as the main file. 00639 /// 00640 /// \return True on success. 00641 bool InitializeSourceManager(StringRef InputFile, 00642 SrcMgr::CharacteristicKind Kind = SrcMgr::C_User); 00643 00644 /// InitializeSourceManager - Initialize the source manager to set InputFile 00645 /// as the main file. 00646 /// 00647 /// \return True on success. 00648 static bool InitializeSourceManager(StringRef InputFile, 00649 SrcMgr::CharacteristicKind Kind, 00650 DiagnosticsEngine &Diags, 00651 FileManager &FileMgr, 00652 SourceManager &SourceMgr, 00653 const FrontendOptions &Opts); 00654 00655 /// } 00656 00657 virtual Module *loadModule(SourceLocation ImportLoc, ModuleIdPath Path, 00658 Module::NameVisibilityKind Visibility, 00659 bool IsInclusionDirective); 00660 }; 00661 00662 } // end namespace clang 00663 00664 #endif