CompilerInstance.cpp revision 33e4e70c8c0a17e0ccb7465d96556b077a68ecb1
1//===--- CompilerInstance.cpp ---------------------------------------------===// 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#include "clang/Frontend/CompilerInstance.h" 11#include "clang/Sema/Sema.h" 12#include "clang/AST/ASTConsumer.h" 13#include "clang/AST/ASTContext.h" 14#include "clang/Basic/Diagnostic.h" 15#include "clang/Basic/FileManager.h" 16#include "clang/Basic/SourceManager.h" 17#include "clang/Basic/TargetInfo.h" 18#include "clang/Basic/Version.h" 19#include "clang/Lex/HeaderSearch.h" 20#include "clang/Lex/Preprocessor.h" 21#include "clang/Lex/PTHManager.h" 22#include "clang/Frontend/ChainedDiagnosticClient.h" 23#include "clang/Frontend/FrontendAction.h" 24#include "clang/Frontend/FrontendDiagnostic.h" 25#include "clang/Frontend/TextDiagnosticPrinter.h" 26#include "clang/Frontend/VerifyDiagnosticsClient.h" 27#include "clang/Frontend/Utils.h" 28#include "clang/Serialization/ASTReader.h" 29#include "clang/Sema/CodeCompleteConsumer.h" 30#include "llvm/LLVMContext.h" 31#include "llvm/Support/MemoryBuffer.h" 32#include "llvm/Support/raw_ostream.h" 33#include "llvm/ADT/Statistic.h" 34#include "llvm/Support/Timer.h" 35#include "llvm/System/Host.h" 36#include "llvm/System/Path.h" 37#include "llvm/System/Program.h" 38#include "llvm/System/Signals.h" 39using namespace clang; 40 41CompilerInstance::CompilerInstance() 42 : Invocation(new CompilerInvocation()) { 43} 44 45CompilerInstance::~CompilerInstance() { 46} 47 48void CompilerInstance::setLLVMContext(llvm::LLVMContext *Value) { 49 LLVMContext.reset(Value); 50} 51 52void CompilerInstance::setInvocation(CompilerInvocation *Value) { 53 Invocation.reset(Value); 54} 55 56void CompilerInstance::setDiagnostics(Diagnostic *Value) { 57 Diagnostics = Value; 58} 59 60void CompilerInstance::setTarget(TargetInfo *Value) { 61 Target.reset(Value); 62} 63 64void CompilerInstance::setFileManager(FileManager *Value) { 65 FileMgr.reset(Value); 66} 67 68void CompilerInstance::setSourceManager(SourceManager *Value) { 69 SourceMgr.reset(Value); 70} 71 72void CompilerInstance::setPreprocessor(Preprocessor *Value) { 73 PP.reset(Value); 74} 75 76void CompilerInstance::setASTContext(ASTContext *Value) { 77 Context.reset(Value); 78} 79 80void CompilerInstance::setSema(Sema *S) { 81 TheSema.reset(S); 82} 83 84void CompilerInstance::setASTConsumer(ASTConsumer *Value) { 85 Consumer.reset(Value); 86} 87 88void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) { 89 CompletionConsumer.reset(Value); 90} 91 92// Diagnostics 93static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts, 94 unsigned argc, const char* const *argv, 95 Diagnostic &Diags) { 96 std::string ErrorInfo; 97 llvm::OwningPtr<llvm::raw_ostream> OS( 98 new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo)); 99 if (!ErrorInfo.empty()) { 100 Diags.Report(diag::err_fe_unable_to_open_logfile) 101 << DiagOpts.DumpBuildInformation << ErrorInfo; 102 return; 103 } 104 105 (*OS) << "clang -cc1 command line arguments: "; 106 for (unsigned i = 0; i != argc; ++i) 107 (*OS) << argv[i] << ' '; 108 (*OS) << '\n'; 109 110 // Chain in a diagnostic client which will log the diagnostics. 111 DiagnosticClient *Logger = 112 new TextDiagnosticPrinter(*OS.take(), DiagOpts, /*OwnsOutputStream=*/true); 113 Diags.setClient(new ChainedDiagnosticClient(Diags.takeClient(), Logger)); 114} 115 116void CompilerInstance::createDiagnostics(int Argc, const char* const *Argv, 117 DiagnosticClient *Client) { 118 Diagnostics = createDiagnostics(getDiagnosticOpts(), Argc, Argv, Client); 119} 120 121llvm::IntrusiveRefCntPtr<Diagnostic> 122CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts, 123 int Argc, const char* const *Argv, 124 DiagnosticClient *Client) { 125 llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs()); 126 llvm::IntrusiveRefCntPtr<Diagnostic> Diags(new Diagnostic(DiagID)); 127 128 // Create the diagnostic client for reporting errors or for 129 // implementing -verify. 130 if (Client) 131 Diags->setClient(Client); 132 else 133 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts)); 134 135 // Chain in -verify checker, if requested. 136 if (Opts.VerifyDiagnostics) 137 Diags->setClient(new VerifyDiagnosticsClient(*Diags, Diags->takeClient())); 138 139 if (!Opts.DumpBuildInformation.empty()) 140 SetUpBuildDumpLog(Opts, Argc, Argv, *Diags); 141 142 // Configure our handling of diagnostics. 143 ProcessWarningOptions(*Diags, Opts); 144 145 return Diags; 146} 147 148// File Manager 149 150void CompilerInstance::createFileManager() { 151 FileMgr.reset(new FileManager()); 152} 153 154// Source Manager 155 156void CompilerInstance::createSourceManager(FileManager &FileMgr, 157 const FileSystemOptions &FSOpts) { 158 SourceMgr.reset(new SourceManager(getDiagnostics(), FileMgr, FSOpts)); 159} 160 161// Preprocessor 162 163void CompilerInstance::createPreprocessor() { 164 PP.reset(createPreprocessor(getDiagnostics(), getLangOpts(), 165 getPreprocessorOpts(), getHeaderSearchOpts(), 166 getDependencyOutputOpts(), getTarget(), 167 getFrontendOpts(), getFileSystemOpts(), 168 getSourceManager(), getFileManager())); 169} 170 171Preprocessor * 172CompilerInstance::createPreprocessor(Diagnostic &Diags, 173 const LangOptions &LangInfo, 174 const PreprocessorOptions &PPOpts, 175 const HeaderSearchOptions &HSOpts, 176 const DependencyOutputOptions &DepOpts, 177 const TargetInfo &Target, 178 const FrontendOptions &FEOpts, 179 const FileSystemOptions &FSOpts, 180 SourceManager &SourceMgr, 181 FileManager &FileMgr) { 182 // Create a PTH manager if we are using some form of a token cache. 183 PTHManager *PTHMgr = 0; 184 if (!PPOpts.TokenCache.empty()) 185 PTHMgr = PTHManager::Create(PPOpts.TokenCache, FileMgr, FSOpts, Diags); 186 187 // Create the Preprocessor. 188 HeaderSearch *HeaderInfo = new HeaderSearch(FileMgr, FSOpts); 189 Preprocessor *PP = new Preprocessor(Diags, LangInfo, Target, 190 SourceMgr, *HeaderInfo, PTHMgr, 191 /*OwnsHeaderSearch=*/true); 192 193 // Note that this is different then passing PTHMgr to Preprocessor's ctor. 194 // That argument is used as the IdentifierInfoLookup argument to 195 // IdentifierTable's ctor. 196 if (PTHMgr) { 197 PTHMgr->setPreprocessor(PP); 198 PP->setPTHManager(PTHMgr); 199 } 200 201 if (PPOpts.DetailedRecord) 202 PP->createPreprocessingRecord(); 203 204 InitializePreprocessor(*PP, FSOpts, PPOpts, HSOpts, FEOpts); 205 206 // Handle generating dependencies, if requested. 207 if (!DepOpts.OutputFile.empty()) 208 AttachDependencyFileGen(*PP, DepOpts); 209 210 return PP; 211} 212 213// ASTContext 214 215void CompilerInstance::createASTContext() { 216 Preprocessor &PP = getPreprocessor(); 217 Context.reset(new ASTContext(getLangOpts(), PP.getSourceManager(), 218 getTarget(), PP.getIdentifierTable(), 219 PP.getSelectorTable(), PP.getBuiltinInfo(), 220 /*size_reserve=*/ 0)); 221} 222 223// ExternalASTSource 224 225void CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path, 226 bool DisablePCHValidation, 227 void *DeserializationListener){ 228 llvm::OwningPtr<ExternalASTSource> Source; 229 bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0; 230 Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot, 231 DisablePCHValidation, 232 getPreprocessor(), getASTContext(), 233 DeserializationListener, 234 Preamble)); 235 getASTContext().setExternalSource(Source); 236} 237 238ExternalASTSource * 239CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path, 240 const std::string &Sysroot, 241 bool DisablePCHValidation, 242 Preprocessor &PP, 243 ASTContext &Context, 244 void *DeserializationListener, 245 bool Preamble) { 246 llvm::OwningPtr<ASTReader> Reader; 247 Reader.reset(new ASTReader(PP, &Context, 248 Sysroot.empty() ? 0 : Sysroot.c_str(), 249 DisablePCHValidation)); 250 251 Reader->setDeserializationListener( 252 static_cast<ASTDeserializationListener *>(DeserializationListener)); 253 switch (Reader->ReadAST(Path, 254 Preamble ? ASTReader::Preamble : ASTReader::PCH)) { 255 case ASTReader::Success: 256 // Set the predefines buffer as suggested by the PCH reader. Typically, the 257 // predefines buffer will be empty. 258 PP.setPredefines(Reader->getSuggestedPredefines()); 259 return Reader.take(); 260 261 case ASTReader::Failure: 262 // Unrecoverable failure: don't even try to process the input file. 263 break; 264 265 case ASTReader::IgnorePCH: 266 // No suitable PCH file could be found. Return an error. 267 break; 268 } 269 270 return 0; 271} 272 273// Code Completion 274 275static bool EnableCodeCompletion(Preprocessor &PP, 276 const std::string &Filename, 277 unsigned Line, 278 unsigned Column) { 279 // Tell the source manager to chop off the given file at a specific 280 // line and column. 281 const FileEntry *Entry = PP.getFileManager().getFile(Filename, 282 PP.getFileSystemOpts()); 283 if (!Entry) { 284 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file) 285 << Filename; 286 return true; 287 } 288 289 // Truncate the named file at the given line/column. 290 PP.SetCodeCompletionPoint(Entry, Line, Column); 291 return false; 292} 293 294void CompilerInstance::createCodeCompletionConsumer() { 295 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt; 296 if (!CompletionConsumer) { 297 CompletionConsumer.reset( 298 createCodeCompletionConsumer(getPreprocessor(), 299 Loc.FileName, Loc.Line, Loc.Column, 300 getFrontendOpts().ShowMacrosInCodeCompletion, 301 getFrontendOpts().ShowCodePatternsInCodeCompletion, 302 getFrontendOpts().ShowGlobalSymbolsInCodeCompletion, 303 llvm::outs())); 304 if (!CompletionConsumer) 305 return; 306 } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName, 307 Loc.Line, Loc.Column)) { 308 CompletionConsumer.reset(); 309 return; 310 } 311 312 if (CompletionConsumer->isOutputBinary() && 313 llvm::sys::Program::ChangeStdoutToBinary()) { 314 getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary); 315 CompletionConsumer.reset(); 316 } 317} 318 319void CompilerInstance::createFrontendTimer() { 320 FrontendTimer.reset(new llvm::Timer("Clang front-end timer")); 321} 322 323CodeCompleteConsumer * 324CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP, 325 const std::string &Filename, 326 unsigned Line, 327 unsigned Column, 328 bool ShowMacros, 329 bool ShowCodePatterns, 330 bool ShowGlobals, 331 llvm::raw_ostream &OS) { 332 if (EnableCodeCompletion(PP, Filename, Line, Column)) 333 return 0; 334 335 // Set up the creation routine for code-completion. 336 return new PrintingCodeCompleteConsumer(ShowMacros, ShowCodePatterns, 337 ShowGlobals, OS); 338} 339 340void CompilerInstance::createSema(bool CompleteTranslationUnit, 341 CodeCompleteConsumer *CompletionConsumer) { 342 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(), 343 CompleteTranslationUnit, CompletionConsumer)); 344} 345 346// Output Files 347 348void CompilerInstance::addOutputFile(const OutputFile &OutFile) { 349 assert(OutFile.OS && "Attempt to add empty stream to output list!"); 350 OutputFiles.push_back(OutFile); 351} 352 353void CompilerInstance::clearOutputFiles(bool EraseFiles) { 354 for (std::list<OutputFile>::iterator 355 it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) { 356 delete it->OS; 357 if (!it->TempFilename.empty()) { 358 llvm::sys::Path TempPath(it->TempFilename); 359 if (EraseFiles) 360 TempPath.eraseFromDisk(); 361 else { 362 std::string Error; 363 llvm::sys::Path NewOutFile(it->Filename); 364 // If '-working-directory' was passed, the output filename should be 365 // relative to that. 366 FileManager::FixupRelativePath(NewOutFile, getFileSystemOpts()); 367 if (TempPath.renamePathOnDisk(NewOutFile, &Error)) { 368 getDiagnostics().Report(diag::err_fe_unable_to_rename_temp) 369 << it->TempFilename << it->Filename << Error; 370 TempPath.eraseFromDisk(); 371 } 372 } 373 } else if (!it->Filename.empty() && EraseFiles) 374 llvm::sys::Path(it->Filename).eraseFromDisk(); 375 376 } 377 OutputFiles.clear(); 378} 379 380llvm::raw_fd_ostream * 381CompilerInstance::createDefaultOutputFile(bool Binary, 382 llvm::StringRef InFile, 383 llvm::StringRef Extension) { 384 return createOutputFile(getFrontendOpts().OutputFile, Binary, 385 InFile, Extension); 386} 387 388llvm::raw_fd_ostream * 389CompilerInstance::createOutputFile(llvm::StringRef OutputPath, 390 bool Binary, 391 llvm::StringRef InFile, 392 llvm::StringRef Extension) { 393 std::string Error, OutputPathName, TempPathName; 394 llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary, 395 InFile, Extension, 396 &OutputPathName, 397 &TempPathName); 398 if (!OS) { 399 getDiagnostics().Report(diag::err_fe_unable_to_open_output) 400 << OutputPath << Error; 401 return 0; 402 } 403 404 // Add the output file -- but don't try to remove "-", since this means we are 405 // using stdin. 406 addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "", 407 TempPathName, OS)); 408 409 return OS; 410} 411 412llvm::raw_fd_ostream * 413CompilerInstance::createOutputFile(llvm::StringRef OutputPath, 414 std::string &Error, 415 bool Binary, 416 llvm::StringRef InFile, 417 llvm::StringRef Extension, 418 std::string *ResultPathName, 419 std::string *TempPathName) { 420 std::string OutFile, TempFile; 421 if (!OutputPath.empty()) { 422 OutFile = OutputPath; 423 } else if (InFile == "-") { 424 OutFile = "-"; 425 } else if (!Extension.empty()) { 426 llvm::sys::Path Path(InFile); 427 Path.eraseSuffix(); 428 Path.appendSuffix(Extension); 429 OutFile = Path.str(); 430 } else { 431 OutFile = "-"; 432 } 433 434 if (OutFile != "-") { 435 llvm::sys::Path OutPath(OutFile); 436 // Only create the temporary if we can actually write to OutPath, otherwise 437 // we want to fail early. 438 if (!OutPath.exists() || 439 (OutPath.isRegularFile() && OutPath.canWrite())) { 440 // Create a temporary file. 441 llvm::sys::Path TempPath(OutFile); 442 if (!TempPath.createTemporaryFileOnDisk()) 443 TempFile = TempPath.str(); 444 } 445 } 446 447 std::string OSFile = OutFile; 448 if (!TempFile.empty()) 449 OSFile = TempFile; 450 451 llvm::OwningPtr<llvm::raw_fd_ostream> OS( 452 new llvm::raw_fd_ostream(OSFile.c_str(), Error, 453 (Binary ? llvm::raw_fd_ostream::F_Binary : 0))); 454 if (!Error.empty()) 455 return 0; 456 457 // Make sure the out stream file gets removed if we crash. 458 llvm::sys::RemoveFileOnSignal(llvm::sys::Path(OSFile)); 459 460 if (ResultPathName) 461 *ResultPathName = OutFile; 462 if (TempPathName) 463 *TempPathName = TempFile; 464 465 return OS.take(); 466} 467 468// Initialization Utilities 469 470bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile) { 471 return InitializeSourceManager(InputFile, getDiagnostics(), getFileManager(), 472 getFileSystemOpts(), 473 getSourceManager(), getFrontendOpts()); 474} 475 476bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile, 477 Diagnostic &Diags, 478 FileManager &FileMgr, 479 const FileSystemOptions &FSOpts, 480 SourceManager &SourceMgr, 481 const FrontendOptions &Opts) { 482 // Figure out where to get and map in the main file. 483 if (InputFile != "-") { 484 const FileEntry *File = FileMgr.getFile(InputFile, FSOpts); 485 if (!File) { 486 Diags.Report(diag::err_fe_error_reading) << InputFile; 487 return false; 488 } 489 SourceMgr.createMainFileID(File); 490 } else { 491 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN(); 492 if (!SB) { 493 Diags.Report(diag::err_fe_error_reading_stdin); 494 return false; 495 } 496 const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(), 497 SB->getBufferSize(), 0, 498 FSOpts); 499 SourceMgr.createMainFileID(File); 500 SourceMgr.overrideFileContents(File, SB); 501 } 502 503 assert(!SourceMgr.getMainFileID().isInvalid() && 504 "Couldn't establish MainFileID!"); 505 return true; 506} 507 508// High-Level Operations 509 510bool CompilerInstance::ExecuteAction(FrontendAction &Act) { 511 assert(hasDiagnostics() && "Diagnostics engine is not initialized!"); 512 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!"); 513 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!"); 514 515 // FIXME: Take this as an argument, once all the APIs we used have moved to 516 // taking it as an input instead of hard-coding llvm::errs. 517 llvm::raw_ostream &OS = llvm::errs(); 518 519 // Create the target instance. 520 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts())); 521 if (!hasTarget()) 522 return false; 523 524 // Inform the target of the language options. 525 // 526 // FIXME: We shouldn't need to do this, the target should be immutable once 527 // created. This complexity should be lifted elsewhere. 528 getTarget().setForcedLangOptions(getLangOpts()); 529 530 // Validate/process some options. 531 if (getHeaderSearchOpts().Verbose) 532 OS << "clang -cc1 version " CLANG_VERSION_STRING 533 << " based upon " << PACKAGE_STRING 534 << " hosted on " << llvm::sys::getHostTriple() << "\n"; 535 536 if (getFrontendOpts().ShowTimers) 537 createFrontendTimer(); 538 539 if (getFrontendOpts().ShowStats) 540 llvm::EnableStatistics(); 541 542 for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) { 543 const std::string &InFile = getFrontendOpts().Inputs[i].second; 544 545 // Reset the ID tables if we are reusing the SourceManager. 546 if (hasSourceManager()) 547 getSourceManager().clearIDTables(); 548 549 if (Act.BeginSourceFile(*this, InFile, getFrontendOpts().Inputs[i].first)) { 550 Act.Execute(); 551 Act.EndSourceFile(); 552 } 553 } 554 555 if (getDiagnosticOpts().ShowCarets) { 556 unsigned NumWarnings = getDiagnostics().getNumWarnings(); 557 unsigned NumErrors = getDiagnostics().getNumErrors() - 558 getDiagnostics().getNumErrorsSuppressed(); 559 560 if (NumWarnings) 561 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s"); 562 if (NumWarnings && NumErrors) 563 OS << " and "; 564 if (NumErrors) 565 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s"); 566 if (NumWarnings || NumErrors) 567 OS << " generated.\n"; 568 } 569 570 if (getFrontendOpts().ShowStats && hasFileManager()) { 571 getFileManager().PrintStats(); 572 OS << "\n"; 573 } 574 575 // Return the appropriate status when verifying diagnostics. 576 // 577 // FIXME: If we could make getNumErrors() do the right thing, we wouldn't need 578 // this. 579 if (getDiagnosticOpts().VerifyDiagnostics) 580 return !static_cast<VerifyDiagnosticsClient&>( 581 getDiagnosticClient()).HadErrors(); 582 583 return !getDiagnostics().getNumErrors(); 584} 585 586 587