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/AST/ASTConsumer.h" 12 #include "clang/AST/ASTContext.h" 13 #include "clang/AST/Decl.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/Frontend/ChainedDiagnosticConsumer.h" 20 #include "clang/Frontend/FrontendAction.h" 21 #include "clang/Frontend/FrontendActions.h" 22 #include "clang/Frontend/FrontendDiagnostic.h" 23 #include "clang/Frontend/LogDiagnosticPrinter.h" 24 #include "clang/Frontend/SerializedDiagnosticPrinter.h" 25 #include "clang/Frontend/TextDiagnosticPrinter.h" 26 #include "clang/Frontend/Utils.h" 27 #include "clang/Frontend/VerifyDiagnosticConsumer.h" 28 #include "clang/Lex/HeaderSearch.h" 29 #include "clang/Lex/PTHManager.h" 30 #include "clang/Lex/Preprocessor.h" 31 #include "clang/Sema/CodeCompleteConsumer.h" 32 #include "clang/Sema/Sema.h" 33 #include "clang/Serialization/ASTReader.h" 34 #include "llvm/ADT/Statistic.h" 35 #include "llvm/Config/config.h" 36 #include "llvm/Support/CrashRecoveryContext.h" 37 #include "llvm/Support/FileSystem.h" 38 #include "llvm/Support/Host.h" 39 #include "llvm/Support/LockFileManager.h" 40 #include "llvm/Support/MemoryBuffer.h" 41 #include "llvm/Support/Path.h" 42 #include "llvm/Support/Program.h" 43 #include "llvm/Support/Signals.h" 44 #include "llvm/Support/Timer.h" 45 #include "llvm/Support/raw_ostream.h" 46 #include "llvm/Support/system_error.h" 47 #include <sys/stat.h> 48 #include <time.h> 49 50 using namespace clang; 51 52 CompilerInstance::CompilerInstance() 53 : Invocation(new CompilerInvocation()), ModuleManager(0), 54 BuildGlobalModuleIndex(false), ModuleBuildFailed(false) { 55 } 56 57 CompilerInstance::~CompilerInstance() { 58 assert(OutputFiles.empty() && "Still output files in flight?"); 59 } 60 61 void CompilerInstance::setInvocation(CompilerInvocation *Value) { 62 Invocation = Value; 63 } 64 65 bool CompilerInstance::shouldBuildGlobalModuleIndex() const { 66 return (BuildGlobalModuleIndex || 67 (ModuleManager && ModuleManager->isGlobalIndexUnavailable() && 68 getFrontendOpts().GenerateGlobalModuleIndex)) && 69 !ModuleBuildFailed; 70 } 71 72 void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) { 73 Diagnostics = Value; 74 } 75 76 void CompilerInstance::setTarget(TargetInfo *Value) { 77 Target = Value; 78 } 79 80 void CompilerInstance::setFileManager(FileManager *Value) { 81 FileMgr = Value; 82 if (Value) 83 VirtualFileSystem = Value->getVirtualFileSystem(); 84 else 85 VirtualFileSystem.reset(); 86 } 87 88 void CompilerInstance::setSourceManager(SourceManager *Value) { 89 SourceMgr = Value; 90 } 91 92 void CompilerInstance::setPreprocessor(Preprocessor *Value) { PP = Value; } 93 94 void CompilerInstance::setASTContext(ASTContext *Value) { Context = Value; } 95 96 void CompilerInstance::setSema(Sema *S) { 97 TheSema.reset(S); 98 } 99 100 void CompilerInstance::setASTConsumer(ASTConsumer *Value) { 101 Consumer.reset(Value); 102 } 103 104 void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) { 105 CompletionConsumer.reset(Value); 106 } 107 108 IntrusiveRefCntPtr<ASTReader> CompilerInstance::getModuleManager() const { 109 return ModuleManager; 110 } 111 void CompilerInstance::setModuleManager(IntrusiveRefCntPtr<ASTReader> Reader) { 112 ModuleManager = Reader; 113 } 114 115 // Diagnostics 116 static void SetUpDiagnosticLog(DiagnosticOptions *DiagOpts, 117 const CodeGenOptions *CodeGenOpts, 118 DiagnosticsEngine &Diags) { 119 std::string ErrorInfo; 120 bool OwnsStream = false; 121 raw_ostream *OS = &llvm::errs(); 122 if (DiagOpts->DiagnosticLogFile != "-") { 123 // Create the output stream. 124 llvm::raw_fd_ostream *FileOS(new llvm::raw_fd_ostream( 125 DiagOpts->DiagnosticLogFile.c_str(), ErrorInfo, 126 llvm::sys::fs::F_Append | llvm::sys::fs::F_Text)); 127 if (!ErrorInfo.empty()) { 128 Diags.Report(diag::warn_fe_cc_log_diagnostics_failure) 129 << DiagOpts->DiagnosticLogFile << ErrorInfo; 130 } else { 131 FileOS->SetUnbuffered(); 132 FileOS->SetUseAtomicWrites(true); 133 OS = FileOS; 134 OwnsStream = true; 135 } 136 } 137 138 // Chain in the diagnostic client which will log the diagnostics. 139 LogDiagnosticPrinter *Logger = new LogDiagnosticPrinter(*OS, DiagOpts, 140 OwnsStream); 141 if (CodeGenOpts) 142 Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags); 143 Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger)); 144 } 145 146 static void SetupSerializedDiagnostics(DiagnosticOptions *DiagOpts, 147 DiagnosticsEngine &Diags, 148 StringRef OutputFile) { 149 std::string ErrorInfo; 150 OwningPtr<llvm::raw_fd_ostream> OS; 151 OS.reset(new llvm::raw_fd_ostream(OutputFile.str().c_str(), ErrorInfo, 152 llvm::sys::fs::F_None)); 153 154 if (!ErrorInfo.empty()) { 155 Diags.Report(diag::warn_fe_serialized_diag_failure) 156 << OutputFile << ErrorInfo; 157 return; 158 } 159 160 DiagnosticConsumer *SerializedConsumer = 161 clang::serialized_diags::create(OS.take(), DiagOpts); 162 163 164 Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), 165 SerializedConsumer)); 166 } 167 168 void CompilerInstance::createDiagnostics(DiagnosticConsumer *Client, 169 bool ShouldOwnClient) { 170 Diagnostics = createDiagnostics(&getDiagnosticOpts(), Client, 171 ShouldOwnClient, &getCodeGenOpts()); 172 } 173 174 IntrusiveRefCntPtr<DiagnosticsEngine> 175 CompilerInstance::createDiagnostics(DiagnosticOptions *Opts, 176 DiagnosticConsumer *Client, 177 bool ShouldOwnClient, 178 const CodeGenOptions *CodeGenOpts) { 179 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs()); 180 IntrusiveRefCntPtr<DiagnosticsEngine> 181 Diags(new DiagnosticsEngine(DiagID, Opts)); 182 183 // Create the diagnostic client for reporting errors or for 184 // implementing -verify. 185 if (Client) { 186 Diags->setClient(Client, ShouldOwnClient); 187 } else 188 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts)); 189 190 // Chain in -verify checker, if requested. 191 if (Opts->VerifyDiagnostics) 192 Diags->setClient(new VerifyDiagnosticConsumer(*Diags)); 193 194 // Chain in -diagnostic-log-file dumper, if requested. 195 if (!Opts->DiagnosticLogFile.empty()) 196 SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags); 197 198 if (!Opts->DiagnosticSerializationFile.empty()) 199 SetupSerializedDiagnostics(Opts, *Diags, 200 Opts->DiagnosticSerializationFile); 201 202 // Configure our handling of diagnostics. 203 ProcessWarningOptions(*Diags, *Opts); 204 205 return Diags; 206 } 207 208 // File Manager 209 210 void CompilerInstance::createFileManager() { 211 if (!hasVirtualFileSystem()) { 212 // TODO: choose the virtual file system based on the CompilerInvocation. 213 setVirtualFileSystem(vfs::getRealFileSystem()); 214 } 215 FileMgr = new FileManager(getFileSystemOpts(), VirtualFileSystem); 216 } 217 218 // Source Manager 219 220 void CompilerInstance::createSourceManager(FileManager &FileMgr) { 221 SourceMgr = new SourceManager(getDiagnostics(), FileMgr); 222 } 223 224 // Preprocessor 225 226 void CompilerInstance::createPreprocessor() { 227 const PreprocessorOptions &PPOpts = getPreprocessorOpts(); 228 229 // Create a PTH manager if we are using some form of a token cache. 230 PTHManager *PTHMgr = 0; 231 if (!PPOpts.TokenCache.empty()) 232 PTHMgr = PTHManager::Create(PPOpts.TokenCache, getDiagnostics()); 233 234 // Create the Preprocessor. 235 HeaderSearch *HeaderInfo = new HeaderSearch(&getHeaderSearchOpts(), 236 getSourceManager(), 237 getDiagnostics(), 238 getLangOpts(), 239 &getTarget()); 240 PP = new Preprocessor(&getPreprocessorOpts(), 241 getDiagnostics(), getLangOpts(), &getTarget(), 242 getSourceManager(), *HeaderInfo, *this, PTHMgr, 243 /*OwnsHeaderSearch=*/true); 244 245 // Note that this is different then passing PTHMgr to Preprocessor's ctor. 246 // That argument is used as the IdentifierInfoLookup argument to 247 // IdentifierTable's ctor. 248 if (PTHMgr) { 249 PTHMgr->setPreprocessor(&*PP); 250 PP->setPTHManager(PTHMgr); 251 } 252 253 if (PPOpts.DetailedRecord) 254 PP->createPreprocessingRecord(); 255 256 InitializePreprocessor(*PP, PPOpts, getHeaderSearchOpts(), getFrontendOpts()); 257 258 PP->setPreprocessedOutput(getPreprocessorOutputOpts().ShowCPP); 259 260 // Set up the module path, including the hash for the 261 // module-creation options. 262 SmallString<256> SpecificModuleCache( 263 getHeaderSearchOpts().ModuleCachePath); 264 if (!getHeaderSearchOpts().DisableModuleHash) 265 llvm::sys::path::append(SpecificModuleCache, 266 getInvocation().getModuleHash()); 267 PP->getHeaderSearchInfo().setModuleCachePath(SpecificModuleCache); 268 269 // Handle generating dependencies, if requested. 270 const DependencyOutputOptions &DepOpts = getDependencyOutputOpts(); 271 if (!DepOpts.OutputFile.empty()) 272 TheDependencyFileGenerator.reset( 273 DependencyFileGenerator::CreateAndAttachToPreprocessor(*PP, DepOpts)); 274 if (!DepOpts.DOTOutputFile.empty()) 275 AttachDependencyGraphGen(*PP, DepOpts.DOTOutputFile, 276 getHeaderSearchOpts().Sysroot); 277 278 279 // Handle generating header include information, if requested. 280 if (DepOpts.ShowHeaderIncludes) 281 AttachHeaderIncludeGen(*PP); 282 if (!DepOpts.HeaderIncludeOutputFile.empty()) { 283 StringRef OutputPath = DepOpts.HeaderIncludeOutputFile; 284 if (OutputPath == "-") 285 OutputPath = ""; 286 AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/true, OutputPath, 287 /*ShowDepth=*/false); 288 } 289 290 if (DepOpts.PrintShowIncludes) { 291 AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/false, /*OutputPath=*/"", 292 /*ShowDepth=*/true, /*MSStyle=*/true); 293 } 294 } 295 296 // ASTContext 297 298 void CompilerInstance::createASTContext() { 299 Preprocessor &PP = getPreprocessor(); 300 Context = new ASTContext(getLangOpts(), PP.getSourceManager(), 301 &getTarget(), PP.getIdentifierTable(), 302 PP.getSelectorTable(), PP.getBuiltinInfo(), 303 /*size_reserve=*/ 0); 304 } 305 306 // ExternalASTSource 307 308 void CompilerInstance::createPCHExternalASTSource(StringRef Path, 309 bool DisablePCHValidation, 310 bool AllowPCHWithCompilerErrors, 311 void *DeserializationListener){ 312 IntrusiveRefCntPtr<ExternalASTSource> Source; 313 bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0; 314 Source = createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot, 315 DisablePCHValidation, 316 AllowPCHWithCompilerErrors, 317 getPreprocessor(), getASTContext(), 318 DeserializationListener, 319 Preamble, 320 getFrontendOpts().UseGlobalModuleIndex); 321 ModuleManager = static_cast<ASTReader*>(Source.getPtr()); 322 getASTContext().setExternalSource(Source); 323 } 324 325 ExternalASTSource * 326 CompilerInstance::createPCHExternalASTSource(StringRef Path, 327 const std::string &Sysroot, 328 bool DisablePCHValidation, 329 bool AllowPCHWithCompilerErrors, 330 Preprocessor &PP, 331 ASTContext &Context, 332 void *DeserializationListener, 333 bool Preamble, 334 bool UseGlobalModuleIndex) { 335 OwningPtr<ASTReader> Reader; 336 Reader.reset(new ASTReader(PP, Context, 337 Sysroot.empty() ? "" : Sysroot.c_str(), 338 DisablePCHValidation, 339 AllowPCHWithCompilerErrors, 340 /*AllowConfigurationMismatch*/false, 341 /*ValidateSystemInputs*/false, 342 UseGlobalModuleIndex)); 343 344 Reader->setDeserializationListener( 345 static_cast<ASTDeserializationListener *>(DeserializationListener)); 346 switch (Reader->ReadAST(Path, 347 Preamble ? serialization::MK_Preamble 348 : serialization::MK_PCH, 349 SourceLocation(), 350 ASTReader::ARR_None)) { 351 case ASTReader::Success: 352 // Set the predefines buffer as suggested by the PCH reader. Typically, the 353 // predefines buffer will be empty. 354 PP.setPredefines(Reader->getSuggestedPredefines()); 355 return Reader.take(); 356 357 case ASTReader::Failure: 358 // Unrecoverable failure: don't even try to process the input file. 359 break; 360 361 case ASTReader::Missing: 362 case ASTReader::OutOfDate: 363 case ASTReader::VersionMismatch: 364 case ASTReader::ConfigurationMismatch: 365 case ASTReader::HadErrors: 366 // No suitable PCH file could be found. Return an error. 367 break; 368 } 369 370 return 0; 371 } 372 373 // Code Completion 374 375 static bool EnableCodeCompletion(Preprocessor &PP, 376 const std::string &Filename, 377 unsigned Line, 378 unsigned Column) { 379 // Tell the source manager to chop off the given file at a specific 380 // line and column. 381 const FileEntry *Entry = PP.getFileManager().getFile(Filename); 382 if (!Entry) { 383 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file) 384 << Filename; 385 return true; 386 } 387 388 // Truncate the named file at the given line/column. 389 PP.SetCodeCompletionPoint(Entry, Line, Column); 390 return false; 391 } 392 393 void CompilerInstance::createCodeCompletionConsumer() { 394 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt; 395 if (!CompletionConsumer) { 396 setCodeCompletionConsumer( 397 createCodeCompletionConsumer(getPreprocessor(), 398 Loc.FileName, Loc.Line, Loc.Column, 399 getFrontendOpts().CodeCompleteOpts, 400 llvm::outs())); 401 if (!CompletionConsumer) 402 return; 403 } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName, 404 Loc.Line, Loc.Column)) { 405 setCodeCompletionConsumer(0); 406 return; 407 } 408 409 if (CompletionConsumer->isOutputBinary() && 410 llvm::sys::ChangeStdoutToBinary()) { 411 getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary); 412 setCodeCompletionConsumer(0); 413 } 414 } 415 416 void CompilerInstance::createFrontendTimer() { 417 FrontendTimer.reset(new llvm::Timer("Clang front-end timer")); 418 } 419 420 CodeCompleteConsumer * 421 CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP, 422 const std::string &Filename, 423 unsigned Line, 424 unsigned Column, 425 const CodeCompleteOptions &Opts, 426 raw_ostream &OS) { 427 if (EnableCodeCompletion(PP, Filename, Line, Column)) 428 return 0; 429 430 // Set up the creation routine for code-completion. 431 return new PrintingCodeCompleteConsumer(Opts, OS); 432 } 433 434 void CompilerInstance::createSema(TranslationUnitKind TUKind, 435 CodeCompleteConsumer *CompletionConsumer) { 436 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(), 437 TUKind, CompletionConsumer)); 438 } 439 440 // Output Files 441 442 void CompilerInstance::addOutputFile(const OutputFile &OutFile) { 443 assert(OutFile.OS && "Attempt to add empty stream to output list!"); 444 OutputFiles.push_back(OutFile); 445 } 446 447 void CompilerInstance::clearOutputFiles(bool EraseFiles) { 448 for (std::list<OutputFile>::iterator 449 it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) { 450 delete it->OS; 451 if (!it->TempFilename.empty()) { 452 if (EraseFiles) { 453 llvm::sys::fs::remove(it->TempFilename); 454 } else { 455 SmallString<128> NewOutFile(it->Filename); 456 457 // If '-working-directory' was passed, the output filename should be 458 // relative to that. 459 FileMgr->FixupRelativePath(NewOutFile); 460 if (llvm::error_code ec = llvm::sys::fs::rename(it->TempFilename, 461 NewOutFile.str())) { 462 getDiagnostics().Report(diag::err_unable_to_rename_temp) 463 << it->TempFilename << it->Filename << ec.message(); 464 465 llvm::sys::fs::remove(it->TempFilename); 466 } 467 } 468 } else if (!it->Filename.empty() && EraseFiles) 469 llvm::sys::fs::remove(it->Filename); 470 471 } 472 OutputFiles.clear(); 473 } 474 475 llvm::raw_fd_ostream * 476 CompilerInstance::createDefaultOutputFile(bool Binary, 477 StringRef InFile, 478 StringRef Extension) { 479 return createOutputFile(getFrontendOpts().OutputFile, Binary, 480 /*RemoveFileOnSignal=*/true, InFile, Extension, 481 /*UseTemporary=*/true); 482 } 483 484 llvm::raw_fd_ostream * 485 CompilerInstance::createOutputFile(StringRef OutputPath, 486 bool Binary, bool RemoveFileOnSignal, 487 StringRef InFile, 488 StringRef Extension, 489 bool UseTemporary, 490 bool CreateMissingDirectories) { 491 std::string Error, OutputPathName, TempPathName; 492 llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary, 493 RemoveFileOnSignal, 494 InFile, Extension, 495 UseTemporary, 496 CreateMissingDirectories, 497 &OutputPathName, 498 &TempPathName); 499 if (!OS) { 500 getDiagnostics().Report(diag::err_fe_unable_to_open_output) 501 << OutputPath << Error; 502 return 0; 503 } 504 505 // Add the output file -- but don't try to remove "-", since this means we are 506 // using stdin. 507 addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "", 508 TempPathName, OS)); 509 510 return OS; 511 } 512 513 llvm::raw_fd_ostream * 514 CompilerInstance::createOutputFile(StringRef OutputPath, 515 std::string &Error, 516 bool Binary, 517 bool RemoveFileOnSignal, 518 StringRef InFile, 519 StringRef Extension, 520 bool UseTemporary, 521 bool CreateMissingDirectories, 522 std::string *ResultPathName, 523 std::string *TempPathName) { 524 assert((!CreateMissingDirectories || UseTemporary) && 525 "CreateMissingDirectories is only allowed when using temporary files"); 526 527 std::string OutFile, TempFile; 528 if (!OutputPath.empty()) { 529 OutFile = OutputPath; 530 } else if (InFile == "-") { 531 OutFile = "-"; 532 } else if (!Extension.empty()) { 533 SmallString<128> Path(InFile); 534 llvm::sys::path::replace_extension(Path, Extension); 535 OutFile = Path.str(); 536 } else { 537 OutFile = "-"; 538 } 539 540 OwningPtr<llvm::raw_fd_ostream> OS; 541 std::string OSFile; 542 543 if (UseTemporary) { 544 if (OutFile == "-") 545 UseTemporary = false; 546 else { 547 llvm::sys::fs::file_status Status; 548 llvm::sys::fs::status(OutputPath, Status); 549 if (llvm::sys::fs::exists(Status)) { 550 // Fail early if we can't write to the final destination. 551 if (!llvm::sys::fs::can_write(OutputPath)) 552 return 0; 553 554 // Don't use a temporary if the output is a special file. This handles 555 // things like '-o /dev/null' 556 if (!llvm::sys::fs::is_regular_file(Status)) 557 UseTemporary = false; 558 } 559 } 560 } 561 562 if (UseTemporary) { 563 // Create a temporary file. 564 SmallString<128> TempPath; 565 TempPath = OutFile; 566 TempPath += "-%%%%%%%%"; 567 int fd; 568 llvm::error_code EC = 569 llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath); 570 571 if (CreateMissingDirectories && 572 EC == llvm::errc::no_such_file_or_directory) { 573 StringRef Parent = llvm::sys::path::parent_path(OutputPath); 574 EC = llvm::sys::fs::create_directories(Parent); 575 if (!EC) { 576 EC = llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath); 577 } 578 } 579 580 if (!EC) { 581 OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true)); 582 OSFile = TempFile = TempPath.str(); 583 } 584 // If we failed to create the temporary, fallback to writing to the file 585 // directly. This handles the corner case where we cannot write to the 586 // directory, but can write to the file. 587 } 588 589 if (!OS) { 590 OSFile = OutFile; 591 OS.reset(new llvm::raw_fd_ostream( 592 OSFile.c_str(), Error, 593 (Binary ? llvm::sys::fs::F_None : llvm::sys::fs::F_Text))); 594 if (!Error.empty()) 595 return 0; 596 } 597 598 // Make sure the out stream file gets removed if we crash. 599 if (RemoveFileOnSignal) 600 llvm::sys::RemoveFileOnSignal(OSFile); 601 602 if (ResultPathName) 603 *ResultPathName = OutFile; 604 if (TempPathName) 605 *TempPathName = TempFile; 606 607 return OS.take(); 608 } 609 610 // Initialization Utilities 611 612 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input){ 613 return InitializeSourceManager(Input, getDiagnostics(), 614 getFileManager(), getSourceManager(), 615 getFrontendOpts()); 616 } 617 618 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input, 619 DiagnosticsEngine &Diags, 620 FileManager &FileMgr, 621 SourceManager &SourceMgr, 622 const FrontendOptions &Opts) { 623 SrcMgr::CharacteristicKind 624 Kind = Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User; 625 626 if (Input.isBuffer()) { 627 SourceMgr.createMainFileIDForMemBuffer(Input.getBuffer(), Kind); 628 assert(!SourceMgr.getMainFileID().isInvalid() && 629 "Couldn't establish MainFileID!"); 630 return true; 631 } 632 633 StringRef InputFile = Input.getFile(); 634 635 // Figure out where to get and map in the main file. 636 if (InputFile != "-") { 637 const FileEntry *File = FileMgr.getFile(InputFile, /*OpenFile=*/true); 638 if (!File) { 639 Diags.Report(diag::err_fe_error_reading) << InputFile; 640 return false; 641 } 642 643 // The natural SourceManager infrastructure can't currently handle named 644 // pipes, but we would at least like to accept them for the main 645 // file. Detect them here, read them with the volatile flag so FileMgr will 646 // pick up the correct size, and simply override their contents as we do for 647 // STDIN. 648 if (File->isNamedPipe()) { 649 std::string ErrorStr; 650 if (llvm::MemoryBuffer *MB = 651 FileMgr.getBufferForFile(File, &ErrorStr, /*isVolatile=*/true)) { 652 // Create a new virtual file that will have the correct size. 653 File = FileMgr.getVirtualFile(InputFile, MB->getBufferSize(), 0); 654 SourceMgr.overrideFileContents(File, MB); 655 } else { 656 Diags.Report(diag::err_cannot_open_file) << InputFile << ErrorStr; 657 return false; 658 } 659 } 660 661 SourceMgr.createMainFileID(File, Kind); 662 } else { 663 OwningPtr<llvm::MemoryBuffer> SB; 664 if (llvm::error_code ec = llvm::MemoryBuffer::getSTDIN(SB)) { 665 Diags.Report(diag::err_fe_error_reading_stdin) << ec.message(); 666 return false; 667 } 668 const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(), 669 SB->getBufferSize(), 0); 670 SourceMgr.createMainFileID(File, Kind); 671 SourceMgr.overrideFileContents(File, SB.take()); 672 } 673 674 assert(!SourceMgr.getMainFileID().isInvalid() && 675 "Couldn't establish MainFileID!"); 676 return true; 677 } 678 679 // High-Level Operations 680 681 bool CompilerInstance::ExecuteAction(FrontendAction &Act) { 682 assert(hasDiagnostics() && "Diagnostics engine is not initialized!"); 683 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!"); 684 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!"); 685 686 // FIXME: Take this as an argument, once all the APIs we used have moved to 687 // taking it as an input instead of hard-coding llvm::errs. 688 raw_ostream &OS = llvm::errs(); 689 690 // Create the target instance. 691 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), &getTargetOpts())); 692 if (!hasTarget()) 693 return false; 694 695 // Inform the target of the language options. 696 // 697 // FIXME: We shouldn't need to do this, the target should be immutable once 698 // created. This complexity should be lifted elsewhere. 699 getTarget().setForcedLangOptions(getLangOpts()); 700 701 // rewriter project will change target built-in bool type from its default. 702 if (getFrontendOpts().ProgramAction == frontend::RewriteObjC) 703 getTarget().noSignedCharForObjCBool(); 704 705 // Validate/process some options. 706 if (getHeaderSearchOpts().Verbose) 707 OS << "clang -cc1 version " CLANG_VERSION_STRING 708 << " based upon " << PACKAGE_STRING 709 << " default target " << llvm::sys::getDefaultTargetTriple() << "\n"; 710 711 if (getFrontendOpts().ShowTimers) 712 createFrontendTimer(); 713 714 if (getFrontendOpts().ShowStats) 715 llvm::EnableStatistics(); 716 717 for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) { 718 // Reset the ID tables if we are reusing the SourceManager. 719 if (hasSourceManager()) 720 getSourceManager().clearIDTables(); 721 722 if (Act.BeginSourceFile(*this, getFrontendOpts().Inputs[i])) { 723 Act.Execute(); 724 Act.EndSourceFile(); 725 } 726 } 727 728 // Notify the diagnostic client that all files were processed. 729 getDiagnostics().getClient()->finish(); 730 731 if (getDiagnosticOpts().ShowCarets) { 732 // We can have multiple diagnostics sharing one diagnostic client. 733 // Get the total number of warnings/errors from the client. 734 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings(); 735 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors(); 736 737 if (NumWarnings) 738 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s"); 739 if (NumWarnings && NumErrors) 740 OS << " and "; 741 if (NumErrors) 742 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s"); 743 if (NumWarnings || NumErrors) 744 OS << " generated.\n"; 745 } 746 747 if (getFrontendOpts().ShowStats && hasFileManager()) { 748 getFileManager().PrintStats(); 749 OS << "\n"; 750 } 751 752 return !getDiagnostics().getClient()->getNumErrors(); 753 } 754 755 /// \brief Determine the appropriate source input kind based on language 756 /// options. 757 static InputKind getSourceInputKindFromOptions(const LangOptions &LangOpts) { 758 if (LangOpts.OpenCL) 759 return IK_OpenCL; 760 if (LangOpts.CUDA) 761 return IK_CUDA; 762 if (LangOpts.ObjC1) 763 return LangOpts.CPlusPlus? IK_ObjCXX : IK_ObjC; 764 return LangOpts.CPlusPlus? IK_CXX : IK_C; 765 } 766 767 /// \brief Compile a module file for the given module, using the options 768 /// provided by the importing compiler instance. 769 static void compileModule(CompilerInstance &ImportingInstance, 770 SourceLocation ImportLoc, 771 Module *Module, 772 StringRef ModuleFileName) { 773 // FIXME: have LockFileManager return an error_code so that we can 774 // avoid the mkdir when the directory already exists. 775 StringRef Dir = llvm::sys::path::parent_path(ModuleFileName); 776 llvm::sys::fs::create_directories(Dir); 777 778 llvm::LockFileManager Locked(ModuleFileName); 779 switch (Locked) { 780 case llvm::LockFileManager::LFS_Error: 781 return; 782 783 case llvm::LockFileManager::LFS_Owned: 784 // We're responsible for building the module ourselves. Do so below. 785 break; 786 787 case llvm::LockFileManager::LFS_Shared: 788 // Someone else is responsible for building the module. Wait for them to 789 // finish. 790 Locked.waitForUnlock(); 791 return; 792 } 793 794 ModuleMap &ModMap 795 = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap(); 796 797 // Construct a compiler invocation for creating this module. 798 IntrusiveRefCntPtr<CompilerInvocation> Invocation 799 (new CompilerInvocation(ImportingInstance.getInvocation())); 800 801 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts(); 802 803 // For any options that aren't intended to affect how a module is built, 804 // reset them to their default values. 805 Invocation->getLangOpts()->resetNonModularOptions(); 806 PPOpts.resetNonModularOptions(); 807 808 // Remove any macro definitions that are explicitly ignored by the module. 809 // They aren't supposed to affect how the module is built anyway. 810 const HeaderSearchOptions &HSOpts = Invocation->getHeaderSearchOpts(); 811 PPOpts.Macros.erase( 812 std::remove_if(PPOpts.Macros.begin(), PPOpts.Macros.end(), 813 [&HSOpts](const std::pair<std::string, bool> &def) { 814 StringRef MacroDef = def.first; 815 return HSOpts.ModulesIgnoreMacros.count(MacroDef.split('=').first) > 0; 816 }), 817 PPOpts.Macros.end()); 818 819 // Note the name of the module we're building. 820 Invocation->getLangOpts()->CurrentModule = Module->getTopLevelModuleName(); 821 822 // Make sure that the failed-module structure has been allocated in 823 // the importing instance, and propagate the pointer to the newly-created 824 // instance. 825 PreprocessorOptions &ImportingPPOpts 826 = ImportingInstance.getInvocation().getPreprocessorOpts(); 827 if (!ImportingPPOpts.FailedModules) 828 ImportingPPOpts.FailedModules = new PreprocessorOptions::FailedModulesSet; 829 PPOpts.FailedModules = ImportingPPOpts.FailedModules; 830 831 // If there is a module map file, build the module using the module map. 832 // Set up the inputs/outputs so that we build the module from its umbrella 833 // header. 834 FrontendOptions &FrontendOpts = Invocation->getFrontendOpts(); 835 FrontendOpts.OutputFile = ModuleFileName.str(); 836 FrontendOpts.DisableFree = false; 837 FrontendOpts.GenerateGlobalModuleIndex = false; 838 FrontendOpts.Inputs.clear(); 839 InputKind IK = getSourceInputKindFromOptions(*Invocation->getLangOpts()); 840 841 // Don't free the remapped file buffers; they are owned by our caller. 842 PPOpts.RetainRemappedFileBuffers = true; 843 844 Invocation->getDiagnosticOpts().VerifyDiagnostics = 0; 845 assert(ImportingInstance.getInvocation().getModuleHash() == 846 Invocation->getModuleHash() && "Module hash mismatch!"); 847 848 // Construct a compiler instance that will be used to actually create the 849 // module. 850 CompilerInstance Instance; 851 Instance.setInvocation(&*Invocation); 852 853 Instance.createDiagnostics(new ForwardingDiagnosticConsumer( 854 ImportingInstance.getDiagnosticClient()), 855 /*ShouldOwnClient=*/true); 856 857 Instance.setVirtualFileSystem(&ImportingInstance.getVirtualFileSystem()); 858 859 // Note that this module is part of the module build stack, so that we 860 // can detect cycles in the module graph. 861 Instance.setFileManager(&ImportingInstance.getFileManager()); 862 Instance.createSourceManager(Instance.getFileManager()); 863 SourceManager &SourceMgr = Instance.getSourceManager(); 864 SourceMgr.setModuleBuildStack( 865 ImportingInstance.getSourceManager().getModuleBuildStack()); 866 SourceMgr.pushModuleBuildStack(Module->getTopLevelModuleName(), 867 FullSourceLoc(ImportLoc, ImportingInstance.getSourceManager())); 868 869 // Get or create the module map that we'll use to build this module. 870 std::string InferredModuleMapContent; 871 if (const FileEntry *ModuleMapFile = 872 ModMap.getContainingModuleMapFile(Module)) { 873 // Use the module map where this module resides. 874 FrontendOpts.Inputs.push_back( 875 FrontendInputFile(ModuleMapFile->getName(), IK)); 876 } else { 877 llvm::raw_string_ostream OS(InferredModuleMapContent); 878 Module->print(OS); 879 OS.flush(); 880 FrontendOpts.Inputs.push_back( 881 FrontendInputFile("__inferred_module.map", IK)); 882 883 const llvm::MemoryBuffer *ModuleMapBuffer = 884 llvm::MemoryBuffer::getMemBuffer(InferredModuleMapContent); 885 ModuleMapFile = Instance.getFileManager().getVirtualFile( 886 "__inferred_module.map", InferredModuleMapContent.size(), 0); 887 SourceMgr.overrideFileContents(ModuleMapFile, ModuleMapBuffer); 888 } 889 890 // Construct a module-generating action. 891 GenerateModuleAction CreateModuleAction(Module->IsSystem); 892 893 // Execute the action to actually build the module in-place. Use a separate 894 // thread so that we get a stack large enough. 895 const unsigned ThreadStackSize = 8 << 20; 896 llvm::CrashRecoveryContext CRC; 897 CRC.RunSafelyOnThread([&]() { Instance.ExecuteAction(CreateModuleAction); }, 898 ThreadStackSize); 899 900 // Delete the temporary module map file. 901 // FIXME: Even though we're executing under crash protection, it would still 902 // be nice to do this with RemoveFileOnSignal when we can. However, that 903 // doesn't make sense for all clients, so clean this up manually. 904 Instance.clearOutputFiles(/*EraseFiles=*/true); 905 906 // We've rebuilt a module. If we're allowed to generate or update the global 907 // module index, record that fact in the importing compiler instance. 908 if (ImportingInstance.getFrontendOpts().GenerateGlobalModuleIndex) { 909 ImportingInstance.setBuildGlobalModuleIndex(true); 910 } 911 } 912 913 /// \brief Diagnose differences between the current definition of the given 914 /// configuration macro and the definition provided on the command line. 915 static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro, 916 Module *Mod, SourceLocation ImportLoc) { 917 IdentifierInfo *Id = PP.getIdentifierInfo(ConfigMacro); 918 SourceManager &SourceMgr = PP.getSourceManager(); 919 920 // If this identifier has never had a macro definition, then it could 921 // not have changed. 922 if (!Id->hadMacroDefinition()) 923 return; 924 925 // If this identifier does not currently have a macro definition, 926 // check whether it had one on the command line. 927 if (!Id->hasMacroDefinition()) { 928 MacroDirective::DefInfo LatestDef = 929 PP.getMacroDirectiveHistory(Id)->getDefinition(); 930 for (MacroDirective::DefInfo Def = LatestDef; Def; 931 Def = Def.getPreviousDefinition()) { 932 FileID FID = SourceMgr.getFileID(Def.getLocation()); 933 if (FID.isInvalid()) 934 continue; 935 936 // We only care about the predefines buffer. 937 if (FID != PP.getPredefinesFileID()) 938 continue; 939 940 // This macro was defined on the command line, then #undef'd later. 941 // Complain. 942 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef) 943 << true << ConfigMacro << Mod->getFullModuleName(); 944 if (LatestDef.isUndefined()) 945 PP.Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here) 946 << true; 947 return; 948 } 949 950 // Okay: no definition in the predefines buffer. 951 return; 952 } 953 954 // This identifier has a macro definition. Check whether we had a definition 955 // on the command line. 956 MacroDirective::DefInfo LatestDef = 957 PP.getMacroDirectiveHistory(Id)->getDefinition(); 958 MacroDirective::DefInfo PredefinedDef; 959 for (MacroDirective::DefInfo Def = LatestDef; Def; 960 Def = Def.getPreviousDefinition()) { 961 FileID FID = SourceMgr.getFileID(Def.getLocation()); 962 if (FID.isInvalid()) 963 continue; 964 965 // We only care about the predefines buffer. 966 if (FID != PP.getPredefinesFileID()) 967 continue; 968 969 PredefinedDef = Def; 970 break; 971 } 972 973 // If there was no definition for this macro in the predefines buffer, 974 // complain. 975 if (!PredefinedDef || 976 (!PredefinedDef.getLocation().isValid() && 977 PredefinedDef.getUndefLocation().isValid())) { 978 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef) 979 << false << ConfigMacro << Mod->getFullModuleName(); 980 PP.Diag(LatestDef.getLocation(), diag::note_module_def_undef_here) 981 << false; 982 return; 983 } 984 985 // If the current macro definition is the same as the predefined macro 986 // definition, it's okay. 987 if (LatestDef.getMacroInfo() == PredefinedDef.getMacroInfo() || 988 LatestDef.getMacroInfo()->isIdenticalTo(*PredefinedDef.getMacroInfo(),PP, 989 /*Syntactically=*/true)) 990 return; 991 992 // The macro definitions differ. 993 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef) 994 << false << ConfigMacro << Mod->getFullModuleName(); 995 PP.Diag(LatestDef.getLocation(), diag::note_module_def_undef_here) 996 << false; 997 } 998 999 /// \brief Write a new timestamp file with the given path. 1000 static void writeTimestampFile(StringRef TimestampFile) { 1001 std::string ErrorInfo; 1002 llvm::raw_fd_ostream Out(TimestampFile.str().c_str(), ErrorInfo, 1003 llvm::sys::fs::F_None); 1004 } 1005 1006 /// \brief Prune the module cache of modules that haven't been accessed in 1007 /// a long time. 1008 static void pruneModuleCache(const HeaderSearchOptions &HSOpts) { 1009 struct stat StatBuf; 1010 llvm::SmallString<128> TimestampFile; 1011 TimestampFile = HSOpts.ModuleCachePath; 1012 llvm::sys::path::append(TimestampFile, "modules.timestamp"); 1013 1014 // Try to stat() the timestamp file. 1015 if (::stat(TimestampFile.c_str(), &StatBuf)) { 1016 // If the timestamp file wasn't there, create one now. 1017 if (errno == ENOENT) { 1018 writeTimestampFile(TimestampFile); 1019 } 1020 return; 1021 } 1022 1023 // Check whether the time stamp is older than our pruning interval. 1024 // If not, do nothing. 1025 time_t TimeStampModTime = StatBuf.st_mtime; 1026 time_t CurrentTime = time(0); 1027 if (CurrentTime - TimeStampModTime <= time_t(HSOpts.ModuleCachePruneInterval)) 1028 return; 1029 1030 // Write a new timestamp file so that nobody else attempts to prune. 1031 // There is a benign race condition here, if two Clang instances happen to 1032 // notice at the same time that the timestamp is out-of-date. 1033 writeTimestampFile(TimestampFile); 1034 1035 // Walk the entire module cache, looking for unused module files and module 1036 // indices. 1037 llvm::error_code EC; 1038 SmallString<128> ModuleCachePathNative; 1039 llvm::sys::path::native(HSOpts.ModuleCachePath, ModuleCachePathNative); 1040 for (llvm::sys::fs::directory_iterator 1041 Dir(ModuleCachePathNative.str(), EC), DirEnd; 1042 Dir != DirEnd && !EC; Dir.increment(EC)) { 1043 // If we don't have a directory, there's nothing to look into. 1044 if (!llvm::sys::fs::is_directory(Dir->path())) 1045 continue; 1046 1047 // Walk all of the files within this directory. 1048 for (llvm::sys::fs::directory_iterator File(Dir->path(), EC), FileEnd; 1049 File != FileEnd && !EC; File.increment(EC)) { 1050 // We only care about module and global module index files. 1051 StringRef Extension = llvm::sys::path::extension(File->path()); 1052 if (Extension != ".pcm" && Extension != ".timestamp" && 1053 llvm::sys::path::filename(File->path()) != "modules.idx") 1054 continue; 1055 1056 // Look at this file. If we can't stat it, there's nothing interesting 1057 // there. 1058 if (::stat(File->path().c_str(), &StatBuf)) 1059 continue; 1060 1061 // If the file has been used recently enough, leave it there. 1062 time_t FileAccessTime = StatBuf.st_atime; 1063 if (CurrentTime - FileAccessTime <= 1064 time_t(HSOpts.ModuleCachePruneAfter)) { 1065 continue; 1066 } 1067 1068 // Remove the file. 1069 llvm::sys::fs::remove(File->path()); 1070 1071 // Remove the timestamp file. 1072 std::string TimpestampFilename = File->path() + ".timestamp"; 1073 llvm::sys::fs::remove(TimpestampFilename); 1074 } 1075 1076 // If we removed all of the files in the directory, remove the directory 1077 // itself. 1078 if (llvm::sys::fs::directory_iterator(Dir->path(), EC) == 1079 llvm::sys::fs::directory_iterator() && !EC) 1080 llvm::sys::fs::remove(Dir->path()); 1081 } 1082 } 1083 1084 ModuleLoadResult 1085 CompilerInstance::loadModule(SourceLocation ImportLoc, 1086 ModuleIdPath Path, 1087 Module::NameVisibilityKind Visibility, 1088 bool IsInclusionDirective) { 1089 // Determine what file we're searching from. 1090 StringRef ModuleName = Path[0].first->getName(); 1091 SourceLocation ModuleNameLoc = Path[0].second; 1092 1093 // If we've already handled this import, just return the cached result. 1094 // This one-element cache is important to eliminate redundant diagnostics 1095 // when both the preprocessor and parser see the same import declaration. 1096 if (!ImportLoc.isInvalid() && LastModuleImportLoc == ImportLoc) { 1097 // Make the named module visible. 1098 if (LastModuleImportResult && ModuleName != getLangOpts().CurrentModule) 1099 ModuleManager->makeModuleVisible(LastModuleImportResult, Visibility, 1100 ImportLoc, /*Complain=*/false); 1101 return LastModuleImportResult; 1102 } 1103 1104 clang::Module *Module = 0; 1105 1106 // If we don't already have information on this module, load the module now. 1107 llvm::DenseMap<const IdentifierInfo *, clang::Module *>::iterator Known 1108 = KnownModules.find(Path[0].first); 1109 if (Known != KnownModules.end()) { 1110 // Retrieve the cached top-level module. 1111 Module = Known->second; 1112 } else if (ModuleName == getLangOpts().CurrentModule) { 1113 // This is the module we're building. 1114 Module = PP->getHeaderSearchInfo().getModuleMap().findModule(ModuleName); 1115 Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first; 1116 } else { 1117 // Search for a module with the given name. 1118 Module = PP->getHeaderSearchInfo().lookupModule(ModuleName); 1119 if (!Module) { 1120 getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found) 1121 << ModuleName 1122 << SourceRange(ImportLoc, ModuleNameLoc); 1123 ModuleBuildFailed = true; 1124 return ModuleLoadResult(); 1125 } 1126 1127 std::string ModuleFileName = PP->getHeaderSearchInfo().getModuleFileName(Module); 1128 1129 // If we don't already have an ASTReader, create one now. 1130 if (!ModuleManager) { 1131 if (!hasASTContext()) 1132 createASTContext(); 1133 1134 // If we're not recursively building a module, check whether we 1135 // need to prune the module cache. 1136 if (getSourceManager().getModuleBuildStack().empty() && 1137 getHeaderSearchOpts().ModuleCachePruneInterval > 0 && 1138 getHeaderSearchOpts().ModuleCachePruneAfter > 0) { 1139 pruneModuleCache(getHeaderSearchOpts()); 1140 } 1141 1142 std::string Sysroot = getHeaderSearchOpts().Sysroot; 1143 const PreprocessorOptions &PPOpts = getPreprocessorOpts(); 1144 ModuleManager = new ASTReader(getPreprocessor(), *Context, 1145 Sysroot.empty() ? "" : Sysroot.c_str(), 1146 PPOpts.DisablePCHValidation, 1147 /*AllowASTWithCompilerErrors=*/false, 1148 /*AllowConfigurationMismatch=*/false, 1149 /*ValidateSystemInputs=*/false, 1150 getFrontendOpts().UseGlobalModuleIndex); 1151 if (hasASTConsumer()) { 1152 ModuleManager->setDeserializationListener( 1153 getASTConsumer().GetASTDeserializationListener()); 1154 getASTContext().setASTMutationListener( 1155 getASTConsumer().GetASTMutationListener()); 1156 } 1157 getASTContext().setExternalSource(ModuleManager); 1158 if (hasSema()) 1159 ModuleManager->InitializeSema(getSema()); 1160 if (hasASTConsumer()) 1161 ModuleManager->StartTranslationUnit(&getASTConsumer()); 1162 } 1163 1164 if (TheDependencyFileGenerator) 1165 TheDependencyFileGenerator->AttachToASTReader(*ModuleManager); 1166 1167 // Try to load the module file. 1168 unsigned ARRFlags = ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing; 1169 switch (ModuleManager->ReadAST(ModuleFileName, serialization::MK_Module, 1170 ImportLoc, ARRFlags)) { 1171 case ASTReader::Success: 1172 break; 1173 1174 case ASTReader::OutOfDate: 1175 case ASTReader::Missing: { 1176 // The module file is missing or out-of-date. Build it. 1177 assert(Module && "missing module file"); 1178 // Check whether there is a cycle in the module graph. 1179 ModuleBuildStack ModPath = getSourceManager().getModuleBuildStack(); 1180 ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end(); 1181 for (; Pos != PosEnd; ++Pos) { 1182 if (Pos->first == ModuleName) 1183 break; 1184 } 1185 1186 if (Pos != PosEnd) { 1187 SmallString<256> CyclePath; 1188 for (; Pos != PosEnd; ++Pos) { 1189 CyclePath += Pos->first; 1190 CyclePath += " -> "; 1191 } 1192 CyclePath += ModuleName; 1193 1194 getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle) 1195 << ModuleName << CyclePath; 1196 return ModuleLoadResult(); 1197 } 1198 1199 // Check whether we have already attempted to build this module (but 1200 // failed). 1201 if (getPreprocessorOpts().FailedModules && 1202 getPreprocessorOpts().FailedModules->hasAlreadyFailed(ModuleName)) { 1203 getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built) 1204 << ModuleName 1205 << SourceRange(ImportLoc, ModuleNameLoc); 1206 ModuleBuildFailed = true; 1207 return ModuleLoadResult(); 1208 } 1209 1210 // Try to compile the module. 1211 compileModule(*this, ModuleNameLoc, Module, ModuleFileName); 1212 1213 // Try to read the module file, now that we've compiled it. 1214 ASTReader::ASTReadResult ReadResult 1215 = ModuleManager->ReadAST(ModuleFileName, 1216 serialization::MK_Module, ImportLoc, 1217 ASTReader::ARR_Missing); 1218 if (ReadResult != ASTReader::Success) { 1219 if (ReadResult == ASTReader::Missing) { 1220 getDiagnostics().Report(ModuleNameLoc, 1221 Module? diag::err_module_not_built 1222 : diag::err_module_not_found) 1223 << ModuleName 1224 << SourceRange(ImportLoc, ModuleNameLoc); 1225 } 1226 1227 if (getPreprocessorOpts().FailedModules) 1228 getPreprocessorOpts().FailedModules->addFailed(ModuleName); 1229 KnownModules[Path[0].first] = 0; 1230 ModuleBuildFailed = true; 1231 return ModuleLoadResult(); 1232 } 1233 1234 // Okay, we've rebuilt and now loaded the module. 1235 break; 1236 } 1237 1238 case ASTReader::VersionMismatch: 1239 case ASTReader::ConfigurationMismatch: 1240 case ASTReader::HadErrors: 1241 ModuleLoader::HadFatalFailure = true; 1242 // FIXME: The ASTReader will already have complained, but can we showhorn 1243 // that diagnostic information into a more useful form? 1244 KnownModules[Path[0].first] = 0; 1245 return ModuleLoadResult(); 1246 1247 case ASTReader::Failure: 1248 ModuleLoader::HadFatalFailure = true; 1249 // Already complained, but note now that we failed. 1250 KnownModules[Path[0].first] = 0; 1251 ModuleBuildFailed = true; 1252 return ModuleLoadResult(); 1253 } 1254 1255 // Cache the result of this top-level module lookup for later. 1256 Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first; 1257 } 1258 1259 // If we never found the module, fail. 1260 if (!Module) 1261 return ModuleLoadResult(); 1262 1263 // Verify that the rest of the module path actually corresponds to 1264 // a submodule. 1265 if (Path.size() > 1) { 1266 for (unsigned I = 1, N = Path.size(); I != N; ++I) { 1267 StringRef Name = Path[I].first->getName(); 1268 clang::Module *Sub = Module->findSubmodule(Name); 1269 1270 if (!Sub) { 1271 // Attempt to perform typo correction to find a module name that works. 1272 SmallVector<StringRef, 2> Best; 1273 unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)(); 1274 1275 for (clang::Module::submodule_iterator J = Module->submodule_begin(), 1276 JEnd = Module->submodule_end(); 1277 J != JEnd; ++J) { 1278 unsigned ED = Name.edit_distance((*J)->Name, 1279 /*AllowReplacements=*/true, 1280 BestEditDistance); 1281 if (ED <= BestEditDistance) { 1282 if (ED < BestEditDistance) { 1283 Best.clear(); 1284 BestEditDistance = ED; 1285 } 1286 1287 Best.push_back((*J)->Name); 1288 } 1289 } 1290 1291 // If there was a clear winner, user it. 1292 if (Best.size() == 1) { 1293 getDiagnostics().Report(Path[I].second, 1294 diag::err_no_submodule_suggest) 1295 << Path[I].first << Module->getFullModuleName() << Best[0] 1296 << SourceRange(Path[0].second, Path[I-1].second) 1297 << FixItHint::CreateReplacement(SourceRange(Path[I].second), 1298 Best[0]); 1299 1300 Sub = Module->findSubmodule(Best[0]); 1301 } 1302 } 1303 1304 if (!Sub) { 1305 // No submodule by this name. Complain, and don't look for further 1306 // submodules. 1307 getDiagnostics().Report(Path[I].second, diag::err_no_submodule) 1308 << Path[I].first << Module->getFullModuleName() 1309 << SourceRange(Path[0].second, Path[I-1].second); 1310 break; 1311 } 1312 1313 Module = Sub; 1314 } 1315 } 1316 1317 // Make the named module visible, if it's not already part of the module 1318 // we are parsing. 1319 if (ModuleName != getLangOpts().CurrentModule) { 1320 if (!Module->IsFromModuleFile) { 1321 // We have an umbrella header or directory that doesn't actually include 1322 // all of the headers within the directory it covers. Complain about 1323 // this missing submodule and recover by forgetting that we ever saw 1324 // this submodule. 1325 // FIXME: Should we detect this at module load time? It seems fairly 1326 // expensive (and rare). 1327 getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule) 1328 << Module->getFullModuleName() 1329 << SourceRange(Path.front().second, Path.back().second); 1330 1331 return ModuleLoadResult(0, true); 1332 } 1333 1334 // Check whether this module is available. 1335 clang::Module::Requirement Requirement; 1336 clang::Module::HeaderDirective MissingHeader; 1337 if (!Module->isAvailable(getLangOpts(), getTarget(), Requirement, 1338 MissingHeader)) { 1339 if (MissingHeader.FileNameLoc.isValid()) { 1340 getDiagnostics().Report(MissingHeader.FileNameLoc, 1341 diag::err_module_header_missing) 1342 << MissingHeader.IsUmbrella << MissingHeader.FileName; 1343 } else { 1344 getDiagnostics().Report(ImportLoc, diag::err_module_unavailable) 1345 << Module->getFullModuleName() 1346 << Requirement.second << Requirement.first 1347 << SourceRange(Path.front().second, Path.back().second); 1348 } 1349 LastModuleImportLoc = ImportLoc; 1350 LastModuleImportResult = ModuleLoadResult(); 1351 return ModuleLoadResult(); 1352 } 1353 1354 ModuleManager->makeModuleVisible(Module, Visibility, ImportLoc, 1355 /*Complain=*/true); 1356 } 1357 1358 // Check for any configuration macros that have changed. 1359 clang::Module *TopModule = Module->getTopLevelModule(); 1360 for (unsigned I = 0, N = TopModule->ConfigMacros.size(); I != N; ++I) { 1361 checkConfigMacro(getPreprocessor(), TopModule->ConfigMacros[I], 1362 Module, ImportLoc); 1363 } 1364 1365 // If this module import was due to an inclusion directive, create an 1366 // implicit import declaration to capture it in the AST. 1367 if (IsInclusionDirective && hasASTContext()) { 1368 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 1369 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 1370 ImportLoc, Module, 1371 Path.back().second); 1372 TU->addDecl(ImportD); 1373 if (Consumer) 1374 Consumer->HandleImplicitImportDecl(ImportD); 1375 } 1376 1377 LastModuleImportLoc = ImportLoc; 1378 LastModuleImportResult = ModuleLoadResult(Module, false); 1379 return LastModuleImportResult; 1380 } 1381 1382 void CompilerInstance::makeModuleVisible(Module *Mod, 1383 Module::NameVisibilityKind Visibility, 1384 SourceLocation ImportLoc, 1385 bool Complain){ 1386 ModuleManager->makeModuleVisible(Mod, Visibility, ImportLoc, Complain); 1387 } 1388 1389