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