1 //===--- CompilerInstance.cpp ---------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "clang/Frontend/CompilerInstance.h" 10 #include "clang/AST/ASTConsumer.h" 11 #include "clang/AST/ASTContext.h" 12 #include "clang/AST/Decl.h" 13 #include "clang/Basic/CharInfo.h" 14 #include "clang/Basic/Diagnostic.h" 15 #include "clang/Basic/DiagnosticOptions.h" 16 #include "clang/Basic/FileManager.h" 17 #include "clang/Basic/LangStandard.h" 18 #include "clang/Basic/SourceManager.h" 19 #include "clang/Basic/Stack.h" 20 #include "clang/Basic/TargetInfo.h" 21 #include "clang/Basic/Version.h" 22 #include "clang/Config/config.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/FrontendPluginRegistry.h" 28 #include "clang/Frontend/LogDiagnosticPrinter.h" 29 #include "clang/Frontend/SARIFDiagnosticPrinter.h" 30 #include "clang/Frontend/SerializedDiagnosticPrinter.h" 31 #include "clang/Frontend/TextDiagnosticPrinter.h" 32 #include "clang/Frontend/Utils.h" 33 #include "clang/Frontend/VerifyDiagnosticConsumer.h" 34 #include "clang/Lex/HeaderSearch.h" 35 #include "clang/Lex/Preprocessor.h" 36 #include "clang/Lex/PreprocessorOptions.h" 37 #include "clang/Sema/CodeCompleteConsumer.h" 38 #include "clang/Sema/Sema.h" 39 #include "clang/Serialization/ASTReader.h" 40 #include "clang/Serialization/GlobalModuleIndex.h" 41 #include "clang/Serialization/InMemoryModuleCache.h" 42 #include "llvm/ADT/ScopeExit.h" 43 #include "llvm/ADT/Statistic.h" 44 #include "llvm/Support/BuryPointer.h" 45 #include "llvm/Support/CrashRecoveryContext.h" 46 #include "llvm/Support/Errc.h" 47 #include "llvm/Support/FileSystem.h" 48 #include "llvm/Support/Host.h" 49 #include "llvm/Support/LockFileManager.h" 50 #include "llvm/Support/MemoryBuffer.h" 51 #include "llvm/Support/Path.h" 52 #include "llvm/Support/Program.h" 53 #include "llvm/Support/Signals.h" 54 #include "llvm/Support/TimeProfiler.h" 55 #include "llvm/Support/Timer.h" 56 #include "llvm/Support/raw_ostream.h" 57 #include <time.h> 58 #include <utility> 59 60 using namespace clang; 61 62 CompilerInstance::CompilerInstance( 63 std::shared_ptr<PCHContainerOperations> PCHContainerOps, 64 InMemoryModuleCache *SharedModuleCache) 65 : ModuleLoader(/* BuildingModule = */ SharedModuleCache), 66 Invocation(new CompilerInvocation()), 67 ModuleCache(SharedModuleCache ? SharedModuleCache 68 : new InMemoryModuleCache), 69 ThePCHContainerOperations(std::move(PCHContainerOps)) {} 70 71 CompilerInstance::~CompilerInstance() { 72 assert(OutputFiles.empty() && "Still output files in flight?"); 73 } 74 75 void CompilerInstance::setInvocation( 76 std::shared_ptr<CompilerInvocation> Value) { 77 Invocation = std::move(Value); 78 } 79 80 bool CompilerInstance::shouldBuildGlobalModuleIndex() const { 81 return (BuildGlobalModuleIndex || 82 (TheASTReader && TheASTReader->isGlobalIndexUnavailable() && 83 getFrontendOpts().GenerateGlobalModuleIndex)) && 84 !DisableGeneratingGlobalModuleIndex; 85 } 86 87 void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) { 88 Diagnostics = Value; 89 } 90 91 void CompilerInstance::setVerboseOutputStream(raw_ostream &Value) { 92 OwnedVerboseOutputStream.reset(); 93 VerboseOutputStream = &Value; 94 } 95 96 void CompilerInstance::setVerboseOutputStream(std::unique_ptr<raw_ostream> Value) { 97 OwnedVerboseOutputStream.swap(Value); 98 VerboseOutputStream = OwnedVerboseOutputStream.get(); 99 } 100 101 void CompilerInstance::setTarget(TargetInfo *Value) { Target = Value; } 102 void CompilerInstance::setAuxTarget(TargetInfo *Value) { AuxTarget = Value; } 103 104 bool CompilerInstance::createTarget() { 105 // Create the target instance. 106 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), 107 getInvocation().TargetOpts)); 108 if (!hasTarget()) 109 return false; 110 111 // Check whether AuxTarget exists, if not, then create TargetInfo for the 112 // other side of CUDA/OpenMP/SYCL compilation. 113 if (!getAuxTarget() && 114 (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 115 getLangOpts().SYCLIsDevice) && 116 !getFrontendOpts().AuxTriple.empty()) { 117 auto TO = std::make_shared<TargetOptions>(); 118 TO->Triple = llvm::Triple::normalize(getFrontendOpts().AuxTriple); 119 if (getFrontendOpts().AuxTargetCPU) 120 TO->CPU = getFrontendOpts().AuxTargetCPU.value(); 121 if (getFrontendOpts().AuxTargetFeatures) 122 TO->FeaturesAsWritten = getFrontendOpts().AuxTargetFeatures.value(); 123 TO->HostTriple = getTarget().getTriple().str(); 124 setAuxTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), TO)); 125 } 126 127 if (!getTarget().hasStrictFP() && !getLangOpts().ExpStrictFP) { 128 if (getLangOpts().RoundingMath) { 129 getDiagnostics().Report(diag::warn_fe_backend_unsupported_fp_rounding); 130 getLangOpts().RoundingMath = false; 131 } 132 auto FPExc = getLangOpts().getFPExceptionMode(); 133 if (FPExc != LangOptions::FPE_Default && FPExc != LangOptions::FPE_Ignore) { 134 getDiagnostics().Report(diag::warn_fe_backend_unsupported_fp_exceptions); 135 getLangOpts().setFPExceptionMode(LangOptions::FPE_Ignore); 136 } 137 // FIXME: can we disable FEnvAccess? 138 } 139 140 // We should do it here because target knows nothing about 141 // language options when it's being created. 142 if (getLangOpts().OpenCL && 143 !getTarget().validateOpenCLTarget(getLangOpts(), getDiagnostics())) 144 return false; 145 146 // Inform the target of the language options. 147 // FIXME: We shouldn't need to do this, the target should be immutable once 148 // created. This complexity should be lifted elsewhere. 149 getTarget().adjust(getDiagnostics(), getLangOpts()); 150 151 // Adjust target options based on codegen options. 152 getTarget().adjustTargetOptions(getCodeGenOpts(), getTargetOpts()); 153 154 if (auto *Aux = getAuxTarget()) 155 getTarget().setAuxTarget(Aux); 156 157 return true; 158 } 159 160 llvm::vfs::FileSystem &CompilerInstance::getVirtualFileSystem() const { 161 return getFileManager().getVirtualFileSystem(); 162 } 163 164 void CompilerInstance::setFileManager(FileManager *Value) { 165 FileMgr = Value; 166 } 167 168 void CompilerInstance::setSourceManager(SourceManager *Value) { 169 SourceMgr = Value; 170 } 171 172 void CompilerInstance::setPreprocessor(std::shared_ptr<Preprocessor> Value) { 173 PP = std::move(Value); 174 } 175 176 void CompilerInstance::setASTContext(ASTContext *Value) { 177 Context = Value; 178 179 if (Context && Consumer) 180 getASTConsumer().Initialize(getASTContext()); 181 } 182 183 void CompilerInstance::setSema(Sema *S) { 184 TheSema.reset(S); 185 } 186 187 void CompilerInstance::setASTConsumer(std::unique_ptr<ASTConsumer> Value) { 188 Consumer = std::move(Value); 189 190 if (Context && Consumer) 191 getASTConsumer().Initialize(getASTContext()); 192 } 193 194 void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) { 195 CompletionConsumer.reset(Value); 196 } 197 198 std::unique_ptr<Sema> CompilerInstance::takeSema() { 199 return std::move(TheSema); 200 } 201 202 IntrusiveRefCntPtr<ASTReader> CompilerInstance::getASTReader() const { 203 return TheASTReader; 204 } 205 void CompilerInstance::setASTReader(IntrusiveRefCntPtr<ASTReader> Reader) { 206 assert(ModuleCache.get() == &Reader->getModuleManager().getModuleCache() && 207 "Expected ASTReader to use the same PCM cache"); 208 TheASTReader = std::move(Reader); 209 } 210 211 std::shared_ptr<ModuleDependencyCollector> 212 CompilerInstance::getModuleDepCollector() const { 213 return ModuleDepCollector; 214 } 215 216 void CompilerInstance::setModuleDepCollector( 217 std::shared_ptr<ModuleDependencyCollector> Collector) { 218 ModuleDepCollector = std::move(Collector); 219 } 220 221 static void collectHeaderMaps(const HeaderSearch &HS, 222 std::shared_ptr<ModuleDependencyCollector> MDC) { 223 SmallVector<std::string, 4> HeaderMapFileNames; 224 HS.getHeaderMapFileNames(HeaderMapFileNames); 225 for (auto &Name : HeaderMapFileNames) 226 MDC->addFile(Name); 227 } 228 229 static void collectIncludePCH(CompilerInstance &CI, 230 std::shared_ptr<ModuleDependencyCollector> MDC) { 231 const PreprocessorOptions &PPOpts = CI.getPreprocessorOpts(); 232 if (PPOpts.ImplicitPCHInclude.empty()) 233 return; 234 235 StringRef PCHInclude = PPOpts.ImplicitPCHInclude; 236 FileManager &FileMgr = CI.getFileManager(); 237 auto PCHDir = FileMgr.getOptionalDirectoryRef(PCHInclude); 238 if (!PCHDir) { 239 MDC->addFile(PCHInclude); 240 return; 241 } 242 243 std::error_code EC; 244 SmallString<128> DirNative; 245 llvm::sys::path::native(PCHDir->getName(), DirNative); 246 llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem(); 247 SimpleASTReaderListener Validator(CI.getPreprocessor()); 248 for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd; 249 Dir != DirEnd && !EC; Dir.increment(EC)) { 250 // Check whether this is an AST file. ASTReader::isAcceptableASTFile is not 251 // used here since we're not interested in validating the PCH at this time, 252 // but only to check whether this is a file containing an AST. 253 if (!ASTReader::readASTFileControlBlock( 254 Dir->path(), FileMgr, CI.getPCHContainerReader(), 255 /*FindModuleFileExtensions=*/false, Validator, 256 /*ValidateDiagnosticOptions=*/false)) 257 MDC->addFile(Dir->path()); 258 } 259 } 260 261 static void collectVFSEntries(CompilerInstance &CI, 262 std::shared_ptr<ModuleDependencyCollector> MDC) { 263 if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty()) 264 return; 265 266 // Collect all VFS found. 267 SmallVector<llvm::vfs::YAMLVFSEntry, 16> VFSEntries; 268 for (const std::string &VFSFile : CI.getHeaderSearchOpts().VFSOverlayFiles) { 269 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer = 270 llvm::MemoryBuffer::getFile(VFSFile); 271 if (!Buffer) 272 return; 273 llvm::vfs::collectVFSFromYAML(std::move(Buffer.get()), 274 /*DiagHandler*/ nullptr, VFSFile, VFSEntries); 275 } 276 277 for (auto &E : VFSEntries) 278 MDC->addFile(E.VPath, E.RPath); 279 } 280 281 // Diagnostics 282 static void SetUpDiagnosticLog(DiagnosticOptions *DiagOpts, 283 const CodeGenOptions *CodeGenOpts, 284 DiagnosticsEngine &Diags) { 285 std::error_code EC; 286 std::unique_ptr<raw_ostream> StreamOwner; 287 raw_ostream *OS = &llvm::errs(); 288 if (DiagOpts->DiagnosticLogFile != "-") { 289 // Create the output stream. 290 auto FileOS = std::make_unique<llvm::raw_fd_ostream>( 291 DiagOpts->DiagnosticLogFile, EC, 292 llvm::sys::fs::OF_Append | llvm::sys::fs::OF_TextWithCRLF); 293 if (EC) { 294 Diags.Report(diag::warn_fe_cc_log_diagnostics_failure) 295 << DiagOpts->DiagnosticLogFile << EC.message(); 296 } else { 297 FileOS->SetUnbuffered(); 298 OS = FileOS.get(); 299 StreamOwner = std::move(FileOS); 300 } 301 } 302 303 // Chain in the diagnostic client which will log the diagnostics. 304 auto Logger = std::make_unique<LogDiagnosticPrinter>(*OS, DiagOpts, 305 std::move(StreamOwner)); 306 if (CodeGenOpts) 307 Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags); 308 if (Diags.ownsClient()) { 309 Diags.setClient( 310 new ChainedDiagnosticConsumer(Diags.takeClient(), std::move(Logger))); 311 } else { 312 Diags.setClient( 313 new ChainedDiagnosticConsumer(Diags.getClient(), std::move(Logger))); 314 } 315 } 316 317 static void SetupSerializedDiagnostics(DiagnosticOptions *DiagOpts, 318 DiagnosticsEngine &Diags, 319 StringRef OutputFile) { 320 auto SerializedConsumer = 321 clang::serialized_diags::create(OutputFile, DiagOpts); 322 323 if (Diags.ownsClient()) { 324 Diags.setClient(new ChainedDiagnosticConsumer( 325 Diags.takeClient(), std::move(SerializedConsumer))); 326 } else { 327 Diags.setClient(new ChainedDiagnosticConsumer( 328 Diags.getClient(), std::move(SerializedConsumer))); 329 } 330 } 331 332 void CompilerInstance::createDiagnostics(DiagnosticConsumer *Client, 333 bool ShouldOwnClient) { 334 Diagnostics = createDiagnostics(&getDiagnosticOpts(), Client, 335 ShouldOwnClient, &getCodeGenOpts()); 336 } 337 338 IntrusiveRefCntPtr<DiagnosticsEngine> 339 CompilerInstance::createDiagnostics(DiagnosticOptions *Opts, 340 DiagnosticConsumer *Client, 341 bool ShouldOwnClient, 342 const CodeGenOptions *CodeGenOpts) { 343 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs()); 344 IntrusiveRefCntPtr<DiagnosticsEngine> 345 Diags(new DiagnosticsEngine(DiagID, Opts)); 346 347 // Create the diagnostic client for reporting errors or for 348 // implementing -verify. 349 if (Client) { 350 Diags->setClient(Client, ShouldOwnClient); 351 } else if (Opts->getFormat() == DiagnosticOptions::SARIF) { 352 Diags->setClient(new SARIFDiagnosticPrinter(llvm::errs(), Opts)); 353 } else 354 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts)); 355 356 // Chain in -verify checker, if requested. 357 if (Opts->VerifyDiagnostics) 358 Diags->setClient(new VerifyDiagnosticConsumer(*Diags)); 359 360 // Chain in -diagnostic-log-file dumper, if requested. 361 if (!Opts->DiagnosticLogFile.empty()) 362 SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags); 363 364 if (!Opts->DiagnosticSerializationFile.empty()) 365 SetupSerializedDiagnostics(Opts, *Diags, 366 Opts->DiagnosticSerializationFile); 367 368 // Configure our handling of diagnostics. 369 ProcessWarningOptions(*Diags, *Opts); 370 371 return Diags; 372 } 373 374 // File Manager 375 376 FileManager *CompilerInstance::createFileManager( 377 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) { 378 if (!VFS) 379 VFS = FileMgr ? &FileMgr->getVirtualFileSystem() 380 : createVFSFromCompilerInvocation(getInvocation(), 381 getDiagnostics()); 382 assert(VFS && "FileManager has no VFS?"); 383 FileMgr = new FileManager(getFileSystemOpts(), std::move(VFS)); 384 return FileMgr.get(); 385 } 386 387 // Source Manager 388 389 void CompilerInstance::createSourceManager(FileManager &FileMgr) { 390 SourceMgr = new SourceManager(getDiagnostics(), FileMgr); 391 } 392 393 // Initialize the remapping of files to alternative contents, e.g., 394 // those specified through other files. 395 static void InitializeFileRemapping(DiagnosticsEngine &Diags, 396 SourceManager &SourceMgr, 397 FileManager &FileMgr, 398 const PreprocessorOptions &InitOpts) { 399 // Remap files in the source manager (with buffers). 400 for (const auto &RB : InitOpts.RemappedFileBuffers) { 401 // Create the file entry for the file that we're mapping from. 402 const FileEntry *FromFile = 403 FileMgr.getVirtualFile(RB.first, RB.second->getBufferSize(), 0); 404 if (!FromFile) { 405 Diags.Report(diag::err_fe_remap_missing_from_file) << RB.first; 406 if (!InitOpts.RetainRemappedFileBuffers) 407 delete RB.second; 408 continue; 409 } 410 411 // Override the contents of the "from" file with the contents of the 412 // "to" file. If the caller owns the buffers, then pass a MemoryBufferRef; 413 // otherwise, pass as a std::unique_ptr<MemoryBuffer> to transfer ownership 414 // to the SourceManager. 415 if (InitOpts.RetainRemappedFileBuffers) 416 SourceMgr.overrideFileContents(FromFile, RB.second->getMemBufferRef()); 417 else 418 SourceMgr.overrideFileContents( 419 FromFile, std::unique_ptr<llvm::MemoryBuffer>( 420 const_cast<llvm::MemoryBuffer *>(RB.second))); 421 } 422 423 // Remap files in the source manager (with other files). 424 for (const auto &RF : InitOpts.RemappedFiles) { 425 // Find the file that we're mapping to. 426 auto ToFile = FileMgr.getFile(RF.second); 427 if (!ToFile) { 428 Diags.Report(diag::err_fe_remap_missing_to_file) << RF.first << RF.second; 429 continue; 430 } 431 432 // Create the file entry for the file that we're mapping from. 433 const FileEntry *FromFile = 434 FileMgr.getVirtualFile(RF.first, (*ToFile)->getSize(), 0); 435 if (!FromFile) { 436 Diags.Report(diag::err_fe_remap_missing_from_file) << RF.first; 437 continue; 438 } 439 440 // Override the contents of the "from" file with the contents of 441 // the "to" file. 442 SourceMgr.overrideFileContents(FromFile, *ToFile); 443 } 444 445 SourceMgr.setOverridenFilesKeepOriginalName( 446 InitOpts.RemappedFilesKeepOriginalName); 447 } 448 449 // Preprocessor 450 451 void CompilerInstance::createPreprocessor(TranslationUnitKind TUKind) { 452 const PreprocessorOptions &PPOpts = getPreprocessorOpts(); 453 454 // The AST reader holds a reference to the old preprocessor (if any). 455 TheASTReader.reset(); 456 457 // Create the Preprocessor. 458 HeaderSearch *HeaderInfo = 459 new HeaderSearch(getHeaderSearchOptsPtr(), getSourceManager(), 460 getDiagnostics(), getLangOpts(), &getTarget()); 461 PP = std::make_shared<Preprocessor>(Invocation->getPreprocessorOptsPtr(), 462 getDiagnostics(), getLangOpts(), 463 getSourceManager(), *HeaderInfo, *this, 464 /*IdentifierInfoLookup=*/nullptr, 465 /*OwnsHeaderSearch=*/true, TUKind); 466 getTarget().adjust(getDiagnostics(), getLangOpts()); 467 PP->Initialize(getTarget(), getAuxTarget()); 468 469 if (PPOpts.DetailedRecord) 470 PP->createPreprocessingRecord(); 471 472 // Apply remappings to the source manager. 473 InitializeFileRemapping(PP->getDiagnostics(), PP->getSourceManager(), 474 PP->getFileManager(), PPOpts); 475 476 // Predefine macros and configure the preprocessor. 477 InitializePreprocessor(*PP, PPOpts, getPCHContainerReader(), 478 getFrontendOpts()); 479 480 // Initialize the header search object. In CUDA compilations, we use the aux 481 // triple (the host triple) to initialize our header search, since we need to 482 // find the host headers in order to compile the CUDA code. 483 const llvm::Triple *HeaderSearchTriple = &PP->getTargetInfo().getTriple(); 484 if (PP->getTargetInfo().getTriple().getOS() == llvm::Triple::CUDA && 485 PP->getAuxTargetInfo()) 486 HeaderSearchTriple = &PP->getAuxTargetInfo()->getTriple(); 487 488 ApplyHeaderSearchOptions(PP->getHeaderSearchInfo(), getHeaderSearchOpts(), 489 PP->getLangOpts(), *HeaderSearchTriple); 490 491 PP->setPreprocessedOutput(getPreprocessorOutputOpts().ShowCPP); 492 493 if (PP->getLangOpts().Modules && PP->getLangOpts().ImplicitModules) { 494 std::string ModuleHash = getInvocation().getModuleHash(); 495 PP->getHeaderSearchInfo().setModuleHash(ModuleHash); 496 PP->getHeaderSearchInfo().setModuleCachePath( 497 getSpecificModuleCachePath(ModuleHash)); 498 } 499 500 // Handle generating dependencies, if requested. 501 const DependencyOutputOptions &DepOpts = getDependencyOutputOpts(); 502 if (!DepOpts.OutputFile.empty()) 503 addDependencyCollector(std::make_shared<DependencyFileGenerator>(DepOpts)); 504 if (!DepOpts.DOTOutputFile.empty()) 505 AttachDependencyGraphGen(*PP, DepOpts.DOTOutputFile, 506 getHeaderSearchOpts().Sysroot); 507 508 // If we don't have a collector, but we are collecting module dependencies, 509 // then we're the top level compiler instance and need to create one. 510 if (!ModuleDepCollector && !DepOpts.ModuleDependencyOutputDir.empty()) { 511 ModuleDepCollector = std::make_shared<ModuleDependencyCollector>( 512 DepOpts.ModuleDependencyOutputDir); 513 } 514 515 // If there is a module dep collector, register with other dep collectors 516 // and also (a) collect header maps and (b) TODO: input vfs overlay files. 517 if (ModuleDepCollector) { 518 addDependencyCollector(ModuleDepCollector); 519 collectHeaderMaps(PP->getHeaderSearchInfo(), ModuleDepCollector); 520 collectIncludePCH(*this, ModuleDepCollector); 521 collectVFSEntries(*this, ModuleDepCollector); 522 } 523 524 for (auto &Listener : DependencyCollectors) 525 Listener->attachToPreprocessor(*PP); 526 527 // Handle generating header include information, if requested. 528 if (DepOpts.ShowHeaderIncludes) 529 AttachHeaderIncludeGen(*PP, DepOpts); 530 if (!DepOpts.HeaderIncludeOutputFile.empty()) { 531 StringRef OutputPath = DepOpts.HeaderIncludeOutputFile; 532 if (OutputPath == "-") 533 OutputPath = ""; 534 AttachHeaderIncludeGen(*PP, DepOpts, 535 /*ShowAllHeaders=*/true, OutputPath, 536 /*ShowDepth=*/false); 537 } 538 539 if (DepOpts.ShowIncludesDest != ShowIncludesDestination::None) { 540 AttachHeaderIncludeGen(*PP, DepOpts, 541 /*ShowAllHeaders=*/true, /*OutputPath=*/"", 542 /*ShowDepth=*/true, /*MSStyle=*/true); 543 } 544 } 545 546 std::string CompilerInstance::getSpecificModuleCachePath(StringRef ModuleHash) { 547 // Set up the module path, including the hash for the module-creation options. 548 SmallString<256> SpecificModuleCache(getHeaderSearchOpts().ModuleCachePath); 549 if (!SpecificModuleCache.empty() && !getHeaderSearchOpts().DisableModuleHash) 550 llvm::sys::path::append(SpecificModuleCache, ModuleHash); 551 return std::string(SpecificModuleCache.str()); 552 } 553 554 // ASTContext 555 556 void CompilerInstance::createASTContext() { 557 Preprocessor &PP = getPreprocessor(); 558 auto *Context = new ASTContext(getLangOpts(), PP.getSourceManager(), 559 PP.getIdentifierTable(), PP.getSelectorTable(), 560 PP.getBuiltinInfo(), PP.TUKind); 561 Context->InitBuiltinTypes(getTarget(), getAuxTarget()); 562 setASTContext(Context); 563 } 564 565 // ExternalASTSource 566 567 namespace { 568 // Helper to recursively read the module names for all modules we're adding. 569 // We mark these as known and redirect any attempt to load that module to 570 // the files we were handed. 571 struct ReadModuleNames : ASTReaderListener { 572 Preprocessor &PP; 573 llvm::SmallVector<std::string, 8> LoadedModules; 574 575 ReadModuleNames(Preprocessor &PP) : PP(PP) {} 576 577 void ReadModuleName(StringRef ModuleName) override { 578 // Keep the module name as a string for now. It's not safe to create a new 579 // IdentifierInfo from an ASTReader callback. 580 LoadedModules.push_back(ModuleName.str()); 581 } 582 583 void registerAll() { 584 ModuleMap &MM = PP.getHeaderSearchInfo().getModuleMap(); 585 for (const std::string &LoadedModule : LoadedModules) 586 MM.cacheModuleLoad(*PP.getIdentifierInfo(LoadedModule), 587 MM.findModule(LoadedModule)); 588 LoadedModules.clear(); 589 } 590 591 void markAllUnavailable() { 592 for (const std::string &LoadedModule : LoadedModules) { 593 if (Module *M = PP.getHeaderSearchInfo().getModuleMap().findModule( 594 LoadedModule)) { 595 M->HasIncompatibleModuleFile = true; 596 597 // Mark module as available if the only reason it was unavailable 598 // was missing headers. 599 SmallVector<Module *, 2> Stack; 600 Stack.push_back(M); 601 while (!Stack.empty()) { 602 Module *Current = Stack.pop_back_val(); 603 if (Current->IsUnimportable) continue; 604 Current->IsAvailable = true; 605 Stack.insert(Stack.end(), 606 Current->submodule_begin(), Current->submodule_end()); 607 } 608 } 609 } 610 LoadedModules.clear(); 611 } 612 }; 613 } // namespace 614 615 void CompilerInstance::createPCHExternalASTSource( 616 StringRef Path, DisableValidationForModuleKind DisableValidation, 617 bool AllowPCHWithCompilerErrors, void *DeserializationListener, 618 bool OwnDeserializationListener) { 619 bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0; 620 TheASTReader = createPCHExternalASTSource( 621 Path, getHeaderSearchOpts().Sysroot, DisableValidation, 622 AllowPCHWithCompilerErrors, getPreprocessor(), getModuleCache(), 623 getASTContext(), getPCHContainerReader(), 624 getFrontendOpts().ModuleFileExtensions, DependencyCollectors, 625 DeserializationListener, OwnDeserializationListener, Preamble, 626 getFrontendOpts().UseGlobalModuleIndex); 627 } 628 629 IntrusiveRefCntPtr<ASTReader> CompilerInstance::createPCHExternalASTSource( 630 StringRef Path, StringRef Sysroot, 631 DisableValidationForModuleKind DisableValidation, 632 bool AllowPCHWithCompilerErrors, Preprocessor &PP, 633 InMemoryModuleCache &ModuleCache, ASTContext &Context, 634 const PCHContainerReader &PCHContainerRdr, 635 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions, 636 ArrayRef<std::shared_ptr<DependencyCollector>> DependencyCollectors, 637 void *DeserializationListener, bool OwnDeserializationListener, 638 bool Preamble, bool UseGlobalModuleIndex) { 639 HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts(); 640 641 IntrusiveRefCntPtr<ASTReader> Reader(new ASTReader( 642 PP, ModuleCache, &Context, PCHContainerRdr, Extensions, 643 Sysroot.empty() ? "" : Sysroot.data(), DisableValidation, 644 AllowPCHWithCompilerErrors, /*AllowConfigurationMismatch*/ false, 645 HSOpts.ModulesValidateSystemHeaders, HSOpts.ValidateASTInputFilesContent, 646 UseGlobalModuleIndex)); 647 648 // We need the external source to be set up before we read the AST, because 649 // eagerly-deserialized declarations may use it. 650 Context.setExternalSource(Reader.get()); 651 652 Reader->setDeserializationListener( 653 static_cast<ASTDeserializationListener *>(DeserializationListener), 654 /*TakeOwnership=*/OwnDeserializationListener); 655 656 for (auto &Listener : DependencyCollectors) 657 Listener->attachToASTReader(*Reader); 658 659 auto Listener = std::make_unique<ReadModuleNames>(PP); 660 auto &ListenerRef = *Listener; 661 ASTReader::ListenerScope ReadModuleNamesListener(*Reader, 662 std::move(Listener)); 663 664 switch (Reader->ReadAST(Path, 665 Preamble ? serialization::MK_Preamble 666 : serialization::MK_PCH, 667 SourceLocation(), 668 ASTReader::ARR_None)) { 669 case ASTReader::Success: 670 // Set the predefines buffer as suggested by the PCH reader. Typically, the 671 // predefines buffer will be empty. 672 PP.setPredefines(Reader->getSuggestedPredefines()); 673 ListenerRef.registerAll(); 674 return Reader; 675 676 case ASTReader::Failure: 677 // Unrecoverable failure: don't even try to process the input file. 678 break; 679 680 case ASTReader::Missing: 681 case ASTReader::OutOfDate: 682 case ASTReader::VersionMismatch: 683 case ASTReader::ConfigurationMismatch: 684 case ASTReader::HadErrors: 685 // No suitable PCH file could be found. Return an error. 686 break; 687 } 688 689 ListenerRef.markAllUnavailable(); 690 Context.setExternalSource(nullptr); 691 return nullptr; 692 } 693 694 // Code Completion 695 696 static bool EnableCodeCompletion(Preprocessor &PP, 697 StringRef Filename, 698 unsigned Line, 699 unsigned Column) { 700 // Tell the source manager to chop off the given file at a specific 701 // line and column. 702 auto Entry = PP.getFileManager().getFile(Filename); 703 if (!Entry) { 704 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file) 705 << Filename; 706 return true; 707 } 708 709 // Truncate the named file at the given line/column. 710 PP.SetCodeCompletionPoint(*Entry, Line, Column); 711 return false; 712 } 713 714 void CompilerInstance::createCodeCompletionConsumer() { 715 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt; 716 if (!CompletionConsumer) { 717 setCodeCompletionConsumer(createCodeCompletionConsumer( 718 getPreprocessor(), Loc.FileName, Loc.Line, Loc.Column, 719 getFrontendOpts().CodeCompleteOpts, llvm::outs())); 720 return; 721 } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName, 722 Loc.Line, Loc.Column)) { 723 setCodeCompletionConsumer(nullptr); 724 return; 725 } 726 } 727 728 void CompilerInstance::createFrontendTimer() { 729 FrontendTimerGroup.reset( 730 new llvm::TimerGroup("frontend", "Clang front-end time report")); 731 FrontendTimer.reset( 732 new llvm::Timer("frontend", "Clang front-end timer", 733 *FrontendTimerGroup)); 734 } 735 736 CodeCompleteConsumer * 737 CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP, 738 StringRef Filename, 739 unsigned Line, 740 unsigned Column, 741 const CodeCompleteOptions &Opts, 742 raw_ostream &OS) { 743 if (EnableCodeCompletion(PP, Filename, Line, Column)) 744 return nullptr; 745 746 // Set up the creation routine for code-completion. 747 return new PrintingCodeCompleteConsumer(Opts, OS); 748 } 749 750 void CompilerInstance::createSema(TranslationUnitKind TUKind, 751 CodeCompleteConsumer *CompletionConsumer) { 752 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(), 753 TUKind, CompletionConsumer)); 754 // Attach the external sema source if there is any. 755 if (ExternalSemaSrc) { 756 TheSema->addExternalSource(ExternalSemaSrc.get()); 757 ExternalSemaSrc->InitializeSema(*TheSema); 758 } 759 } 760 761 // Output Files 762 763 void CompilerInstance::clearOutputFiles(bool EraseFiles) { 764 // The ASTConsumer can own streams that write to the output files. 765 assert(!hasASTConsumer() && "ASTConsumer should be reset"); 766 // Ignore errors that occur when trying to discard the temp file. 767 for (OutputFile &OF : OutputFiles) { 768 if (EraseFiles) { 769 if (OF.File) 770 consumeError(OF.File->discard()); 771 if (!OF.Filename.empty()) 772 llvm::sys::fs::remove(OF.Filename); 773 continue; 774 } 775 776 if (!OF.File) 777 continue; 778 779 if (OF.File->TmpName.empty()) { 780 consumeError(OF.File->discard()); 781 continue; 782 } 783 784 llvm::Error E = OF.File->keep(OF.Filename); 785 if (!E) 786 continue; 787 788 getDiagnostics().Report(diag::err_unable_to_rename_temp) 789 << OF.File->TmpName << OF.Filename << std::move(E); 790 791 llvm::sys::fs::remove(OF.File->TmpName); 792 } 793 OutputFiles.clear(); 794 if (DeleteBuiltModules) { 795 for (auto &Module : BuiltModules) 796 llvm::sys::fs::remove(Module.second); 797 BuiltModules.clear(); 798 } 799 } 800 801 std::unique_ptr<raw_pwrite_stream> CompilerInstance::createDefaultOutputFile( 802 bool Binary, StringRef InFile, StringRef Extension, bool RemoveFileOnSignal, 803 bool CreateMissingDirectories, bool ForceUseTemporary) { 804 StringRef OutputPath = getFrontendOpts().OutputFile; 805 Optional<SmallString<128>> PathStorage; 806 if (OutputPath.empty()) { 807 if (InFile == "-" || Extension.empty()) { 808 OutputPath = "-"; 809 } else { 810 PathStorage.emplace(InFile); 811 llvm::sys::path::replace_extension(*PathStorage, Extension); 812 OutputPath = *PathStorage; 813 } 814 } 815 816 return createOutputFile(OutputPath, Binary, RemoveFileOnSignal, 817 getFrontendOpts().UseTemporary || ForceUseTemporary, 818 CreateMissingDirectories); 819 } 820 821 std::unique_ptr<raw_pwrite_stream> CompilerInstance::createNullOutputFile() { 822 return std::make_unique<llvm::raw_null_ostream>(); 823 } 824 825 std::unique_ptr<raw_pwrite_stream> 826 CompilerInstance::createOutputFile(StringRef OutputPath, bool Binary, 827 bool RemoveFileOnSignal, bool UseTemporary, 828 bool CreateMissingDirectories) { 829 Expected<std::unique_ptr<raw_pwrite_stream>> OS = 830 createOutputFileImpl(OutputPath, Binary, RemoveFileOnSignal, UseTemporary, 831 CreateMissingDirectories); 832 if (OS) 833 return std::move(*OS); 834 getDiagnostics().Report(diag::err_fe_unable_to_open_output) 835 << OutputPath << errorToErrorCode(OS.takeError()).message(); 836 return nullptr; 837 } 838 839 Expected<std::unique_ptr<llvm::raw_pwrite_stream>> 840 CompilerInstance::createOutputFileImpl(StringRef OutputPath, bool Binary, 841 bool RemoveFileOnSignal, 842 bool UseTemporary, 843 bool CreateMissingDirectories) { 844 assert((!CreateMissingDirectories || UseTemporary) && 845 "CreateMissingDirectories is only allowed when using temporary files"); 846 847 // If '-working-directory' was passed, the output filename should be 848 // relative to that. 849 Optional<SmallString<128>> AbsPath; 850 if (OutputPath != "-" && !llvm::sys::path::is_absolute(OutputPath)) { 851 AbsPath.emplace(OutputPath); 852 FileMgr->FixupRelativePath(*AbsPath); 853 OutputPath = *AbsPath; 854 } 855 856 std::unique_ptr<llvm::raw_fd_ostream> OS; 857 Optional<StringRef> OSFile; 858 859 if (UseTemporary) { 860 if (OutputPath == "-") 861 UseTemporary = false; 862 else { 863 llvm::sys::fs::file_status Status; 864 llvm::sys::fs::status(OutputPath, Status); 865 if (llvm::sys::fs::exists(Status)) { 866 // Fail early if we can't write to the final destination. 867 if (!llvm::sys::fs::can_write(OutputPath)) 868 return llvm::errorCodeToError( 869 make_error_code(llvm::errc::operation_not_permitted)); 870 871 // Don't use a temporary if the output is a special file. This handles 872 // things like '-o /dev/null' 873 if (!llvm::sys::fs::is_regular_file(Status)) 874 UseTemporary = false; 875 } 876 } 877 } 878 879 Optional<llvm::sys::fs::TempFile> Temp; 880 if (UseTemporary) { 881 // Create a temporary file. 882 // Insert -%%%%%%%% before the extension (if any), and because some tools 883 // (noticeable, clang's own GlobalModuleIndex.cpp) glob for build 884 // artifacts, also append .tmp. 885 StringRef OutputExtension = llvm::sys::path::extension(OutputPath); 886 SmallString<128> TempPath = 887 StringRef(OutputPath).drop_back(OutputExtension.size()); 888 TempPath += "-%%%%%%%%"; 889 TempPath += OutputExtension; 890 TempPath += ".tmp"; 891 Expected<llvm::sys::fs::TempFile> ExpectedFile = 892 llvm::sys::fs::TempFile::create( 893 TempPath, llvm::sys::fs::all_read | llvm::sys::fs::all_write, 894 Binary ? llvm::sys::fs::OF_None : llvm::sys::fs::OF_Text); 895 896 llvm::Error E = handleErrors( 897 ExpectedFile.takeError(), [&](const llvm::ECError &E) -> llvm::Error { 898 std::error_code EC = E.convertToErrorCode(); 899 if (CreateMissingDirectories && 900 EC == llvm::errc::no_such_file_or_directory) { 901 StringRef Parent = llvm::sys::path::parent_path(OutputPath); 902 EC = llvm::sys::fs::create_directories(Parent); 903 if (!EC) { 904 ExpectedFile = llvm::sys::fs::TempFile::create(TempPath); 905 if (!ExpectedFile) 906 return llvm::errorCodeToError( 907 llvm::errc::no_such_file_or_directory); 908 } 909 } 910 return llvm::errorCodeToError(EC); 911 }); 912 913 if (E) { 914 consumeError(std::move(E)); 915 } else { 916 Temp = std::move(ExpectedFile.get()); 917 OS.reset(new llvm::raw_fd_ostream(Temp->FD, /*shouldClose=*/false)); 918 OSFile = Temp->TmpName; 919 } 920 // If we failed to create the temporary, fallback to writing to the file 921 // directly. This handles the corner case where we cannot write to the 922 // directory, but can write to the file. 923 } 924 925 if (!OS) { 926 OSFile = OutputPath; 927 std::error_code EC; 928 OS.reset(new llvm::raw_fd_ostream( 929 *OSFile, EC, 930 (Binary ? llvm::sys::fs::OF_None : llvm::sys::fs::OF_TextWithCRLF))); 931 if (EC) 932 return llvm::errorCodeToError(EC); 933 } 934 935 // Add the output file -- but don't try to remove "-", since this means we are 936 // using stdin. 937 OutputFiles.emplace_back(((OutputPath != "-") ? OutputPath : "").str(), 938 std::move(Temp)); 939 940 if (!Binary || OS->supportsSeeking()) 941 return std::move(OS); 942 943 return std::make_unique<llvm::buffer_unique_ostream>(std::move(OS)); 944 } 945 946 // Initialization Utilities 947 948 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input){ 949 return InitializeSourceManager(Input, getDiagnostics(), getFileManager(), 950 getSourceManager()); 951 } 952 953 // static 954 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input, 955 DiagnosticsEngine &Diags, 956 FileManager &FileMgr, 957 SourceManager &SourceMgr) { 958 SrcMgr::CharacteristicKind Kind = 959 Input.getKind().getFormat() == InputKind::ModuleMap 960 ? Input.isSystem() ? SrcMgr::C_System_ModuleMap 961 : SrcMgr::C_User_ModuleMap 962 : Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User; 963 964 if (Input.isBuffer()) { 965 SourceMgr.setMainFileID(SourceMgr.createFileID(Input.getBuffer(), Kind)); 966 assert(SourceMgr.getMainFileID().isValid() && 967 "Couldn't establish MainFileID!"); 968 return true; 969 } 970 971 StringRef InputFile = Input.getFile(); 972 973 // Figure out where to get and map in the main file. 974 auto FileOrErr = InputFile == "-" 975 ? FileMgr.getSTDIN() 976 : FileMgr.getFileRef(InputFile, /*OpenFile=*/true); 977 if (!FileOrErr) { 978 // FIXME: include the error in the diagnostic even when it's not stdin. 979 auto EC = llvm::errorToErrorCode(FileOrErr.takeError()); 980 if (InputFile != "-") 981 Diags.Report(diag::err_fe_error_reading) << InputFile; 982 else 983 Diags.Report(diag::err_fe_error_reading_stdin) << EC.message(); 984 return false; 985 } 986 987 SourceMgr.setMainFileID( 988 SourceMgr.createFileID(*FileOrErr, SourceLocation(), Kind)); 989 990 assert(SourceMgr.getMainFileID().isValid() && 991 "Couldn't establish MainFileID!"); 992 return true; 993 } 994 995 // High-Level Operations 996 997 bool CompilerInstance::ExecuteAction(FrontendAction &Act) { 998 assert(hasDiagnostics() && "Diagnostics engine is not initialized!"); 999 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!"); 1000 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!"); 1001 1002 // Mark this point as the bottom of the stack if we don't have somewhere 1003 // better. We generally expect frontend actions to be invoked with (nearly) 1004 // DesiredStackSpace available. 1005 noteBottomOfStack(); 1006 1007 auto FinishDiagnosticClient = llvm::make_scope_exit([&]() { 1008 // Notify the diagnostic client that all files were processed. 1009 getDiagnosticClient().finish(); 1010 }); 1011 1012 raw_ostream &OS = getVerboseOutputStream(); 1013 1014 if (!Act.PrepareToExecute(*this)) 1015 return false; 1016 1017 if (!createTarget()) 1018 return false; 1019 1020 // rewriter project will change target built-in bool type from its default. 1021 if (getFrontendOpts().ProgramAction == frontend::RewriteObjC) 1022 getTarget().noSignedCharForObjCBool(); 1023 1024 // Validate/process some options. 1025 if (getHeaderSearchOpts().Verbose) 1026 OS << "clang -cc1 version " CLANG_VERSION_STRING 1027 << " based upon " << BACKEND_PACKAGE_STRING 1028 << " default target " << llvm::sys::getDefaultTargetTriple() << "\n"; 1029 1030 if (getCodeGenOpts().TimePasses) 1031 createFrontendTimer(); 1032 1033 if (getFrontendOpts().ShowStats || !getFrontendOpts().StatsFile.empty()) 1034 llvm::EnableStatistics(false); 1035 1036 for (const FrontendInputFile &FIF : getFrontendOpts().Inputs) { 1037 // Reset the ID tables if we are reusing the SourceManager and parsing 1038 // regular files. 1039 if (hasSourceManager() && !Act.isModelParsingAction()) 1040 getSourceManager().clearIDTables(); 1041 1042 if (Act.BeginSourceFile(*this, FIF)) { 1043 if (llvm::Error Err = Act.Execute()) { 1044 consumeError(std::move(Err)); // FIXME this drops errors on the floor. 1045 } 1046 Act.EndSourceFile(); 1047 } 1048 } 1049 1050 if (getDiagnosticOpts().ShowCarets) { 1051 // We can have multiple diagnostics sharing one diagnostic client. 1052 // Get the total number of warnings/errors from the client. 1053 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings(); 1054 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors(); 1055 1056 if (NumWarnings) 1057 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s"); 1058 if (NumWarnings && NumErrors) 1059 OS << " and "; 1060 if (NumErrors) 1061 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s"); 1062 if (NumWarnings || NumErrors) { 1063 OS << " generated"; 1064 if (getLangOpts().CUDA) { 1065 if (!getLangOpts().CUDAIsDevice) { 1066 OS << " when compiling for host"; 1067 } else { 1068 OS << " when compiling for " << getTargetOpts().CPU; 1069 } 1070 } 1071 OS << ".\n"; 1072 } 1073 } 1074 1075 if (getFrontendOpts().ShowStats) { 1076 if (hasFileManager()) { 1077 getFileManager().PrintStats(); 1078 OS << '\n'; 1079 } 1080 llvm::PrintStatistics(OS); 1081 } 1082 StringRef StatsFile = getFrontendOpts().StatsFile; 1083 if (!StatsFile.empty()) { 1084 std::error_code EC; 1085 auto StatS = std::make_unique<llvm::raw_fd_ostream>( 1086 StatsFile, EC, llvm::sys::fs::OF_TextWithCRLF); 1087 if (EC) { 1088 getDiagnostics().Report(diag::warn_fe_unable_to_open_stats_file) 1089 << StatsFile << EC.message(); 1090 } else { 1091 llvm::PrintStatisticsJSON(*StatS); 1092 } 1093 } 1094 1095 return !getDiagnostics().getClient()->getNumErrors(); 1096 } 1097 1098 void CompilerInstance::LoadRequestedPlugins() { 1099 // Load any requested plugins. 1100 for (const std::string &Path : getFrontendOpts().Plugins) { 1101 std::string Error; 1102 if (llvm::sys::DynamicLibrary::LoadLibraryPermanently(Path.c_str(), &Error)) 1103 getDiagnostics().Report(diag::err_fe_unable_to_load_plugin) 1104 << Path << Error; 1105 } 1106 1107 // Check if any of the loaded plugins replaces the main AST action 1108 for (const FrontendPluginRegistry::entry &Plugin : 1109 FrontendPluginRegistry::entries()) { 1110 std::unique_ptr<PluginASTAction> P(Plugin.instantiate()); 1111 if (P->getActionType() == PluginASTAction::ReplaceAction) { 1112 getFrontendOpts().ProgramAction = clang::frontend::PluginAction; 1113 getFrontendOpts().ActionName = Plugin.getName().str(); 1114 break; 1115 } 1116 } 1117 } 1118 1119 /// Determine the appropriate source input kind based on language 1120 /// options. 1121 static Language getLanguageFromOptions(const LangOptions &LangOpts) { 1122 if (LangOpts.OpenCL) 1123 return Language::OpenCL; 1124 if (LangOpts.CUDA) 1125 return Language::CUDA; 1126 if (LangOpts.ObjC) 1127 return LangOpts.CPlusPlus ? Language::ObjCXX : Language::ObjC; 1128 return LangOpts.CPlusPlus ? Language::CXX : Language::C; 1129 } 1130 1131 /// Compile a module file for the given module, using the options 1132 /// provided by the importing compiler instance. Returns true if the module 1133 /// was built without errors. 1134 static bool 1135 compileModuleImpl(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, 1136 StringRef ModuleName, FrontendInputFile Input, 1137 StringRef OriginalModuleMapFile, StringRef ModuleFileName, 1138 llvm::function_ref<void(CompilerInstance &)> PreBuildStep = 1139 [](CompilerInstance &) {}, 1140 llvm::function_ref<void(CompilerInstance &)> PostBuildStep = 1141 [](CompilerInstance &) {}) { 1142 llvm::TimeTraceScope TimeScope("Module Compile", ModuleName); 1143 1144 // Never compile a module that's already finalized - this would cause the 1145 // existing module to be freed, causing crashes if it is later referenced 1146 if (ImportingInstance.getModuleCache().isPCMFinal(ModuleFileName)) { 1147 ImportingInstance.getDiagnostics().Report( 1148 ImportLoc, diag::err_module_rebuild_finalized) 1149 << ModuleName; 1150 return false; 1151 } 1152 1153 // Construct a compiler invocation for creating this module. 1154 auto Invocation = 1155 std::make_shared<CompilerInvocation>(ImportingInstance.getInvocation()); 1156 1157 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts(); 1158 1159 // For any options that aren't intended to affect how a module is built, 1160 // reset them to their default values. 1161 Invocation->resetNonModularOptions(); 1162 1163 // Remove any macro definitions that are explicitly ignored by the module. 1164 // They aren't supposed to affect how the module is built anyway. 1165 HeaderSearchOptions &HSOpts = Invocation->getHeaderSearchOpts(); 1166 llvm::erase_if(PPOpts.Macros, 1167 [&HSOpts](const std::pair<std::string, bool> &def) { 1168 StringRef MacroDef = def.first; 1169 return HSOpts.ModulesIgnoreMacros.contains( 1170 llvm::CachedHashString(MacroDef.split('=').first)); 1171 }); 1172 1173 // If the original compiler invocation had -fmodule-name, pass it through. 1174 Invocation->getLangOpts()->ModuleName = 1175 ImportingInstance.getInvocation().getLangOpts()->ModuleName; 1176 1177 // Note the name of the module we're building. 1178 Invocation->getLangOpts()->CurrentModule = std::string(ModuleName); 1179 1180 // Make sure that the failed-module structure has been allocated in 1181 // the importing instance, and propagate the pointer to the newly-created 1182 // instance. 1183 PreprocessorOptions &ImportingPPOpts 1184 = ImportingInstance.getInvocation().getPreprocessorOpts(); 1185 if (!ImportingPPOpts.FailedModules) 1186 ImportingPPOpts.FailedModules = 1187 std::make_shared<PreprocessorOptions::FailedModulesSet>(); 1188 PPOpts.FailedModules = ImportingPPOpts.FailedModules; 1189 1190 // If there is a module map file, build the module using the module map. 1191 // Set up the inputs/outputs so that we build the module from its umbrella 1192 // header. 1193 FrontendOptions &FrontendOpts = Invocation->getFrontendOpts(); 1194 FrontendOpts.OutputFile = ModuleFileName.str(); 1195 FrontendOpts.DisableFree = false; 1196 FrontendOpts.GenerateGlobalModuleIndex = false; 1197 FrontendOpts.BuildingImplicitModule = true; 1198 FrontendOpts.OriginalModuleMap = std::string(OriginalModuleMapFile); 1199 // Force implicitly-built modules to hash the content of the module file. 1200 HSOpts.ModulesHashContent = true; 1201 FrontendOpts.Inputs = {Input}; 1202 1203 // Don't free the remapped file buffers; they are owned by our caller. 1204 PPOpts.RetainRemappedFileBuffers = true; 1205 1206 Invocation->getDiagnosticOpts().VerifyDiagnostics = 0; 1207 assert(ImportingInstance.getInvocation().getModuleHash() == 1208 Invocation->getModuleHash() && "Module hash mismatch!"); 1209 1210 // Construct a compiler instance that will be used to actually create the 1211 // module. Since we're sharing an in-memory module cache, 1212 // CompilerInstance::CompilerInstance is responsible for finalizing the 1213 // buffers to prevent use-after-frees. 1214 CompilerInstance Instance(ImportingInstance.getPCHContainerOperations(), 1215 &ImportingInstance.getModuleCache()); 1216 auto &Inv = *Invocation; 1217 Instance.setInvocation(std::move(Invocation)); 1218 1219 Instance.createDiagnostics(new ForwardingDiagnosticConsumer( 1220 ImportingInstance.getDiagnosticClient()), 1221 /*ShouldOwnClient=*/true); 1222 1223 if (FrontendOpts.ModulesShareFileManager) { 1224 Instance.setFileManager(&ImportingInstance.getFileManager()); 1225 } else { 1226 Instance.createFileManager(&ImportingInstance.getVirtualFileSystem()); 1227 } 1228 Instance.createSourceManager(Instance.getFileManager()); 1229 SourceManager &SourceMgr = Instance.getSourceManager(); 1230 1231 // Note that this module is part of the module build stack, so that we 1232 // can detect cycles in the module graph. 1233 SourceMgr.setModuleBuildStack( 1234 ImportingInstance.getSourceManager().getModuleBuildStack()); 1235 SourceMgr.pushModuleBuildStack(ModuleName, 1236 FullSourceLoc(ImportLoc, ImportingInstance.getSourceManager())); 1237 1238 // If we're collecting module dependencies, we need to share a collector 1239 // between all of the module CompilerInstances. Other than that, we don't 1240 // want to produce any dependency output from the module build. 1241 Instance.setModuleDepCollector(ImportingInstance.getModuleDepCollector()); 1242 Inv.getDependencyOutputOpts() = DependencyOutputOptions(); 1243 1244 ImportingInstance.getDiagnostics().Report(ImportLoc, 1245 diag::remark_module_build) 1246 << ModuleName << ModuleFileName; 1247 1248 PreBuildStep(Instance); 1249 1250 // Execute the action to actually build the module in-place. Use a separate 1251 // thread so that we get a stack large enough. 1252 bool Crashed = !llvm::CrashRecoveryContext().RunSafelyOnThread( 1253 [&]() { 1254 GenerateModuleFromModuleMapAction Action; 1255 Instance.ExecuteAction(Action); 1256 }, 1257 DesiredStackSize); 1258 1259 PostBuildStep(Instance); 1260 1261 ImportingInstance.getDiagnostics().Report(ImportLoc, 1262 diag::remark_module_build_done) 1263 << ModuleName; 1264 1265 if (Crashed) { 1266 // Clear the ASTConsumer if it hasn't been already, in case it owns streams 1267 // that must be closed before clearing output files. 1268 Instance.setSema(nullptr); 1269 Instance.setASTConsumer(nullptr); 1270 1271 // Delete any remaining temporary files related to Instance. 1272 Instance.clearOutputFiles(/*EraseFiles=*/true); 1273 } 1274 1275 // If \p AllowPCMWithCompilerErrors is set return 'success' even if errors 1276 // occurred. 1277 return !Instance.getDiagnostics().hasErrorOccurred() || 1278 Instance.getFrontendOpts().AllowPCMWithCompilerErrors; 1279 } 1280 1281 static const FileEntry *getPublicModuleMap(const FileEntry *File, 1282 FileManager &FileMgr) { 1283 StringRef Filename = llvm::sys::path::filename(File->getName()); 1284 SmallString<128> PublicFilename(File->getDir()->getName()); 1285 if (Filename == "module_private.map") 1286 llvm::sys::path::append(PublicFilename, "module.map"); 1287 else if (Filename == "module.private.modulemap") 1288 llvm::sys::path::append(PublicFilename, "module.modulemap"); 1289 else 1290 return nullptr; 1291 if (auto FE = FileMgr.getFile(PublicFilename)) 1292 return *FE; 1293 return nullptr; 1294 } 1295 1296 /// Compile a module file for the given module in a separate compiler instance, 1297 /// using the options provided by the importing compiler instance. Returns true 1298 /// if the module was built without errors. 1299 static bool compileModule(CompilerInstance &ImportingInstance, 1300 SourceLocation ImportLoc, Module *Module, 1301 StringRef ModuleFileName) { 1302 InputKind IK(getLanguageFromOptions(ImportingInstance.getLangOpts()), 1303 InputKind::ModuleMap); 1304 1305 // Get or create the module map that we'll use to build this module. 1306 ModuleMap &ModMap 1307 = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap(); 1308 bool Result; 1309 if (const FileEntry *ModuleMapFile = 1310 ModMap.getContainingModuleMapFile(Module)) { 1311 // Canonicalize compilation to start with the public module map. This is 1312 // vital for submodules declarations in the private module maps to be 1313 // correctly parsed when depending on a top level module in the public one. 1314 if (const FileEntry *PublicMMFile = getPublicModuleMap( 1315 ModuleMapFile, ImportingInstance.getFileManager())) 1316 ModuleMapFile = PublicMMFile; 1317 1318 // FIXME: Update header search to keep FileEntryRef rather than rely on 1319 // getLastRef(). 1320 StringRef ModuleMapFilePath = 1321 ModuleMapFile->getLastRef().getNameAsRequested(); 1322 1323 // Use the module map where this module resides. 1324 Result = compileModuleImpl( 1325 ImportingInstance, ImportLoc, Module->getTopLevelModuleName(), 1326 FrontendInputFile(ModuleMapFilePath, IK, +Module->IsSystem), 1327 ModMap.getModuleMapFileForUniquing(Module)->getName(), ModuleFileName); 1328 } else { 1329 // FIXME: We only need to fake up an input file here as a way of 1330 // transporting the module's directory to the module map parser. We should 1331 // be able to do that more directly, and parse from a memory buffer without 1332 // inventing this file. 1333 SmallString<128> FakeModuleMapFile(Module->Directory->getName()); 1334 llvm::sys::path::append(FakeModuleMapFile, "__inferred_module.map"); 1335 1336 std::string InferredModuleMapContent; 1337 llvm::raw_string_ostream OS(InferredModuleMapContent); 1338 Module->print(OS); 1339 OS.flush(); 1340 1341 Result = compileModuleImpl( 1342 ImportingInstance, ImportLoc, Module->getTopLevelModuleName(), 1343 FrontendInputFile(FakeModuleMapFile, IK, +Module->IsSystem), 1344 ModMap.getModuleMapFileForUniquing(Module)->getName(), 1345 ModuleFileName, 1346 [&](CompilerInstance &Instance) { 1347 std::unique_ptr<llvm::MemoryBuffer> ModuleMapBuffer = 1348 llvm::MemoryBuffer::getMemBuffer(InferredModuleMapContent); 1349 ModuleMapFile = Instance.getFileManager().getVirtualFile( 1350 FakeModuleMapFile, InferredModuleMapContent.size(), 0); 1351 Instance.getSourceManager().overrideFileContents( 1352 ModuleMapFile, std::move(ModuleMapBuffer)); 1353 }); 1354 } 1355 1356 // We've rebuilt a module. If we're allowed to generate or update the global 1357 // module index, record that fact in the importing compiler instance. 1358 if (ImportingInstance.getFrontendOpts().GenerateGlobalModuleIndex) { 1359 ImportingInstance.setBuildGlobalModuleIndex(true); 1360 } 1361 1362 return Result; 1363 } 1364 1365 /// Read the AST right after compiling the module. 1366 static bool readASTAfterCompileModule(CompilerInstance &ImportingInstance, 1367 SourceLocation ImportLoc, 1368 SourceLocation ModuleNameLoc, 1369 Module *Module, StringRef ModuleFileName, 1370 bool *OutOfDate) { 1371 DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics(); 1372 1373 unsigned ModuleLoadCapabilities = ASTReader::ARR_Missing; 1374 if (OutOfDate) 1375 ModuleLoadCapabilities |= ASTReader::ARR_OutOfDate; 1376 1377 // Try to read the module file, now that we've compiled it. 1378 ASTReader::ASTReadResult ReadResult = 1379 ImportingInstance.getASTReader()->ReadAST( 1380 ModuleFileName, serialization::MK_ImplicitModule, ImportLoc, 1381 ModuleLoadCapabilities); 1382 if (ReadResult == ASTReader::Success) 1383 return true; 1384 1385 // The caller wants to handle out-of-date failures. 1386 if (OutOfDate && ReadResult == ASTReader::OutOfDate) { 1387 *OutOfDate = true; 1388 return false; 1389 } 1390 1391 // The ASTReader didn't diagnose the error, so conservatively report it. 1392 if (ReadResult == ASTReader::Missing || !Diags.hasErrorOccurred()) 1393 Diags.Report(ModuleNameLoc, diag::err_module_not_built) 1394 << Module->Name << SourceRange(ImportLoc, ModuleNameLoc); 1395 1396 return false; 1397 } 1398 1399 /// Compile a module in a separate compiler instance and read the AST, 1400 /// returning true if the module compiles without errors. 1401 static bool compileModuleAndReadASTImpl(CompilerInstance &ImportingInstance, 1402 SourceLocation ImportLoc, 1403 SourceLocation ModuleNameLoc, 1404 Module *Module, 1405 StringRef ModuleFileName) { 1406 if (!compileModule(ImportingInstance, ModuleNameLoc, Module, 1407 ModuleFileName)) { 1408 ImportingInstance.getDiagnostics().Report(ModuleNameLoc, 1409 diag::err_module_not_built) 1410 << Module->Name << SourceRange(ImportLoc, ModuleNameLoc); 1411 return false; 1412 } 1413 1414 return readASTAfterCompileModule(ImportingInstance, ImportLoc, ModuleNameLoc, 1415 Module, ModuleFileName, 1416 /*OutOfDate=*/nullptr); 1417 } 1418 1419 /// Compile a module in a separate compiler instance and read the AST, 1420 /// returning true if the module compiles without errors, using a lock manager 1421 /// to avoid building the same module in multiple compiler instances. 1422 /// 1423 /// Uses a lock file manager and exponential backoff to reduce the chances that 1424 /// multiple instances will compete to create the same module. On timeout, 1425 /// deletes the lock file in order to avoid deadlock from crashing processes or 1426 /// bugs in the lock file manager. 1427 static bool compileModuleAndReadASTBehindLock( 1428 CompilerInstance &ImportingInstance, SourceLocation ImportLoc, 1429 SourceLocation ModuleNameLoc, Module *Module, StringRef ModuleFileName) { 1430 DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics(); 1431 1432 Diags.Report(ModuleNameLoc, diag::remark_module_lock) 1433 << ModuleFileName << Module->Name; 1434 1435 // FIXME: have LockFileManager return an error_code so that we can 1436 // avoid the mkdir when the directory already exists. 1437 StringRef Dir = llvm::sys::path::parent_path(ModuleFileName); 1438 llvm::sys::fs::create_directories(Dir); 1439 1440 while (true) { 1441 llvm::LockFileManager Locked(ModuleFileName); 1442 switch (Locked) { 1443 case llvm::LockFileManager::LFS_Error: 1444 // ModuleCache takes care of correctness and locks are only necessary for 1445 // performance. Fallback to building the module in case of any lock 1446 // related errors. 1447 Diags.Report(ModuleNameLoc, diag::remark_module_lock_failure) 1448 << Module->Name << Locked.getErrorMessage(); 1449 // Clear out any potential leftover. 1450 Locked.unsafeRemoveLockFile(); 1451 [[fallthrough]]; 1452 case llvm::LockFileManager::LFS_Owned: 1453 // We're responsible for building the module ourselves. 1454 return compileModuleAndReadASTImpl(ImportingInstance, ImportLoc, 1455 ModuleNameLoc, Module, ModuleFileName); 1456 1457 case llvm::LockFileManager::LFS_Shared: 1458 break; // The interesting case. 1459 } 1460 1461 // Someone else is responsible for building the module. Wait for them to 1462 // finish. 1463 switch (Locked.waitForUnlock()) { 1464 case llvm::LockFileManager::Res_Success: 1465 break; // The interesting case. 1466 case llvm::LockFileManager::Res_OwnerDied: 1467 continue; // try again to get the lock. 1468 case llvm::LockFileManager::Res_Timeout: 1469 // Since ModuleCache takes care of correctness, we try waiting for 1470 // another process to complete the build so clang does not do it done 1471 // twice. If case of timeout, build it ourselves. 1472 Diags.Report(ModuleNameLoc, diag::remark_module_lock_timeout) 1473 << Module->Name; 1474 // Clear the lock file so that future invocations can make progress. 1475 Locked.unsafeRemoveLockFile(); 1476 continue; 1477 } 1478 1479 // Read the module that was just written by someone else. 1480 bool OutOfDate = false; 1481 if (readASTAfterCompileModule(ImportingInstance, ImportLoc, ModuleNameLoc, 1482 Module, ModuleFileName, &OutOfDate)) 1483 return true; 1484 if (!OutOfDate) 1485 return false; 1486 1487 // The module may be out of date in the presence of file system races, 1488 // or if one of its imports depends on header search paths that are not 1489 // consistent with this ImportingInstance. Try again... 1490 } 1491 } 1492 1493 /// Compile a module in a separate compiler instance and read the AST, 1494 /// returning true if the module compiles without errors, potentially using a 1495 /// lock manager to avoid building the same module in multiple compiler 1496 /// instances. 1497 static bool compileModuleAndReadAST(CompilerInstance &ImportingInstance, 1498 SourceLocation ImportLoc, 1499 SourceLocation ModuleNameLoc, 1500 Module *Module, StringRef ModuleFileName) { 1501 return ImportingInstance.getInvocation() 1502 .getFrontendOpts() 1503 .BuildingImplicitModuleUsesLock 1504 ? compileModuleAndReadASTBehindLock(ImportingInstance, ImportLoc, 1505 ModuleNameLoc, Module, 1506 ModuleFileName) 1507 : compileModuleAndReadASTImpl(ImportingInstance, ImportLoc, 1508 ModuleNameLoc, Module, 1509 ModuleFileName); 1510 } 1511 1512 /// Diagnose differences between the current definition of the given 1513 /// configuration macro and the definition provided on the command line. 1514 static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro, 1515 Module *Mod, SourceLocation ImportLoc) { 1516 IdentifierInfo *Id = PP.getIdentifierInfo(ConfigMacro); 1517 SourceManager &SourceMgr = PP.getSourceManager(); 1518 1519 // If this identifier has never had a macro definition, then it could 1520 // not have changed. 1521 if (!Id->hadMacroDefinition()) 1522 return; 1523 auto *LatestLocalMD = PP.getLocalMacroDirectiveHistory(Id); 1524 1525 // Find the macro definition from the command line. 1526 MacroInfo *CmdLineDefinition = nullptr; 1527 for (auto *MD = LatestLocalMD; MD; MD = MD->getPrevious()) { 1528 // We only care about the predefines buffer. 1529 FileID FID = SourceMgr.getFileID(MD->getLocation()); 1530 if (FID.isInvalid() || FID != PP.getPredefinesFileID()) 1531 continue; 1532 if (auto *DMD = dyn_cast<DefMacroDirective>(MD)) 1533 CmdLineDefinition = DMD->getMacroInfo(); 1534 break; 1535 } 1536 1537 auto *CurrentDefinition = PP.getMacroInfo(Id); 1538 if (CurrentDefinition == CmdLineDefinition) { 1539 // Macro matches. Nothing to do. 1540 } else if (!CurrentDefinition) { 1541 // This macro was defined on the command line, then #undef'd later. 1542 // Complain. 1543 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef) 1544 << true << ConfigMacro << Mod->getFullModuleName(); 1545 auto LatestDef = LatestLocalMD->getDefinition(); 1546 assert(LatestDef.isUndefined() && 1547 "predefined macro went away with no #undef?"); 1548 PP.Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here) 1549 << true; 1550 return; 1551 } else if (!CmdLineDefinition) { 1552 // There was no definition for this macro in the predefines buffer, 1553 // but there was a local definition. Complain. 1554 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef) 1555 << false << ConfigMacro << Mod->getFullModuleName(); 1556 PP.Diag(CurrentDefinition->getDefinitionLoc(), 1557 diag::note_module_def_undef_here) 1558 << false; 1559 } else if (!CurrentDefinition->isIdenticalTo(*CmdLineDefinition, PP, 1560 /*Syntactically=*/true)) { 1561 // The macro definitions differ. 1562 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef) 1563 << false << ConfigMacro << Mod->getFullModuleName(); 1564 PP.Diag(CurrentDefinition->getDefinitionLoc(), 1565 diag::note_module_def_undef_here) 1566 << false; 1567 } 1568 } 1569 1570 /// Write a new timestamp file with the given path. 1571 static void writeTimestampFile(StringRef TimestampFile) { 1572 std::error_code EC; 1573 llvm::raw_fd_ostream Out(TimestampFile.str(), EC, llvm::sys::fs::OF_None); 1574 } 1575 1576 /// Prune the module cache of modules that haven't been accessed in 1577 /// a long time. 1578 static void pruneModuleCache(const HeaderSearchOptions &HSOpts) { 1579 llvm::sys::fs::file_status StatBuf; 1580 llvm::SmallString<128> TimestampFile; 1581 TimestampFile = HSOpts.ModuleCachePath; 1582 assert(!TimestampFile.empty()); 1583 llvm::sys::path::append(TimestampFile, "modules.timestamp"); 1584 1585 // Try to stat() the timestamp file. 1586 if (std::error_code EC = llvm::sys::fs::status(TimestampFile, StatBuf)) { 1587 // If the timestamp file wasn't there, create one now. 1588 if (EC == std::errc::no_such_file_or_directory) { 1589 writeTimestampFile(TimestampFile); 1590 } 1591 return; 1592 } 1593 1594 // Check whether the time stamp is older than our pruning interval. 1595 // If not, do nothing. 1596 time_t TimeStampModTime = 1597 llvm::sys::toTimeT(StatBuf.getLastModificationTime()); 1598 time_t CurrentTime = time(nullptr); 1599 if (CurrentTime - TimeStampModTime <= time_t(HSOpts.ModuleCachePruneInterval)) 1600 return; 1601 1602 // Write a new timestamp file so that nobody else attempts to prune. 1603 // There is a benign race condition here, if two Clang instances happen to 1604 // notice at the same time that the timestamp is out-of-date. 1605 writeTimestampFile(TimestampFile); 1606 1607 // Walk the entire module cache, looking for unused module files and module 1608 // indices. 1609 std::error_code EC; 1610 SmallString<128> ModuleCachePathNative; 1611 llvm::sys::path::native(HSOpts.ModuleCachePath, ModuleCachePathNative); 1612 for (llvm::sys::fs::directory_iterator Dir(ModuleCachePathNative, EC), DirEnd; 1613 Dir != DirEnd && !EC; Dir.increment(EC)) { 1614 // If we don't have a directory, there's nothing to look into. 1615 if (!llvm::sys::fs::is_directory(Dir->path())) 1616 continue; 1617 1618 // Walk all of the files within this directory. 1619 for (llvm::sys::fs::directory_iterator File(Dir->path(), EC), FileEnd; 1620 File != FileEnd && !EC; File.increment(EC)) { 1621 // We only care about module and global module index files. 1622 StringRef Extension = llvm::sys::path::extension(File->path()); 1623 if (Extension != ".pcm" && Extension != ".timestamp" && 1624 llvm::sys::path::filename(File->path()) != "modules.idx") 1625 continue; 1626 1627 // Look at this file. If we can't stat it, there's nothing interesting 1628 // there. 1629 if (llvm::sys::fs::status(File->path(), StatBuf)) 1630 continue; 1631 1632 // If the file has been used recently enough, leave it there. 1633 time_t FileAccessTime = llvm::sys::toTimeT(StatBuf.getLastAccessedTime()); 1634 if (CurrentTime - FileAccessTime <= 1635 time_t(HSOpts.ModuleCachePruneAfter)) { 1636 continue; 1637 } 1638 1639 // Remove the file. 1640 llvm::sys::fs::remove(File->path()); 1641 1642 // Remove the timestamp file. 1643 std::string TimpestampFilename = File->path() + ".timestamp"; 1644 llvm::sys::fs::remove(TimpestampFilename); 1645 } 1646 1647 // If we removed all of the files in the directory, remove the directory 1648 // itself. 1649 if (llvm::sys::fs::directory_iterator(Dir->path(), EC) == 1650 llvm::sys::fs::directory_iterator() && !EC) 1651 llvm::sys::fs::remove(Dir->path()); 1652 } 1653 } 1654 1655 void CompilerInstance::createASTReader() { 1656 if (TheASTReader) 1657 return; 1658 1659 if (!hasASTContext()) 1660 createASTContext(); 1661 1662 // If we're implicitly building modules but not currently recursively 1663 // building a module, check whether we need to prune the module cache. 1664 if (getSourceManager().getModuleBuildStack().empty() && 1665 !getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty() && 1666 getHeaderSearchOpts().ModuleCachePruneInterval > 0 && 1667 getHeaderSearchOpts().ModuleCachePruneAfter > 0) { 1668 pruneModuleCache(getHeaderSearchOpts()); 1669 } 1670 1671 HeaderSearchOptions &HSOpts = getHeaderSearchOpts(); 1672 std::string Sysroot = HSOpts.Sysroot; 1673 const PreprocessorOptions &PPOpts = getPreprocessorOpts(); 1674 const FrontendOptions &FEOpts = getFrontendOpts(); 1675 std::unique_ptr<llvm::Timer> ReadTimer; 1676 1677 if (FrontendTimerGroup) 1678 ReadTimer = std::make_unique<llvm::Timer>("reading_modules", 1679 "Reading modules", 1680 *FrontendTimerGroup); 1681 TheASTReader = new ASTReader( 1682 getPreprocessor(), getModuleCache(), &getASTContext(), 1683 getPCHContainerReader(), getFrontendOpts().ModuleFileExtensions, 1684 Sysroot.empty() ? "" : Sysroot.c_str(), 1685 PPOpts.DisablePCHOrModuleValidation, 1686 /*AllowASTWithCompilerErrors=*/FEOpts.AllowPCMWithCompilerErrors, 1687 /*AllowConfigurationMismatch=*/false, HSOpts.ModulesValidateSystemHeaders, 1688 HSOpts.ValidateASTInputFilesContent, 1689 getFrontendOpts().UseGlobalModuleIndex, std::move(ReadTimer)); 1690 if (hasASTConsumer()) { 1691 TheASTReader->setDeserializationListener( 1692 getASTConsumer().GetASTDeserializationListener()); 1693 getASTContext().setASTMutationListener( 1694 getASTConsumer().GetASTMutationListener()); 1695 } 1696 getASTContext().setExternalSource(TheASTReader); 1697 if (hasSema()) 1698 TheASTReader->InitializeSema(getSema()); 1699 if (hasASTConsumer()) 1700 TheASTReader->StartTranslationUnit(&getASTConsumer()); 1701 1702 for (auto &Listener : DependencyCollectors) 1703 Listener->attachToASTReader(*TheASTReader); 1704 } 1705 1706 bool CompilerInstance::loadModuleFile(StringRef FileName) { 1707 llvm::Timer Timer; 1708 if (FrontendTimerGroup) 1709 Timer.init("preloading." + FileName.str(), "Preloading " + FileName.str(), 1710 *FrontendTimerGroup); 1711 llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer : nullptr); 1712 1713 // If we don't already have an ASTReader, create one now. 1714 if (!TheASTReader) 1715 createASTReader(); 1716 1717 // If -Wmodule-file-config-mismatch is mapped as an error or worse, allow the 1718 // ASTReader to diagnose it, since it can produce better errors that we can. 1719 bool ConfigMismatchIsRecoverable = 1720 getDiagnostics().getDiagnosticLevel(diag::warn_module_config_mismatch, 1721 SourceLocation()) 1722 <= DiagnosticsEngine::Warning; 1723 1724 auto Listener = std::make_unique<ReadModuleNames>(*PP); 1725 auto &ListenerRef = *Listener; 1726 ASTReader::ListenerScope ReadModuleNamesListener(*TheASTReader, 1727 std::move(Listener)); 1728 1729 // Try to load the module file. 1730 switch (TheASTReader->ReadAST( 1731 FileName, serialization::MK_ExplicitModule, SourceLocation(), 1732 ConfigMismatchIsRecoverable ? ASTReader::ARR_ConfigurationMismatch : 0)) { 1733 case ASTReader::Success: 1734 // We successfully loaded the module file; remember the set of provided 1735 // modules so that we don't try to load implicit modules for them. 1736 ListenerRef.registerAll(); 1737 return true; 1738 1739 case ASTReader::ConfigurationMismatch: 1740 // Ignore unusable module files. 1741 getDiagnostics().Report(SourceLocation(), diag::warn_module_config_mismatch) 1742 << FileName; 1743 // All modules provided by any files we tried and failed to load are now 1744 // unavailable; includes of those modules should now be handled textually. 1745 ListenerRef.markAllUnavailable(); 1746 return true; 1747 1748 default: 1749 return false; 1750 } 1751 } 1752 1753 namespace { 1754 enum ModuleSource { 1755 MS_ModuleNotFound, 1756 MS_ModuleCache, 1757 MS_PrebuiltModulePath, 1758 MS_ModuleBuildPragma 1759 }; 1760 } // end namespace 1761 1762 /// Select a source for loading the named module and compute the filename to 1763 /// load it from. 1764 static ModuleSource selectModuleSource( 1765 Module *M, StringRef ModuleName, std::string &ModuleFilename, 1766 const std::map<std::string, std::string, std::less<>> &BuiltModules, 1767 HeaderSearch &HS) { 1768 assert(ModuleFilename.empty() && "Already has a module source?"); 1769 1770 // Check to see if the module has been built as part of this compilation 1771 // via a module build pragma. 1772 auto BuiltModuleIt = BuiltModules.find(ModuleName); 1773 if (BuiltModuleIt != BuiltModules.end()) { 1774 ModuleFilename = BuiltModuleIt->second; 1775 return MS_ModuleBuildPragma; 1776 } 1777 1778 // Try to load the module from the prebuilt module path. 1779 const HeaderSearchOptions &HSOpts = HS.getHeaderSearchOpts(); 1780 if (!HSOpts.PrebuiltModuleFiles.empty() || 1781 !HSOpts.PrebuiltModulePaths.empty()) { 1782 ModuleFilename = HS.getPrebuiltModuleFileName(ModuleName); 1783 if (HSOpts.EnablePrebuiltImplicitModules && ModuleFilename.empty()) 1784 ModuleFilename = HS.getPrebuiltImplicitModuleFileName(M); 1785 if (!ModuleFilename.empty()) 1786 return MS_PrebuiltModulePath; 1787 } 1788 1789 // Try to load the module from the module cache. 1790 if (M) { 1791 ModuleFilename = HS.getCachedModuleFileName(M); 1792 return MS_ModuleCache; 1793 } 1794 1795 return MS_ModuleNotFound; 1796 } 1797 1798 ModuleLoadResult CompilerInstance::findOrCompileModuleAndReadAST( 1799 StringRef ModuleName, SourceLocation ImportLoc, 1800 SourceLocation ModuleNameLoc, bool IsInclusionDirective) { 1801 // Search for a module with the given name. 1802 HeaderSearch &HS = PP->getHeaderSearchInfo(); 1803 Module *M = 1804 HS.lookupModule(ModuleName, ImportLoc, true, !IsInclusionDirective); 1805 1806 // Select the source and filename for loading the named module. 1807 std::string ModuleFilename; 1808 ModuleSource Source = 1809 selectModuleSource(M, ModuleName, ModuleFilename, BuiltModules, HS); 1810 if (Source == MS_ModuleNotFound) { 1811 // We can't find a module, error out here. 1812 getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found) 1813 << ModuleName << SourceRange(ImportLoc, ModuleNameLoc); 1814 return nullptr; 1815 } 1816 if (ModuleFilename.empty()) { 1817 if (M && M->HasIncompatibleModuleFile) { 1818 // We tried and failed to load a module file for this module. Fall 1819 // back to textual inclusion for its headers. 1820 return ModuleLoadResult::ConfigMismatch; 1821 } 1822 1823 getDiagnostics().Report(ModuleNameLoc, diag::err_module_build_disabled) 1824 << ModuleName; 1825 return nullptr; 1826 } 1827 1828 // Create an ASTReader on demand. 1829 if (!getASTReader()) 1830 createASTReader(); 1831 1832 // Time how long it takes to load the module. 1833 llvm::Timer Timer; 1834 if (FrontendTimerGroup) 1835 Timer.init("loading." + ModuleFilename, "Loading " + ModuleFilename, 1836 *FrontendTimerGroup); 1837 llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer : nullptr); 1838 llvm::TimeTraceScope TimeScope("Module Load", ModuleName); 1839 1840 // Try to load the module file. If we are not trying to load from the 1841 // module cache, we don't know how to rebuild modules. 1842 unsigned ARRFlags = Source == MS_ModuleCache 1843 ? ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing | 1844 ASTReader::ARR_TreatModuleWithErrorsAsOutOfDate 1845 : Source == MS_PrebuiltModulePath 1846 ? 0 1847 : ASTReader::ARR_ConfigurationMismatch; 1848 switch (getASTReader()->ReadAST(ModuleFilename, 1849 Source == MS_PrebuiltModulePath 1850 ? serialization::MK_PrebuiltModule 1851 : Source == MS_ModuleBuildPragma 1852 ? serialization::MK_ExplicitModule 1853 : serialization::MK_ImplicitModule, 1854 ImportLoc, ARRFlags)) { 1855 case ASTReader::Success: { 1856 if (M) 1857 return M; 1858 assert(Source != MS_ModuleCache && 1859 "missing module, but file loaded from cache"); 1860 1861 // A prebuilt module is indexed as a ModuleFile; the Module does not exist 1862 // until the first call to ReadAST. Look it up now. 1863 M = HS.lookupModule(ModuleName, ImportLoc, true, !IsInclusionDirective); 1864 1865 // Check whether M refers to the file in the prebuilt module path. 1866 if (M && M->getASTFile()) 1867 if (auto ModuleFile = FileMgr->getFile(ModuleFilename)) 1868 if (*ModuleFile == M->getASTFile()) 1869 return M; 1870 1871 getDiagnostics().Report(ModuleNameLoc, diag::err_module_prebuilt) 1872 << ModuleName; 1873 return ModuleLoadResult(); 1874 } 1875 1876 case ASTReader::OutOfDate: 1877 case ASTReader::Missing: 1878 // The most interesting case. 1879 break; 1880 1881 case ASTReader::ConfigurationMismatch: 1882 if (Source == MS_PrebuiltModulePath) 1883 // FIXME: We shouldn't be setting HadFatalFailure below if we only 1884 // produce a warning here! 1885 getDiagnostics().Report(SourceLocation(), 1886 diag::warn_module_config_mismatch) 1887 << ModuleFilename; 1888 // Fall through to error out. 1889 [[fallthrough]]; 1890 case ASTReader::VersionMismatch: 1891 case ASTReader::HadErrors: 1892 ModuleLoader::HadFatalFailure = true; 1893 // FIXME: The ASTReader will already have complained, but can we shoehorn 1894 // that diagnostic information into a more useful form? 1895 return ModuleLoadResult(); 1896 1897 case ASTReader::Failure: 1898 ModuleLoader::HadFatalFailure = true; 1899 return ModuleLoadResult(); 1900 } 1901 1902 // ReadAST returned Missing or OutOfDate. 1903 if (Source != MS_ModuleCache) { 1904 // We don't know the desired configuration for this module and don't 1905 // necessarily even have a module map. Since ReadAST already produces 1906 // diagnostics for these two cases, we simply error out here. 1907 return ModuleLoadResult(); 1908 } 1909 1910 // The module file is missing or out-of-date. Build it. 1911 assert(M && "missing module, but trying to compile for cache"); 1912 1913 // Check whether there is a cycle in the module graph. 1914 ModuleBuildStack ModPath = getSourceManager().getModuleBuildStack(); 1915 ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end(); 1916 for (; Pos != PosEnd; ++Pos) { 1917 if (Pos->first == ModuleName) 1918 break; 1919 } 1920 1921 if (Pos != PosEnd) { 1922 SmallString<256> CyclePath; 1923 for (; Pos != PosEnd; ++Pos) { 1924 CyclePath += Pos->first; 1925 CyclePath += " -> "; 1926 } 1927 CyclePath += ModuleName; 1928 1929 getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle) 1930 << ModuleName << CyclePath; 1931 return nullptr; 1932 } 1933 1934 // Check whether we have already attempted to build this module (but 1935 // failed). 1936 if (getPreprocessorOpts().FailedModules && 1937 getPreprocessorOpts().FailedModules->hasAlreadyFailed(ModuleName)) { 1938 getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built) 1939 << ModuleName << SourceRange(ImportLoc, ModuleNameLoc); 1940 return nullptr; 1941 } 1942 1943 // Try to compile and then read the AST. 1944 if (!compileModuleAndReadAST(*this, ImportLoc, ModuleNameLoc, M, 1945 ModuleFilename)) { 1946 assert(getDiagnostics().hasErrorOccurred() && 1947 "undiagnosed error in compileModuleAndReadAST"); 1948 if (getPreprocessorOpts().FailedModules) 1949 getPreprocessorOpts().FailedModules->addFailed(ModuleName); 1950 return nullptr; 1951 } 1952 1953 // Okay, we've rebuilt and now loaded the module. 1954 return M; 1955 } 1956 1957 ModuleLoadResult 1958 CompilerInstance::loadModule(SourceLocation ImportLoc, 1959 ModuleIdPath Path, 1960 Module::NameVisibilityKind Visibility, 1961 bool IsInclusionDirective) { 1962 // Determine what file we're searching from. 1963 StringRef ModuleName = Path[0].first->getName(); 1964 SourceLocation ModuleNameLoc = Path[0].second; 1965 1966 // If we've already handled this import, just return the cached result. 1967 // This one-element cache is important to eliminate redundant diagnostics 1968 // when both the preprocessor and parser see the same import declaration. 1969 if (ImportLoc.isValid() && LastModuleImportLoc == ImportLoc) { 1970 // Make the named module visible. 1971 if (LastModuleImportResult && ModuleName != getLangOpts().CurrentModule) 1972 TheASTReader->makeModuleVisible(LastModuleImportResult, Visibility, 1973 ImportLoc); 1974 return LastModuleImportResult; 1975 } 1976 1977 // If we don't already have information on this module, load the module now. 1978 Module *Module = nullptr; 1979 ModuleMap &MM = getPreprocessor().getHeaderSearchInfo().getModuleMap(); 1980 if (auto MaybeModule = MM.getCachedModuleLoad(*Path[0].first)) { 1981 // Use the cached result, which may be nullptr. 1982 Module = *MaybeModule; 1983 } else if (ModuleName == getLangOpts().CurrentModule) { 1984 // This is the module we're building. 1985 Module = PP->getHeaderSearchInfo().lookupModule( 1986 ModuleName, ImportLoc, /*AllowSearch*/ true, 1987 /*AllowExtraModuleMapSearch*/ !IsInclusionDirective); 1988 /// FIXME: perhaps we should (a) look for a module using the module name 1989 // to file map (PrebuiltModuleFiles) and (b) diagnose if still not found? 1990 //if (Module == nullptr) { 1991 // getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found) 1992 // << ModuleName; 1993 // DisableGeneratingGlobalModuleIndex = true; 1994 // return ModuleLoadResult(); 1995 //} 1996 MM.cacheModuleLoad(*Path[0].first, Module); 1997 } else { 1998 ModuleLoadResult Result = findOrCompileModuleAndReadAST( 1999 ModuleName, ImportLoc, ModuleNameLoc, IsInclusionDirective); 2000 if (!Result.isNormal()) 2001 return Result; 2002 if (!Result) 2003 DisableGeneratingGlobalModuleIndex = true; 2004 Module = Result; 2005 MM.cacheModuleLoad(*Path[0].first, Module); 2006 } 2007 2008 // If we never found the module, fail. Otherwise, verify the module and link 2009 // it up. 2010 if (!Module) 2011 return ModuleLoadResult(); 2012 2013 // Verify that the rest of the module path actually corresponds to 2014 // a submodule. 2015 bool MapPrivateSubModToTopLevel = false; 2016 for (unsigned I = 1, N = Path.size(); I != N; ++I) { 2017 StringRef Name = Path[I].first->getName(); 2018 clang::Module *Sub = Module->findSubmodule(Name); 2019 2020 // If the user is requesting Foo.Private and it doesn't exist, try to 2021 // match Foo_Private and emit a warning asking for the user to write 2022 // @import Foo_Private instead. FIXME: remove this when existing clients 2023 // migrate off of Foo.Private syntax. 2024 if (!Sub && Name == "Private" && Module == Module->getTopLevelModule()) { 2025 SmallString<128> PrivateModule(Module->Name); 2026 PrivateModule.append("_Private"); 2027 2028 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> PrivPath; 2029 auto &II = PP->getIdentifierTable().get( 2030 PrivateModule, PP->getIdentifierInfo(Module->Name)->getTokenID()); 2031 PrivPath.push_back(std::make_pair(&II, Path[0].second)); 2032 2033 if (PP->getHeaderSearchInfo().lookupModule(PrivateModule, ImportLoc, true, 2034 !IsInclusionDirective)) 2035 Sub = loadModule(ImportLoc, PrivPath, Visibility, IsInclusionDirective); 2036 if (Sub) { 2037 MapPrivateSubModToTopLevel = true; 2038 PP->markModuleAsAffecting(Module); 2039 if (!getDiagnostics().isIgnored( 2040 diag::warn_no_priv_submodule_use_toplevel, ImportLoc)) { 2041 getDiagnostics().Report(Path[I].second, 2042 diag::warn_no_priv_submodule_use_toplevel) 2043 << Path[I].first << Module->getFullModuleName() << PrivateModule 2044 << SourceRange(Path[0].second, Path[I].second) 2045 << FixItHint::CreateReplacement(SourceRange(Path[0].second), 2046 PrivateModule); 2047 getDiagnostics().Report(Sub->DefinitionLoc, 2048 diag::note_private_top_level_defined); 2049 } 2050 } 2051 } 2052 2053 if (!Sub) { 2054 // Attempt to perform typo correction to find a module name that works. 2055 SmallVector<StringRef, 2> Best; 2056 unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)(); 2057 2058 for (class Module *SubModule : Module->submodules()) { 2059 unsigned ED = 2060 Name.edit_distance(SubModule->Name, 2061 /*AllowReplacements=*/true, BestEditDistance); 2062 if (ED <= BestEditDistance) { 2063 if (ED < BestEditDistance) { 2064 Best.clear(); 2065 BestEditDistance = ED; 2066 } 2067 2068 Best.push_back(SubModule->Name); 2069 } 2070 } 2071 2072 // If there was a clear winner, user it. 2073 if (Best.size() == 1) { 2074 getDiagnostics().Report(Path[I].second, diag::err_no_submodule_suggest) 2075 << Path[I].first << Module->getFullModuleName() << Best[0] 2076 << SourceRange(Path[0].second, Path[I - 1].second) 2077 << FixItHint::CreateReplacement(SourceRange(Path[I].second), 2078 Best[0]); 2079 2080 Sub = Module->findSubmodule(Best[0]); 2081 } 2082 } 2083 2084 if (!Sub) { 2085 // No submodule by this name. Complain, and don't look for further 2086 // submodules. 2087 getDiagnostics().Report(Path[I].second, diag::err_no_submodule) 2088 << Path[I].first << Module->getFullModuleName() 2089 << SourceRange(Path[0].second, Path[I - 1].second); 2090 break; 2091 } 2092 2093 Module = Sub; 2094 } 2095 2096 // Make the named module visible, if it's not already part of the module 2097 // we are parsing. 2098 if (ModuleName != getLangOpts().CurrentModule) { 2099 if (!Module->IsFromModuleFile && !MapPrivateSubModToTopLevel) { 2100 // We have an umbrella header or directory that doesn't actually include 2101 // all of the headers within the directory it covers. Complain about 2102 // this missing submodule and recover by forgetting that we ever saw 2103 // this submodule. 2104 // FIXME: Should we detect this at module load time? It seems fairly 2105 // expensive (and rare). 2106 getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule) 2107 << Module->getFullModuleName() 2108 << SourceRange(Path.front().second, Path.back().second); 2109 2110 return ModuleLoadResult(Module, ModuleLoadResult::MissingExpected); 2111 } 2112 2113 // Check whether this module is available. 2114 if (Preprocessor::checkModuleIsAvailable(getLangOpts(), getTarget(), 2115 getDiagnostics(), Module)) { 2116 getDiagnostics().Report(ImportLoc, diag::note_module_import_here) 2117 << SourceRange(Path.front().second, Path.back().second); 2118 LastModuleImportLoc = ImportLoc; 2119 LastModuleImportResult = ModuleLoadResult(); 2120 return ModuleLoadResult(); 2121 } 2122 2123 TheASTReader->makeModuleVisible(Module, Visibility, ImportLoc); 2124 } 2125 2126 // Check for any configuration macros that have changed. 2127 clang::Module *TopModule = Module->getTopLevelModule(); 2128 for (unsigned I = 0, N = TopModule->ConfigMacros.size(); I != N; ++I) { 2129 checkConfigMacro(getPreprocessor(), TopModule->ConfigMacros[I], 2130 Module, ImportLoc); 2131 } 2132 2133 // Resolve any remaining module using export_as for this one. 2134 getPreprocessor() 2135 .getHeaderSearchInfo() 2136 .getModuleMap() 2137 .resolveLinkAsDependencies(TopModule); 2138 2139 LastModuleImportLoc = ImportLoc; 2140 LastModuleImportResult = ModuleLoadResult(Module); 2141 return LastModuleImportResult; 2142 } 2143 2144 void CompilerInstance::createModuleFromSource(SourceLocation ImportLoc, 2145 StringRef ModuleName, 2146 StringRef Source) { 2147 // Avoid creating filenames with special characters. 2148 SmallString<128> CleanModuleName(ModuleName); 2149 for (auto &C : CleanModuleName) 2150 if (!isAlphanumeric(C)) 2151 C = '_'; 2152 2153 // FIXME: Using a randomized filename here means that our intermediate .pcm 2154 // output is nondeterministic (as .pcm files refer to each other by name). 2155 // Can this affect the output in any way? 2156 SmallString<128> ModuleFileName; 2157 if (std::error_code EC = llvm::sys::fs::createTemporaryFile( 2158 CleanModuleName, "pcm", ModuleFileName)) { 2159 getDiagnostics().Report(ImportLoc, diag::err_fe_unable_to_open_output) 2160 << ModuleFileName << EC.message(); 2161 return; 2162 } 2163 std::string ModuleMapFileName = (CleanModuleName + ".map").str(); 2164 2165 FrontendInputFile Input( 2166 ModuleMapFileName, 2167 InputKind(getLanguageFromOptions(*Invocation->getLangOpts()), 2168 InputKind::ModuleMap, /*Preprocessed*/true)); 2169 2170 std::string NullTerminatedSource(Source.str()); 2171 2172 auto PreBuildStep = [&](CompilerInstance &Other) { 2173 // Create a virtual file containing our desired source. 2174 // FIXME: We shouldn't need to do this. 2175 const FileEntry *ModuleMapFile = Other.getFileManager().getVirtualFile( 2176 ModuleMapFileName, NullTerminatedSource.size(), 0); 2177 Other.getSourceManager().overrideFileContents( 2178 ModuleMapFile, llvm::MemoryBuffer::getMemBuffer(NullTerminatedSource)); 2179 2180 Other.BuiltModules = std::move(BuiltModules); 2181 Other.DeleteBuiltModules = false; 2182 }; 2183 2184 auto PostBuildStep = [this](CompilerInstance &Other) { 2185 BuiltModules = std::move(Other.BuiltModules); 2186 }; 2187 2188 // Build the module, inheriting any modules that we've built locally. 2189 if (compileModuleImpl(*this, ImportLoc, ModuleName, Input, StringRef(), 2190 ModuleFileName, PreBuildStep, PostBuildStep)) { 2191 BuiltModules[std::string(ModuleName)] = std::string(ModuleFileName.str()); 2192 llvm::sys::RemoveFileOnSignal(ModuleFileName); 2193 } 2194 } 2195 2196 void CompilerInstance::makeModuleVisible(Module *Mod, 2197 Module::NameVisibilityKind Visibility, 2198 SourceLocation ImportLoc) { 2199 if (!TheASTReader) 2200 createASTReader(); 2201 if (!TheASTReader) 2202 return; 2203 2204 TheASTReader->makeModuleVisible(Mod, Visibility, ImportLoc); 2205 } 2206 2207 GlobalModuleIndex *CompilerInstance::loadGlobalModuleIndex( 2208 SourceLocation TriggerLoc) { 2209 if (getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty()) 2210 return nullptr; 2211 if (!TheASTReader) 2212 createASTReader(); 2213 // Can't do anything if we don't have the module manager. 2214 if (!TheASTReader) 2215 return nullptr; 2216 // Get an existing global index. This loads it if not already 2217 // loaded. 2218 TheASTReader->loadGlobalIndex(); 2219 GlobalModuleIndex *GlobalIndex = TheASTReader->getGlobalIndex(); 2220 // If the global index doesn't exist, create it. 2221 if (!GlobalIndex && shouldBuildGlobalModuleIndex() && hasFileManager() && 2222 hasPreprocessor()) { 2223 llvm::sys::fs::create_directories( 2224 getPreprocessor().getHeaderSearchInfo().getModuleCachePath()); 2225 if (llvm::Error Err = GlobalModuleIndex::writeIndex( 2226 getFileManager(), getPCHContainerReader(), 2227 getPreprocessor().getHeaderSearchInfo().getModuleCachePath())) { 2228 // FIXME this drops the error on the floor. This code is only used for 2229 // typo correction and drops more than just this one source of errors 2230 // (such as the directory creation failure above). It should handle the 2231 // error. 2232 consumeError(std::move(Err)); 2233 return nullptr; 2234 } 2235 TheASTReader->resetForReload(); 2236 TheASTReader->loadGlobalIndex(); 2237 GlobalIndex = TheASTReader->getGlobalIndex(); 2238 } 2239 // For finding modules needing to be imported for fixit messages, 2240 // we need to make the global index cover all modules, so we do that here. 2241 if (!HaveFullGlobalModuleIndex && GlobalIndex && !buildingModule()) { 2242 ModuleMap &MMap = getPreprocessor().getHeaderSearchInfo().getModuleMap(); 2243 bool RecreateIndex = false; 2244 for (ModuleMap::module_iterator I = MMap.module_begin(), 2245 E = MMap.module_end(); I != E; ++I) { 2246 Module *TheModule = I->second; 2247 const FileEntry *Entry = TheModule->getASTFile(); 2248 if (!Entry) { 2249 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path; 2250 Path.push_back(std::make_pair( 2251 getPreprocessor().getIdentifierInfo(TheModule->Name), TriggerLoc)); 2252 std::reverse(Path.begin(), Path.end()); 2253 // Load a module as hidden. This also adds it to the global index. 2254 loadModule(TheModule->DefinitionLoc, Path, Module::Hidden, false); 2255 RecreateIndex = true; 2256 } 2257 } 2258 if (RecreateIndex) { 2259 if (llvm::Error Err = GlobalModuleIndex::writeIndex( 2260 getFileManager(), getPCHContainerReader(), 2261 getPreprocessor().getHeaderSearchInfo().getModuleCachePath())) { 2262 // FIXME As above, this drops the error on the floor. 2263 consumeError(std::move(Err)); 2264 return nullptr; 2265 } 2266 TheASTReader->resetForReload(); 2267 TheASTReader->loadGlobalIndex(); 2268 GlobalIndex = TheASTReader->getGlobalIndex(); 2269 } 2270 HaveFullGlobalModuleIndex = true; 2271 } 2272 return GlobalIndex; 2273 } 2274 2275 // Check global module index for missing imports. 2276 bool 2277 CompilerInstance::lookupMissingImports(StringRef Name, 2278 SourceLocation TriggerLoc) { 2279 // Look for the symbol in non-imported modules, but only if an error 2280 // actually occurred. 2281 if (!buildingModule()) { 2282 // Load global module index, or retrieve a previously loaded one. 2283 GlobalModuleIndex *GlobalIndex = loadGlobalModuleIndex( 2284 TriggerLoc); 2285 2286 // Only if we have a global index. 2287 if (GlobalIndex) { 2288 GlobalModuleIndex::HitSet FoundModules; 2289 2290 // Find the modules that reference the identifier. 2291 // Note that this only finds top-level modules. 2292 // We'll let diagnoseTypo find the actual declaration module. 2293 if (GlobalIndex->lookupIdentifier(Name, FoundModules)) 2294 return true; 2295 } 2296 } 2297 2298 return false; 2299 } 2300 void CompilerInstance::resetAndLeakSema() { llvm::BuryPointer(takeSema()); } 2301 2302 void CompilerInstance::setExternalSemaSource( 2303 IntrusiveRefCntPtr<ExternalSemaSource> ESS) { 2304 ExternalSemaSrc = std::move(ESS); 2305 } 2306