CompilerInstance.cpp revision 621bc69624599da62abd9bc9e5edd8a63ac99fe6
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/ChainedDiagnosticConsumer.h" 23#include "clang/Frontend/FrontendAction.h" 24#include "clang/Frontend/FrontendActions.h" 25#include "clang/Frontend/FrontendDiagnostic.h" 26#include "clang/Frontend/LogDiagnosticPrinter.h" 27#include "clang/Frontend/TextDiagnosticPrinter.h" 28#include "clang/Frontend/VerifyDiagnosticConsumer.h" 29#include "clang/Frontend/Utils.h" 30#include "clang/Serialization/ASTReader.h" 31#include "clang/Sema/CodeCompleteConsumer.h" 32#include "llvm/Support/FileSystem.h" 33#include "llvm/Support/MemoryBuffer.h" 34#include "llvm/Support/raw_ostream.h" 35#include "llvm/ADT/Statistic.h" 36#include "llvm/Support/Timer.h" 37#include "llvm/Support/Host.h" 38#include "llvm/Support/Path.h" 39#include "llvm/Support/Program.h" 40#include "llvm/Support/Signals.h" 41#include "llvm/Support/system_error.h" 42#include "llvm/Config/config.h" 43using namespace clang; 44 45CompilerInstance::CompilerInstance() 46 : Invocation(new CompilerInvocation()), ModuleManager(0) { 47} 48 49CompilerInstance::~CompilerInstance() { 50} 51 52void CompilerInstance::setInvocation(CompilerInvocation *Value) { 53 Invocation = Value; 54} 55 56void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) { 57 Diagnostics = Value; 58} 59 60void CompilerInstance::setTarget(TargetInfo *Value) { 61 Target = Value; 62} 63 64void CompilerInstance::setFileManager(FileManager *Value) { 65 FileMgr = Value; 66} 67 68void CompilerInstance::setSourceManager(SourceManager *Value) { 69 SourceMgr = Value; 70} 71 72void CompilerInstance::setPreprocessor(Preprocessor *Value) { PP = Value; } 73 74void CompilerInstance::setASTContext(ASTContext *Value) { Context = Value; } 75 76void CompilerInstance::setSema(Sema *S) { 77 TheSema.reset(S); 78} 79 80void CompilerInstance::setASTConsumer(ASTConsumer *Value) { 81 Consumer.reset(Value); 82} 83 84void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) { 85 CompletionConsumer.reset(Value); 86} 87 88// Diagnostics 89static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts, 90 unsigned argc, const char* const *argv, 91 DiagnosticsEngine &Diags) { 92 std::string ErrorInfo; 93 llvm::OwningPtr<raw_ostream> OS( 94 new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo)); 95 if (!ErrorInfo.empty()) { 96 Diags.Report(diag::err_fe_unable_to_open_logfile) 97 << DiagOpts.DumpBuildInformation << ErrorInfo; 98 return; 99 } 100 101 (*OS) << "clang -cc1 command line arguments: "; 102 for (unsigned i = 0; i != argc; ++i) 103 (*OS) << argv[i] << ' '; 104 (*OS) << '\n'; 105 106 // Chain in a diagnostic client which will log the diagnostics. 107 DiagnosticConsumer *Logger = 108 new TextDiagnosticPrinter(*OS.take(), DiagOpts, /*OwnsOutputStream=*/true); 109 Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger)); 110} 111 112static void SetUpDiagnosticLog(const DiagnosticOptions &DiagOpts, 113 const CodeGenOptions *CodeGenOpts, 114 DiagnosticsEngine &Diags) { 115 std::string ErrorInfo; 116 bool OwnsStream = false; 117 raw_ostream *OS = &llvm::errs(); 118 if (DiagOpts.DiagnosticLogFile != "-") { 119 // Create the output stream. 120 llvm::raw_fd_ostream *FileOS( 121 new llvm::raw_fd_ostream(DiagOpts.DiagnosticLogFile.c_str(), 122 ErrorInfo, llvm::raw_fd_ostream::F_Append)); 123 if (!ErrorInfo.empty()) { 124 Diags.Report(diag::warn_fe_cc_log_diagnostics_failure) 125 << DiagOpts.DumpBuildInformation << ErrorInfo; 126 } else { 127 FileOS->SetUnbuffered(); 128 FileOS->SetUseAtomicWrites(true); 129 OS = FileOS; 130 OwnsStream = true; 131 } 132 } 133 134 // Chain in the diagnostic client which will log the diagnostics. 135 LogDiagnosticPrinter *Logger = new LogDiagnosticPrinter(*OS, DiagOpts, 136 OwnsStream); 137 if (CodeGenOpts) 138 Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags); 139 Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger)); 140} 141 142void CompilerInstance::createDiagnostics(int Argc, const char* const *Argv, 143 DiagnosticConsumer *Client, 144 bool ShouldOwnClient) { 145 Diagnostics = createDiagnostics(getDiagnosticOpts(), Argc, Argv, Client, 146 ShouldOwnClient, &getCodeGenOpts()); 147} 148 149llvm::IntrusiveRefCntPtr<DiagnosticsEngine> 150CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts, 151 int Argc, const char* const *Argv, 152 DiagnosticConsumer *Client, 153 bool ShouldOwnClient, 154 const CodeGenOptions *CodeGenOpts) { 155 llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs()); 156 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> 157 Diags(new DiagnosticsEngine(DiagID)); 158 159 // Create the diagnostic client for reporting errors or for 160 // implementing -verify. 161 if (Client) 162 Diags->setClient(Client, ShouldOwnClient); 163 else 164 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts)); 165 166 // Chain in -verify checker, if requested. 167 if (Opts.VerifyDiagnostics) 168 Diags->setClient(new VerifyDiagnosticConsumer(*Diags)); 169 170 // Chain in -diagnostic-log-file dumper, if requested. 171 if (!Opts.DiagnosticLogFile.empty()) 172 SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags); 173 174 if (!Opts.DumpBuildInformation.empty()) 175 SetUpBuildDumpLog(Opts, Argc, Argv, *Diags); 176 177 // Configure our handling of diagnostics. 178 ProcessWarningOptions(*Diags, Opts); 179 180 return Diags; 181} 182 183// File Manager 184 185void CompilerInstance::createFileManager() { 186 FileMgr = new FileManager(getFileSystemOpts()); 187} 188 189// Source Manager 190 191void CompilerInstance::createSourceManager(FileManager &FileMgr) { 192 SourceMgr = new SourceManager(getDiagnostics(), FileMgr); 193} 194 195// Preprocessor 196 197void CompilerInstance::createPreprocessor() { 198 const PreprocessorOptions &PPOpts = getPreprocessorOpts(); 199 200 // Create a PTH manager if we are using some form of a token cache. 201 PTHManager *PTHMgr = 0; 202 if (!PPOpts.TokenCache.empty()) 203 PTHMgr = PTHManager::Create(PPOpts.TokenCache, getDiagnostics()); 204 205 // Create the Preprocessor. 206 HeaderSearch *HeaderInfo = new HeaderSearch(getFileManager()); 207 PP = new Preprocessor(getDiagnostics(), getLangOpts(), &getTarget(), 208 getSourceManager(), *HeaderInfo, *this, PTHMgr, 209 /*OwnsHeaderSearch=*/true); 210 211 // Note that this is different then passing PTHMgr to Preprocessor's ctor. 212 // That argument is used as the IdentifierInfoLookup argument to 213 // IdentifierTable's ctor. 214 if (PTHMgr) { 215 PTHMgr->setPreprocessor(&*PP); 216 PP->setPTHManager(PTHMgr); 217 } 218 219 if (PPOpts.DetailedRecord) 220 PP->createPreprocessingRecord( 221 PPOpts.DetailedRecordIncludesNestedMacroExpansions); 222 223 InitializePreprocessor(*PP, PPOpts, getHeaderSearchOpts(), getFrontendOpts()); 224 225 // Set up the module path, including the hash for the 226 // module-creation options. 227 llvm::SmallString<256> SpecificModuleCache( 228 getHeaderSearchOpts().ModuleCachePath); 229 if (!getHeaderSearchOpts().DisableModuleHash) 230 llvm::sys::path::append(SpecificModuleCache, 231 getInvocation().getModuleHash()); 232 PP->getHeaderSearchInfo().configureModules(SpecificModuleCache, 233 getPreprocessorOpts().ModuleBuildPath.empty() 234 ? std::string() 235 : getPreprocessorOpts().ModuleBuildPath.back()); 236 237 // Handle generating dependencies, if requested. 238 const DependencyOutputOptions &DepOpts = getDependencyOutputOpts(); 239 if (!DepOpts.OutputFile.empty()) 240 AttachDependencyFileGen(*PP, DepOpts); 241 242 // Handle generating header include information, if requested. 243 if (DepOpts.ShowHeaderIncludes) 244 AttachHeaderIncludeGen(*PP); 245 if (!DepOpts.HeaderIncludeOutputFile.empty()) { 246 StringRef OutputPath = DepOpts.HeaderIncludeOutputFile; 247 if (OutputPath == "-") 248 OutputPath = ""; 249 AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/true, OutputPath, 250 /*ShowDepth=*/false); 251 } 252} 253 254// ASTContext 255 256void CompilerInstance::createASTContext() { 257 Preprocessor &PP = getPreprocessor(); 258 Context = new ASTContext(getLangOpts(), PP.getSourceManager(), 259 &getTarget(), PP.getIdentifierTable(), 260 PP.getSelectorTable(), PP.getBuiltinInfo(), 261 /*size_reserve=*/ 0); 262} 263 264// ExternalASTSource 265 266void CompilerInstance::createPCHExternalASTSource(StringRef Path, 267 bool DisablePCHValidation, 268 bool DisableStatCache, 269 void *DeserializationListener){ 270 llvm::OwningPtr<ExternalASTSource> Source; 271 bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0; 272 Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot, 273 DisablePCHValidation, 274 DisableStatCache, 275 getPreprocessor(), getASTContext(), 276 DeserializationListener, 277 Preamble)); 278 ModuleManager = static_cast<ASTReader*>(Source.get()); 279 getASTContext().setExternalSource(Source); 280} 281 282ExternalASTSource * 283CompilerInstance::createPCHExternalASTSource(StringRef Path, 284 const std::string &Sysroot, 285 bool DisablePCHValidation, 286 bool DisableStatCache, 287 Preprocessor &PP, 288 ASTContext &Context, 289 void *DeserializationListener, 290 bool Preamble) { 291 llvm::OwningPtr<ASTReader> Reader; 292 Reader.reset(new ASTReader(PP, Context, 293 Sysroot.empty() ? "" : Sysroot.c_str(), 294 DisablePCHValidation, DisableStatCache)); 295 296 Reader->setDeserializationListener( 297 static_cast<ASTDeserializationListener *>(DeserializationListener)); 298 switch (Reader->ReadAST(Path, 299 Preamble ? serialization::MK_Preamble 300 : serialization::MK_PCH)) { 301 case ASTReader::Success: 302 // Set the predefines buffer as suggested by the PCH reader. Typically, the 303 // predefines buffer will be empty. 304 PP.setPredefines(Reader->getSuggestedPredefines()); 305 return Reader.take(); 306 307 case ASTReader::Failure: 308 // Unrecoverable failure: don't even try to process the input file. 309 break; 310 311 case ASTReader::IgnorePCH: 312 // No suitable PCH file could be found. Return an error. 313 break; 314 } 315 316 return 0; 317} 318 319// Code Completion 320 321static bool EnableCodeCompletion(Preprocessor &PP, 322 const std::string &Filename, 323 unsigned Line, 324 unsigned Column) { 325 // Tell the source manager to chop off the given file at a specific 326 // line and column. 327 const FileEntry *Entry = PP.getFileManager().getFile(Filename); 328 if (!Entry) { 329 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file) 330 << Filename; 331 return true; 332 } 333 334 // Truncate the named file at the given line/column. 335 PP.SetCodeCompletionPoint(Entry, Line, Column); 336 return false; 337} 338 339void CompilerInstance::createCodeCompletionConsumer() { 340 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt; 341 if (!CompletionConsumer) { 342 CompletionConsumer.reset( 343 createCodeCompletionConsumer(getPreprocessor(), 344 Loc.FileName, Loc.Line, Loc.Column, 345 getFrontendOpts().ShowMacrosInCodeCompletion, 346 getFrontendOpts().ShowCodePatternsInCodeCompletion, 347 getFrontendOpts().ShowGlobalSymbolsInCodeCompletion, 348 llvm::outs())); 349 if (!CompletionConsumer) 350 return; 351 } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName, 352 Loc.Line, Loc.Column)) { 353 CompletionConsumer.reset(); 354 return; 355 } 356 357 if (CompletionConsumer->isOutputBinary() && 358 llvm::sys::Program::ChangeStdoutToBinary()) { 359 getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary); 360 CompletionConsumer.reset(); 361 } 362} 363 364void CompilerInstance::createFrontendTimer() { 365 FrontendTimer.reset(new llvm::Timer("Clang front-end timer")); 366} 367 368CodeCompleteConsumer * 369CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP, 370 const std::string &Filename, 371 unsigned Line, 372 unsigned Column, 373 bool ShowMacros, 374 bool ShowCodePatterns, 375 bool ShowGlobals, 376 raw_ostream &OS) { 377 if (EnableCodeCompletion(PP, Filename, Line, Column)) 378 return 0; 379 380 // Set up the creation routine for code-completion. 381 return new PrintingCodeCompleteConsumer(ShowMacros, ShowCodePatterns, 382 ShowGlobals, OS); 383} 384 385void CompilerInstance::createSema(TranslationUnitKind TUKind, 386 CodeCompleteConsumer *CompletionConsumer) { 387 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(), 388 TUKind, CompletionConsumer)); 389} 390 391// Output Files 392 393void CompilerInstance::addOutputFile(const OutputFile &OutFile) { 394 assert(OutFile.OS && "Attempt to add empty stream to output list!"); 395 OutputFiles.push_back(OutFile); 396} 397 398void CompilerInstance::clearOutputFiles(bool EraseFiles) { 399 for (std::list<OutputFile>::iterator 400 it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) { 401 delete it->OS; 402 if (!it->TempFilename.empty()) { 403 if (EraseFiles) { 404 bool existed; 405 llvm::sys::fs::remove(it->TempFilename, existed); 406 } else { 407 llvm::SmallString<128> NewOutFile(it->Filename); 408 409 // If '-working-directory' was passed, the output filename should be 410 // relative to that. 411 FileMgr->FixupRelativePath(NewOutFile); 412 if (llvm::error_code ec = llvm::sys::fs::rename(it->TempFilename, 413 NewOutFile.str())) { 414 getDiagnostics().Report(diag::err_fe_unable_to_rename_temp) 415 << it->TempFilename << it->Filename << ec.message(); 416 417 bool existed; 418 llvm::sys::fs::remove(it->TempFilename, existed); 419 } 420 } 421 } else if (!it->Filename.empty() && EraseFiles) 422 llvm::sys::Path(it->Filename).eraseFromDisk(); 423 424 } 425 OutputFiles.clear(); 426} 427 428llvm::raw_fd_ostream * 429CompilerInstance::createDefaultOutputFile(bool Binary, 430 StringRef InFile, 431 StringRef Extension) { 432 return createOutputFile(getFrontendOpts().OutputFile, Binary, 433 /*RemoveFileOnSignal=*/true, InFile, Extension); 434} 435 436llvm::raw_fd_ostream * 437CompilerInstance::createOutputFile(StringRef OutputPath, 438 bool Binary, bool RemoveFileOnSignal, 439 StringRef InFile, 440 StringRef Extension, 441 bool UseTemporary) { 442 std::string Error, OutputPathName, TempPathName; 443 llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary, 444 RemoveFileOnSignal, 445 InFile, Extension, 446 UseTemporary, 447 &OutputPathName, 448 &TempPathName); 449 if (!OS) { 450 getDiagnostics().Report(diag::err_fe_unable_to_open_output) 451 << OutputPath << Error; 452 return 0; 453 } 454 455 // Add the output file -- but don't try to remove "-", since this means we are 456 // using stdin. 457 addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "", 458 TempPathName, OS)); 459 460 return OS; 461} 462 463llvm::raw_fd_ostream * 464CompilerInstance::createOutputFile(StringRef OutputPath, 465 std::string &Error, 466 bool Binary, 467 bool RemoveFileOnSignal, 468 StringRef InFile, 469 StringRef Extension, 470 bool UseTemporary, 471 std::string *ResultPathName, 472 std::string *TempPathName) { 473 std::string OutFile, TempFile; 474 if (!OutputPath.empty()) { 475 OutFile = OutputPath; 476 } else if (InFile == "-") { 477 OutFile = "-"; 478 } else if (!Extension.empty()) { 479 llvm::sys::Path Path(InFile); 480 Path.eraseSuffix(); 481 Path.appendSuffix(Extension); 482 OutFile = Path.str(); 483 } else { 484 OutFile = "-"; 485 } 486 487 llvm::OwningPtr<llvm::raw_fd_ostream> OS; 488 std::string OSFile; 489 490 if (UseTemporary && OutFile != "-") { 491 llvm::sys::Path OutPath(OutFile); 492 // Only create the temporary if we can actually write to OutPath, otherwise 493 // we want to fail early. 494 bool Exists; 495 if ((llvm::sys::fs::exists(OutPath.str(), Exists) || !Exists) || 496 (OutPath.isRegularFile() && OutPath.canWrite())) { 497 // Create a temporary file. 498 llvm::SmallString<128> TempPath; 499 TempPath = OutFile; 500 TempPath += "-%%%%%%%%"; 501 int fd; 502 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath, 503 /*makeAbsolute=*/false) == llvm::errc::success) { 504 OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true)); 505 OSFile = TempFile = TempPath.str(); 506 } 507 } 508 } 509 510 if (!OS) { 511 OSFile = OutFile; 512 OS.reset( 513 new llvm::raw_fd_ostream(OSFile.c_str(), Error, 514 (Binary ? llvm::raw_fd_ostream::F_Binary : 0))); 515 if (!Error.empty()) 516 return 0; 517 } 518 519 // Make sure the out stream file gets removed if we crash. 520 if (RemoveFileOnSignal) 521 llvm::sys::RemoveFileOnSignal(llvm::sys::Path(OSFile)); 522 523 if (ResultPathName) 524 *ResultPathName = OutFile; 525 if (TempPathName) 526 *TempPathName = TempFile; 527 528 return OS.take(); 529} 530 531// Initialization Utilities 532 533bool CompilerInstance::InitializeSourceManager(StringRef InputFile) { 534 return InitializeSourceManager(InputFile, getDiagnostics(), getFileManager(), 535 getSourceManager(), getFrontendOpts()); 536} 537 538bool CompilerInstance::InitializeSourceManager(StringRef InputFile, 539 DiagnosticsEngine &Diags, 540 FileManager &FileMgr, 541 SourceManager &SourceMgr, 542 const FrontendOptions &Opts) { 543 // Figure out where to get and map in the main file. 544 if (InputFile != "-") { 545 const FileEntry *File = FileMgr.getFile(InputFile); 546 if (!File) { 547 Diags.Report(diag::err_fe_error_reading) << InputFile; 548 return false; 549 } 550 SourceMgr.createMainFileID(File); 551 } else { 552 llvm::OwningPtr<llvm::MemoryBuffer> SB; 553 if (llvm::MemoryBuffer::getSTDIN(SB)) { 554 // FIXME: Give ec.message() in this diag. 555 Diags.Report(diag::err_fe_error_reading_stdin); 556 return false; 557 } 558 const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(), 559 SB->getBufferSize(), 0); 560 SourceMgr.createMainFileID(File); 561 SourceMgr.overrideFileContents(File, SB.take()); 562 } 563 564 assert(!SourceMgr.getMainFileID().isInvalid() && 565 "Couldn't establish MainFileID!"); 566 return true; 567} 568 569// High-Level Operations 570 571bool CompilerInstance::ExecuteAction(FrontendAction &Act) { 572 assert(hasDiagnostics() && "Diagnostics engine is not initialized!"); 573 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!"); 574 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!"); 575 576 // FIXME: Take this as an argument, once all the APIs we used have moved to 577 // taking it as an input instead of hard-coding llvm::errs. 578 raw_ostream &OS = llvm::errs(); 579 580 // Create the target instance. 581 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts())); 582 if (!hasTarget()) 583 return false; 584 585 // Inform the target of the language options. 586 // 587 // FIXME: We shouldn't need to do this, the target should be immutable once 588 // created. This complexity should be lifted elsewhere. 589 getTarget().setForcedLangOptions(getLangOpts()); 590 591 // Validate/process some options. 592 if (getHeaderSearchOpts().Verbose) 593 OS << "clang -cc1 version " CLANG_VERSION_STRING 594 << " based upon " << PACKAGE_STRING 595 << " hosted on " << llvm::sys::getHostTriple() << "\n"; 596 597 if (getFrontendOpts().ShowTimers) 598 createFrontendTimer(); 599 600 if (getFrontendOpts().ShowStats) 601 llvm::EnableStatistics(); 602 603 for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) { 604 const std::string &InFile = getFrontendOpts().Inputs[i].second; 605 606 // Reset the ID tables if we are reusing the SourceManager. 607 if (hasSourceManager()) 608 getSourceManager().clearIDTables(); 609 610 if (Act.BeginSourceFile(*this, InFile, getFrontendOpts().Inputs[i].first)) { 611 Act.Execute(); 612 Act.EndSourceFile(); 613 } 614 } 615 616 if (getDiagnosticOpts().ShowCarets) { 617 // We can have multiple diagnostics sharing one diagnostic client. 618 // Get the total number of warnings/errors from the client. 619 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings(); 620 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors(); 621 622 if (NumWarnings) 623 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s"); 624 if (NumWarnings && NumErrors) 625 OS << " and "; 626 if (NumErrors) 627 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s"); 628 if (NumWarnings || NumErrors) 629 OS << " generated.\n"; 630 } 631 632 if (getFrontendOpts().ShowStats && hasFileManager()) { 633 getFileManager().PrintStats(); 634 OS << "\n"; 635 } 636 637 return !getDiagnostics().getClient()->getNumErrors(); 638} 639 640/// \brief Determine the appropriate source input kind based on language 641/// options. 642static InputKind getSourceInputKindFromOptions(const LangOptions &LangOpts) { 643 if (LangOpts.OpenCL) 644 return IK_OpenCL; 645 if (LangOpts.CUDA) 646 return IK_CUDA; 647 if (LangOpts.ObjC1) 648 return LangOpts.CPlusPlus? IK_ObjCXX : IK_ObjC; 649 return LangOpts.CPlusPlus? IK_CXX : IK_C; 650} 651 652/// \brief Compile a module file for the given module name with the given 653/// umbrella header, using the options provided by the importing compiler 654/// instance. 655static void compileModule(CompilerInstance &ImportingInstance, 656 StringRef ModuleName, 657 StringRef ModuleFileName, 658 StringRef UmbrellaHeader) { 659 // Construct a compiler invocation for creating this module. 660 llvm::IntrusiveRefCntPtr<CompilerInvocation> Invocation 661 (new CompilerInvocation(ImportingInstance.getInvocation())); 662 663 // For any options that aren't intended to affect how a module is built, 664 // reset them to their default values. 665 Invocation->getLangOpts().resetNonModularOptions(); 666 Invocation->getPreprocessorOpts().resetNonModularOptions(); 667 668 // Note that this module is part of the module build path, so that we 669 // can detect cycles in the module graph. 670 Invocation->getPreprocessorOpts().ModuleBuildPath.push_back(ModuleName); 671 672 // Set up the inputs/outputs so that we build the module from its umbrella 673 // header. 674 FrontendOptions &FrontendOpts = Invocation->getFrontendOpts(); 675 FrontendOpts.OutputFile = ModuleFileName.str(); 676 FrontendOpts.DisableFree = false; 677 FrontendOpts.Inputs.clear(); 678 FrontendOpts.Inputs.push_back( 679 std::make_pair(getSourceInputKindFromOptions(Invocation->getLangOpts()), 680 UmbrellaHeader)); 681 682 Invocation->getDiagnosticOpts().VerifyDiagnostics = 0; 683 684 685 assert(ImportingInstance.getInvocation().getModuleHash() == 686 Invocation->getModuleHash() && "Module hash mismatch!"); 687 688 // Construct a compiler instance that will be used to actually create the 689 // module. 690 CompilerInstance Instance; 691 Instance.setInvocation(&*Invocation); 692 Instance.createDiagnostics(/*argc=*/0, /*argv=*/0, 693 &ImportingInstance.getDiagnosticClient(), 694 /*ShouldOwnClient=*/false); 695 696 // Construct a module-generating action. 697 GeneratePCHAction CreateModuleAction(true); 698 699 // Execute the action to actually build the module in-place. 700 // FIXME: Need to synchronize when multiple processes do this. 701 Instance.ExecuteAction(CreateModuleAction); 702 703 // Tell the diagnostic client that it's (re-)starting to process a source 704 // file. 705 // FIXME: This is a hack. We probably want to clone the diagnostic client. 706 ImportingInstance.getDiagnosticClient() 707 .BeginSourceFile(ImportingInstance.getLangOpts(), 708 &ImportingInstance.getPreprocessor()); 709} 710 711ModuleKey CompilerInstance::loadModule(SourceLocation ImportLoc, 712 IdentifierInfo &ModuleName, 713 SourceLocation ModuleNameLoc) { 714 // Determine what file we're searching from. 715 SourceManager &SourceMgr = getSourceManager(); 716 SourceLocation ExpandedImportLoc = SourceMgr.getExpansionLoc(ImportLoc); 717 const FileEntry *CurFile 718 = SourceMgr.getFileEntryForID(SourceMgr.getFileID(ExpandedImportLoc)); 719 if (!CurFile) 720 CurFile = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()); 721 722 // Search for a module with the given name. 723 std::string UmbrellaHeader; 724 std::string ModuleFileName; 725 const FileEntry *ModuleFile 726 = PP->getHeaderSearchInfo().lookupModule(ModuleName.getName(), 727 &ModuleFileName, 728 &UmbrellaHeader); 729 730 bool BuildingModule = false; 731 if (!ModuleFile && !UmbrellaHeader.empty()) { 732 // We didn't find the module, but there is an umbrella header that 733 // can be used to create the module file. Create a separate compilation 734 // module to do so. 735 736 // Check whether there is a cycle in the module graph. 737 SmallVectorImpl<std::string> &ModuleBuildPath 738 = getPreprocessorOpts().ModuleBuildPath; 739 SmallVectorImpl<std::string>::iterator Pos 740 = std::find(ModuleBuildPath.begin(), ModuleBuildPath.end(), 741 ModuleName.getName()); 742 if (Pos != ModuleBuildPath.end()) { 743 llvm::SmallString<256> CyclePath; 744 for (; Pos != ModuleBuildPath.end(); ++Pos) { 745 CyclePath += *Pos; 746 CyclePath += " -> "; 747 } 748 CyclePath += ModuleName.getName(); 749 750 getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle) 751 << ModuleName.getName() << CyclePath; 752 return 0; 753 } 754 755 BuildingModule = true; 756 compileModule(*this, ModuleName.getName(), ModuleFileName, UmbrellaHeader); 757 ModuleFile = PP->getHeaderSearchInfo().lookupModule(ModuleName.getName()); 758 } 759 760 if (!ModuleFile) { 761 getDiagnostics().Report(ModuleNameLoc, 762 BuildingModule? diag::err_module_not_built 763 : diag::err_module_not_found) 764 << ModuleName.getName() 765 << SourceRange(ImportLoc, ModuleNameLoc); 766 return 0; 767 } 768 769 // If we don't already have an ASTReader, create one now. 770 if (!ModuleManager) { 771 if (!hasASTContext()) 772 createASTContext(); 773 774 std::string Sysroot = getHeaderSearchOpts().Sysroot; 775 const PreprocessorOptions &PPOpts = getPreprocessorOpts(); 776 ModuleManager = new ASTReader(getPreprocessor(), *Context, 777 Sysroot.empty() ? "" : Sysroot.c_str(), 778 PPOpts.DisablePCHValidation, 779 PPOpts.DisableStatCache); 780 if (hasASTConsumer()) { 781 ModuleManager->setDeserializationListener( 782 getASTConsumer().GetASTDeserializationListener()); 783 getASTContext().setASTMutationListener( 784 getASTConsumer().GetASTMutationListener()); 785 } 786 llvm::OwningPtr<ExternalASTSource> Source; 787 Source.reset(ModuleManager); 788 getASTContext().setExternalSource(Source); 789 if (hasSema()) 790 ModuleManager->InitializeSema(getSema()); 791 if (hasASTConsumer()) 792 ModuleManager->StartTranslationUnit(&getASTConsumer()); 793 } 794 795 // Try to load the module we found. 796 switch (ModuleManager->ReadAST(ModuleFile->getName(), 797 serialization::MK_Module)) { 798 case ASTReader::Success: 799 break; 800 801 case ASTReader::IgnorePCH: 802 // FIXME: The ASTReader will already have complained, but can we showhorn 803 // that diagnostic information into a more useful form? 804 return 0; 805 806 case ASTReader::Failure: 807 // Already complained. 808 return 0; 809 } 810 811 // FIXME: The module file's FileEntry makes a poor key indeed! 812 return (ModuleKey)ModuleFile; 813} 814 815