CompilerInstance.h revision 49009ec701feb3009450e57e40c656e2ad7c1f41
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/Lex/ModuleLoader.h" 15#include "clang/Lex/ModuleMap.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 26namespace llvm { 27class raw_fd_ostream; 28class Timer; 29} 30 31namespace clang { 32class ASTContext; 33class ASTConsumer; 34class ASTReader; 35class CodeCompleteConsumer; 36class DiagnosticsEngine; 37class DiagnosticConsumer; 38class ExternalASTSource; 39class FileEntry; 40class FileManager; 41class FrontendAction; 42class Preprocessor; 43class Sema; 44class SourceManager; 45class TargetInfo; 46 47/// CompilerInstance - Helper class for managing a single instance of the Clang 48/// compiler. 49/// 50/// The CompilerInstance serves two purposes: 51/// (1) It manages the various objects which are necessary to run the compiler, 52/// for example the preprocessor, the target information, and the AST 53/// context. 54/// (2) It provides utility routines for constructing and manipulating the 55/// common Clang objects. 56/// 57/// The compiler instance generally owns the instance of all the objects that it 58/// manages. However, clients can still share objects by manually setting the 59/// object and retaking ownership prior to destroying the CompilerInstance. 60/// 61/// The compiler instance is intended to simplify clients, but not to lock them 62/// in to the compiler instance for everything. When possible, utility functions 63/// come in two forms; a short form that reuses the CompilerInstance objects, 64/// and a long form that takes explicit instances of any required objects. 65class CompilerInstance : public ModuleLoader { 66 /// The options used in this compiler instance. 67 llvm::IntrusiveRefCntPtr<CompilerInvocation> Invocation; 68 69 /// The diagnostics engine instance. 70 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diagnostics; 71 72 /// The target being compiled for. 73 llvm::IntrusiveRefCntPtr<TargetInfo> Target; 74 75 /// The file manager. 76 llvm::IntrusiveRefCntPtr<FileManager> FileMgr; 77 78 /// The source manager. 79 llvm::IntrusiveRefCntPtr<SourceManager> SourceMgr; 80 81 /// The preprocessor. 82 llvm::IntrusiveRefCntPtr<Preprocessor> PP; 83 84 /// The AST context. 85 llvm::IntrusiveRefCntPtr<ASTContext> Context; 86 87 /// The AST consumer. 88 llvm::OwningPtr<ASTConsumer> Consumer; 89 90 /// The code completion consumer. 91 llvm::OwningPtr<CodeCompleteConsumer> CompletionConsumer; 92 93 /// \brief The semantic analysis object. 94 llvm::OwningPtr<Sema> TheSema; 95 96 /// \brief The frontend timer 97 llvm::OwningPtr<llvm::Timer> FrontendTimer; 98 99 /// \brief Non-owning reference to the ASTReader, if one exists. 100 ASTReader *ModuleManager; 101 102 /// \brief A module that we have already attempted to load, which is known 103 /// by either a file entry (FIXME: a temporary measure) or via its module 104 /// definition. 105 typedef llvm::PointerUnion<const FileEntry *, ModuleMap::Module *> 106 KnownModule; 107 108 /// \brief The set of top-level modules that has already been loaded, 109 /// along with the module map 110 llvm::DenseMap<const IdentifierInfo *, KnownModule> KnownModules; 111 112 /// \brief Holds information about the output file. 113 /// 114 /// If TempFilename is not empty we must rename it to Filename at the end. 115 /// TempFilename may be empty and Filename non empty if creating the temporary 116 /// failed. 117 struct OutputFile { 118 std::string Filename; 119 std::string TempFilename; 120 raw_ostream *OS; 121 122 OutputFile(const std::string &filename, const std::string &tempFilename, 123 raw_ostream *os) 124 : Filename(filename), TempFilename(tempFilename), OS(os) { } 125 }; 126 127 /// The list of active output files. 128 std::list<OutputFile> OutputFiles; 129 130 void operator=(const CompilerInstance &); // DO NOT IMPLEMENT 131 CompilerInstance(const CompilerInstance&); // DO NOT IMPLEMENT 132public: 133 CompilerInstance(); 134 ~CompilerInstance(); 135 136 /// @name High-Level Operations 137 /// { 138 139 /// ExecuteAction - Execute the provided action against the compiler's 140 /// CompilerInvocation object. 141 /// 142 /// This function makes the following assumptions: 143 /// 144 /// - The invocation options should be initialized. This function does not 145 /// handle the '-help' or '-version' options, clients should handle those 146 /// directly. 147 /// 148 /// - The diagnostics engine should have already been created by the client. 149 /// 150 /// - No other CompilerInstance state should have been initialized (this is 151 /// an unchecked error). 152 /// 153 /// - Clients should have initialized any LLVM target features that may be 154 /// required. 155 /// 156 /// - Clients should eventually call llvm_shutdown() upon the completion of 157 /// this routine to ensure that any managed objects are properly destroyed. 158 /// 159 /// Note that this routine may write output to 'stderr'. 160 /// 161 /// \param Act - The action to execute. 162 /// \return - True on success. 163 // 164 // FIXME: This function should take the stream to write any debugging / 165 // verbose output to as an argument. 166 // 167 // FIXME: Eliminate the llvm_shutdown requirement, that should either be part 168 // of the context or else not CompilerInstance specific. 169 bool ExecuteAction(FrontendAction &Act); 170 171 /// } 172 /// @name Compiler Invocation and Options 173 /// { 174 175 bool hasInvocation() const { return Invocation != 0; } 176 177 CompilerInvocation &getInvocation() { 178 assert(Invocation && "Compiler instance has no invocation!"); 179 return *Invocation; 180 } 181 182 /// setInvocation - Replace the current invocation. 183 void setInvocation(CompilerInvocation *Value); 184 185 /// } 186 /// @name Forwarding Methods 187 /// { 188 189 AnalyzerOptions &getAnalyzerOpts() { 190 return Invocation->getAnalyzerOpts(); 191 } 192 const AnalyzerOptions &getAnalyzerOpts() const { 193 return Invocation->getAnalyzerOpts(); 194 } 195 196 CodeGenOptions &getCodeGenOpts() { 197 return Invocation->getCodeGenOpts(); 198 } 199 const CodeGenOptions &getCodeGenOpts() const { 200 return Invocation->getCodeGenOpts(); 201 } 202 203 DependencyOutputOptions &getDependencyOutputOpts() { 204 return Invocation->getDependencyOutputOpts(); 205 } 206 const DependencyOutputOptions &getDependencyOutputOpts() const { 207 return Invocation->getDependencyOutputOpts(); 208 } 209 210 DiagnosticOptions &getDiagnosticOpts() { 211 return Invocation->getDiagnosticOpts(); 212 } 213 const DiagnosticOptions &getDiagnosticOpts() const { 214 return Invocation->getDiagnosticOpts(); 215 } 216 217 const FileSystemOptions &getFileSystemOpts() const { 218 return Invocation->getFileSystemOpts(); 219 } 220 221 FrontendOptions &getFrontendOpts() { 222 return Invocation->getFrontendOpts(); 223 } 224 const FrontendOptions &getFrontendOpts() const { 225 return Invocation->getFrontendOpts(); 226 } 227 228 HeaderSearchOptions &getHeaderSearchOpts() { 229 return Invocation->getHeaderSearchOpts(); 230 } 231 const HeaderSearchOptions &getHeaderSearchOpts() const { 232 return Invocation->getHeaderSearchOpts(); 233 } 234 235 LangOptions &getLangOpts() { 236 return *Invocation->getLangOpts(); 237 } 238 const LangOptions &getLangOpts() const { 239 return *Invocation->getLangOpts(); 240 } 241 242 PreprocessorOptions &getPreprocessorOpts() { 243 return Invocation->getPreprocessorOpts(); 244 } 245 const PreprocessorOptions &getPreprocessorOpts() const { 246 return Invocation->getPreprocessorOpts(); 247 } 248 249 PreprocessorOutputOptions &getPreprocessorOutputOpts() { 250 return Invocation->getPreprocessorOutputOpts(); 251 } 252 const PreprocessorOutputOptions &getPreprocessorOutputOpts() const { 253 return Invocation->getPreprocessorOutputOpts(); 254 } 255 256 TargetOptions &getTargetOpts() { 257 return Invocation->getTargetOpts(); 258 } 259 const TargetOptions &getTargetOpts() const { 260 return Invocation->getTargetOpts(); 261 } 262 263 /// } 264 /// @name Diagnostics Engine 265 /// { 266 267 bool hasDiagnostics() const { return Diagnostics != 0; } 268 269 /// Get the current diagnostics engine. 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 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 288 bool hasTarget() const { return Target != 0; } 289 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 302 bool hasFileManager() const { return FileMgr != 0; } 303 304 /// Return the current file manager to the caller. 305 FileManager &getFileManager() const { 306 assert(FileMgr && "Compiler instance has no file manager!"); 307 return *FileMgr; 308 } 309 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 321 bool hasSourceManager() const { return SourceMgr != 0; } 322 323 /// Return the current source manager. 324 SourceManager &getSourceManager() const { 325 assert(SourceMgr && "Compiler instance has no source manager!"); 326 return *SourceMgr; 327 } 328 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 340 bool hasPreprocessor() const { return PP != 0; } 341 342 /// Return the current preprocessor. 343 Preprocessor &getPreprocessor() const { 344 assert(PP && "Compiler instance has no preprocessor!"); 345 return *PP; 346 } 347 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 359 bool hasASTContext() const { return Context != 0; } 360 361 ASTContext &getASTContext() const { 362 assert(Context && "Compiler instance has no AST context!"); 363 return *Context; 364 } 365 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 381 bool hasASTConsumer() const { return Consumer != 0; } 382 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. 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 /// { 399 bool hasSema() const { return TheSema != 0; } 400 401 Sema &getSema() const { 402 assert(TheSema && "Compiler instance has no Sema object!"); 403 return *TheSema; 404 } 405 406 Sema *takeSema() { return TheSema.take(); } 407 408 /// } 409 /// @name Module Management 410 /// { 411 412 ASTReader *getModuleManager() const { return ModuleManager; } 413 414 /// } 415 /// @name Code Completion 416 /// { 417 418 bool hasCodeCompletionConsumer() const { return CompletionConsumer != 0; } 419 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. 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 440 bool hasFrontendTimer() const { return FrontendTimer != 0; } 441 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 llvm::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 void *DeserializationListener); 536 537 /// Create an external AST source to read a PCH file. 538 /// 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 DisableStatCache, 544 Preprocessor &PP, ASTContext &Context, 545 void *DeserializationListener, bool Preamble); 546 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(); 551 552 /// Create a code completion consumer to print code completion results, at 553 /// \arg Filename, \arg Line, and \arg Column, to the given output stream \arg 554 /// OS. 555 static CodeCompleteConsumer * 556 createCodeCompletionConsumer(Preprocessor &PP, const std::string &Filename, 557 unsigned Line, unsigned Column, 558 bool ShowMacros, 559 bool ShowCodePatterns, bool ShowGlobals, 560 raw_ostream &OS); 561 562 /// \brief Create the Sema object to be used for parsing. 563 void createSema(TranslationUnitKind TUKind, 564 CodeCompleteConsumer *CompletionConsumer); 565 566 /// Create the frontend timer and replace any existing one with it. 567 void createFrontendTimer(); 568 569 /// Create the default output file (from the invocation's options) and add it 570 /// to the list of tracked output files. 571 /// 572 /// \return - Null on error. 573 llvm::raw_fd_ostream * 574 createDefaultOutputFile(bool Binary = true, StringRef BaseInput = "", 575 StringRef Extension = ""); 576 577 /// Create a new output file and add it to the list of tracked output files, 578 /// optionally deriving the output path name. 579 /// 580 /// \return - Null on error. 581 llvm::raw_fd_ostream * 582 createOutputFile(StringRef OutputPath, 583 bool Binary = true, bool RemoveFileOnSignal = true, 584 StringRef BaseInput = "", 585 StringRef Extension = "", 586 bool UseTemporary = false); 587 588 /// Create a new output file, optionally deriving the output path name. 589 /// 590 /// If \arg OutputPath is empty, then createOutputFile will derive an output 591 /// path location as \arg BaseInput, with any suffix removed, and \arg 592 /// Extension appended. If OutputPath is not stdout and \arg UseTemporary 593 /// is true, createOutputFile will create a new temporary file that must be 594 /// renamed to OutputPath in the end. 595 /// 596 /// \param OutputPath - If given, the path to the output file. 597 /// \param Error [out] - On failure, the error message. 598 /// \param BaseInput - If \arg OutputPath is empty, the input path name to use 599 /// for deriving the output path. 600 /// \param Extension - The extension to use for derived output names. 601 /// \param Binary - The mode to open the file in. 602 /// \param RemoveFileOnSignal - Whether the file should be registered with 603 /// llvm::sys::RemoveFileOnSignal. Note that this is not safe for 604 /// multithreaded use, as the underlying signal mechanism is not reentrant 605 /// \param UseTemporary - Create a new temporary file that must be renamed to 606 /// OutputPath in the end 607 /// \param ResultPathName [out] - If given, the result path name will be 608 /// stored here on success. 609 /// \param TempPathName [out] - If given, the temporary file path name 610 /// will be stored here on success. 611 static llvm::raw_fd_ostream * 612 createOutputFile(StringRef OutputPath, std::string &Error, 613 bool Binary = true, bool RemoveFileOnSignal = true, 614 StringRef BaseInput = "", 615 StringRef Extension = "", 616 bool UseTemporary = false, 617 std::string *ResultPathName = 0, 618 std::string *TempPathName = 0); 619 620 /// } 621 /// @name Initialization Utility Methods 622 /// { 623 624 /// InitializeSourceManager - Initialize the source manager to set InputFile 625 /// as the main file. 626 /// 627 /// \return True on success. 628 bool InitializeSourceManager(StringRef InputFile); 629 630 /// InitializeSourceManager - Initialize the source manager to set InputFile 631 /// as the main file. 632 /// 633 /// \return True on success. 634 static bool InitializeSourceManager(StringRef InputFile, 635 DiagnosticsEngine &Diags, 636 FileManager &FileMgr, 637 SourceManager &SourceMgr, 638 const FrontendOptions &Opts); 639 640 /// } 641 642 virtual ModuleKey loadModule(SourceLocation ImportLoc, ModuleIdPath Path); 643}; 644 645} // end namespace clang 646 647#endif 648