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