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/Config/config.h" 20 #include "clang/Frontend/ChainedDiagnosticConsumer.h" 21 #include "clang/Frontend/FrontendAction.h" 22 #include "clang/Frontend/FrontendActions.h" 23 #include "clang/Frontend/FrontendDiagnostic.h" 24 #include "clang/Frontend/LogDiagnosticPrinter.h" 25 #include "clang/Frontend/SerializedDiagnosticPrinter.h" 26 #include "clang/Frontend/TextDiagnosticPrinter.h" 27 #include "clang/Frontend/Utils.h" 28 #include "clang/Frontend/VerifyDiagnosticConsumer.h" 29 #include "clang/Lex/HeaderSearch.h" 30 #include "clang/Lex/PTHManager.h" 31 #include "clang/Lex/Preprocessor.h" 32 #include "clang/Lex/PreprocessorOptions.h" 33 #include "clang/Sema/CodeCompleteConsumer.h" 34 #include "clang/Sema/Sema.h" 35 #include "clang/Serialization/ASTReader.h" 36 #include "clang/Serialization/GlobalModuleIndex.h" 37 #include "llvm/ADT/Statistic.h" 38 #include "llvm/Support/CrashRecoveryContext.h" 39 #include "llvm/Support/Errc.h" 40 #include "llvm/Support/FileSystem.h" 41 #include "llvm/Support/Host.h" 42 #include "llvm/Support/LockFileManager.h" 43 #include "llvm/Support/MemoryBuffer.h" 44 #include "llvm/Support/Path.h" 45 #include "llvm/Support/Program.h" 46 #include "llvm/Support/Signals.h" 47 #include "llvm/Support/Timer.h" 48 #include "llvm/Support/raw_ostream.h" 49 #include <sys/stat.h> 50 #include <system_error> 51 #include <time.h> 52 #include <utility> 53 54 using namespace clang; 55 56 CompilerInstance::CompilerInstance( 57 std::shared_ptr<PCHContainerOperations> PCHContainerOps, 58 bool BuildingModule) 59 : ModuleLoader(BuildingModule), Invocation(new CompilerInvocation()), 60 ModuleManager(nullptr), 61 ThePCHContainerOperations(std::move(PCHContainerOps)), 62 BuildGlobalModuleIndex(false), HaveFullGlobalModuleIndex(false), 63 ModuleBuildFailed(false) {} 64 65 CompilerInstance::~CompilerInstance() { 66 assert(OutputFiles.empty() && "Still output files in flight?"); 67 } 68 69 void CompilerInstance::setInvocation(CompilerInvocation *Value) { 70 Invocation = Value; 71 } 72 73 bool CompilerInstance::shouldBuildGlobalModuleIndex() const { 74 return (BuildGlobalModuleIndex || 75 (ModuleManager && ModuleManager->isGlobalIndexUnavailable() && 76 getFrontendOpts().GenerateGlobalModuleIndex)) && 77 !ModuleBuildFailed; 78 } 79 80 void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) { 81 Diagnostics = Value; 82 } 83 84 void CompilerInstance::setTarget(TargetInfo *Value) { Target = Value; } 85 void CompilerInstance::setAuxTarget(TargetInfo *Value) { AuxTarget = Value; } 86 87 void CompilerInstance::setFileManager(FileManager *Value) { 88 FileMgr = Value; 89 if (Value) 90 VirtualFileSystem = Value->getVirtualFileSystem(); 91 else 92 VirtualFileSystem.reset(); 93 } 94 95 void CompilerInstance::setSourceManager(SourceManager *Value) { 96 SourceMgr = Value; 97 } 98 99 void CompilerInstance::setPreprocessor(Preprocessor *Value) { PP = Value; } 100 101 void CompilerInstance::setASTContext(ASTContext *Value) { 102 Context = Value; 103 104 if (Context && Consumer) 105 getASTConsumer().Initialize(getASTContext()); 106 } 107 108 void CompilerInstance::setSema(Sema *S) { 109 TheSema.reset(S); 110 } 111 112 void CompilerInstance::setASTConsumer(std::unique_ptr<ASTConsumer> Value) { 113 Consumer = std::move(Value); 114 115 if (Context && Consumer) 116 getASTConsumer().Initialize(getASTContext()); 117 } 118 119 void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) { 120 CompletionConsumer.reset(Value); 121 } 122 123 std::unique_ptr<Sema> CompilerInstance::takeSema() { 124 return std::move(TheSema); 125 } 126 127 IntrusiveRefCntPtr<ASTReader> CompilerInstance::getModuleManager() const { 128 return ModuleManager; 129 } 130 void CompilerInstance::setModuleManager(IntrusiveRefCntPtr<ASTReader> Reader) { 131 ModuleManager = std::move(Reader); 132 } 133 134 std::shared_ptr<ModuleDependencyCollector> 135 CompilerInstance::getModuleDepCollector() const { 136 return ModuleDepCollector; 137 } 138 139 void CompilerInstance::setModuleDepCollector( 140 std::shared_ptr<ModuleDependencyCollector> Collector) { 141 ModuleDepCollector = std::move(Collector); 142 } 143 144 static void collectHeaderMaps(const HeaderSearch &HS, 145 std::shared_ptr<ModuleDependencyCollector> MDC) { 146 SmallVector<std::string, 4> HeaderMapFileNames; 147 HS.getHeaderMapFileNames(HeaderMapFileNames); 148 for (auto &Name : HeaderMapFileNames) 149 MDC->addFile(Name); 150 } 151 152 static void collectIncludePCH(CompilerInstance &CI, 153 std::shared_ptr<ModuleDependencyCollector> MDC) { 154 const PreprocessorOptions &PPOpts = CI.getPreprocessorOpts(); 155 if (PPOpts.ImplicitPCHInclude.empty()) 156 return; 157 158 StringRef PCHInclude = PPOpts.ImplicitPCHInclude; 159 FileManager &FileMgr = CI.getFileManager(); 160 const DirectoryEntry *PCHDir = FileMgr.getDirectory(PCHInclude); 161 if (!PCHDir) { 162 MDC->addFile(PCHInclude); 163 return; 164 } 165 166 std::error_code EC; 167 SmallString<128> DirNative; 168 llvm::sys::path::native(PCHDir->getName(), DirNative); 169 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem(); 170 SimpleASTReaderListener Validator(CI.getPreprocessor()); 171 for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd; 172 Dir != DirEnd && !EC; Dir.increment(EC)) { 173 // Check whether this is an AST file. ASTReader::isAcceptableASTFile is not 174 // used here since we're not interested in validating the PCH at this time, 175 // but only to check whether this is a file containing an AST. 176 if (!ASTReader::readASTFileControlBlock( 177 Dir->getName(), FileMgr, CI.getPCHContainerReader(), 178 /*FindModuleFileExtensions=*/false, Validator, 179 /*ValidateDiagnosticOptions=*/false)) 180 MDC->addFile(Dir->getName()); 181 } 182 } 183 184 // Diagnostics 185 static void SetUpDiagnosticLog(DiagnosticOptions *DiagOpts, 186 const CodeGenOptions *CodeGenOpts, 187 DiagnosticsEngine &Diags) { 188 std::error_code EC; 189 std::unique_ptr<raw_ostream> StreamOwner; 190 raw_ostream *OS = &llvm::errs(); 191 if (DiagOpts->DiagnosticLogFile != "-") { 192 // Create the output stream. 193 auto FileOS = llvm::make_unique<llvm::raw_fd_ostream>( 194 DiagOpts->DiagnosticLogFile, EC, 195 llvm::sys::fs::F_Append | llvm::sys::fs::F_Text); 196 if (EC) { 197 Diags.Report(diag::warn_fe_cc_log_diagnostics_failure) 198 << DiagOpts->DiagnosticLogFile << EC.message(); 199 } else { 200 FileOS->SetUnbuffered(); 201 OS = FileOS.get(); 202 StreamOwner = std::move(FileOS); 203 } 204 } 205 206 // Chain in the diagnostic client which will log the diagnostics. 207 auto Logger = llvm::make_unique<LogDiagnosticPrinter>(*OS, DiagOpts, 208 std::move(StreamOwner)); 209 if (CodeGenOpts) 210 Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags); 211 assert(Diags.ownsClient()); 212 Diags.setClient( 213 new ChainedDiagnosticConsumer(Diags.takeClient(), std::move(Logger))); 214 } 215 216 static void SetupSerializedDiagnostics(DiagnosticOptions *DiagOpts, 217 DiagnosticsEngine &Diags, 218 StringRef OutputFile) { 219 auto SerializedConsumer = 220 clang::serialized_diags::create(OutputFile, DiagOpts); 221 222 if (Diags.ownsClient()) { 223 Diags.setClient(new ChainedDiagnosticConsumer( 224 Diags.takeClient(), std::move(SerializedConsumer))); 225 } else { 226 Diags.setClient(new ChainedDiagnosticConsumer( 227 Diags.getClient(), std::move(SerializedConsumer))); 228 } 229 } 230 231 void CompilerInstance::createDiagnostics(DiagnosticConsumer *Client, 232 bool ShouldOwnClient) { 233 Diagnostics = createDiagnostics(&getDiagnosticOpts(), Client, 234 ShouldOwnClient, &getCodeGenOpts()); 235 } 236 237 IntrusiveRefCntPtr<DiagnosticsEngine> 238 CompilerInstance::createDiagnostics(DiagnosticOptions *Opts, 239 DiagnosticConsumer *Client, 240 bool ShouldOwnClient, 241 const CodeGenOptions *CodeGenOpts) { 242 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs()); 243 IntrusiveRefCntPtr<DiagnosticsEngine> 244 Diags(new DiagnosticsEngine(DiagID, Opts)); 245 246 // Create the diagnostic client for reporting errors or for 247 // implementing -verify. 248 if (Client) { 249 Diags->setClient(Client, ShouldOwnClient); 250 } else 251 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts)); 252 253 // Chain in -verify checker, if requested. 254 if (Opts->VerifyDiagnostics) 255 Diags->setClient(new VerifyDiagnosticConsumer(*Diags)); 256 257 // Chain in -diagnostic-log-file dumper, if requested. 258 if (!Opts->DiagnosticLogFile.empty()) 259 SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags); 260 261 if (!Opts->DiagnosticSerializationFile.empty()) 262 SetupSerializedDiagnostics(Opts, *Diags, 263 Opts->DiagnosticSerializationFile); 264 265 // Configure our handling of diagnostics. 266 ProcessWarningOptions(*Diags, *Opts); 267 268 return Diags; 269 } 270 271 // File Manager 272 273 void CompilerInstance::createFileManager() { 274 if (!hasVirtualFileSystem()) { 275 // TODO: choose the virtual file system based on the CompilerInvocation. 276 setVirtualFileSystem(vfs::getRealFileSystem()); 277 } 278 FileMgr = new FileManager(getFileSystemOpts(), VirtualFileSystem); 279 } 280 281 // Source Manager 282 283 void CompilerInstance::createSourceManager(FileManager &FileMgr) { 284 SourceMgr = new SourceManager(getDiagnostics(), FileMgr); 285 } 286 287 // Initialize the remapping of files to alternative contents, e.g., 288 // those specified through other files. 289 static void InitializeFileRemapping(DiagnosticsEngine &Diags, 290 SourceManager &SourceMgr, 291 FileManager &FileMgr, 292 const PreprocessorOptions &InitOpts) { 293 // Remap files in the source manager (with buffers). 294 for (const auto &RB : InitOpts.RemappedFileBuffers) { 295 // Create the file entry for the file that we're mapping from. 296 const FileEntry *FromFile = 297 FileMgr.getVirtualFile(RB.first, RB.second->getBufferSize(), 0); 298 if (!FromFile) { 299 Diags.Report(diag::err_fe_remap_missing_from_file) << RB.first; 300 if (!InitOpts.RetainRemappedFileBuffers) 301 delete RB.second; 302 continue; 303 } 304 305 // Override the contents of the "from" file with the contents of 306 // the "to" file. 307 SourceMgr.overrideFileContents(FromFile, RB.second, 308 InitOpts.RetainRemappedFileBuffers); 309 } 310 311 // Remap files in the source manager (with other files). 312 for (const auto &RF : InitOpts.RemappedFiles) { 313 // Find the file that we're mapping to. 314 const FileEntry *ToFile = FileMgr.getFile(RF.second); 315 if (!ToFile) { 316 Diags.Report(diag::err_fe_remap_missing_to_file) << RF.first << RF.second; 317 continue; 318 } 319 320 // Create the file entry for the file that we're mapping from. 321 const FileEntry *FromFile = 322 FileMgr.getVirtualFile(RF.first, ToFile->getSize(), 0); 323 if (!FromFile) { 324 Diags.Report(diag::err_fe_remap_missing_from_file) << RF.first; 325 continue; 326 } 327 328 // Override the contents of the "from" file with the contents of 329 // the "to" file. 330 SourceMgr.overrideFileContents(FromFile, ToFile); 331 } 332 333 SourceMgr.setOverridenFilesKeepOriginalName( 334 InitOpts.RemappedFilesKeepOriginalName); 335 } 336 337 // Preprocessor 338 339 void CompilerInstance::createPreprocessor(TranslationUnitKind TUKind) { 340 const PreprocessorOptions &PPOpts = getPreprocessorOpts(); 341 342 // Create a PTH manager if we are using some form of a token cache. 343 PTHManager *PTHMgr = nullptr; 344 if (!PPOpts.TokenCache.empty()) 345 PTHMgr = PTHManager::Create(PPOpts.TokenCache, getDiagnostics()); 346 347 // Create the Preprocessor. 348 HeaderSearch *HeaderInfo = new HeaderSearch(&getHeaderSearchOpts(), 349 getSourceManager(), 350 getDiagnostics(), 351 getLangOpts(), 352 &getTarget()); 353 PP = new Preprocessor(&getPreprocessorOpts(), getDiagnostics(), getLangOpts(), 354 getSourceManager(), *HeaderInfo, *this, PTHMgr, 355 /*OwnsHeaderSearch=*/true, TUKind); 356 PP->Initialize(getTarget(), getAuxTarget()); 357 358 // Note that this is different then passing PTHMgr to Preprocessor's ctor. 359 // That argument is used as the IdentifierInfoLookup argument to 360 // IdentifierTable's ctor. 361 if (PTHMgr) { 362 PTHMgr->setPreprocessor(&*PP); 363 PP->setPTHManager(PTHMgr); 364 } 365 366 if (PPOpts.DetailedRecord) 367 PP->createPreprocessingRecord(); 368 369 // Apply remappings to the source manager. 370 InitializeFileRemapping(PP->getDiagnostics(), PP->getSourceManager(), 371 PP->getFileManager(), PPOpts); 372 373 // Predefine macros and configure the preprocessor. 374 InitializePreprocessor(*PP, PPOpts, getPCHContainerReader(), 375 getFrontendOpts()); 376 377 // Initialize the header search object. In CUDA compilations, we use the aux 378 // triple (the host triple) to initialize our header search, since we need to 379 // find the host headers in order to compile the CUDA code. 380 const llvm::Triple *HeaderSearchTriple = &PP->getTargetInfo().getTriple(); 381 if (PP->getTargetInfo().getTriple().getOS() == llvm::Triple::CUDA && 382 PP->getAuxTargetInfo()) 383 HeaderSearchTriple = &PP->getAuxTargetInfo()->getTriple(); 384 385 ApplyHeaderSearchOptions(PP->getHeaderSearchInfo(), getHeaderSearchOpts(), 386 PP->getLangOpts(), *HeaderSearchTriple); 387 388 PP->setPreprocessedOutput(getPreprocessorOutputOpts().ShowCPP); 389 390 if (PP->getLangOpts().Modules && PP->getLangOpts().ImplicitModules) 391 PP->getHeaderSearchInfo().setModuleCachePath(getSpecificModuleCachePath()); 392 393 // Handle generating dependencies, if requested. 394 const DependencyOutputOptions &DepOpts = getDependencyOutputOpts(); 395 if (!DepOpts.OutputFile.empty()) 396 TheDependencyFileGenerator.reset( 397 DependencyFileGenerator::CreateAndAttachToPreprocessor(*PP, DepOpts)); 398 if (!DepOpts.DOTOutputFile.empty()) 399 AttachDependencyGraphGen(*PP, DepOpts.DOTOutputFile, 400 getHeaderSearchOpts().Sysroot); 401 402 // If we don't have a collector, but we are collecting module dependencies, 403 // then we're the top level compiler instance and need to create one. 404 if (!ModuleDepCollector && !DepOpts.ModuleDependencyOutputDir.empty()) { 405 ModuleDepCollector = std::make_shared<ModuleDependencyCollector>( 406 DepOpts.ModuleDependencyOutputDir); 407 } 408 409 // If there is a module dep collector, register with other dep collectors 410 // and also (a) collect header maps and (b) TODO: input vfs overlay files. 411 if (ModuleDepCollector) { 412 addDependencyCollector(ModuleDepCollector); 413 collectHeaderMaps(PP->getHeaderSearchInfo(), ModuleDepCollector); 414 collectIncludePCH(*this, ModuleDepCollector); 415 } 416 417 for (auto &Listener : DependencyCollectors) 418 Listener->attachToPreprocessor(*PP); 419 420 // Handle generating header include information, if requested. 421 if (DepOpts.ShowHeaderIncludes) 422 AttachHeaderIncludeGen(*PP, DepOpts); 423 if (!DepOpts.HeaderIncludeOutputFile.empty()) { 424 StringRef OutputPath = DepOpts.HeaderIncludeOutputFile; 425 if (OutputPath == "-") 426 OutputPath = ""; 427 AttachHeaderIncludeGen(*PP, DepOpts, 428 /*ShowAllHeaders=*/true, OutputPath, 429 /*ShowDepth=*/false); 430 } 431 432 if (DepOpts.PrintShowIncludes) { 433 AttachHeaderIncludeGen(*PP, DepOpts, 434 /*ShowAllHeaders=*/true, /*OutputPath=*/"", 435 /*ShowDepth=*/true, /*MSStyle=*/true); 436 } 437 } 438 439 std::string CompilerInstance::getSpecificModuleCachePath() { 440 // Set up the module path, including the hash for the 441 // module-creation options. 442 SmallString<256> SpecificModuleCache(getHeaderSearchOpts().ModuleCachePath); 443 if (!SpecificModuleCache.empty() && !getHeaderSearchOpts().DisableModuleHash) 444 llvm::sys::path::append(SpecificModuleCache, 445 getInvocation().getModuleHash()); 446 return SpecificModuleCache.str(); 447 } 448 449 // ASTContext 450 451 void CompilerInstance::createASTContext() { 452 Preprocessor &PP = getPreprocessor(); 453 auto *Context = new ASTContext(getLangOpts(), PP.getSourceManager(), 454 PP.getIdentifierTable(), PP.getSelectorTable(), 455 PP.getBuiltinInfo()); 456 Context->InitBuiltinTypes(getTarget(), getAuxTarget()); 457 setASTContext(Context); 458 } 459 460 // ExternalASTSource 461 462 void CompilerInstance::createPCHExternalASTSource( 463 StringRef Path, bool DisablePCHValidation, bool AllowPCHWithCompilerErrors, 464 void *DeserializationListener, bool OwnDeserializationListener) { 465 bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0; 466 ModuleManager = createPCHExternalASTSource( 467 Path, getHeaderSearchOpts().Sysroot, DisablePCHValidation, 468 AllowPCHWithCompilerErrors, getPreprocessor(), getASTContext(), 469 getPCHContainerReader(), 470 getFrontendOpts().ModuleFileExtensions, 471 DeserializationListener, 472 OwnDeserializationListener, Preamble, 473 getFrontendOpts().UseGlobalModuleIndex); 474 } 475 476 IntrusiveRefCntPtr<ASTReader> CompilerInstance::createPCHExternalASTSource( 477 StringRef Path, StringRef Sysroot, bool DisablePCHValidation, 478 bool AllowPCHWithCompilerErrors, Preprocessor &PP, ASTContext &Context, 479 const PCHContainerReader &PCHContainerRdr, 480 ArrayRef<IntrusiveRefCntPtr<ModuleFileExtension>> Extensions, 481 void *DeserializationListener, bool OwnDeserializationListener, 482 bool Preamble, bool UseGlobalModuleIndex) { 483 HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts(); 484 485 IntrusiveRefCntPtr<ASTReader> Reader(new ASTReader( 486 PP, Context, PCHContainerRdr, Extensions, 487 Sysroot.empty() ? "" : Sysroot.data(), DisablePCHValidation, 488 AllowPCHWithCompilerErrors, /*AllowConfigurationMismatch*/ false, 489 HSOpts.ModulesValidateSystemHeaders, UseGlobalModuleIndex)); 490 491 // We need the external source to be set up before we read the AST, because 492 // eagerly-deserialized declarations may use it. 493 Context.setExternalSource(Reader.get()); 494 495 Reader->setDeserializationListener( 496 static_cast<ASTDeserializationListener *>(DeserializationListener), 497 /*TakeOwnership=*/OwnDeserializationListener); 498 switch (Reader->ReadAST(Path, 499 Preamble ? serialization::MK_Preamble 500 : serialization::MK_PCH, 501 SourceLocation(), 502 ASTReader::ARR_None)) { 503 case ASTReader::Success: 504 // Set the predefines buffer as suggested by the PCH reader. Typically, the 505 // predefines buffer will be empty. 506 PP.setPredefines(Reader->getSuggestedPredefines()); 507 return Reader; 508 509 case ASTReader::Failure: 510 // Unrecoverable failure: don't even try to process the input file. 511 break; 512 513 case ASTReader::Missing: 514 case ASTReader::OutOfDate: 515 case ASTReader::VersionMismatch: 516 case ASTReader::ConfigurationMismatch: 517 case ASTReader::HadErrors: 518 // No suitable PCH file could be found. Return an error. 519 break; 520 } 521 522 Context.setExternalSource(nullptr); 523 return nullptr; 524 } 525 526 // Code Completion 527 528 static bool EnableCodeCompletion(Preprocessor &PP, 529 StringRef Filename, 530 unsigned Line, 531 unsigned Column) { 532 // Tell the source manager to chop off the given file at a specific 533 // line and column. 534 const FileEntry *Entry = PP.getFileManager().getFile(Filename); 535 if (!Entry) { 536 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file) 537 << Filename; 538 return true; 539 } 540 541 // Truncate the named file at the given line/column. 542 PP.SetCodeCompletionPoint(Entry, Line, Column); 543 return false; 544 } 545 546 void CompilerInstance::createCodeCompletionConsumer() { 547 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt; 548 if (!CompletionConsumer) { 549 setCodeCompletionConsumer( 550 createCodeCompletionConsumer(getPreprocessor(), 551 Loc.FileName, Loc.Line, Loc.Column, 552 getFrontendOpts().CodeCompleteOpts, 553 llvm::outs())); 554 if (!CompletionConsumer) 555 return; 556 } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName, 557 Loc.Line, Loc.Column)) { 558 setCodeCompletionConsumer(nullptr); 559 return; 560 } 561 562 if (CompletionConsumer->isOutputBinary() && 563 llvm::sys::ChangeStdoutToBinary()) { 564 getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary); 565 setCodeCompletionConsumer(nullptr); 566 } 567 } 568 569 void CompilerInstance::createFrontendTimer() { 570 FrontendTimerGroup.reset( 571 new llvm::TimerGroup("frontend", "Clang front-end time report")); 572 FrontendTimer.reset( 573 new llvm::Timer("frontend", "Clang front-end timer", 574 *FrontendTimerGroup)); 575 } 576 577 CodeCompleteConsumer * 578 CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP, 579 StringRef Filename, 580 unsigned Line, 581 unsigned Column, 582 const CodeCompleteOptions &Opts, 583 raw_ostream &OS) { 584 if (EnableCodeCompletion(PP, Filename, Line, Column)) 585 return nullptr; 586 587 // Set up the creation routine for code-completion. 588 return new PrintingCodeCompleteConsumer(Opts, OS); 589 } 590 591 void CompilerInstance::createSema(TranslationUnitKind TUKind, 592 CodeCompleteConsumer *CompletionConsumer) { 593 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(), 594 TUKind, CompletionConsumer)); 595 // Attach the external sema source if there is any. 596 if (ExternalSemaSrc) { 597 TheSema->addExternalSource(ExternalSemaSrc.get()); 598 ExternalSemaSrc->InitializeSema(*TheSema); 599 } 600 } 601 602 // Output Files 603 604 void CompilerInstance::addOutputFile(OutputFile &&OutFile) { 605 OutputFiles.push_back(std::move(OutFile)); 606 } 607 608 void CompilerInstance::clearOutputFiles(bool EraseFiles) { 609 for (OutputFile &OF : OutputFiles) { 610 if (!OF.TempFilename.empty()) { 611 if (EraseFiles) { 612 llvm::sys::fs::remove(OF.TempFilename); 613 } else { 614 SmallString<128> NewOutFile(OF.Filename); 615 616 // If '-working-directory' was passed, the output filename should be 617 // relative to that. 618 FileMgr->FixupRelativePath(NewOutFile); 619 if (std::error_code ec = 620 llvm::sys::fs::rename(OF.TempFilename, NewOutFile)) { 621 getDiagnostics().Report(diag::err_unable_to_rename_temp) 622 << OF.TempFilename << OF.Filename << ec.message(); 623 624 llvm::sys::fs::remove(OF.TempFilename); 625 } 626 } 627 } else if (!OF.Filename.empty() && EraseFiles) 628 llvm::sys::fs::remove(OF.Filename); 629 } 630 OutputFiles.clear(); 631 NonSeekStream.reset(); 632 } 633 634 std::unique_ptr<raw_pwrite_stream> 635 CompilerInstance::createDefaultOutputFile(bool Binary, StringRef InFile, 636 StringRef Extension) { 637 return createOutputFile(getFrontendOpts().OutputFile, Binary, 638 /*RemoveFileOnSignal=*/true, InFile, Extension, 639 /*UseTemporary=*/true); 640 } 641 642 std::unique_ptr<raw_pwrite_stream> CompilerInstance::createNullOutputFile() { 643 return llvm::make_unique<llvm::raw_null_ostream>(); 644 } 645 646 std::unique_ptr<raw_pwrite_stream> 647 CompilerInstance::createOutputFile(StringRef OutputPath, bool Binary, 648 bool RemoveFileOnSignal, StringRef InFile, 649 StringRef Extension, bool UseTemporary, 650 bool CreateMissingDirectories) { 651 std::string OutputPathName, TempPathName; 652 std::error_code EC; 653 std::unique_ptr<raw_pwrite_stream> OS = createOutputFile( 654 OutputPath, EC, Binary, RemoveFileOnSignal, InFile, Extension, 655 UseTemporary, CreateMissingDirectories, &OutputPathName, &TempPathName); 656 if (!OS) { 657 getDiagnostics().Report(diag::err_fe_unable_to_open_output) << OutputPath 658 << EC.message(); 659 return nullptr; 660 } 661 662 // Add the output file -- but don't try to remove "-", since this means we are 663 // using stdin. 664 addOutputFile( 665 OutputFile((OutputPathName != "-") ? OutputPathName : "", TempPathName)); 666 667 return OS; 668 } 669 670 std::unique_ptr<llvm::raw_pwrite_stream> CompilerInstance::createOutputFile( 671 StringRef OutputPath, std::error_code &Error, bool Binary, 672 bool RemoveFileOnSignal, StringRef InFile, StringRef Extension, 673 bool UseTemporary, bool CreateMissingDirectories, 674 std::string *ResultPathName, std::string *TempPathName) { 675 assert((!CreateMissingDirectories || UseTemporary) && 676 "CreateMissingDirectories is only allowed when using temporary files"); 677 678 std::string OutFile, TempFile; 679 if (!OutputPath.empty()) { 680 OutFile = OutputPath; 681 } else if (InFile == "-") { 682 OutFile = "-"; 683 } else if (!Extension.empty()) { 684 SmallString<128> Path(InFile); 685 llvm::sys::path::replace_extension(Path, Extension); 686 OutFile = Path.str(); 687 } else { 688 OutFile = "-"; 689 } 690 691 std::unique_ptr<llvm::raw_fd_ostream> OS; 692 std::string OSFile; 693 694 if (UseTemporary) { 695 if (OutFile == "-") 696 UseTemporary = false; 697 else { 698 llvm::sys::fs::file_status Status; 699 llvm::sys::fs::status(OutputPath, Status); 700 if (llvm::sys::fs::exists(Status)) { 701 // Fail early if we can't write to the final destination. 702 if (!llvm::sys::fs::can_write(OutputPath)) { 703 Error = make_error_code(llvm::errc::operation_not_permitted); 704 return nullptr; 705 } 706 707 // Don't use a temporary if the output is a special file. This handles 708 // things like '-o /dev/null' 709 if (!llvm::sys::fs::is_regular_file(Status)) 710 UseTemporary = false; 711 } 712 } 713 } 714 715 if (UseTemporary) { 716 // Create a temporary file. 717 SmallString<128> TempPath; 718 TempPath = OutFile; 719 TempPath += "-%%%%%%%%"; 720 int fd; 721 std::error_code EC = 722 llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath); 723 724 if (CreateMissingDirectories && 725 EC == llvm::errc::no_such_file_or_directory) { 726 StringRef Parent = llvm::sys::path::parent_path(OutputPath); 727 EC = llvm::sys::fs::create_directories(Parent); 728 if (!EC) { 729 EC = llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath); 730 } 731 } 732 733 if (!EC) { 734 OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true)); 735 OSFile = TempFile = TempPath.str(); 736 } 737 // If we failed to create the temporary, fallback to writing to the file 738 // directly. This handles the corner case where we cannot write to the 739 // directory, but can write to the file. 740 } 741 742 if (!OS) { 743 OSFile = OutFile; 744 OS.reset(new llvm::raw_fd_ostream( 745 OSFile, Error, 746 (Binary ? llvm::sys::fs::F_None : llvm::sys::fs::F_Text))); 747 if (Error) 748 return nullptr; 749 } 750 751 // Make sure the out stream file gets removed if we crash. 752 if (RemoveFileOnSignal) 753 llvm::sys::RemoveFileOnSignal(OSFile); 754 755 if (ResultPathName) 756 *ResultPathName = OutFile; 757 if (TempPathName) 758 *TempPathName = TempFile; 759 760 if (!Binary || OS->supportsSeeking()) 761 return std::move(OS); 762 763 auto B = llvm::make_unique<llvm::buffer_ostream>(*OS); 764 assert(!NonSeekStream); 765 NonSeekStream = std::move(OS); 766 return std::move(B); 767 } 768 769 // Initialization Utilities 770 771 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input){ 772 return InitializeSourceManager( 773 Input, getDiagnostics(), getFileManager(), getSourceManager(), 774 hasPreprocessor() ? &getPreprocessor().getHeaderSearchInfo() : nullptr, 775 getDependencyOutputOpts(), getFrontendOpts()); 776 } 777 778 // static 779 bool CompilerInstance::InitializeSourceManager( 780 const FrontendInputFile &Input, DiagnosticsEngine &Diags, 781 FileManager &FileMgr, SourceManager &SourceMgr, HeaderSearch *HS, 782 DependencyOutputOptions &DepOpts, const FrontendOptions &Opts) { 783 SrcMgr::CharacteristicKind 784 Kind = Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User; 785 786 if (Input.isBuffer()) { 787 SourceMgr.setMainFileID(SourceMgr.createFileID( 788 std::unique_ptr<llvm::MemoryBuffer>(Input.getBuffer()), Kind)); 789 assert(SourceMgr.getMainFileID().isValid() && 790 "Couldn't establish MainFileID!"); 791 return true; 792 } 793 794 StringRef InputFile = Input.getFile(); 795 796 // Figure out where to get and map in the main file. 797 if (InputFile != "-") { 798 const FileEntry *File; 799 if (Opts.FindPchSource.empty()) { 800 File = FileMgr.getFile(InputFile, /*OpenFile=*/true); 801 } else { 802 // When building a pch file in clang-cl mode, the .h file is built as if 803 // it was included by a cc file. Since the driver doesn't know about 804 // all include search directories, the frontend must search the input 805 // file through HeaderSearch here, as if it had been included by the 806 // cc file at Opts.FindPchSource. 807 const FileEntry *FindFile = FileMgr.getFile(Opts.FindPchSource); 808 if (!FindFile) { 809 Diags.Report(diag::err_fe_error_reading) << Opts.FindPchSource; 810 return false; 811 } 812 const DirectoryLookup *UnusedCurDir; 813 SmallVector<std::pair<const FileEntry *, const DirectoryEntry *>, 16> 814 Includers; 815 Includers.push_back(std::make_pair(FindFile, FindFile->getDir())); 816 File = HS->LookupFile(InputFile, SourceLocation(), /*isAngled=*/false, 817 /*FromDir=*/nullptr, 818 /*CurDir=*/UnusedCurDir, Includers, 819 /*SearchPath=*/nullptr, 820 /*RelativePath=*/nullptr, 821 /*RequestingModule=*/nullptr, 822 /*SuggestedModule=*/nullptr, /*SkipCache=*/true); 823 // Also add the header to /showIncludes output. 824 if (File) 825 DepOpts.ShowIncludesPretendHeader = File->getName(); 826 } 827 if (!File) { 828 Diags.Report(diag::err_fe_error_reading) << InputFile; 829 return false; 830 } 831 832 // The natural SourceManager infrastructure can't currently handle named 833 // pipes, but we would at least like to accept them for the main 834 // file. Detect them here, read them with the volatile flag so FileMgr will 835 // pick up the correct size, and simply override their contents as we do for 836 // STDIN. 837 if (File->isNamedPipe()) { 838 auto MB = FileMgr.getBufferForFile(File, /*isVolatile=*/true); 839 if (MB) { 840 // Create a new virtual file that will have the correct size. 841 File = FileMgr.getVirtualFile(InputFile, (*MB)->getBufferSize(), 0); 842 SourceMgr.overrideFileContents(File, std::move(*MB)); 843 } else { 844 Diags.Report(diag::err_cannot_open_file) << InputFile 845 << MB.getError().message(); 846 return false; 847 } 848 } 849 850 SourceMgr.setMainFileID( 851 SourceMgr.createFileID(File, SourceLocation(), Kind)); 852 } else { 853 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> SBOrErr = 854 llvm::MemoryBuffer::getSTDIN(); 855 if (std::error_code EC = SBOrErr.getError()) { 856 Diags.Report(diag::err_fe_error_reading_stdin) << EC.message(); 857 return false; 858 } 859 std::unique_ptr<llvm::MemoryBuffer> SB = std::move(SBOrErr.get()); 860 861 const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(), 862 SB->getBufferSize(), 0); 863 SourceMgr.setMainFileID( 864 SourceMgr.createFileID(File, SourceLocation(), Kind)); 865 SourceMgr.overrideFileContents(File, std::move(SB)); 866 } 867 868 assert(SourceMgr.getMainFileID().isValid() && 869 "Couldn't establish MainFileID!"); 870 return true; 871 } 872 873 // High-Level Operations 874 875 bool CompilerInstance::ExecuteAction(FrontendAction &Act) { 876 assert(hasDiagnostics() && "Diagnostics engine is not initialized!"); 877 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!"); 878 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!"); 879 880 // FIXME: Take this as an argument, once all the APIs we used have moved to 881 // taking it as an input instead of hard-coding llvm::errs. 882 raw_ostream &OS = llvm::errs(); 883 884 // Create the target instance. 885 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), 886 getInvocation().TargetOpts)); 887 if (!hasTarget()) 888 return false; 889 890 // Create TargetInfo for the other side of CUDA compilation. 891 if (getLangOpts().CUDA && !getFrontendOpts().AuxTriple.empty()) { 892 auto TO = std::make_shared<TargetOptions>(); 893 TO->Triple = getFrontendOpts().AuxTriple; 894 TO->HostTriple = getTarget().getTriple().str(); 895 setAuxTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), TO)); 896 } 897 898 // Inform the target of the language options. 899 // 900 // FIXME: We shouldn't need to do this, the target should be immutable once 901 // created. This complexity should be lifted elsewhere. 902 getTarget().adjust(getLangOpts()); 903 904 // Adjust target options based on codegen options. 905 getTarget().adjustTargetOptions(getCodeGenOpts(), getTargetOpts()); 906 907 // rewriter project will change target built-in bool type from its default. 908 if (getFrontendOpts().ProgramAction == frontend::RewriteObjC) 909 getTarget().noSignedCharForObjCBool(); 910 911 // Validate/process some options. 912 if (getHeaderSearchOpts().Verbose) 913 OS << "clang -cc1 version " CLANG_VERSION_STRING 914 << " based upon " << BACKEND_PACKAGE_STRING 915 << " default target " << llvm::sys::getDefaultTargetTriple() << "\n"; 916 917 if (getFrontendOpts().ShowTimers) 918 createFrontendTimer(); 919 920 if (getFrontendOpts().ShowStats || !getFrontendOpts().StatsFile.empty()) 921 llvm::EnableStatistics(false); 922 923 for (const FrontendInputFile &FIF : getFrontendOpts().Inputs) { 924 // Reset the ID tables if we are reusing the SourceManager and parsing 925 // regular files. 926 if (hasSourceManager() && !Act.isModelParsingAction()) 927 getSourceManager().clearIDTables(); 928 929 if (Act.BeginSourceFile(*this, FIF)) { 930 Act.Execute(); 931 Act.EndSourceFile(); 932 } 933 } 934 935 // Notify the diagnostic client that all files were processed. 936 getDiagnostics().getClient()->finish(); 937 938 if (getDiagnosticOpts().ShowCarets) { 939 // We can have multiple diagnostics sharing one diagnostic client. 940 // Get the total number of warnings/errors from the client. 941 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings(); 942 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors(); 943 944 if (NumWarnings) 945 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s"); 946 if (NumWarnings && NumErrors) 947 OS << " and "; 948 if (NumErrors) 949 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s"); 950 if (NumWarnings || NumErrors) 951 OS << " generated.\n"; 952 } 953 954 if (getFrontendOpts().ShowStats) { 955 if (hasFileManager()) { 956 getFileManager().PrintStats(); 957 OS << '\n'; 958 } 959 llvm::PrintStatistics(OS); 960 } 961 StringRef StatsFile = getFrontendOpts().StatsFile; 962 if (!StatsFile.empty()) { 963 std::error_code EC; 964 auto StatS = llvm::make_unique<llvm::raw_fd_ostream>(StatsFile, EC, 965 llvm::sys::fs::F_Text); 966 if (EC) { 967 getDiagnostics().Report(diag::warn_fe_unable_to_open_stats_file) 968 << StatsFile << EC.message(); 969 } else { 970 llvm::PrintStatisticsJSON(*StatS); 971 } 972 } 973 974 return !getDiagnostics().getClient()->getNumErrors(); 975 } 976 977 /// \brief Determine the appropriate source input kind based on language 978 /// options. 979 static InputKind getSourceInputKindFromOptions(const LangOptions &LangOpts) { 980 if (LangOpts.OpenCL) 981 return IK_OpenCL; 982 if (LangOpts.CUDA) 983 return IK_CUDA; 984 if (LangOpts.ObjC1) 985 return LangOpts.CPlusPlus? IK_ObjCXX : IK_ObjC; 986 return LangOpts.CPlusPlus? IK_CXX : IK_C; 987 } 988 989 /// \brief Compile a module file for the given module, using the options 990 /// provided by the importing compiler instance. Returns true if the module 991 /// was built without errors. 992 static bool compileModuleImpl(CompilerInstance &ImportingInstance, 993 SourceLocation ImportLoc, 994 Module *Module, 995 StringRef ModuleFileName) { 996 ModuleMap &ModMap 997 = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap(); 998 999 // Construct a compiler invocation for creating this module. 1000 IntrusiveRefCntPtr<CompilerInvocation> Invocation 1001 (new CompilerInvocation(ImportingInstance.getInvocation())); 1002 1003 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts(); 1004 1005 // For any options that aren't intended to affect how a module is built, 1006 // reset them to their default values. 1007 Invocation->getLangOpts()->resetNonModularOptions(); 1008 PPOpts.resetNonModularOptions(); 1009 1010 // Remove any macro definitions that are explicitly ignored by the module. 1011 // They aren't supposed to affect how the module is built anyway. 1012 const HeaderSearchOptions &HSOpts = Invocation->getHeaderSearchOpts(); 1013 PPOpts.Macros.erase( 1014 std::remove_if(PPOpts.Macros.begin(), PPOpts.Macros.end(), 1015 [&HSOpts](const std::pair<std::string, bool> &def) { 1016 StringRef MacroDef = def.first; 1017 return HSOpts.ModulesIgnoreMacros.count( 1018 llvm::CachedHashString(MacroDef.split('=').first)) > 0; 1019 }), 1020 PPOpts.Macros.end()); 1021 1022 // Note the name of the module we're building. 1023 Invocation->getLangOpts()->CurrentModule = Module->getTopLevelModuleName(); 1024 1025 // Make sure that the failed-module structure has been allocated in 1026 // the importing instance, and propagate the pointer to the newly-created 1027 // instance. 1028 PreprocessorOptions &ImportingPPOpts 1029 = ImportingInstance.getInvocation().getPreprocessorOpts(); 1030 if (!ImportingPPOpts.FailedModules) 1031 ImportingPPOpts.FailedModules = new PreprocessorOptions::FailedModulesSet; 1032 PPOpts.FailedModules = ImportingPPOpts.FailedModules; 1033 1034 // If there is a module map file, build the module using the module map. 1035 // Set up the inputs/outputs so that we build the module from its umbrella 1036 // header. 1037 FrontendOptions &FrontendOpts = Invocation->getFrontendOpts(); 1038 FrontendOpts.OutputFile = ModuleFileName.str(); 1039 FrontendOpts.DisableFree = false; 1040 FrontendOpts.GenerateGlobalModuleIndex = false; 1041 FrontendOpts.BuildingImplicitModule = true; 1042 FrontendOpts.Inputs.clear(); 1043 InputKind IK = getSourceInputKindFromOptions(*Invocation->getLangOpts()); 1044 1045 // Don't free the remapped file buffers; they are owned by our caller. 1046 PPOpts.RetainRemappedFileBuffers = true; 1047 1048 Invocation->getDiagnosticOpts().VerifyDiagnostics = 0; 1049 assert(ImportingInstance.getInvocation().getModuleHash() == 1050 Invocation->getModuleHash() && "Module hash mismatch!"); 1051 1052 // Construct a compiler instance that will be used to actually create the 1053 // module. 1054 CompilerInstance Instance(ImportingInstance.getPCHContainerOperations(), 1055 /*BuildingModule=*/true); 1056 Instance.setInvocation(&*Invocation); 1057 1058 Instance.createDiagnostics(new ForwardingDiagnosticConsumer( 1059 ImportingInstance.getDiagnosticClient()), 1060 /*ShouldOwnClient=*/true); 1061 1062 Instance.setVirtualFileSystem(&ImportingInstance.getVirtualFileSystem()); 1063 1064 // Note that this module is part of the module build stack, so that we 1065 // can detect cycles in the module graph. 1066 Instance.setFileManager(&ImportingInstance.getFileManager()); 1067 Instance.createSourceManager(Instance.getFileManager()); 1068 SourceManager &SourceMgr = Instance.getSourceManager(); 1069 SourceMgr.setModuleBuildStack( 1070 ImportingInstance.getSourceManager().getModuleBuildStack()); 1071 SourceMgr.pushModuleBuildStack(Module->getTopLevelModuleName(), 1072 FullSourceLoc(ImportLoc, ImportingInstance.getSourceManager())); 1073 1074 // If we're collecting module dependencies, we need to share a collector 1075 // between all of the module CompilerInstances. Other than that, we don't 1076 // want to produce any dependency output from the module build. 1077 Instance.setModuleDepCollector(ImportingInstance.getModuleDepCollector()); 1078 Invocation->getDependencyOutputOpts() = DependencyOutputOptions(); 1079 1080 // Get or create the module map that we'll use to build this module. 1081 std::string InferredModuleMapContent; 1082 if (const FileEntry *ModuleMapFile = 1083 ModMap.getContainingModuleMapFile(Module)) { 1084 // Use the module map where this module resides. 1085 FrontendOpts.Inputs.emplace_back(ModuleMapFile->getName(), IK); 1086 } else { 1087 SmallString<128> FakeModuleMapFile(Module->Directory->getName()); 1088 llvm::sys::path::append(FakeModuleMapFile, "__inferred_module.map"); 1089 FrontendOpts.Inputs.emplace_back(FakeModuleMapFile, IK); 1090 1091 llvm::raw_string_ostream OS(InferredModuleMapContent); 1092 Module->print(OS); 1093 OS.flush(); 1094 1095 std::unique_ptr<llvm::MemoryBuffer> ModuleMapBuffer = 1096 llvm::MemoryBuffer::getMemBuffer(InferredModuleMapContent); 1097 ModuleMapFile = Instance.getFileManager().getVirtualFile( 1098 FakeModuleMapFile, InferredModuleMapContent.size(), 0); 1099 SourceMgr.overrideFileContents(ModuleMapFile, std::move(ModuleMapBuffer)); 1100 } 1101 1102 // Construct a module-generating action. Passing through the module map is 1103 // safe because the FileManager is shared between the compiler instances. 1104 GenerateModuleFromModuleMapAction CreateModuleAction( 1105 ModMap.getModuleMapFileForUniquing(Module), Module->IsSystem); 1106 1107 ImportingInstance.getDiagnostics().Report(ImportLoc, 1108 diag::remark_module_build) 1109 << Module->Name << ModuleFileName; 1110 1111 // Execute the action to actually build the module in-place. Use a separate 1112 // thread so that we get a stack large enough. 1113 const unsigned ThreadStackSize = 8 << 20; 1114 llvm::CrashRecoveryContext CRC; 1115 CRC.RunSafelyOnThread([&]() { Instance.ExecuteAction(CreateModuleAction); }, 1116 ThreadStackSize); 1117 1118 ImportingInstance.getDiagnostics().Report(ImportLoc, 1119 diag::remark_module_build_done) 1120 << Module->Name; 1121 1122 // Delete the temporary module map file. 1123 // FIXME: Even though we're executing under crash protection, it would still 1124 // be nice to do this with RemoveFileOnSignal when we can. However, that 1125 // doesn't make sense for all clients, so clean this up manually. 1126 Instance.clearOutputFiles(/*EraseFiles=*/true); 1127 1128 // We've rebuilt a module. If we're allowed to generate or update the global 1129 // module index, record that fact in the importing compiler instance. 1130 if (ImportingInstance.getFrontendOpts().GenerateGlobalModuleIndex) { 1131 ImportingInstance.setBuildGlobalModuleIndex(true); 1132 } 1133 1134 return !Instance.getDiagnostics().hasErrorOccurred(); 1135 } 1136 1137 static bool compileAndLoadModule(CompilerInstance &ImportingInstance, 1138 SourceLocation ImportLoc, 1139 SourceLocation ModuleNameLoc, Module *Module, 1140 StringRef ModuleFileName) { 1141 DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics(); 1142 1143 auto diagnoseBuildFailure = [&] { 1144 Diags.Report(ModuleNameLoc, diag::err_module_not_built) 1145 << Module->Name << SourceRange(ImportLoc, ModuleNameLoc); 1146 }; 1147 1148 // FIXME: have LockFileManager return an error_code so that we can 1149 // avoid the mkdir when the directory already exists. 1150 StringRef Dir = llvm::sys::path::parent_path(ModuleFileName); 1151 llvm::sys::fs::create_directories(Dir); 1152 1153 while (1) { 1154 unsigned ModuleLoadCapabilities = ASTReader::ARR_Missing; 1155 llvm::LockFileManager Locked(ModuleFileName); 1156 switch (Locked) { 1157 case llvm::LockFileManager::LFS_Error: 1158 Diags.Report(ModuleNameLoc, diag::err_module_lock_failure) 1159 << Module->Name << Locked.getErrorMessage(); 1160 return false; 1161 1162 case llvm::LockFileManager::LFS_Owned: 1163 // We're responsible for building the module ourselves. 1164 if (!compileModuleImpl(ImportingInstance, ModuleNameLoc, Module, 1165 ModuleFileName)) { 1166 diagnoseBuildFailure(); 1167 return false; 1168 } 1169 break; 1170 1171 case llvm::LockFileManager::LFS_Shared: 1172 // Someone else is responsible for building the module. Wait for them to 1173 // finish. 1174 switch (Locked.waitForUnlock()) { 1175 case llvm::LockFileManager::Res_Success: 1176 ModuleLoadCapabilities |= ASTReader::ARR_OutOfDate; 1177 break; 1178 case llvm::LockFileManager::Res_OwnerDied: 1179 continue; // try again to get the lock. 1180 case llvm::LockFileManager::Res_Timeout: 1181 Diags.Report(ModuleNameLoc, diag::err_module_lock_timeout) 1182 << Module->Name; 1183 // Clear the lock file so that future invokations can make progress. 1184 Locked.unsafeRemoveLockFile(); 1185 return false; 1186 } 1187 break; 1188 } 1189 1190 // Try to read the module file, now that we've compiled it. 1191 ASTReader::ASTReadResult ReadResult = 1192 ImportingInstance.getModuleManager()->ReadAST( 1193 ModuleFileName, serialization::MK_ImplicitModule, ImportLoc, 1194 ModuleLoadCapabilities); 1195 1196 if (ReadResult == ASTReader::OutOfDate && 1197 Locked == llvm::LockFileManager::LFS_Shared) { 1198 // The module may be out of date in the presence of file system races, 1199 // or if one of its imports depends on header search paths that are not 1200 // consistent with this ImportingInstance. Try again... 1201 continue; 1202 } else if (ReadResult == ASTReader::Missing) { 1203 diagnoseBuildFailure(); 1204 } else if (ReadResult != ASTReader::Success && 1205 !Diags.hasErrorOccurred()) { 1206 // The ASTReader didn't diagnose the error, so conservatively report it. 1207 diagnoseBuildFailure(); 1208 } 1209 return ReadResult == ASTReader::Success; 1210 } 1211 } 1212 1213 /// \brief Diagnose differences between the current definition of the given 1214 /// configuration macro and the definition provided on the command line. 1215 static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro, 1216 Module *Mod, SourceLocation ImportLoc) { 1217 IdentifierInfo *Id = PP.getIdentifierInfo(ConfigMacro); 1218 SourceManager &SourceMgr = PP.getSourceManager(); 1219 1220 // If this identifier has never had a macro definition, then it could 1221 // not have changed. 1222 if (!Id->hadMacroDefinition()) 1223 return; 1224 auto *LatestLocalMD = PP.getLocalMacroDirectiveHistory(Id); 1225 1226 // Find the macro definition from the command line. 1227 MacroInfo *CmdLineDefinition = nullptr; 1228 for (auto *MD = LatestLocalMD; MD; MD = MD->getPrevious()) { 1229 // We only care about the predefines buffer. 1230 FileID FID = SourceMgr.getFileID(MD->getLocation()); 1231 if (FID.isInvalid() || FID != PP.getPredefinesFileID()) 1232 continue; 1233 if (auto *DMD = dyn_cast<DefMacroDirective>(MD)) 1234 CmdLineDefinition = DMD->getMacroInfo(); 1235 break; 1236 } 1237 1238 auto *CurrentDefinition = PP.getMacroInfo(Id); 1239 if (CurrentDefinition == CmdLineDefinition) { 1240 // Macro matches. Nothing to do. 1241 } else if (!CurrentDefinition) { 1242 // This macro was defined on the command line, then #undef'd later. 1243 // Complain. 1244 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef) 1245 << true << ConfigMacro << Mod->getFullModuleName(); 1246 auto LatestDef = LatestLocalMD->getDefinition(); 1247 assert(LatestDef.isUndefined() && 1248 "predefined macro went away with no #undef?"); 1249 PP.Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here) 1250 << true; 1251 return; 1252 } else if (!CmdLineDefinition) { 1253 // There was no definition for this macro in the predefines buffer, 1254 // but there was a local definition. Complain. 1255 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef) 1256 << false << ConfigMacro << Mod->getFullModuleName(); 1257 PP.Diag(CurrentDefinition->getDefinitionLoc(), 1258 diag::note_module_def_undef_here) 1259 << false; 1260 } else if (!CurrentDefinition->isIdenticalTo(*CmdLineDefinition, PP, 1261 /*Syntactically=*/true)) { 1262 // The macro definitions differ. 1263 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef) 1264 << false << ConfigMacro << Mod->getFullModuleName(); 1265 PP.Diag(CurrentDefinition->getDefinitionLoc(), 1266 diag::note_module_def_undef_here) 1267 << false; 1268 } 1269 } 1270 1271 /// \brief Write a new timestamp file with the given path. 1272 static void writeTimestampFile(StringRef TimestampFile) { 1273 std::error_code EC; 1274 llvm::raw_fd_ostream Out(TimestampFile.str(), EC, llvm::sys::fs::F_None); 1275 } 1276 1277 /// \brief Prune the module cache of modules that haven't been accessed in 1278 /// a long time. 1279 static void pruneModuleCache(const HeaderSearchOptions &HSOpts) { 1280 struct stat StatBuf; 1281 llvm::SmallString<128> TimestampFile; 1282 TimestampFile = HSOpts.ModuleCachePath; 1283 assert(!TimestampFile.empty()); 1284 llvm::sys::path::append(TimestampFile, "modules.timestamp"); 1285 1286 // Try to stat() the timestamp file. 1287 if (::stat(TimestampFile.c_str(), &StatBuf)) { 1288 // If the timestamp file wasn't there, create one now. 1289 if (errno == ENOENT) { 1290 writeTimestampFile(TimestampFile); 1291 } 1292 return; 1293 } 1294 1295 // Check whether the time stamp is older than our pruning interval. 1296 // If not, do nothing. 1297 time_t TimeStampModTime = StatBuf.st_mtime; 1298 time_t CurrentTime = time(nullptr); 1299 if (CurrentTime - TimeStampModTime <= time_t(HSOpts.ModuleCachePruneInterval)) 1300 return; 1301 1302 // Write a new timestamp file so that nobody else attempts to prune. 1303 // There is a benign race condition here, if two Clang instances happen to 1304 // notice at the same time that the timestamp is out-of-date. 1305 writeTimestampFile(TimestampFile); 1306 1307 // Walk the entire module cache, looking for unused module files and module 1308 // indices. 1309 std::error_code EC; 1310 SmallString<128> ModuleCachePathNative; 1311 llvm::sys::path::native(HSOpts.ModuleCachePath, ModuleCachePathNative); 1312 for (llvm::sys::fs::directory_iterator Dir(ModuleCachePathNative, EC), DirEnd; 1313 Dir != DirEnd && !EC; Dir.increment(EC)) { 1314 // If we don't have a directory, there's nothing to look into. 1315 if (!llvm::sys::fs::is_directory(Dir->path())) 1316 continue; 1317 1318 // Walk all of the files within this directory. 1319 for (llvm::sys::fs::directory_iterator File(Dir->path(), EC), FileEnd; 1320 File != FileEnd && !EC; File.increment(EC)) { 1321 // We only care about module and global module index files. 1322 StringRef Extension = llvm::sys::path::extension(File->path()); 1323 if (Extension != ".pcm" && Extension != ".timestamp" && 1324 llvm::sys::path::filename(File->path()) != "modules.idx") 1325 continue; 1326 1327 // Look at this file. If we can't stat it, there's nothing interesting 1328 // there. 1329 if (::stat(File->path().c_str(), &StatBuf)) 1330 continue; 1331 1332 // If the file has been used recently enough, leave it there. 1333 time_t FileAccessTime = StatBuf.st_atime; 1334 if (CurrentTime - FileAccessTime <= 1335 time_t(HSOpts.ModuleCachePruneAfter)) { 1336 continue; 1337 } 1338 1339 // Remove the file. 1340 llvm::sys::fs::remove(File->path()); 1341 1342 // Remove the timestamp file. 1343 std::string TimpestampFilename = File->path() + ".timestamp"; 1344 llvm::sys::fs::remove(TimpestampFilename); 1345 } 1346 1347 // If we removed all of the files in the directory, remove the directory 1348 // itself. 1349 if (llvm::sys::fs::directory_iterator(Dir->path(), EC) == 1350 llvm::sys::fs::directory_iterator() && !EC) 1351 llvm::sys::fs::remove(Dir->path()); 1352 } 1353 } 1354 1355 void CompilerInstance::createModuleManager() { 1356 if (!ModuleManager) { 1357 if (!hasASTContext()) 1358 createASTContext(); 1359 1360 // If we're implicitly building modules but not currently recursively 1361 // building a module, check whether we need to prune the module cache. 1362 if (getSourceManager().getModuleBuildStack().empty() && 1363 !getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty() && 1364 getHeaderSearchOpts().ModuleCachePruneInterval > 0 && 1365 getHeaderSearchOpts().ModuleCachePruneAfter > 0) { 1366 pruneModuleCache(getHeaderSearchOpts()); 1367 } 1368 1369 HeaderSearchOptions &HSOpts = getHeaderSearchOpts(); 1370 std::string Sysroot = HSOpts.Sysroot; 1371 const PreprocessorOptions &PPOpts = getPreprocessorOpts(); 1372 std::unique_ptr<llvm::Timer> ReadTimer; 1373 if (FrontendTimerGroup) 1374 ReadTimer = llvm::make_unique<llvm::Timer>("reading_modules", 1375 "Reading modules", 1376 *FrontendTimerGroup); 1377 ModuleManager = new ASTReader( 1378 getPreprocessor(), getASTContext(), getPCHContainerReader(), 1379 getFrontendOpts().ModuleFileExtensions, 1380 Sysroot.empty() ? "" : Sysroot.c_str(), PPOpts.DisablePCHValidation, 1381 /*AllowASTWithCompilerErrors=*/false, 1382 /*AllowConfigurationMismatch=*/false, 1383 HSOpts.ModulesValidateSystemHeaders, 1384 getFrontendOpts().UseGlobalModuleIndex, 1385 std::move(ReadTimer)); 1386 if (hasASTConsumer()) { 1387 ModuleManager->setDeserializationListener( 1388 getASTConsumer().GetASTDeserializationListener()); 1389 getASTContext().setASTMutationListener( 1390 getASTConsumer().GetASTMutationListener()); 1391 } 1392 getASTContext().setExternalSource(ModuleManager); 1393 if (hasSema()) 1394 ModuleManager->InitializeSema(getSema()); 1395 if (hasASTConsumer()) 1396 ModuleManager->StartTranslationUnit(&getASTConsumer()); 1397 1398 if (TheDependencyFileGenerator) 1399 TheDependencyFileGenerator->AttachToASTReader(*ModuleManager); 1400 for (auto &Listener : DependencyCollectors) 1401 Listener->attachToASTReader(*ModuleManager); 1402 } 1403 } 1404 1405 bool CompilerInstance::loadModuleFile(StringRef FileName) { 1406 llvm::Timer Timer; 1407 if (FrontendTimerGroup) 1408 Timer.init("preloading." + FileName.str(), "Preloading " + FileName.str(), 1409 *FrontendTimerGroup); 1410 llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer : nullptr); 1411 1412 // Helper to recursively read the module names for all modules we're adding. 1413 // We mark these as known and redirect any attempt to load that module to 1414 // the files we were handed. 1415 struct ReadModuleNames : ASTReaderListener { 1416 CompilerInstance &CI; 1417 llvm::SmallVector<IdentifierInfo*, 8> LoadedModules; 1418 1419 ReadModuleNames(CompilerInstance &CI) : CI(CI) {} 1420 1421 void ReadModuleName(StringRef ModuleName) override { 1422 LoadedModules.push_back( 1423 CI.getPreprocessor().getIdentifierInfo(ModuleName)); 1424 } 1425 1426 void registerAll() { 1427 for (auto *II : LoadedModules) { 1428 CI.KnownModules[II] = CI.getPreprocessor() 1429 .getHeaderSearchInfo() 1430 .getModuleMap() 1431 .findModule(II->getName()); 1432 } 1433 LoadedModules.clear(); 1434 } 1435 1436 void markAllUnavailable() { 1437 for (auto *II : LoadedModules) { 1438 if (Module *M = CI.getPreprocessor() 1439 .getHeaderSearchInfo() 1440 .getModuleMap() 1441 .findModule(II->getName())) { 1442 M->HasIncompatibleModuleFile = true; 1443 1444 // Mark module as available if the only reason it was unavailable 1445 // was missing headers. 1446 SmallVector<Module *, 2> Stack; 1447 Stack.push_back(M); 1448 while (!Stack.empty()) { 1449 Module *Current = Stack.pop_back_val(); 1450 if (Current->IsMissingRequirement) continue; 1451 Current->IsAvailable = true; 1452 Stack.insert(Stack.end(), 1453 Current->submodule_begin(), Current->submodule_end()); 1454 } 1455 } 1456 } 1457 LoadedModules.clear(); 1458 } 1459 }; 1460 1461 // If we don't already have an ASTReader, create one now. 1462 if (!ModuleManager) 1463 createModuleManager(); 1464 1465 auto Listener = llvm::make_unique<ReadModuleNames>(*this); 1466 auto &ListenerRef = *Listener; 1467 ASTReader::ListenerScope ReadModuleNamesListener(*ModuleManager, 1468 std::move(Listener)); 1469 1470 // Try to load the module file. 1471 switch (ModuleManager->ReadAST(FileName, serialization::MK_ExplicitModule, 1472 SourceLocation(), 1473 ASTReader::ARR_ConfigurationMismatch)) { 1474 case ASTReader::Success: 1475 // We successfully loaded the module file; remember the set of provided 1476 // modules so that we don't try to load implicit modules for them. 1477 ListenerRef.registerAll(); 1478 return true; 1479 1480 case ASTReader::ConfigurationMismatch: 1481 // Ignore unusable module files. 1482 getDiagnostics().Report(SourceLocation(), diag::warn_module_config_mismatch) 1483 << FileName; 1484 // All modules provided by any files we tried and failed to load are now 1485 // unavailable; includes of those modules should now be handled textually. 1486 ListenerRef.markAllUnavailable(); 1487 return true; 1488 1489 default: 1490 return false; 1491 } 1492 } 1493 1494 ModuleLoadResult 1495 CompilerInstance::loadModule(SourceLocation ImportLoc, 1496 ModuleIdPath Path, 1497 Module::NameVisibilityKind Visibility, 1498 bool IsInclusionDirective) { 1499 // Determine what file we're searching from. 1500 StringRef ModuleName = Path[0].first->getName(); 1501 SourceLocation ModuleNameLoc = Path[0].second; 1502 1503 // If we've already handled this import, just return the cached result. 1504 // This one-element cache is important to eliminate redundant diagnostics 1505 // when both the preprocessor and parser see the same import declaration. 1506 if (ImportLoc.isValid() && LastModuleImportLoc == ImportLoc) { 1507 // Make the named module visible. 1508 if (LastModuleImportResult && ModuleName != getLangOpts().CurrentModule) 1509 ModuleManager->makeModuleVisible(LastModuleImportResult, Visibility, 1510 ImportLoc); 1511 return LastModuleImportResult; 1512 } 1513 1514 clang::Module *Module = nullptr; 1515 1516 // If we don't already have information on this module, load the module now. 1517 llvm::DenseMap<const IdentifierInfo *, clang::Module *>::iterator Known 1518 = KnownModules.find(Path[0].first); 1519 if (Known != KnownModules.end()) { 1520 // Retrieve the cached top-level module. 1521 Module = Known->second; 1522 } else if (ModuleName == getLangOpts().CurrentModule) { 1523 // This is the module we're building. 1524 Module = PP->getHeaderSearchInfo().lookupModule(ModuleName); 1525 Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first; 1526 } else { 1527 // Search for a module with the given name. 1528 Module = PP->getHeaderSearchInfo().lookupModule(ModuleName); 1529 HeaderSearchOptions &HSOpts = 1530 PP->getHeaderSearchInfo().getHeaderSearchOpts(); 1531 1532 std::string ModuleFileName; 1533 bool LoadFromPrebuiltModulePath = false; 1534 // We try to load the module from the prebuilt module paths. If not 1535 // successful, we then try to find it in the module cache. 1536 if (!HSOpts.PrebuiltModulePaths.empty()) { 1537 // Load the module from the prebuilt module path. 1538 ModuleFileName = PP->getHeaderSearchInfo().getModuleFileName( 1539 ModuleName, "", /*UsePrebuiltPath*/ true); 1540 if (!ModuleFileName.empty()) 1541 LoadFromPrebuiltModulePath = true; 1542 } 1543 if (!LoadFromPrebuiltModulePath && Module) { 1544 // Load the module from the module cache. 1545 ModuleFileName = PP->getHeaderSearchInfo().getModuleFileName(Module); 1546 } else if (!LoadFromPrebuiltModulePath) { 1547 // We can't find a module, error out here. 1548 getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found) 1549 << ModuleName 1550 << SourceRange(ImportLoc, ModuleNameLoc); 1551 ModuleBuildFailed = true; 1552 return ModuleLoadResult(); 1553 } 1554 1555 if (ModuleFileName.empty()) { 1556 if (Module && Module->HasIncompatibleModuleFile) { 1557 // We tried and failed to load a module file for this module. Fall 1558 // back to textual inclusion for its headers. 1559 return ModuleLoadResult::ConfigMismatch; 1560 } 1561 1562 getDiagnostics().Report(ModuleNameLoc, diag::err_module_build_disabled) 1563 << ModuleName; 1564 ModuleBuildFailed = true; 1565 return ModuleLoadResult(); 1566 } 1567 1568 // If we don't already have an ASTReader, create one now. 1569 if (!ModuleManager) 1570 createModuleManager(); 1571 1572 llvm::Timer Timer; 1573 if (FrontendTimerGroup) 1574 Timer.init("loading." + ModuleFileName, "Loading " + ModuleFileName, 1575 *FrontendTimerGroup); 1576 llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer : nullptr); 1577 1578 // Try to load the module file. If we are trying to load from the prebuilt 1579 // module path, we don't have the module map files and don't know how to 1580 // rebuild modules. 1581 unsigned ARRFlags = LoadFromPrebuiltModulePath ? 1582 ASTReader::ARR_ConfigurationMismatch : 1583 ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing; 1584 switch (ModuleManager->ReadAST(ModuleFileName, 1585 LoadFromPrebuiltModulePath ? 1586 serialization::MK_PrebuiltModule : 1587 serialization::MK_ImplicitModule, 1588 ImportLoc, 1589 ARRFlags)) { 1590 case ASTReader::Success: { 1591 if (LoadFromPrebuiltModulePath && !Module) { 1592 Module = PP->getHeaderSearchInfo().lookupModule(ModuleName); 1593 if (!Module || !Module->getASTFile() || 1594 FileMgr->getFile(ModuleFileName) != Module->getASTFile()) { 1595 // Error out if Module does not refer to the file in the prebuilt 1596 // module path. 1597 getDiagnostics().Report(ModuleNameLoc, diag::err_module_prebuilt) 1598 << ModuleName; 1599 ModuleBuildFailed = true; 1600 KnownModules[Path[0].first] = nullptr; 1601 return ModuleLoadResult(); 1602 } 1603 } 1604 break; 1605 } 1606 1607 case ASTReader::OutOfDate: 1608 case ASTReader::Missing: { 1609 if (LoadFromPrebuiltModulePath) { 1610 // We can't rebuild the module without a module map. Since ReadAST 1611 // already produces diagnostics for these two cases, we simply 1612 // error out here. 1613 ModuleBuildFailed = true; 1614 KnownModules[Path[0].first] = nullptr; 1615 return ModuleLoadResult(); 1616 } 1617 1618 // The module file is missing or out-of-date. Build it. 1619 assert(Module && "missing module file"); 1620 // Check whether there is a cycle in the module graph. 1621 ModuleBuildStack ModPath = getSourceManager().getModuleBuildStack(); 1622 ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end(); 1623 for (; Pos != PosEnd; ++Pos) { 1624 if (Pos->first == ModuleName) 1625 break; 1626 } 1627 1628 if (Pos != PosEnd) { 1629 SmallString<256> CyclePath; 1630 for (; Pos != PosEnd; ++Pos) { 1631 CyclePath += Pos->first; 1632 CyclePath += " -> "; 1633 } 1634 CyclePath += ModuleName; 1635 1636 getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle) 1637 << ModuleName << CyclePath; 1638 return ModuleLoadResult(); 1639 } 1640 1641 // Check whether we have already attempted to build this module (but 1642 // failed). 1643 if (getPreprocessorOpts().FailedModules && 1644 getPreprocessorOpts().FailedModules->hasAlreadyFailed(ModuleName)) { 1645 getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built) 1646 << ModuleName 1647 << SourceRange(ImportLoc, ModuleNameLoc); 1648 ModuleBuildFailed = true; 1649 return ModuleLoadResult(); 1650 } 1651 1652 // Try to compile and then load the module. 1653 if (!compileAndLoadModule(*this, ImportLoc, ModuleNameLoc, Module, 1654 ModuleFileName)) { 1655 assert(getDiagnostics().hasErrorOccurred() && 1656 "undiagnosed error in compileAndLoadModule"); 1657 if (getPreprocessorOpts().FailedModules) 1658 getPreprocessorOpts().FailedModules->addFailed(ModuleName); 1659 KnownModules[Path[0].first] = nullptr; 1660 ModuleBuildFailed = true; 1661 return ModuleLoadResult(); 1662 } 1663 1664 // Okay, we've rebuilt and now loaded the module. 1665 break; 1666 } 1667 1668 case ASTReader::ConfigurationMismatch: 1669 if (LoadFromPrebuiltModulePath) 1670 getDiagnostics().Report(SourceLocation(), 1671 diag::warn_module_config_mismatch) 1672 << ModuleFileName; 1673 // Fall through to error out. 1674 case ASTReader::VersionMismatch: 1675 case ASTReader::HadErrors: 1676 ModuleLoader::HadFatalFailure = true; 1677 // FIXME: The ASTReader will already have complained, but can we shoehorn 1678 // that diagnostic information into a more useful form? 1679 KnownModules[Path[0].first] = nullptr; 1680 return ModuleLoadResult(); 1681 1682 case ASTReader::Failure: 1683 ModuleLoader::HadFatalFailure = true; 1684 // Already complained, but note now that we failed. 1685 KnownModules[Path[0].first] = nullptr; 1686 ModuleBuildFailed = true; 1687 return ModuleLoadResult(); 1688 } 1689 1690 // Cache the result of this top-level module lookup for later. 1691 Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first; 1692 } 1693 1694 // If we never found the module, fail. 1695 if (!Module) 1696 return ModuleLoadResult(); 1697 1698 // Verify that the rest of the module path actually corresponds to 1699 // a submodule. 1700 if (Path.size() > 1) { 1701 for (unsigned I = 1, N = Path.size(); I != N; ++I) { 1702 StringRef Name = Path[I].first->getName(); 1703 clang::Module *Sub = Module->findSubmodule(Name); 1704 1705 if (!Sub) { 1706 // Attempt to perform typo correction to find a module name that works. 1707 SmallVector<StringRef, 2> Best; 1708 unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)(); 1709 1710 for (clang::Module::submodule_iterator J = Module->submodule_begin(), 1711 JEnd = Module->submodule_end(); 1712 J != JEnd; ++J) { 1713 unsigned ED = Name.edit_distance((*J)->Name, 1714 /*AllowReplacements=*/true, 1715 BestEditDistance); 1716 if (ED <= BestEditDistance) { 1717 if (ED < BestEditDistance) { 1718 Best.clear(); 1719 BestEditDistance = ED; 1720 } 1721 1722 Best.push_back((*J)->Name); 1723 } 1724 } 1725 1726 // If there was a clear winner, user it. 1727 if (Best.size() == 1) { 1728 getDiagnostics().Report(Path[I].second, 1729 diag::err_no_submodule_suggest) 1730 << Path[I].first << Module->getFullModuleName() << Best[0] 1731 << SourceRange(Path[0].second, Path[I-1].second) 1732 << FixItHint::CreateReplacement(SourceRange(Path[I].second), 1733 Best[0]); 1734 1735 Sub = Module->findSubmodule(Best[0]); 1736 } 1737 } 1738 1739 if (!Sub) { 1740 // No submodule by this name. Complain, and don't look for further 1741 // submodules. 1742 getDiagnostics().Report(Path[I].second, diag::err_no_submodule) 1743 << Path[I].first << Module->getFullModuleName() 1744 << SourceRange(Path[0].second, Path[I-1].second); 1745 break; 1746 } 1747 1748 Module = Sub; 1749 } 1750 } 1751 1752 // Make the named module visible, if it's not already part of the module 1753 // we are parsing. 1754 if (ModuleName != getLangOpts().CurrentModule) { 1755 if (!Module->IsFromModuleFile) { 1756 // We have an umbrella header or directory that doesn't actually include 1757 // all of the headers within the directory it covers. Complain about 1758 // this missing submodule and recover by forgetting that we ever saw 1759 // this submodule. 1760 // FIXME: Should we detect this at module load time? It seems fairly 1761 // expensive (and rare). 1762 getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule) 1763 << Module->getFullModuleName() 1764 << SourceRange(Path.front().second, Path.back().second); 1765 1766 return ModuleLoadResult::MissingExpected; 1767 } 1768 1769 // Check whether this module is available. 1770 clang::Module::Requirement Requirement; 1771 clang::Module::UnresolvedHeaderDirective MissingHeader; 1772 if (!Module->isAvailable(getLangOpts(), getTarget(), Requirement, 1773 MissingHeader)) { 1774 if (MissingHeader.FileNameLoc.isValid()) { 1775 getDiagnostics().Report(MissingHeader.FileNameLoc, 1776 diag::err_module_header_missing) 1777 << MissingHeader.IsUmbrella << MissingHeader.FileName; 1778 } else { 1779 getDiagnostics().Report(ImportLoc, diag::err_module_unavailable) 1780 << Module->getFullModuleName() 1781 << Requirement.second << Requirement.first 1782 << SourceRange(Path.front().second, Path.back().second); 1783 } 1784 LastModuleImportLoc = ImportLoc; 1785 LastModuleImportResult = ModuleLoadResult(); 1786 return ModuleLoadResult(); 1787 } 1788 1789 ModuleManager->makeModuleVisible(Module, Visibility, ImportLoc); 1790 } 1791 1792 // Check for any configuration macros that have changed. 1793 clang::Module *TopModule = Module->getTopLevelModule(); 1794 for (unsigned I = 0, N = TopModule->ConfigMacros.size(); I != N; ++I) { 1795 checkConfigMacro(getPreprocessor(), TopModule->ConfigMacros[I], 1796 Module, ImportLoc); 1797 } 1798 1799 LastModuleImportLoc = ImportLoc; 1800 LastModuleImportResult = ModuleLoadResult(Module); 1801 return LastModuleImportResult; 1802 } 1803 1804 void CompilerInstance::makeModuleVisible(Module *Mod, 1805 Module::NameVisibilityKind Visibility, 1806 SourceLocation ImportLoc) { 1807 if (!ModuleManager) 1808 createModuleManager(); 1809 if (!ModuleManager) 1810 return; 1811 1812 ModuleManager->makeModuleVisible(Mod, Visibility, ImportLoc); 1813 } 1814 1815 GlobalModuleIndex *CompilerInstance::loadGlobalModuleIndex( 1816 SourceLocation TriggerLoc) { 1817 if (getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty()) 1818 return nullptr; 1819 if (!ModuleManager) 1820 createModuleManager(); 1821 // Can't do anything if we don't have the module manager. 1822 if (!ModuleManager) 1823 return nullptr; 1824 // Get an existing global index. This loads it if not already 1825 // loaded. 1826 ModuleManager->loadGlobalIndex(); 1827 GlobalModuleIndex *GlobalIndex = ModuleManager->getGlobalIndex(); 1828 // If the global index doesn't exist, create it. 1829 if (!GlobalIndex && shouldBuildGlobalModuleIndex() && hasFileManager() && 1830 hasPreprocessor()) { 1831 llvm::sys::fs::create_directories( 1832 getPreprocessor().getHeaderSearchInfo().getModuleCachePath()); 1833 GlobalModuleIndex::writeIndex( 1834 getFileManager(), getPCHContainerReader(), 1835 getPreprocessor().getHeaderSearchInfo().getModuleCachePath()); 1836 ModuleManager->resetForReload(); 1837 ModuleManager->loadGlobalIndex(); 1838 GlobalIndex = ModuleManager->getGlobalIndex(); 1839 } 1840 // For finding modules needing to be imported for fixit messages, 1841 // we need to make the global index cover all modules, so we do that here. 1842 if (!HaveFullGlobalModuleIndex && GlobalIndex && !buildingModule()) { 1843 ModuleMap &MMap = getPreprocessor().getHeaderSearchInfo().getModuleMap(); 1844 bool RecreateIndex = false; 1845 for (ModuleMap::module_iterator I = MMap.module_begin(), 1846 E = MMap.module_end(); I != E; ++I) { 1847 Module *TheModule = I->second; 1848 const FileEntry *Entry = TheModule->getASTFile(); 1849 if (!Entry) { 1850 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path; 1851 Path.push_back(std::make_pair( 1852 getPreprocessor().getIdentifierInfo(TheModule->Name), TriggerLoc)); 1853 std::reverse(Path.begin(), Path.end()); 1854 // Load a module as hidden. This also adds it to the global index. 1855 loadModule(TheModule->DefinitionLoc, Path, Module::Hidden, false); 1856 RecreateIndex = true; 1857 } 1858 } 1859 if (RecreateIndex) { 1860 GlobalModuleIndex::writeIndex( 1861 getFileManager(), getPCHContainerReader(), 1862 getPreprocessor().getHeaderSearchInfo().getModuleCachePath()); 1863 ModuleManager->resetForReload(); 1864 ModuleManager->loadGlobalIndex(); 1865 GlobalIndex = ModuleManager->getGlobalIndex(); 1866 } 1867 HaveFullGlobalModuleIndex = true; 1868 } 1869 return GlobalIndex; 1870 } 1871 1872 // Check global module index for missing imports. 1873 bool 1874 CompilerInstance::lookupMissingImports(StringRef Name, 1875 SourceLocation TriggerLoc) { 1876 // Look for the symbol in non-imported modules, but only if an error 1877 // actually occurred. 1878 if (!buildingModule()) { 1879 // Load global module index, or retrieve a previously loaded one. 1880 GlobalModuleIndex *GlobalIndex = loadGlobalModuleIndex( 1881 TriggerLoc); 1882 1883 // Only if we have a global index. 1884 if (GlobalIndex) { 1885 GlobalModuleIndex::HitSet FoundModules; 1886 1887 // Find the modules that reference the identifier. 1888 // Note that this only finds top-level modules. 1889 // We'll let diagnoseTypo find the actual declaration module. 1890 if (GlobalIndex->lookupIdentifier(Name, FoundModules)) 1891 return true; 1892 } 1893 } 1894 1895 return false; 1896 } 1897 void CompilerInstance::resetAndLeakSema() { BuryPointer(takeSema()); } 1898 1899 void CompilerInstance::setExternalSemaSource( 1900 IntrusiveRefCntPtr<ExternalSemaSource> ESS) { 1901 ExternalSemaSrc = std::move(ESS); 1902 } 1903