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/AST/Decl.h" 15 #include "clang/Basic/Diagnostic.h" 16 #include "clang/Basic/FileManager.h" 17 #include "clang/Basic/SourceManager.h" 18 #include "clang/Basic/TargetInfo.h" 19 #include "clang/Basic/Version.h" 20 #include "clang/Lex/HeaderSearch.h" 21 #include "clang/Lex/Preprocessor.h" 22 #include "clang/Lex/PTHManager.h" 23 #include "clang/Frontend/ChainedDiagnosticConsumer.h" 24 #include "clang/Frontend/FrontendAction.h" 25 #include "clang/Frontend/FrontendActions.h" 26 #include "clang/Frontend/FrontendDiagnostic.h" 27 #include "clang/Frontend/LogDiagnosticPrinter.h" 28 #include "clang/Frontend/SerializedDiagnosticPrinter.h" 29 #include "clang/Frontend/TextDiagnosticPrinter.h" 30 #include "clang/Frontend/VerifyDiagnosticConsumer.h" 31 #include "clang/Frontend/Utils.h" 32 #include "clang/Serialization/ASTReader.h" 33 #include "clang/Sema/CodeCompleteConsumer.h" 34 #include "llvm/Support/FileSystem.h" 35 #include "llvm/Support/MemoryBuffer.h" 36 #include "llvm/Support/raw_ostream.h" 37 #include "llvm/ADT/Statistic.h" 38 #include "llvm/Support/Timer.h" 39 #include "llvm/Support/Host.h" 40 #include "llvm/Support/Path.h" 41 #include "llvm/Support/Program.h" 42 #include "llvm/Support/Signals.h" 43 #include "llvm/Support/system_error.h" 44 #include "llvm/Support/CrashRecoveryContext.h" 45 #include "llvm/Config/config.h" 46 47 // Support for FileLockManager 48 #include <fstream> 49 #include <sys/types.h> 50 #include <sys/stat.h> 51 52 #if LLVM_ON_WIN32 53 #include <windows.h> 54 #endif 55 #if LLVM_ON_UNIX 56 #include <unistd.h> 57 #endif 58 59 using namespace clang; 60 61 CompilerInstance::CompilerInstance() 62 : Invocation(new CompilerInvocation()), ModuleManager(0) { 63 } 64 65 CompilerInstance::~CompilerInstance() { 66 } 67 68 void CompilerInstance::setInvocation(CompilerInvocation *Value) { 69 Invocation = Value; 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 } 83 84 void CompilerInstance::setSourceManager(SourceManager *Value) { 85 SourceMgr = Value; 86 } 87 88 void CompilerInstance::setPreprocessor(Preprocessor *Value) { PP = Value; } 89 90 void CompilerInstance::setASTContext(ASTContext *Value) { Context = Value; } 91 92 void CompilerInstance::setSema(Sema *S) { 93 TheSema.reset(S); 94 } 95 96 void CompilerInstance::setASTConsumer(ASTConsumer *Value) { 97 Consumer.reset(Value); 98 } 99 100 void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) { 101 CompletionConsumer.reset(Value); 102 } 103 104 // Diagnostics 105 static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts, 106 unsigned argc, const char* const *argv, 107 DiagnosticsEngine &Diags) { 108 std::string ErrorInfo; 109 llvm::OwningPtr<raw_ostream> OS( 110 new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo)); 111 if (!ErrorInfo.empty()) { 112 Diags.Report(diag::err_fe_unable_to_open_logfile) 113 << DiagOpts.DumpBuildInformation << ErrorInfo; 114 return; 115 } 116 117 (*OS) << "clang -cc1 command line arguments: "; 118 for (unsigned i = 0; i != argc; ++i) 119 (*OS) << argv[i] << ' '; 120 (*OS) << '\n'; 121 122 // Chain in a diagnostic client which will log the diagnostics. 123 DiagnosticConsumer *Logger = 124 new TextDiagnosticPrinter(*OS.take(), DiagOpts, /*OwnsOutputStream=*/true); 125 Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger)); 126 } 127 128 static void SetUpDiagnosticLog(const DiagnosticOptions &DiagOpts, 129 const CodeGenOptions *CodeGenOpts, 130 DiagnosticsEngine &Diags) { 131 std::string ErrorInfo; 132 bool OwnsStream = false; 133 raw_ostream *OS = &llvm::errs(); 134 if (DiagOpts.DiagnosticLogFile != "-") { 135 // Create the output stream. 136 llvm::raw_fd_ostream *FileOS( 137 new llvm::raw_fd_ostream(DiagOpts.DiagnosticLogFile.c_str(), 138 ErrorInfo, llvm::raw_fd_ostream::F_Append)); 139 if (!ErrorInfo.empty()) { 140 Diags.Report(diag::warn_fe_cc_log_diagnostics_failure) 141 << DiagOpts.DumpBuildInformation << ErrorInfo; 142 } else { 143 FileOS->SetUnbuffered(); 144 FileOS->SetUseAtomicWrites(true); 145 OS = FileOS; 146 OwnsStream = true; 147 } 148 } 149 150 // Chain in the diagnostic client which will log the diagnostics. 151 LogDiagnosticPrinter *Logger = new LogDiagnosticPrinter(*OS, DiagOpts, 152 OwnsStream); 153 if (CodeGenOpts) 154 Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags); 155 Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger)); 156 } 157 158 static void SetupSerializedDiagnostics(const DiagnosticOptions &DiagOpts, 159 DiagnosticsEngine &Diags, 160 StringRef OutputFile) { 161 std::string ErrorInfo; 162 llvm::OwningPtr<llvm::raw_fd_ostream> OS; 163 OS.reset(new llvm::raw_fd_ostream(OutputFile.str().c_str(), ErrorInfo, 164 llvm::raw_fd_ostream::F_Binary)); 165 166 if (!ErrorInfo.empty()) { 167 Diags.Report(diag::warn_fe_serialized_diag_failure) 168 << OutputFile << ErrorInfo; 169 return; 170 } 171 172 DiagnosticConsumer *SerializedConsumer = 173 clang::serialized_diags::create(OS.take()); 174 175 176 Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), 177 SerializedConsumer)); 178 } 179 180 void CompilerInstance::createDiagnostics(int Argc, const char* const *Argv, 181 DiagnosticConsumer *Client, 182 bool ShouldOwnClient, 183 bool ShouldCloneClient) { 184 Diagnostics = createDiagnostics(getDiagnosticOpts(), Argc, Argv, Client, 185 ShouldOwnClient, ShouldCloneClient, 186 &getCodeGenOpts()); 187 } 188 189 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> 190 CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts, 191 int Argc, const char* const *Argv, 192 DiagnosticConsumer *Client, 193 bool ShouldOwnClient, 194 bool ShouldCloneClient, 195 const CodeGenOptions *CodeGenOpts) { 196 llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs()); 197 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> 198 Diags(new DiagnosticsEngine(DiagID)); 199 200 // Create the diagnostic client for reporting errors or for 201 // implementing -verify. 202 if (Client) { 203 if (ShouldCloneClient) 204 Diags->setClient(Client->clone(*Diags), ShouldOwnClient); 205 else 206 Diags->setClient(Client, ShouldOwnClient); 207 } else 208 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts)); 209 210 // Chain in -verify checker, if requested. 211 if (Opts.VerifyDiagnostics) 212 Diags->setClient(new VerifyDiagnosticConsumer(*Diags)); 213 214 // Chain in -diagnostic-log-file dumper, if requested. 215 if (!Opts.DiagnosticLogFile.empty()) 216 SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags); 217 218 if (!Opts.DumpBuildInformation.empty()) 219 SetUpBuildDumpLog(Opts, Argc, Argv, *Diags); 220 221 if (!Opts.DiagnosticSerializationFile.empty()) 222 SetupSerializedDiagnostics(Opts, *Diags, 223 Opts.DiagnosticSerializationFile); 224 225 // Configure our handling of diagnostics. 226 ProcessWarningOptions(*Diags, Opts); 227 228 return Diags; 229 } 230 231 // File Manager 232 233 void CompilerInstance::createFileManager() { 234 FileMgr = new FileManager(getFileSystemOpts()); 235 } 236 237 // Source Manager 238 239 void CompilerInstance::createSourceManager(FileManager &FileMgr) { 240 SourceMgr = new SourceManager(getDiagnostics(), FileMgr); 241 } 242 243 // Preprocessor 244 245 void CompilerInstance::createPreprocessor() { 246 const PreprocessorOptions &PPOpts = getPreprocessorOpts(); 247 248 // Create a PTH manager if we are using some form of a token cache. 249 PTHManager *PTHMgr = 0; 250 if (!PPOpts.TokenCache.empty()) 251 PTHMgr = PTHManager::Create(PPOpts.TokenCache, getDiagnostics()); 252 253 // Create the Preprocessor. 254 HeaderSearch *HeaderInfo = new HeaderSearch(getFileManager(), 255 getDiagnostics()); 256 PP = new Preprocessor(getDiagnostics(), getLangOpts(), &getTarget(), 257 getSourceManager(), *HeaderInfo, *this, PTHMgr, 258 /*OwnsHeaderSearch=*/true); 259 260 // Note that this is different then passing PTHMgr to Preprocessor's ctor. 261 // That argument is used as the IdentifierInfoLookup argument to 262 // IdentifierTable's ctor. 263 if (PTHMgr) { 264 PTHMgr->setPreprocessor(&*PP); 265 PP->setPTHManager(PTHMgr); 266 } 267 268 if (PPOpts.DetailedRecord) 269 PP->createPreprocessingRecord( 270 PPOpts.DetailedRecordIncludesNestedMacroExpansions); 271 272 InitializePreprocessor(*PP, PPOpts, getHeaderSearchOpts(), getFrontendOpts()); 273 274 // Set up the module path, including the hash for the 275 // module-creation options. 276 llvm::SmallString<256> SpecificModuleCache( 277 getHeaderSearchOpts().ModuleCachePath); 278 if (!getHeaderSearchOpts().DisableModuleHash) 279 llvm::sys::path::append(SpecificModuleCache, 280 getInvocation().getModuleHash()); 281 PP->getHeaderSearchInfo().setModuleCachePath(SpecificModuleCache); 282 283 // Handle generating dependencies, if requested. 284 const DependencyOutputOptions &DepOpts = getDependencyOutputOpts(); 285 if (!DepOpts.OutputFile.empty()) 286 AttachDependencyFileGen(*PP, DepOpts); 287 288 // Handle generating header include information, if requested. 289 if (DepOpts.ShowHeaderIncludes) 290 AttachHeaderIncludeGen(*PP); 291 if (!DepOpts.HeaderIncludeOutputFile.empty()) { 292 StringRef OutputPath = DepOpts.HeaderIncludeOutputFile; 293 if (OutputPath == "-") 294 OutputPath = ""; 295 AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/true, OutputPath, 296 /*ShowDepth=*/false); 297 } 298 } 299 300 // ASTContext 301 302 void CompilerInstance::createASTContext() { 303 Preprocessor &PP = getPreprocessor(); 304 Context = new ASTContext(getLangOpts(), PP.getSourceManager(), 305 &getTarget(), PP.getIdentifierTable(), 306 PP.getSelectorTable(), PP.getBuiltinInfo(), 307 /*size_reserve=*/ 0); 308 } 309 310 // ExternalASTSource 311 312 void CompilerInstance::createPCHExternalASTSource(StringRef Path, 313 bool DisablePCHValidation, 314 bool DisableStatCache, 315 void *DeserializationListener){ 316 llvm::OwningPtr<ExternalASTSource> Source; 317 bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0; 318 Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot, 319 DisablePCHValidation, 320 DisableStatCache, 321 getPreprocessor(), getASTContext(), 322 DeserializationListener, 323 Preamble)); 324 ModuleManager = static_cast<ASTReader*>(Source.get()); 325 getASTContext().setExternalSource(Source); 326 } 327 328 ExternalASTSource * 329 CompilerInstance::createPCHExternalASTSource(StringRef Path, 330 const std::string &Sysroot, 331 bool DisablePCHValidation, 332 bool DisableStatCache, 333 Preprocessor &PP, 334 ASTContext &Context, 335 void *DeserializationListener, 336 bool Preamble) { 337 llvm::OwningPtr<ASTReader> Reader; 338 Reader.reset(new ASTReader(PP, Context, 339 Sysroot.empty() ? "" : Sysroot.c_str(), 340 DisablePCHValidation, DisableStatCache)); 341 342 Reader->setDeserializationListener( 343 static_cast<ASTDeserializationListener *>(DeserializationListener)); 344 switch (Reader->ReadAST(Path, 345 Preamble ? serialization::MK_Preamble 346 : serialization::MK_PCH)) { 347 case ASTReader::Success: 348 // Set the predefines buffer as suggested by the PCH reader. Typically, the 349 // predefines buffer will be empty. 350 PP.setPredefines(Reader->getSuggestedPredefines()); 351 return Reader.take(); 352 353 case ASTReader::Failure: 354 // Unrecoverable failure: don't even try to process the input file. 355 break; 356 357 case ASTReader::IgnorePCH: 358 // No suitable PCH file could be found. Return an error. 359 break; 360 } 361 362 return 0; 363 } 364 365 // Code Completion 366 367 static bool EnableCodeCompletion(Preprocessor &PP, 368 const std::string &Filename, 369 unsigned Line, 370 unsigned Column) { 371 // Tell the source manager to chop off the given file at a specific 372 // line and column. 373 const FileEntry *Entry = PP.getFileManager().getFile(Filename); 374 if (!Entry) { 375 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file) 376 << Filename; 377 return true; 378 } 379 380 // Truncate the named file at the given line/column. 381 PP.SetCodeCompletionPoint(Entry, Line, Column); 382 return false; 383 } 384 385 void CompilerInstance::createCodeCompletionConsumer() { 386 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt; 387 if (!CompletionConsumer) { 388 CompletionConsumer.reset( 389 createCodeCompletionConsumer(getPreprocessor(), 390 Loc.FileName, Loc.Line, Loc.Column, 391 getFrontendOpts().ShowMacrosInCodeCompletion, 392 getFrontendOpts().ShowCodePatternsInCodeCompletion, 393 getFrontendOpts().ShowGlobalSymbolsInCodeCompletion, 394 llvm::outs())); 395 if (!CompletionConsumer) 396 return; 397 } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName, 398 Loc.Line, Loc.Column)) { 399 CompletionConsumer.reset(); 400 return; 401 } 402 403 if (CompletionConsumer->isOutputBinary() && 404 llvm::sys::Program::ChangeStdoutToBinary()) { 405 getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary); 406 CompletionConsumer.reset(); 407 } 408 } 409 410 void CompilerInstance::createFrontendTimer() { 411 FrontendTimer.reset(new llvm::Timer("Clang front-end timer")); 412 } 413 414 CodeCompleteConsumer * 415 CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP, 416 const std::string &Filename, 417 unsigned Line, 418 unsigned Column, 419 bool ShowMacros, 420 bool ShowCodePatterns, 421 bool ShowGlobals, 422 raw_ostream &OS) { 423 if (EnableCodeCompletion(PP, Filename, Line, Column)) 424 return 0; 425 426 // Set up the creation routine for code-completion. 427 return new PrintingCodeCompleteConsumer(ShowMacros, ShowCodePatterns, 428 ShowGlobals, OS); 429 } 430 431 void CompilerInstance::createSema(TranslationUnitKind TUKind, 432 CodeCompleteConsumer *CompletionConsumer) { 433 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(), 434 TUKind, CompletionConsumer)); 435 } 436 437 // Output Files 438 439 void CompilerInstance::addOutputFile(const OutputFile &OutFile) { 440 assert(OutFile.OS && "Attempt to add empty stream to output list!"); 441 OutputFiles.push_back(OutFile); 442 } 443 444 void CompilerInstance::clearOutputFiles(bool EraseFiles) { 445 for (std::list<OutputFile>::iterator 446 it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) { 447 delete it->OS; 448 if (!it->TempFilename.empty()) { 449 if (EraseFiles) { 450 bool existed; 451 llvm::sys::fs::remove(it->TempFilename, existed); 452 } else { 453 llvm::SmallString<128> NewOutFile(it->Filename); 454 455 // If '-working-directory' was passed, the output filename should be 456 // relative to that. 457 FileMgr->FixupRelativePath(NewOutFile); 458 if (llvm::error_code ec = llvm::sys::fs::rename(it->TempFilename, 459 NewOutFile.str())) { 460 getDiagnostics().Report(diag::err_fe_unable_to_rename_temp) 461 << it->TempFilename << it->Filename << ec.message(); 462 463 bool existed; 464 llvm::sys::fs::remove(it->TempFilename, existed); 465 } 466 } 467 } else if (!it->Filename.empty() && EraseFiles) 468 llvm::sys::Path(it->Filename).eraseFromDisk(); 469 470 } 471 OutputFiles.clear(); 472 } 473 474 llvm::raw_fd_ostream * 475 CompilerInstance::createDefaultOutputFile(bool Binary, 476 StringRef InFile, 477 StringRef Extension) { 478 return createOutputFile(getFrontendOpts().OutputFile, Binary, 479 /*RemoveFileOnSignal=*/true, InFile, Extension); 480 } 481 482 llvm::raw_fd_ostream * 483 CompilerInstance::createOutputFile(StringRef OutputPath, 484 bool Binary, bool RemoveFileOnSignal, 485 StringRef InFile, 486 StringRef Extension, 487 bool UseTemporary) { 488 std::string Error, OutputPathName, TempPathName; 489 llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary, 490 RemoveFileOnSignal, 491 InFile, Extension, 492 UseTemporary, 493 &OutputPathName, 494 &TempPathName); 495 if (!OS) { 496 getDiagnostics().Report(diag::err_fe_unable_to_open_output) 497 << OutputPath << Error; 498 return 0; 499 } 500 501 // Add the output file -- but don't try to remove "-", since this means we are 502 // using stdin. 503 addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "", 504 TempPathName, OS)); 505 506 return OS; 507 } 508 509 llvm::raw_fd_ostream * 510 CompilerInstance::createOutputFile(StringRef OutputPath, 511 std::string &Error, 512 bool Binary, 513 bool RemoveFileOnSignal, 514 StringRef InFile, 515 StringRef Extension, 516 bool UseTemporary, 517 std::string *ResultPathName, 518 std::string *TempPathName) { 519 std::string OutFile, TempFile; 520 if (!OutputPath.empty()) { 521 OutFile = OutputPath; 522 } else if (InFile == "-") { 523 OutFile = "-"; 524 } else if (!Extension.empty()) { 525 llvm::sys::Path Path(InFile); 526 Path.eraseSuffix(); 527 Path.appendSuffix(Extension); 528 OutFile = Path.str(); 529 } else { 530 OutFile = "-"; 531 } 532 533 llvm::OwningPtr<llvm::raw_fd_ostream> OS; 534 std::string OSFile; 535 536 if (UseTemporary && OutFile != "-") { 537 llvm::sys::Path OutPath(OutFile); 538 // Only create the temporary if we can actually write to OutPath, otherwise 539 // we want to fail early. 540 bool Exists; 541 if ((llvm::sys::fs::exists(OutPath.str(), Exists) || !Exists) || 542 (OutPath.isRegularFile() && OutPath.canWrite())) { 543 // Create a temporary file. 544 llvm::SmallString<128> TempPath; 545 TempPath = OutFile; 546 TempPath += "-%%%%%%%%"; 547 int fd; 548 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath, 549 /*makeAbsolute=*/false) == llvm::errc::success) { 550 OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true)); 551 OSFile = TempFile = TempPath.str(); 552 } 553 } 554 } 555 556 if (!OS) { 557 OSFile = OutFile; 558 OS.reset( 559 new llvm::raw_fd_ostream(OSFile.c_str(), Error, 560 (Binary ? llvm::raw_fd_ostream::F_Binary : 0))); 561 if (!Error.empty()) 562 return 0; 563 } 564 565 // Make sure the out stream file gets removed if we crash. 566 if (RemoveFileOnSignal) 567 llvm::sys::RemoveFileOnSignal(llvm::sys::Path(OSFile)); 568 569 if (ResultPathName) 570 *ResultPathName = OutFile; 571 if (TempPathName) 572 *TempPathName = TempFile; 573 574 return OS.take(); 575 } 576 577 // Initialization Utilities 578 579 bool CompilerInstance::InitializeSourceManager(StringRef InputFile) { 580 return InitializeSourceManager(InputFile, getDiagnostics(), getFileManager(), 581 getSourceManager(), getFrontendOpts()); 582 } 583 584 bool CompilerInstance::InitializeSourceManager(StringRef InputFile, 585 DiagnosticsEngine &Diags, 586 FileManager &FileMgr, 587 SourceManager &SourceMgr, 588 const FrontendOptions &Opts) { 589 // Figure out where to get and map in the main file. 590 if (InputFile != "-") { 591 const FileEntry *File = FileMgr.getFile(InputFile); 592 if (!File) { 593 Diags.Report(diag::err_fe_error_reading) << InputFile; 594 return false; 595 } 596 SourceMgr.createMainFileID(File); 597 } else { 598 llvm::OwningPtr<llvm::MemoryBuffer> SB; 599 if (llvm::MemoryBuffer::getSTDIN(SB)) { 600 // FIXME: Give ec.message() in this diag. 601 Diags.Report(diag::err_fe_error_reading_stdin); 602 return false; 603 } 604 const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(), 605 SB->getBufferSize(), 0); 606 SourceMgr.createMainFileID(File); 607 SourceMgr.overrideFileContents(File, SB.take()); 608 } 609 610 assert(!SourceMgr.getMainFileID().isInvalid() && 611 "Couldn't establish MainFileID!"); 612 return true; 613 } 614 615 // High-Level Operations 616 617 bool CompilerInstance::ExecuteAction(FrontendAction &Act) { 618 assert(hasDiagnostics() && "Diagnostics engine is not initialized!"); 619 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!"); 620 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!"); 621 622 // FIXME: Take this as an argument, once all the APIs we used have moved to 623 // taking it as an input instead of hard-coding llvm::errs. 624 raw_ostream &OS = llvm::errs(); 625 626 // Create the target instance. 627 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts())); 628 if (!hasTarget()) 629 return false; 630 631 // Inform the target of the language options. 632 // 633 // FIXME: We shouldn't need to do this, the target should be immutable once 634 // created. This complexity should be lifted elsewhere. 635 getTarget().setForcedLangOptions(getLangOpts()); 636 637 // Validate/process some options. 638 if (getHeaderSearchOpts().Verbose) 639 OS << "clang -cc1 version " CLANG_VERSION_STRING 640 << " based upon " << PACKAGE_STRING 641 << " default target " << llvm::sys::getDefaultTargetTriple() << "\n"; 642 643 if (getFrontendOpts().ShowTimers) 644 createFrontendTimer(); 645 646 if (getFrontendOpts().ShowStats) 647 llvm::EnableStatistics(); 648 649 for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) { 650 const std::string &InFile = getFrontendOpts().Inputs[i].second; 651 652 // Reset the ID tables if we are reusing the SourceManager. 653 if (hasSourceManager()) 654 getSourceManager().clearIDTables(); 655 656 if (Act.BeginSourceFile(*this, InFile, getFrontendOpts().Inputs[i].first)) { 657 Act.Execute(); 658 Act.EndSourceFile(); 659 } 660 } 661 662 // Notify the diagnostic client that all files were processed. 663 getDiagnostics().getClient()->finish(); 664 665 if (getDiagnosticOpts().ShowCarets) { 666 // We can have multiple diagnostics sharing one diagnostic client. 667 // Get the total number of warnings/errors from the client. 668 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings(); 669 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors(); 670 671 if (NumWarnings) 672 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s"); 673 if (NumWarnings && NumErrors) 674 OS << " and "; 675 if (NumErrors) 676 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s"); 677 if (NumWarnings || NumErrors) 678 OS << " generated.\n"; 679 } 680 681 if (getFrontendOpts().ShowStats && hasFileManager()) { 682 getFileManager().PrintStats(); 683 OS << "\n"; 684 } 685 686 return !getDiagnostics().getClient()->getNumErrors(); 687 } 688 689 /// \brief Determine the appropriate source input kind based on language 690 /// options. 691 static InputKind getSourceInputKindFromOptions(const LangOptions &LangOpts) { 692 if (LangOpts.OpenCL) 693 return IK_OpenCL; 694 if (LangOpts.CUDA) 695 return IK_CUDA; 696 if (LangOpts.ObjC1) 697 return LangOpts.CPlusPlus? IK_ObjCXX : IK_ObjC; 698 return LangOpts.CPlusPlus? IK_CXX : IK_C; 699 } 700 701 namespace { 702 struct CompileModuleMapData { 703 CompilerInstance &Instance; 704 GenerateModuleAction &CreateModuleAction; 705 }; 706 } 707 708 /// \brief Helper function that executes the module-generating action under 709 /// a crash recovery context. 710 static void doCompileMapModule(void *UserData) { 711 CompileModuleMapData &Data 712 = *reinterpret_cast<CompileModuleMapData *>(UserData); 713 Data.Instance.ExecuteAction(Data.CreateModuleAction); 714 } 715 716 namespace { 717 /// \brief Class that manages the creation of a lock file to aid 718 /// implicit coordination between different processes. 719 /// 720 /// The implicit coordination works by creating a ".lock" file alongside 721 /// the file that we're coordinating for, using the atomicity of the file 722 /// system to ensure that only a single process can create that ".lock" file. 723 /// When the lock file is removed, the owning process has finished the 724 /// operation. 725 class LockFileManager { 726 public: 727 /// \brief Describes the state of a lock file. 728 enum LockFileState { 729 /// \brief The lock file has been created and is owned by this instance 730 /// of the object. 731 LFS_Owned, 732 /// \brief The lock file already exists and is owned by some other 733 /// instance. 734 LFS_Shared, 735 /// \brief An error occurred while trying to create or find the lock 736 /// file. 737 LFS_Error 738 }; 739 740 private: 741 llvm::SmallString<128> LockFileName; 742 llvm::SmallString<128> UniqueLockFileName; 743 744 llvm::Optional<std::pair<std::string, int> > Owner; 745 llvm::Optional<llvm::error_code> Error; 746 747 LockFileManager(const LockFileManager &); 748 LockFileManager &operator=(const LockFileManager &); 749 750 static llvm::Optional<std::pair<std::string, int> > 751 readLockFile(StringRef LockFileName); 752 753 static bool processStillExecuting(StringRef Hostname, int PID); 754 755 public: 756 757 LockFileManager(StringRef FileName); 758 ~LockFileManager(); 759 760 /// \brief Determine the state of the lock file. 761 LockFileState getState() const; 762 763 operator LockFileState() const { return getState(); } 764 765 /// \brief For a shared lock, wait until the owner releases the lock. 766 void waitForUnlock(); 767 }; 768 } 769 770 /// \brief Attempt to read the lock file with the given name, if it exists. 771 /// 772 /// \param LockFileName The name of the lock file to read. 773 /// 774 /// \returns The process ID of the process that owns this lock file 775 llvm::Optional<std::pair<std::string, int> > 776 LockFileManager::readLockFile(StringRef LockFileName) { 777 // Check whether the lock file exists. If not, clearly there's nothing 778 // to read, so we just return. 779 bool Exists = false; 780 if (llvm::sys::fs::exists(LockFileName, Exists) || !Exists) 781 return llvm::Optional<std::pair<std::string, int> >(); 782 783 // Read the owning host and PID out of the lock file. If it appears that the 784 // owning process is dead, the lock file is invalid. 785 int PID = 0; 786 std::string Hostname; 787 std::ifstream Input(LockFileName.str().c_str()); 788 if (Input >> Hostname >> PID && PID > 0 && 789 processStillExecuting(Hostname, PID)) 790 return std::make_pair(Hostname, PID); 791 792 // Delete the lock file. It's invalid anyway. 793 bool Existed; 794 llvm::sys::fs::remove(LockFileName, Existed); 795 return llvm::Optional<std::pair<std::string, int> >(); 796 } 797 798 bool LockFileManager::processStillExecuting(StringRef Hostname, int PID) { 799 #if LLVM_ON_UNIX 800 char MyHostname[256]; 801 MyHostname[255] = 0; 802 MyHostname[0] = 0; 803 gethostname(MyHostname, 255); 804 // Check whether the process is dead. If so, we're done. 805 if (MyHostname == Hostname && getsid(PID) == -1 && errno == ESRCH) 806 return false; 807 #endif 808 809 return true; 810 } 811 812 LockFileManager::LockFileManager(StringRef FileName) 813 { 814 LockFileName = FileName; 815 LockFileName += ".lock"; 816 817 // If the lock file already exists, don't bother to try to create our own 818 // lock file; it won't work anyway. Just figure out who owns this lock file. 819 if ((Owner = readLockFile(LockFileName))) 820 return; 821 822 // Create a lock file that is unique to this instance. 823 UniqueLockFileName = LockFileName; 824 UniqueLockFileName += "-%%%%%%%%"; 825 int UniqueLockFileID; 826 if (llvm::error_code EC 827 = llvm::sys::fs::unique_file(UniqueLockFileName.str(), 828 UniqueLockFileID, 829 UniqueLockFileName, 830 /*makeAbsolute=*/false)) { 831 Error = EC; 832 return; 833 } 834 835 // Write our process ID to our unique lock file. 836 { 837 llvm::raw_fd_ostream Out(UniqueLockFileID, /*shouldClose=*/true); 838 839 #if LLVM_ON_UNIX 840 // FIXME: move getpid() call into LLVM 841 char hostname[256]; 842 hostname[255] = 0; 843 hostname[0] = 0; 844 gethostname(hostname, 255); 845 Out << hostname << ' ' << getpid(); 846 #else 847 Out << "localhost 1"; 848 #endif 849 Out.close(); 850 851 if (Out.has_error()) { 852 // We failed to write out PID, so make up an excuse, remove the 853 // unique lock file, and fail. 854 Error = llvm::make_error_code(llvm::errc::no_space_on_device); 855 bool Existed; 856 llvm::sys::fs::remove(UniqueLockFileName.c_str(), Existed); 857 return; 858 } 859 } 860 861 // Create a hard link from the lock file name. If this succeeds, we're done. 862 llvm::error_code EC 863 = llvm::sys::fs::create_hard_link(UniqueLockFileName.str(), 864 LockFileName.str()); 865 if (EC == llvm::errc::success) 866 return; 867 868 // Creating the hard link failed. 869 870 #ifdef LLVM_ON_UNIX 871 // The creation of the hard link may appear to fail, but if stat'ing the 872 // unique file returns a link count of 2, then we can still declare success. 873 struct stat StatBuf; 874 if (stat(UniqueLockFileName.c_str(), &StatBuf) == 0 && 875 StatBuf.st_nlink == 2) 876 return; 877 #endif 878 879 // Someone else managed to create the lock file first. Wipe out our unique 880 // lock file (it's useless now) and read the process ID from the lock file. 881 bool Existed; 882 llvm::sys::fs::remove(UniqueLockFileName.str(), Existed); 883 if ((Owner = readLockFile(LockFileName))) 884 return; 885 886 // There is a lock file that nobody owns; try to clean it up and report 887 // an error. 888 llvm::sys::fs::remove(LockFileName.str(), Existed); 889 Error = EC; 890 } 891 892 LockFileManager::LockFileState LockFileManager::getState() const { 893 if (Owner) 894 return LFS_Shared; 895 896 if (Error) 897 return LFS_Error; 898 899 return LFS_Owned; 900 } 901 902 LockFileManager::~LockFileManager() { 903 if (getState() != LFS_Owned) 904 return; 905 906 // Since we own the lock, remove the lock file and our own unique lock file. 907 bool Existed; 908 llvm::sys::fs::remove(LockFileName.str(), Existed); 909 llvm::sys::fs::remove(UniqueLockFileName.str(), Existed); 910 } 911 912 void LockFileManager::waitForUnlock() { 913 if (getState() != LFS_Shared) 914 return; 915 916 #if LLVM_ON_WIN32 917 unsigned long Interval = 1; 918 #else 919 struct timespec Interval; 920 Interval.tv_sec = 0; 921 Interval.tv_nsec = 1000000; 922 #endif 923 // Don't wait more than an hour for the file to appear. 924 const unsigned MaxSeconds = 3600; 925 do { 926 // Sleep for the designated interval, to allow the owning process time to 927 // finish up and 928 // FIXME: Should we hook in to system APIs to get a notification when the 929 // lock file is deleted? 930 #if LLVM_ON_WIN32 931 Sleep(Interval); 932 #else 933 nanosleep(&Interval, NULL); 934 #endif 935 // If the file no longer exists, we're done. 936 bool Exists = false; 937 if (!llvm::sys::fs::exists(LockFileName.str(), Exists) && !Exists) 938 return; 939 940 if (!processStillExecuting((*Owner).first, (*Owner).second)) 941 return; 942 943 // Exponentially increase the time we wait for the lock to be removed. 944 #if LLVM_ON_WIN32 945 Interval *= 2; 946 #else 947 Interval.tv_sec *= 2; 948 Interval.tv_nsec *= 2; 949 if (Interval.tv_nsec >= 1000000000) { 950 ++Interval.tv_sec; 951 Interval.tv_nsec -= 1000000000; 952 } 953 #endif 954 } while ( 955 #if LLVM_ON_WIN32 956 Interval < MaxSeconds * 1000 957 #else 958 Interval.tv_sec < (time_t)MaxSeconds 959 #endif 960 ); 961 962 // Give up. 963 } 964 965 /// \brief Compile a module file for the given module, using the options 966 /// provided by the importing compiler instance. 967 static void compileModule(CompilerInstance &ImportingInstance, 968 Module *Module, 969 StringRef ModuleFileName) { 970 LockFileManager Locked(ModuleFileName); 971 switch (Locked) { 972 case LockFileManager::LFS_Error: 973 return; 974 975 case LockFileManager::LFS_Owned: 976 // We're responsible for building the module ourselves. Do so below. 977 break; 978 979 case LockFileManager::LFS_Shared: 980 // Someone else is responsible for building the module. Wait for them to 981 // finish. 982 Locked.waitForUnlock(); 983 break; 984 } 985 986 ModuleMap &ModMap 987 = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap(); 988 989 // Construct a compiler invocation for creating this module. 990 llvm::IntrusiveRefCntPtr<CompilerInvocation> Invocation 991 (new CompilerInvocation(ImportingInstance.getInvocation())); 992 993 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts(); 994 995 // For any options that aren't intended to affect how a module is built, 996 // reset them to their default values. 997 Invocation->getLangOpts()->resetNonModularOptions(); 998 PPOpts.resetNonModularOptions(); 999 1000 // Note the name of the module we're building. 1001 Invocation->getLangOpts()->CurrentModule = Module->getTopLevelModuleName(); 1002 1003 // Note that this module is part of the module build path, so that we 1004 // can detect cycles in the module graph. 1005 PPOpts.ModuleBuildPath.push_back(Module->getTopLevelModuleName()); 1006 1007 // If there is a module map file, build the module using the module map. 1008 // Set up the inputs/outputs so that we build the module from its umbrella 1009 // header. 1010 FrontendOptions &FrontendOpts = Invocation->getFrontendOpts(); 1011 FrontendOpts.OutputFile = ModuleFileName.str(); 1012 FrontendOpts.DisableFree = false; 1013 FrontendOpts.Inputs.clear(); 1014 InputKind IK = getSourceInputKindFromOptions(*Invocation->getLangOpts()); 1015 1016 // Get or create the module map that we'll use to build this module. 1017 llvm::SmallString<128> TempModuleMapFileName; 1018 if (const FileEntry *ModuleMapFile 1019 = ModMap.getContainingModuleMapFile(Module)) { 1020 // Use the module map where this module resides. 1021 FrontendOpts.Inputs.push_back(std::make_pair(IK, ModuleMapFile->getName())); 1022 } else { 1023 // Create a temporary module map file. 1024 TempModuleMapFileName = Module->Name; 1025 TempModuleMapFileName += "-%%%%%%%%.map"; 1026 int FD; 1027 if (llvm::sys::fs::unique_file(TempModuleMapFileName.str(), FD, 1028 TempModuleMapFileName, 1029 /*makeAbsolute=*/true) 1030 != llvm::errc::success) { 1031 ImportingInstance.getDiagnostics().Report(diag::err_module_map_temp_file) 1032 << TempModuleMapFileName; 1033 return; 1034 } 1035 // Print the module map to this file. 1036 llvm::raw_fd_ostream OS(FD, /*shouldClose=*/true); 1037 Module->print(OS); 1038 FrontendOpts.Inputs.push_back( 1039 std::make_pair(IK, TempModuleMapFileName.str().str())); 1040 } 1041 1042 // Don't free the remapped file buffers; they are owned by our caller. 1043 PPOpts.RetainRemappedFileBuffers = true; 1044 1045 Invocation->getDiagnosticOpts().VerifyDiagnostics = 0; 1046 assert(ImportingInstance.getInvocation().getModuleHash() == 1047 Invocation->getModuleHash() && "Module hash mismatch!"); 1048 1049 // Construct a compiler instance that will be used to actually create the 1050 // module. 1051 CompilerInstance Instance; 1052 Instance.setInvocation(&*Invocation); 1053 Instance.createDiagnostics(/*argc=*/0, /*argv=*/0, 1054 &ImportingInstance.getDiagnosticClient(), 1055 /*ShouldOwnClient=*/true, 1056 /*ShouldCloneClient=*/true); 1057 1058 // Construct a module-generating action. 1059 GenerateModuleAction CreateModuleAction; 1060 1061 // Execute the action to actually build the module in-place. Use a separate 1062 // thread so that we get a stack large enough. 1063 const unsigned ThreadStackSize = 8 << 20; 1064 llvm::CrashRecoveryContext CRC; 1065 CompileModuleMapData Data = { Instance, CreateModuleAction }; 1066 CRC.RunSafelyOnThread(&doCompileMapModule, &Data, ThreadStackSize); 1067 1068 // Delete the temporary module map file. 1069 // FIXME: Even though we're executing under crash protection, it would still 1070 // be nice to do this with RemoveFileOnSignal when we can. However, that 1071 // doesn't make sense for all clients, so clean this up manually. 1072 if (!TempModuleMapFileName.empty()) 1073 llvm::sys::Path(TempModuleMapFileName).eraseFromDisk(); 1074 } 1075 1076 Module *CompilerInstance::loadModule(SourceLocation ImportLoc, 1077 ModuleIdPath Path, 1078 Module::NameVisibilityKind Visibility, 1079 bool IsInclusionDirective) { 1080 // If we've already handled this import, just return the cached result. 1081 // This one-element cache is important to eliminate redundant diagnostics 1082 // when both the preprocessor and parser see the same import declaration. 1083 if (!ImportLoc.isInvalid() && LastModuleImportLoc == ImportLoc) { 1084 // Make the named module visible. 1085 if (LastModuleImportResult) 1086 ModuleManager->makeModuleVisible(LastModuleImportResult, Visibility); 1087 return LastModuleImportResult; 1088 } 1089 1090 // Determine what file we're searching from. 1091 SourceManager &SourceMgr = getSourceManager(); 1092 SourceLocation ExpandedImportLoc = SourceMgr.getExpansionLoc(ImportLoc); 1093 const FileEntry *CurFile 1094 = SourceMgr.getFileEntryForID(SourceMgr.getFileID(ExpandedImportLoc)); 1095 if (!CurFile) 1096 CurFile = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()); 1097 1098 StringRef ModuleName = Path[0].first->getName(); 1099 SourceLocation ModuleNameLoc = Path[0].second; 1100 1101 clang::Module *Module = 0; 1102 const FileEntry *ModuleFile = 0; 1103 1104 // If we don't already have information on this module, load the module now. 1105 llvm::DenseMap<const IdentifierInfo *, clang::Module *>::iterator Known 1106 = KnownModules.find(Path[0].first); 1107 if (Known != KnownModules.end()) { 1108 // Retrieve the cached top-level module. 1109 Module = Known->second; 1110 } else if (ModuleName == getLangOpts().CurrentModule) { 1111 // This is the module we're building. 1112 Module = PP->getHeaderSearchInfo().getModuleMap().findModule(ModuleName); 1113 Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first; 1114 } else { 1115 // Search for a module with the given name. 1116 std::string ModuleFileName; 1117 ModuleFile 1118 = PP->getHeaderSearchInfo().lookupModule(ModuleName, Module, 1119 &ModuleFileName); 1120 1121 bool BuildingModule = false; 1122 if (!ModuleFile && Module) { 1123 // The module is not cached, but we have a module map from which we can 1124 // build the module. 1125 1126 // Check whether there is a cycle in the module graph. 1127 SmallVectorImpl<std::string> &ModuleBuildPath 1128 = getPreprocessorOpts().ModuleBuildPath; 1129 SmallVectorImpl<std::string>::iterator Pos 1130 = std::find(ModuleBuildPath.begin(), ModuleBuildPath.end(), ModuleName); 1131 if (Pos != ModuleBuildPath.end()) { 1132 llvm::SmallString<256> CyclePath; 1133 for (; Pos != ModuleBuildPath.end(); ++Pos) { 1134 CyclePath += *Pos; 1135 CyclePath += " -> "; 1136 } 1137 CyclePath += ModuleName; 1138 1139 getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle) 1140 << ModuleName << CyclePath; 1141 return 0; 1142 } 1143 1144 getDiagnostics().Report(ModuleNameLoc, diag::warn_module_build) 1145 << ModuleName; 1146 BuildingModule = true; 1147 compileModule(*this, Module, ModuleFileName); 1148 ModuleFile = FileMgr->getFile(ModuleFileName); 1149 } 1150 1151 if (!ModuleFile) { 1152 getDiagnostics().Report(ModuleNameLoc, 1153 BuildingModule? diag::err_module_not_built 1154 : diag::err_module_not_found) 1155 << ModuleName 1156 << SourceRange(ImportLoc, ModuleNameLoc); 1157 return 0; 1158 } 1159 1160 // If we don't already have an ASTReader, create one now. 1161 if (!ModuleManager) { 1162 if (!hasASTContext()) 1163 createASTContext(); 1164 1165 std::string Sysroot = getHeaderSearchOpts().Sysroot; 1166 const PreprocessorOptions &PPOpts = getPreprocessorOpts(); 1167 ModuleManager = new ASTReader(getPreprocessor(), *Context, 1168 Sysroot.empty() ? "" : Sysroot.c_str(), 1169 PPOpts.DisablePCHValidation, 1170 PPOpts.DisableStatCache); 1171 if (hasASTConsumer()) { 1172 ModuleManager->setDeserializationListener( 1173 getASTConsumer().GetASTDeserializationListener()); 1174 getASTContext().setASTMutationListener( 1175 getASTConsumer().GetASTMutationListener()); 1176 } 1177 llvm::OwningPtr<ExternalASTSource> Source; 1178 Source.reset(ModuleManager); 1179 getASTContext().setExternalSource(Source); 1180 if (hasSema()) 1181 ModuleManager->InitializeSema(getSema()); 1182 if (hasASTConsumer()) 1183 ModuleManager->StartTranslationUnit(&getASTConsumer()); 1184 } 1185 1186 // Try to load the module we found. 1187 switch (ModuleManager->ReadAST(ModuleFile->getName(), 1188 serialization::MK_Module)) { 1189 case ASTReader::Success: 1190 break; 1191 1192 case ASTReader::IgnorePCH: 1193 // FIXME: The ASTReader will already have complained, but can we showhorn 1194 // that diagnostic information into a more useful form? 1195 KnownModules[Path[0].first] = 0; 1196 return 0; 1197 1198 case ASTReader::Failure: 1199 // Already complained, but note now that we failed. 1200 KnownModules[Path[0].first] = 0; 1201 return 0; 1202 } 1203 1204 if (!Module) { 1205 // If we loaded the module directly, without finding a module map first, 1206 // we'll have loaded the module's information from the module itself. 1207 Module = PP->getHeaderSearchInfo().getModuleMap() 1208 .findModule((Path[0].first->getName())); 1209 } 1210 1211 // Cache the result of this top-level module lookup for later. 1212 Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first; 1213 } 1214 1215 // If we never found the module, fail. 1216 if (!Module) 1217 return 0; 1218 1219 // Verify that the rest of the module path actually corresponds to 1220 // a submodule. 1221 if (Path.size() > 1) { 1222 for (unsigned I = 1, N = Path.size(); I != N; ++I) { 1223 StringRef Name = Path[I].first->getName(); 1224 llvm::StringMap<clang::Module *>::iterator Pos 1225 = Module->SubModules.find(Name); 1226 1227 if (Pos == Module->SubModules.end()) { 1228 // Attempt to perform typo correction to find a module name that works. 1229 llvm::SmallVector<StringRef, 2> Best; 1230 unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)(); 1231 1232 for (llvm::StringMap<clang::Module *>::iterator 1233 J = Module->SubModules.begin(), 1234 JEnd = Module->SubModules.end(); 1235 J != JEnd; ++J) { 1236 unsigned ED = Name.edit_distance(J->getValue()->Name, 1237 /*AllowReplacements=*/true, 1238 BestEditDistance); 1239 if (ED <= BestEditDistance) { 1240 if (ED < BestEditDistance) 1241 Best.clear(); 1242 Best.push_back(J->getValue()->Name); 1243 } 1244 } 1245 1246 // If there was a clear winner, user it. 1247 if (Best.size() == 1) { 1248 getDiagnostics().Report(Path[I].second, 1249 diag::err_no_submodule_suggest) 1250 << Path[I].first << Module->getFullModuleName() << Best[0] 1251 << SourceRange(Path[0].second, Path[I-1].second) 1252 << FixItHint::CreateReplacement(SourceRange(Path[I].second), 1253 Best[0]); 1254 Pos = Module->SubModules.find(Best[0]); 1255 } 1256 } 1257 1258 if (Pos == Module->SubModules.end()) { 1259 // No submodule by this name. Complain, and don't look for further 1260 // submodules. 1261 getDiagnostics().Report(Path[I].second, diag::err_no_submodule) 1262 << Path[I].first << Module->getFullModuleName() 1263 << SourceRange(Path[0].second, Path[I-1].second); 1264 break; 1265 } 1266 1267 Module = Pos->getValue(); 1268 } 1269 } 1270 1271 // Make the named module visible, if it's not already part of the module 1272 // we are parsing. 1273 if (ModuleName != getLangOpts().CurrentModule) 1274 ModuleManager->makeModuleVisible(Module, Visibility); 1275 1276 // If this module import was due to an inclusion directive, create an 1277 // implicit import declaration to capture it in the AST. 1278 if (IsInclusionDirective && hasASTContext()) { 1279 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 1280 TU->addDecl(ImportDecl::CreateImplicit(getASTContext(), TU, 1281 ImportLoc, Module, 1282 Path.back().second)); 1283 } 1284 1285 LastModuleImportLoc = ImportLoc; 1286 LastModuleImportResult = Module; 1287 return Module; 1288 } 1289