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