1 //===-- CompilerInstance.h - Clang Compiler Instance ------------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #ifndef LLVM_CLANG_FRONTEND_COMPILERINSTANCE_H_ 11 #define LLVM_CLANG_FRONTEND_COMPILERINSTANCE_H_ 12 13 #include "clang/Frontend/CompilerInvocation.h" 14 #include "clang/Basic/SourceManager.h" 15 #include "clang/Lex/ModuleLoader.h" 16 #include "llvm/ADT/ArrayRef.h" 17 #include "llvm/ADT/DenseMap.h" 18 #include "llvm/ADT/IntrusiveRefCntPtr.h" 19 #include "llvm/ADT/StringRef.h" 20 #include "llvm/ADT/OwningPtr.h" 21 #include <cassert> 22 #include <list> 23 #include <string> 24 #include <utility> 25 26 namespace llvm { 27 class raw_fd_ostream; 28 class Timer; 29 } 30 31 namespace clang { 32 class ASTContext; 33 class ASTConsumer; 34 class ASTReader; 35 class CodeCompleteConsumer; 36 class DiagnosticsEngine; 37 class DiagnosticConsumer; 38 class ExternalASTSource; 39 class FileEntry; 40 class FileManager; 41 class FrontendAction; 42 class Module; 43 class Preprocessor; 44 class Sema; 45 class SourceManager; 46 class TargetInfo; 47 48 /// CompilerInstance - Helper class for managing a single instance of the Clang 49 /// compiler. 50 /// 51 /// The CompilerInstance serves two purposes: 52 /// (1) It manages the various objects which are necessary to run the compiler, 53 /// for example the preprocessor, the target information, and the AST 54 /// context. 55 /// (2) It provides utility routines for constructing and manipulating the 56 /// common Clang objects. 57 /// 58 /// The compiler instance generally owns the instance of all the objects that it 59 /// manages. However, clients can still share objects by manually setting the 60 /// object and retaking ownership prior to destroying the CompilerInstance. 61 /// 62 /// The compiler instance is intended to simplify clients, but not to lock them 63 /// in to the compiler instance for everything. When possible, utility functions 64 /// come in two forms; a short form that reuses the CompilerInstance objects, 65 /// and a long form that takes explicit instances of any required objects. 66 class CompilerInstance : public ModuleLoader { 67 /// The options used in this compiler instance. 68 IntrusiveRefCntPtr<CompilerInvocation> Invocation; 69 70 /// The diagnostics engine instance. 71 IntrusiveRefCntPtr<DiagnosticsEngine> Diagnostics; 72 73 /// The target being compiled for. 74 IntrusiveRefCntPtr<TargetInfo> Target; 75 76 /// The file manager. 77 IntrusiveRefCntPtr<FileManager> FileMgr; 78 79 /// The source manager. 80 IntrusiveRefCntPtr<SourceManager> SourceMgr; 81 82 /// The preprocessor. 83 IntrusiveRefCntPtr<Preprocessor> PP; 84 85 /// The AST context. 86 IntrusiveRefCntPtr<ASTContext> Context; 87 88 /// The AST consumer. 89 OwningPtr<ASTConsumer> Consumer; 90 91 /// The code completion consumer. 92 OwningPtr<CodeCompleteConsumer> CompletionConsumer; 93 94 /// \brief The semantic analysis object. 95 OwningPtr<Sema> TheSema; 96 97 /// \brief The frontend timer 98 OwningPtr<llvm::Timer> FrontendTimer; 99 100 /// \brief Non-owning reference to the ASTReader, if one exists. 101 ASTReader *ModuleManager; 102 103 /// \brief The set of top-level modules that has already been loaded, 104 /// along with the module map 105 llvm::DenseMap<const IdentifierInfo *, Module *> KnownModules; 106 107 /// \brief The location of the module-import keyword for the last module 108 /// import. 109 SourceLocation LastModuleImportLoc; 110 111 /// \brief The result of the last module import. 112 /// 113 Module *LastModuleImportResult; 114 115 /// \brief Holds information about the output file. 116 /// 117 /// If TempFilename is not empty we must rename it to Filename at the end. 118 /// TempFilename may be empty and Filename non empty if creating the temporary 119 /// failed. 120 struct OutputFile { 121 std::string Filename; 122 std::string TempFilename; 123 raw_ostream *OS; 124 OutputFileOutputFile125 OutputFile(const std::string &filename, const std::string &tempFilename, 126 raw_ostream *os) 127 : Filename(filename), TempFilename(tempFilename), OS(os) { } 128 }; 129 130 /// The list of active output files. 131 std::list<OutputFile> OutputFiles; 132 133 void operator=(const CompilerInstance &); // DO NOT IMPLEMENT 134 CompilerInstance(const CompilerInstance&); // DO NOT IMPLEMENT 135 public: 136 CompilerInstance(); 137 ~CompilerInstance(); 138 139 /// @name High-Level Operations 140 /// { 141 142 /// ExecuteAction - Execute the provided action against the compiler's 143 /// CompilerInvocation object. 144 /// 145 /// This function makes the following assumptions: 146 /// 147 /// - The invocation options should be initialized. This function does not 148 /// handle the '-help' or '-version' options, clients should handle those 149 /// directly. 150 /// 151 /// - The diagnostics engine should have already been created by the client. 152 /// 153 /// - No other CompilerInstance state should have been initialized (this is 154 /// an unchecked error). 155 /// 156 /// - Clients should have initialized any LLVM target features that may be 157 /// required. 158 /// 159 /// - Clients should eventually call llvm_shutdown() upon the completion of 160 /// this routine to ensure that any managed objects are properly destroyed. 161 /// 162 /// Note that this routine may write output to 'stderr'. 163 /// 164 /// \param Act - The action to execute. 165 /// \return - True on success. 166 // 167 // FIXME: This function should take the stream to write any debugging / 168 // verbose output to as an argument. 169 // 170 // FIXME: Eliminate the llvm_shutdown requirement, that should either be part 171 // of the context or else not CompilerInstance specific. 172 bool ExecuteAction(FrontendAction &Act); 173 174 /// } 175 /// @name Compiler Invocation and Options 176 /// { 177 hasInvocation()178 bool hasInvocation() const { return Invocation != 0; } 179 getInvocation()180 CompilerInvocation &getInvocation() { 181 assert(Invocation && "Compiler instance has no invocation!"); 182 return *Invocation; 183 } 184 185 /// setInvocation - Replace the current invocation. 186 void setInvocation(CompilerInvocation *Value); 187 188 /// } 189 /// @name Forwarding Methods 190 /// { 191 getAnalyzerOpts()192 AnalyzerOptionsRef getAnalyzerOpts() { 193 return Invocation->getAnalyzerOpts(); 194 } 195 getCodeGenOpts()196 CodeGenOptions &getCodeGenOpts() { 197 return Invocation->getCodeGenOpts(); 198 } getCodeGenOpts()199 const CodeGenOptions &getCodeGenOpts() const { 200 return Invocation->getCodeGenOpts(); 201 } 202 getDependencyOutputOpts()203 DependencyOutputOptions &getDependencyOutputOpts() { 204 return Invocation->getDependencyOutputOpts(); 205 } getDependencyOutputOpts()206 const DependencyOutputOptions &getDependencyOutputOpts() const { 207 return Invocation->getDependencyOutputOpts(); 208 } 209 getDiagnosticOpts()210 DiagnosticOptions &getDiagnosticOpts() { 211 return Invocation->getDiagnosticOpts(); 212 } getDiagnosticOpts()213 const DiagnosticOptions &getDiagnosticOpts() const { 214 return Invocation->getDiagnosticOpts(); 215 } 216 getFileSystemOpts()217 const FileSystemOptions &getFileSystemOpts() const { 218 return Invocation->getFileSystemOpts(); 219 } 220 getFrontendOpts()221 FrontendOptions &getFrontendOpts() { 222 return Invocation->getFrontendOpts(); 223 } getFrontendOpts()224 const FrontendOptions &getFrontendOpts() const { 225 return Invocation->getFrontendOpts(); 226 } 227 getHeaderSearchOpts()228 HeaderSearchOptions &getHeaderSearchOpts() { 229 return Invocation->getHeaderSearchOpts(); 230 } getHeaderSearchOpts()231 const HeaderSearchOptions &getHeaderSearchOpts() const { 232 return Invocation->getHeaderSearchOpts(); 233 } 234 getLangOpts()235 LangOptions &getLangOpts() { 236 return *Invocation->getLangOpts(); 237 } getLangOpts()238 const LangOptions &getLangOpts() const { 239 return *Invocation->getLangOpts(); 240 } 241 getPreprocessorOpts()242 PreprocessorOptions &getPreprocessorOpts() { 243 return Invocation->getPreprocessorOpts(); 244 } getPreprocessorOpts()245 const PreprocessorOptions &getPreprocessorOpts() const { 246 return Invocation->getPreprocessorOpts(); 247 } 248 getPreprocessorOutputOpts()249 PreprocessorOutputOptions &getPreprocessorOutputOpts() { 250 return Invocation->getPreprocessorOutputOpts(); 251 } getPreprocessorOutputOpts()252 const PreprocessorOutputOptions &getPreprocessorOutputOpts() const { 253 return Invocation->getPreprocessorOutputOpts(); 254 } 255 getTargetOpts()256 TargetOptions &getTargetOpts() { 257 return Invocation->getTargetOpts(); 258 } getTargetOpts()259 const TargetOptions &getTargetOpts() const { 260 return Invocation->getTargetOpts(); 261 } 262 263 /// } 264 /// @name Diagnostics Engine 265 /// { 266 hasDiagnostics()267 bool hasDiagnostics() const { return Diagnostics != 0; } 268 269 /// Get the current diagnostics engine. getDiagnostics()270 DiagnosticsEngine &getDiagnostics() const { 271 assert(Diagnostics && "Compiler instance has no diagnostics!"); 272 return *Diagnostics; 273 } 274 275 /// setDiagnostics - Replace the current diagnostics engine. 276 void setDiagnostics(DiagnosticsEngine *Value); 277 getDiagnosticClient()278 DiagnosticConsumer &getDiagnosticClient() const { 279 assert(Diagnostics && Diagnostics->getClient() && 280 "Compiler instance has no diagnostic client!"); 281 return *Diagnostics->getClient(); 282 } 283 284 /// } 285 /// @name Target Info 286 /// { 287 hasTarget()288 bool hasTarget() const { return Target != 0; } 289 getTarget()290 TargetInfo &getTarget() const { 291 assert(Target && "Compiler instance has no target!"); 292 return *Target; 293 } 294 295 /// Replace the current diagnostics engine. 296 void setTarget(TargetInfo *Value); 297 298 /// } 299 /// @name File Manager 300 /// { 301 hasFileManager()302 bool hasFileManager() const { return FileMgr != 0; } 303 304 /// Return the current file manager to the caller. getFileManager()305 FileManager &getFileManager() const { 306 assert(FileMgr && "Compiler instance has no file manager!"); 307 return *FileMgr; 308 } 309 resetAndLeakFileManager()310 void resetAndLeakFileManager() { 311 FileMgr.resetWithoutRelease(); 312 } 313 314 /// setFileManager - Replace the current file manager. 315 void setFileManager(FileManager *Value); 316 317 /// } 318 /// @name Source Manager 319 /// { 320 hasSourceManager()321 bool hasSourceManager() const { return SourceMgr != 0; } 322 323 /// Return the current source manager. getSourceManager()324 SourceManager &getSourceManager() const { 325 assert(SourceMgr && "Compiler instance has no source manager!"); 326 return *SourceMgr; 327 } 328 resetAndLeakSourceManager()329 void resetAndLeakSourceManager() { 330 SourceMgr.resetWithoutRelease(); 331 } 332 333 /// setSourceManager - Replace the current source manager. 334 void setSourceManager(SourceManager *Value); 335 336 /// } 337 /// @name Preprocessor 338 /// { 339 hasPreprocessor()340 bool hasPreprocessor() const { return PP != 0; } 341 342 /// Return the current preprocessor. getPreprocessor()343 Preprocessor &getPreprocessor() const { 344 assert(PP && "Compiler instance has no preprocessor!"); 345 return *PP; 346 } 347 resetAndLeakPreprocessor()348 void resetAndLeakPreprocessor() { 349 PP.resetWithoutRelease(); 350 } 351 352 /// Replace the current preprocessor. 353 void setPreprocessor(Preprocessor *Value); 354 355 /// } 356 /// @name ASTContext 357 /// { 358 hasASTContext()359 bool hasASTContext() const { return Context != 0; } 360 getASTContext()361 ASTContext &getASTContext() const { 362 assert(Context && "Compiler instance has no AST context!"); 363 return *Context; 364 } 365 resetAndLeakASTContext()366 void resetAndLeakASTContext() { 367 Context.resetWithoutRelease(); 368 } 369 370 /// setASTContext - Replace the current AST context. 371 void setASTContext(ASTContext *Value); 372 373 /// \brief Replace the current Sema; the compiler instance takes ownership 374 /// of S. 375 void setSema(Sema *S); 376 377 /// } 378 /// @name ASTConsumer 379 /// { 380 hasASTConsumer()381 bool hasASTConsumer() const { return Consumer != 0; } 382 getASTConsumer()383 ASTConsumer &getASTConsumer() const { 384 assert(Consumer && "Compiler instance has no AST consumer!"); 385 return *Consumer; 386 } 387 388 /// takeASTConsumer - Remove the current AST consumer and give ownership to 389 /// the caller. takeASTConsumer()390 ASTConsumer *takeASTConsumer() { return Consumer.take(); } 391 392 /// setASTConsumer - Replace the current AST consumer; the compiler instance 393 /// takes ownership of \arg Value. 394 void setASTConsumer(ASTConsumer *Value); 395 396 /// } 397 /// @name Semantic analysis 398 /// { hasSema()399 bool hasSema() const { return TheSema != 0; } 400 getSema()401 Sema &getSema() const { 402 assert(TheSema && "Compiler instance has no Sema object!"); 403 return *TheSema; 404 } 405 takeSema()406 Sema *takeSema() { return TheSema.take(); } 407 408 /// } 409 /// @name Module Management 410 /// { 411 getModuleManager()412 ASTReader *getModuleManager() const { return ModuleManager; } 413 414 /// } 415 /// @name Code Completion 416 /// { 417 hasCodeCompletionConsumer()418 bool hasCodeCompletionConsumer() const { return CompletionConsumer != 0; } 419 getCodeCompletionConsumer()420 CodeCompleteConsumer &getCodeCompletionConsumer() const { 421 assert(CompletionConsumer && 422 "Compiler instance has no code completion consumer!"); 423 return *CompletionConsumer; 424 } 425 426 /// takeCodeCompletionConsumer - Remove the current code completion consumer 427 /// and give ownership to the caller. takeCodeCompletionConsumer()428 CodeCompleteConsumer *takeCodeCompletionConsumer() { 429 return CompletionConsumer.take(); 430 } 431 432 /// setCodeCompletionConsumer - Replace the current code completion consumer; 433 /// the compiler instance takes ownership of \arg Value. 434 void setCodeCompletionConsumer(CodeCompleteConsumer *Value); 435 436 /// } 437 /// @name Frontend timer 438 /// { 439 hasFrontendTimer()440 bool hasFrontendTimer() const { return FrontendTimer != 0; } 441 getFrontendTimer()442 llvm::Timer &getFrontendTimer() const { 443 assert(FrontendTimer && "Compiler instance has no frontend timer!"); 444 return *FrontendTimer; 445 } 446 447 /// } 448 /// @name Output Files 449 /// { 450 451 /// addOutputFile - Add an output file onto the list of tracked output files. 452 /// 453 /// \param OutFile - The output file info. 454 void addOutputFile(const OutputFile &OutFile); 455 456 /// clearOutputFiles - Clear the output file list, destroying the contained 457 /// output streams. 458 /// 459 /// \param EraseFiles - If true, attempt to erase the files from disk. 460 void clearOutputFiles(bool EraseFiles); 461 462 /// } 463 /// @name Construction Utility Methods 464 /// { 465 466 /// Create the diagnostics engine using the invocation's diagnostic options 467 /// and replace any existing one with it. 468 /// 469 /// Note that this routine also replaces the diagnostic client, 470 /// allocating one if one is not provided. 471 /// 472 /// \param Client If non-NULL, a diagnostic client that will be 473 /// attached to (and, then, owned by) the DiagnosticsEngine inside this AST 474 /// unit. 475 /// 476 /// \param ShouldOwnClient If Client is non-NULL, specifies whether 477 /// the diagnostic object should take ownership of the client. 478 /// 479 /// \param ShouldCloneClient If Client is non-NULL, specifies whether that 480 /// client should be cloned. 481 void createDiagnostics(int Argc, const char* const *Argv, 482 DiagnosticConsumer *Client = 0, 483 bool ShouldOwnClient = true, 484 bool ShouldCloneClient = true); 485 486 /// Create a DiagnosticsEngine object with a the TextDiagnosticPrinter. 487 /// 488 /// The \arg Argc and \arg Argv arguments are used only for logging purposes, 489 /// when the diagnostic options indicate that the compiler should output 490 /// logging information. 491 /// 492 /// If no diagnostic client is provided, this creates a 493 /// DiagnosticConsumer that is owned by the returned diagnostic 494 /// object, if using directly the caller is responsible for 495 /// releasing the returned DiagnosticsEngine's client eventually. 496 /// 497 /// \param Opts - The diagnostic options; note that the created text 498 /// diagnostic object contains a reference to these options and its lifetime 499 /// must extend past that of the diagnostic engine. 500 /// 501 /// \param Client If non-NULL, a diagnostic client that will be 502 /// attached to (and, then, owned by) the returned DiagnosticsEngine 503 /// object. 504 /// 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). 507 /// 508 /// \return The new object on success, or null on failure. 509 static IntrusiveRefCntPtr<DiagnosticsEngine> 510 createDiagnostics(const 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); 516 517 /// Create the file manager and replace any existing one with it. 518 void createFileManager(); 519 520 /// Create the source manager and replace any existing one with it. 521 void createSourceManager(FileManager &FileMgr); 522 523 /// Create the preprocessor, using the invocation, file, and source managers, 524 /// and replace any existing one with it. 525 void createPreprocessor(); 526 527 /// Create the AST context. 528 void createASTContext(); 529 530 /// Create an external AST source to read a PCH file and attach it to the AST 531 /// context. 532 void createPCHExternalASTSource(StringRef Path, 533 bool DisablePCHValidation, 534 bool DisableStatCache, 535 bool AllowPCHWithCompilerErrors, 536 void *DeserializationListener); 537 538 /// Create an external AST source to read a PCH file. 539 /// 540 /// \return - The new object on success, or null on failure. 541 static ExternalASTSource * 542 createPCHExternalASTSource(StringRef Path, const std::string &Sysroot, 543 bool DisablePCHValidation, 544 bool DisableStatCache, 545 bool AllowPCHWithCompilerErrors, 546 Preprocessor &PP, ASTContext &Context, 547 void *DeserializationListener, bool Preamble); 548 549 /// Create a code completion consumer using the invocation; note that this 550 /// will cause the source manager to truncate the input source file at the 551 /// completion point. 552 void createCodeCompletionConsumer(); 553 554 /// Create a code completion consumer to print code completion results, at 555 /// \arg Filename, \arg Line, and \arg Column, to the given output stream \arg 556 /// OS. 557 static CodeCompleteConsumer * 558 createCodeCompletionConsumer(Preprocessor &PP, const std::string &Filename, 559 unsigned Line, unsigned Column, 560 const CodeCompleteOptions &Opts, 561 raw_ostream &OS); 562 563 /// \brief Create the Sema object to be used for parsing. 564 void createSema(TranslationUnitKind TUKind, 565 CodeCompleteConsumer *CompletionConsumer); 566 567 /// Create the frontend timer and replace any existing one with it. 568 void createFrontendTimer(); 569 570 /// Create the default output file (from the invocation's options) and add it 571 /// to the list of tracked output files. 572 /// 573 /// The files created by this function always use temporary files to write to 574 /// their result (that is, the data is written to a temporary file which will 575 /// atomically replace the target output on success). 576 /// 577 /// \return - Null on error. 578 llvm::raw_fd_ostream * 579 createDefaultOutputFile(bool Binary = true, StringRef BaseInput = "", 580 StringRef Extension = ""); 581 582 /// Create a new output file and add it to the list of tracked output files, 583 /// optionally deriving the output path name. 584 /// 585 /// \return - Null on error. 586 llvm::raw_fd_ostream * 587 createOutputFile(StringRef OutputPath, 588 bool Binary = true, bool RemoveFileOnSignal = true, 589 StringRef BaseInput = "", 590 StringRef Extension = "", 591 bool UseTemporary = false, 592 bool CreateMissingDirectories = false); 593 594 /// Create a new output file, optionally deriving the output path name. 595 /// 596 /// If \arg OutputPath is empty, then createOutputFile will derive an output 597 /// path location as \arg BaseInput, with any suffix removed, and \arg 598 /// Extension appended. If OutputPath is not stdout and \arg UseTemporary 599 /// is true, createOutputFile will create a new temporary file that must be 600 /// renamed to OutputPath in the end. 601 /// 602 /// \param OutputPath - If given, the path to the output file. 603 /// \param Error [out] - On failure, the error message. 604 /// \param BaseInput - If \arg OutputPath is empty, the input path name to use 605 /// for deriving the output path. 606 /// \param Extension - The extension to use for derived output names. 607 /// \param Binary - The mode to open the file in. 608 /// \param RemoveFileOnSignal - Whether the file should be registered with 609 /// llvm::sys::RemoveFileOnSignal. Note that this is not safe for 610 /// multithreaded use, as the underlying signal mechanism is not reentrant 611 /// \param UseTemporary - Create a new temporary file that must be renamed to 612 /// OutputPath in the end. 613 /// \param CreateMissingDirectories - When \arg UseTemporary is true, create 614 /// missing directories in the output path. 615 /// \param ResultPathName [out] - If given, the result path name will be 616 /// stored here on success. 617 /// \param TempPathName [out] - If given, the temporary file path name 618 /// will be stored here on success. 619 static llvm::raw_fd_ostream * 620 createOutputFile(StringRef OutputPath, std::string &Error, 621 bool Binary = true, bool RemoveFileOnSignal = true, 622 StringRef BaseInput = "", 623 StringRef Extension = "", 624 bool UseTemporary = false, 625 bool CreateMissingDirectories = false, 626 std::string *ResultPathName = 0, 627 std::string *TempPathName = 0); 628 629 /// } 630 /// @name Initialization Utility Methods 631 /// { 632 633 /// InitializeSourceManager - Initialize the source manager to set InputFile 634 /// as the main file. 635 /// 636 /// \return True on success. 637 bool InitializeSourceManager(StringRef InputFile, 638 SrcMgr::CharacteristicKind Kind = SrcMgr::C_User); 639 640 /// InitializeSourceManager - Initialize the source manager to set InputFile 641 /// as the main file. 642 /// 643 /// \return True on success. 644 static bool InitializeSourceManager(StringRef InputFile, 645 SrcMgr::CharacteristicKind Kind, 646 DiagnosticsEngine &Diags, 647 FileManager &FileMgr, 648 SourceManager &SourceMgr, 649 const FrontendOptions &Opts); 650 651 /// } 652 653 virtual Module *loadModule(SourceLocation ImportLoc, ModuleIdPath Path, 654 Module::NameVisibilityKind Visibility, 655 bool IsInclusionDirective); 656 }; 657 658 } // end namespace clang 659 660 #endif 661