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