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 #define DEBUG_TYPE "modules" 59 60 ALWAYS_ENABLED_STATISTIC(NumCompiledModules, "Number of compiled modules."); 61 62 CompilerInstance::CompilerInstance( 63 std::shared_ptr<PCHContainerOperations> PCHContainerOps, 64 InMemoryModuleCache *SharedModuleCache) 65 : ModuleLoader(/* BuildingModule = */ SharedModuleCache), 66 Invocation(new CompilerInvocation()), 67 ModuleCache(SharedModuleCache ? SharedModuleCache 68 : new InMemoryModuleCache), 69 ThePCHContainerOperations(std::move(PCHContainerOps)) {} 70 71 CompilerInstance::~CompilerInstance() { 72 assert(OutputFiles.empty() && "Still output files in flight?"); 73 } 74 75 void CompilerInstance::setInvocation( 76 std::shared_ptr<CompilerInvocation> Value) { 77 Invocation = std::move(Value); 78 } 79 80 bool CompilerInstance::shouldBuildGlobalModuleIndex() const { 81 return (BuildGlobalModuleIndex || 82 (TheASTReader && TheASTReader->isGlobalIndexUnavailable() && 83 getFrontendOpts().GenerateGlobalModuleIndex)) && 84 !ModuleBuildFailed; 85 } 86 87 void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) { 88 Diagnostics = Value; 89 } 90 91 void CompilerInstance::setVerboseOutputStream(raw_ostream &Value) { 92 OwnedVerboseOutputStream.release(); 93 VerboseOutputStream = &Value; 94 } 95 96 void CompilerInstance::setVerboseOutputStream(std::unique_ptr<raw_ostream> Value) { 97 OwnedVerboseOutputStream.swap(Value); 98 VerboseOutputStream = OwnedVerboseOutputStream.get(); 99 } 100 101 void CompilerInstance::setTarget(TargetInfo *Value) { Target = Value; } 102 void CompilerInstance::setAuxTarget(TargetInfo *Value) { AuxTarget = Value; } 103 104 llvm::vfs::FileSystem &CompilerInstance::getVirtualFileSystem() const { 105 return getFileManager().getVirtualFileSystem(); 106 } 107 108 void CompilerInstance::setFileManager(FileManager *Value) { 109 FileMgr = Value; 110 } 111 112 void CompilerInstance::setSourceManager(SourceManager *Value) { 113 SourceMgr = Value; 114 } 115 116 void CompilerInstance::setPreprocessor(std::shared_ptr<Preprocessor> Value) { 117 PP = std::move(Value); 118 } 119 120 void CompilerInstance::setASTContext(ASTContext *Value) { 121 Context = Value; 122 123 if (Context && Consumer) 124 getASTConsumer().Initialize(getASTContext()); 125 } 126 127 void CompilerInstance::setSema(Sema *S) { 128 TheSema.reset(S); 129 } 130 131 void CompilerInstance::setASTConsumer(std::unique_ptr<ASTConsumer> Value) { 132 Consumer = std::move(Value); 133 134 if (Context && Consumer) 135 getASTConsumer().Initialize(getASTContext()); 136 } 137 138 void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) { 139 CompletionConsumer.reset(Value); 140 } 141 142 std::unique_ptr<Sema> CompilerInstance::takeSema() { 143 return std::move(TheSema); 144 } 145 146 IntrusiveRefCntPtr<ASTReader> CompilerInstance::getASTReader() const { 147 return TheASTReader; 148 } 149 void CompilerInstance::setASTReader(IntrusiveRefCntPtr<ASTReader> Reader) { 150 assert(ModuleCache.get() == &Reader->getModuleManager().getModuleCache() && 151 "Expected ASTReader to use the same PCM cache"); 152 TheASTReader = std::move(Reader); 153 } 154 155 std::shared_ptr<ModuleDependencyCollector> 156 CompilerInstance::getModuleDepCollector() const { 157 return ModuleDepCollector; 158 } 159 160 void CompilerInstance::setModuleDepCollector( 161 std::shared_ptr<ModuleDependencyCollector> Collector) { 162 ModuleDepCollector = std::move(Collector); 163 } 164 165 static void collectHeaderMaps(const HeaderSearch &HS, 166 std::shared_ptr<ModuleDependencyCollector> MDC) { 167 SmallVector<std::string, 4> HeaderMapFileNames; 168 HS.getHeaderMapFileNames(HeaderMapFileNames); 169 for (auto &Name : HeaderMapFileNames) 170 MDC->addFile(Name); 171 } 172 173 static void collectIncludePCH(CompilerInstance &CI, 174 std::shared_ptr<ModuleDependencyCollector> MDC) { 175 const PreprocessorOptions &PPOpts = CI.getPreprocessorOpts(); 176 if (PPOpts.ImplicitPCHInclude.empty()) 177 return; 178 179 StringRef PCHInclude = PPOpts.ImplicitPCHInclude; 180 FileManager &FileMgr = CI.getFileManager(); 181 auto PCHDir = FileMgr.getDirectory(PCHInclude); 182 if (!PCHDir) { 183 MDC->addFile(PCHInclude); 184 return; 185 } 186 187 std::error_code EC; 188 SmallString<128> DirNative; 189 llvm::sys::path::native((*PCHDir)->getName(), DirNative); 190 llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem(); 191 SimpleASTReaderListener Validator(CI.getPreprocessor()); 192 for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd; 193 Dir != DirEnd && !EC; Dir.increment(EC)) { 194 // Check whether this is an AST file. ASTReader::isAcceptableASTFile is not 195 // used here since we're not interested in validating the PCH at this time, 196 // but only to check whether this is a file containing an AST. 197 if (!ASTReader::readASTFileControlBlock( 198 Dir->path(), FileMgr, CI.getPCHContainerReader(), 199 /*FindModuleFileExtensions=*/false, Validator, 200 /*ValidateDiagnosticOptions=*/false)) 201 MDC->addFile(Dir->path()); 202 } 203 } 204 205 static void collectVFSEntries(CompilerInstance &CI, 206 std::shared_ptr<ModuleDependencyCollector> MDC) { 207 if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty()) 208 return; 209 210 // Collect all VFS found. 211 SmallVector<llvm::vfs::YAMLVFSEntry, 16> VFSEntries; 212 for (const std::string &VFSFile : CI.getHeaderSearchOpts().VFSOverlayFiles) { 213 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer = 214 llvm::MemoryBuffer::getFile(VFSFile); 215 if (!Buffer) 216 return; 217 llvm::vfs::collectVFSFromYAML(std::move(Buffer.get()), 218 /*DiagHandler*/ nullptr, VFSFile, VFSEntries); 219 } 220 221 for (auto &E : VFSEntries) 222 MDC->addFile(E.VPath, E.RPath); 223 } 224 225 // Diagnostics 226 static void SetUpDiagnosticLog(DiagnosticOptions *DiagOpts, 227 const CodeGenOptions *CodeGenOpts, 228 DiagnosticsEngine &Diags) { 229 std::error_code EC; 230 std::unique_ptr<raw_ostream> StreamOwner; 231 raw_ostream *OS = &llvm::errs(); 232 if (DiagOpts->DiagnosticLogFile != "-") { 233 // Create the output stream. 234 auto FileOS = std::make_unique<llvm::raw_fd_ostream>( 235 DiagOpts->DiagnosticLogFile, EC, 236 llvm::sys::fs::OF_Append | llvm::sys::fs::OF_Text); 237 if (EC) { 238 Diags.Report(diag::warn_fe_cc_log_diagnostics_failure) 239 << DiagOpts->DiagnosticLogFile << EC.message(); 240 } else { 241 FileOS->SetUnbuffered(); 242 OS = FileOS.get(); 243 StreamOwner = std::move(FileOS); 244 } 245 } 246 247 // Chain in the diagnostic client which will log the diagnostics. 248 auto Logger = std::make_unique<LogDiagnosticPrinter>(*OS, DiagOpts, 249 std::move(StreamOwner)); 250 if (CodeGenOpts) 251 Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags); 252 if (Diags.ownsClient()) { 253 Diags.setClient( 254 new ChainedDiagnosticConsumer(Diags.takeClient(), std::move(Logger))); 255 } else { 256 Diags.setClient( 257 new ChainedDiagnosticConsumer(Diags.getClient(), std::move(Logger))); 258 } 259 } 260 261 static void SetupSerializedDiagnostics(DiagnosticOptions *DiagOpts, 262 DiagnosticsEngine &Diags, 263 StringRef OutputFile) { 264 auto SerializedConsumer = 265 clang::serialized_diags::create(OutputFile, DiagOpts); 266 267 if (Diags.ownsClient()) { 268 Diags.setClient(new ChainedDiagnosticConsumer( 269 Diags.takeClient(), std::move(SerializedConsumer))); 270 } else { 271 Diags.setClient(new ChainedDiagnosticConsumer( 272 Diags.getClient(), std::move(SerializedConsumer))); 273 } 274 } 275 276 void CompilerInstance::createDiagnostics(DiagnosticConsumer *Client, 277 bool ShouldOwnClient) { 278 Diagnostics = createDiagnostics(&getDiagnosticOpts(), Client, 279 ShouldOwnClient, &getCodeGenOpts()); 280 } 281 282 IntrusiveRefCntPtr<DiagnosticsEngine> 283 CompilerInstance::createDiagnostics(DiagnosticOptions *Opts, 284 DiagnosticConsumer *Client, 285 bool ShouldOwnClient, 286 const CodeGenOptions *CodeGenOpts) { 287 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs()); 288 IntrusiveRefCntPtr<DiagnosticsEngine> 289 Diags(new DiagnosticsEngine(DiagID, Opts)); 290 291 // Create the diagnostic client for reporting errors or for 292 // implementing -verify. 293 if (Client) { 294 Diags->setClient(Client, ShouldOwnClient); 295 } else 296 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts)); 297 298 // Chain in -verify checker, if requested. 299 if (Opts->VerifyDiagnostics) 300 Diags->setClient(new VerifyDiagnosticConsumer(*Diags)); 301 302 // Chain in -diagnostic-log-file dumper, if requested. 303 if (!Opts->DiagnosticLogFile.empty()) 304 SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags); 305 306 if (!Opts->DiagnosticSerializationFile.empty()) 307 SetupSerializedDiagnostics(Opts, *Diags, 308 Opts->DiagnosticSerializationFile); 309 310 // Configure our handling of diagnostics. 311 ProcessWarningOptions(*Diags, *Opts); 312 313 return Diags; 314 } 315 316 // File Manager 317 318 FileManager *CompilerInstance::createFileManager( 319 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) { 320 if (!VFS) 321 VFS = FileMgr ? &FileMgr->getVirtualFileSystem() 322 : createVFSFromCompilerInvocation(getInvocation(), 323 getDiagnostics()); 324 assert(VFS && "FileManager has no VFS?"); 325 FileMgr = new FileManager(getFileSystemOpts(), std::move(VFS)); 326 return FileMgr.get(); 327 } 328 329 // Source Manager 330 331 void CompilerInstance::createSourceManager(FileManager &FileMgr) { 332 SourceMgr = new SourceManager(getDiagnostics(), FileMgr); 333 } 334 335 // Initialize the remapping of files to alternative contents, e.g., 336 // those specified through other files. 337 static void InitializeFileRemapping(DiagnosticsEngine &Diags, 338 SourceManager &SourceMgr, 339 FileManager &FileMgr, 340 const PreprocessorOptions &InitOpts) { 341 // Remap files in the source manager (with buffers). 342 for (const auto &RB : InitOpts.RemappedFileBuffers) { 343 // Create the file entry for the file that we're mapping from. 344 const FileEntry *FromFile = 345 FileMgr.getVirtualFile(RB.first, RB.second->getBufferSize(), 0); 346 if (!FromFile) { 347 Diags.Report(diag::err_fe_remap_missing_from_file) << RB.first; 348 if (!InitOpts.RetainRemappedFileBuffers) 349 delete RB.second; 350 continue; 351 } 352 353 // Override the contents of the "from" file with the contents of 354 // the "to" file. 355 SourceMgr.overrideFileContents(FromFile, RB.second, 356 InitOpts.RetainRemappedFileBuffers); 357 } 358 359 // Remap files in the source manager (with other files). 360 for (const auto &RF : InitOpts.RemappedFiles) { 361 // Find the file that we're mapping to. 362 auto ToFile = FileMgr.getFile(RF.second); 363 if (!ToFile) { 364 Diags.Report(diag::err_fe_remap_missing_to_file) << RF.first << RF.second; 365 continue; 366 } 367 368 // Create the file entry for the file that we're mapping from. 369 const FileEntry *FromFile = 370 FileMgr.getVirtualFile(RF.first, (*ToFile)->getSize(), 0); 371 if (!FromFile) { 372 Diags.Report(diag::err_fe_remap_missing_from_file) << RF.first; 373 continue; 374 } 375 376 // Override the contents of the "from" file with the contents of 377 // the "to" file. 378 SourceMgr.overrideFileContents(FromFile, *ToFile); 379 } 380 381 SourceMgr.setOverridenFilesKeepOriginalName( 382 InitOpts.RemappedFilesKeepOriginalName); 383 } 384 385 // Preprocessor 386 387 void CompilerInstance::createPreprocessor(TranslationUnitKind TUKind) { 388 const PreprocessorOptions &PPOpts = getPreprocessorOpts(); 389 390 // The AST reader holds a reference to the old preprocessor (if any). 391 TheASTReader.reset(); 392 393 // Create the Preprocessor. 394 HeaderSearch *HeaderInfo = 395 new HeaderSearch(getHeaderSearchOptsPtr(), getSourceManager(), 396 getDiagnostics(), getLangOpts(), &getTarget()); 397 PP = std::make_shared<Preprocessor>(Invocation->getPreprocessorOptsPtr(), 398 getDiagnostics(), getLangOpts(), 399 getSourceManager(), *HeaderInfo, *this, 400 /*IdentifierInfoLookup=*/nullptr, 401 /*OwnsHeaderSearch=*/true, TUKind); 402 getTarget().adjust(getLangOpts()); 403 PP->Initialize(getTarget(), getAuxTarget()); 404 405 if (PPOpts.DetailedRecord) 406 PP->createPreprocessingRecord(); 407 408 // Apply remappings to the source manager. 409 InitializeFileRemapping(PP->getDiagnostics(), PP->getSourceManager(), 410 PP->getFileManager(), PPOpts); 411 412 // Predefine macros and configure the preprocessor. 413 InitializePreprocessor(*PP, PPOpts, getPCHContainerReader(), 414 getFrontendOpts()); 415 416 // Initialize the header search object. In CUDA compilations, we use the aux 417 // triple (the host triple) to initialize our header search, since we need to 418 // find the host headers in order to compile the CUDA code. 419 const llvm::Triple *HeaderSearchTriple = &PP->getTargetInfo().getTriple(); 420 if (PP->getTargetInfo().getTriple().getOS() == llvm::Triple::CUDA && 421 PP->getAuxTargetInfo()) 422 HeaderSearchTriple = &PP->getAuxTargetInfo()->getTriple(); 423 424 ApplyHeaderSearchOptions(PP->getHeaderSearchInfo(), getHeaderSearchOpts(), 425 PP->getLangOpts(), *HeaderSearchTriple); 426 427 PP->setPreprocessedOutput(getPreprocessorOutputOpts().ShowCPP); 428 429 if (PP->getLangOpts().Modules && PP->getLangOpts().ImplicitModules) 430 PP->getHeaderSearchInfo().setModuleCachePath(getSpecificModuleCachePath()); 431 432 // Handle generating dependencies, if requested. 433 const DependencyOutputOptions &DepOpts = getDependencyOutputOpts(); 434 if (!DepOpts.OutputFile.empty()) 435 addDependencyCollector(std::make_shared<DependencyFileGenerator>(DepOpts)); 436 if (!DepOpts.DOTOutputFile.empty()) 437 AttachDependencyGraphGen(*PP, DepOpts.DOTOutputFile, 438 getHeaderSearchOpts().Sysroot); 439 440 // If we don't have a collector, but we are collecting module dependencies, 441 // then we're the top level compiler instance and need to create one. 442 if (!ModuleDepCollector && !DepOpts.ModuleDependencyOutputDir.empty()) { 443 ModuleDepCollector = std::make_shared<ModuleDependencyCollector>( 444 DepOpts.ModuleDependencyOutputDir); 445 } 446 447 // If there is a module dep collector, register with other dep collectors 448 // and also (a) collect header maps and (b) TODO: input vfs overlay files. 449 if (ModuleDepCollector) { 450 addDependencyCollector(ModuleDepCollector); 451 collectHeaderMaps(PP->getHeaderSearchInfo(), ModuleDepCollector); 452 collectIncludePCH(*this, ModuleDepCollector); 453 collectVFSEntries(*this, ModuleDepCollector); 454 } 455 456 for (auto &Listener : DependencyCollectors) 457 Listener->attachToPreprocessor(*PP); 458 459 // Handle generating header include information, if requested. 460 if (DepOpts.ShowHeaderIncludes) 461 AttachHeaderIncludeGen(*PP, DepOpts); 462 if (!DepOpts.HeaderIncludeOutputFile.empty()) { 463 StringRef OutputPath = DepOpts.HeaderIncludeOutputFile; 464 if (OutputPath == "-") 465 OutputPath = ""; 466 AttachHeaderIncludeGen(*PP, DepOpts, 467 /*ShowAllHeaders=*/true, OutputPath, 468 /*ShowDepth=*/false); 469 } 470 471 if (DepOpts.ShowIncludesDest != ShowIncludesDestination::None) { 472 AttachHeaderIncludeGen(*PP, DepOpts, 473 /*ShowAllHeaders=*/true, /*OutputPath=*/"", 474 /*ShowDepth=*/true, /*MSStyle=*/true); 475 } 476 } 477 478 std::string CompilerInstance::getSpecificModuleCachePath() { 479 // Set up the module path, including the hash for the 480 // module-creation options. 481 SmallString<256> SpecificModuleCache(getHeaderSearchOpts().ModuleCachePath); 482 if (!SpecificModuleCache.empty() && !getHeaderSearchOpts().DisableModuleHash) 483 llvm::sys::path::append(SpecificModuleCache, 484 getInvocation().getModuleHash()); 485 return std::string(SpecificModuleCache.str()); 486 } 487 488 // ASTContext 489 490 void CompilerInstance::createASTContext() { 491 Preprocessor &PP = getPreprocessor(); 492 auto *Context = new ASTContext(getLangOpts(), PP.getSourceManager(), 493 PP.getIdentifierTable(), PP.getSelectorTable(), 494 PP.getBuiltinInfo()); 495 Context->InitBuiltinTypes(getTarget(), getAuxTarget()); 496 setASTContext(Context); 497 } 498 499 // ExternalASTSource 500 501 void CompilerInstance::createPCHExternalASTSource( 502 StringRef Path, bool DisablePCHValidation, bool AllowPCHWithCompilerErrors, 503 void *DeserializationListener, bool OwnDeserializationListener) { 504 bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0; 505 TheASTReader = createPCHExternalASTSource( 506 Path, getHeaderSearchOpts().Sysroot, DisablePCHValidation, 507 AllowPCHWithCompilerErrors, getPreprocessor(), getModuleCache(), 508 getASTContext(), getPCHContainerReader(), 509 getFrontendOpts().ModuleFileExtensions, DependencyCollectors, 510 DeserializationListener, OwnDeserializationListener, Preamble, 511 getFrontendOpts().UseGlobalModuleIndex); 512 } 513 514 IntrusiveRefCntPtr<ASTReader> CompilerInstance::createPCHExternalASTSource( 515 StringRef Path, StringRef Sysroot, bool DisablePCHValidation, 516 bool AllowPCHWithCompilerErrors, Preprocessor &PP, 517 InMemoryModuleCache &ModuleCache, ASTContext &Context, 518 const PCHContainerReader &PCHContainerRdr, 519 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions, 520 ArrayRef<std::shared_ptr<DependencyCollector>> DependencyCollectors, 521 void *DeserializationListener, bool OwnDeserializationListener, 522 bool Preamble, bool UseGlobalModuleIndex) { 523 HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts(); 524 525 IntrusiveRefCntPtr<ASTReader> Reader(new ASTReader( 526 PP, ModuleCache, &Context, PCHContainerRdr, Extensions, 527 Sysroot.empty() ? "" : Sysroot.data(), DisablePCHValidation, 528 AllowPCHWithCompilerErrors, /*AllowConfigurationMismatch*/ false, 529 HSOpts.ModulesValidateSystemHeaders, HSOpts.ValidateASTInputFilesContent, 530 UseGlobalModuleIndex)); 531 532 // We need the external source to be set up before we read the AST, because 533 // eagerly-deserialized declarations may use it. 534 Context.setExternalSource(Reader.get()); 535 536 Reader->setDeserializationListener( 537 static_cast<ASTDeserializationListener *>(DeserializationListener), 538 /*TakeOwnership=*/OwnDeserializationListener); 539 540 for (auto &Listener : DependencyCollectors) 541 Listener->attachToASTReader(*Reader); 542 543 switch (Reader->ReadAST(Path, 544 Preamble ? serialization::MK_Preamble 545 : serialization::MK_PCH, 546 SourceLocation(), 547 ASTReader::ARR_None)) { 548 case ASTReader::Success: 549 // Set the predefines buffer as suggested by the PCH reader. Typically, the 550 // predefines buffer will be empty. 551 PP.setPredefines(Reader->getSuggestedPredefines()); 552 return Reader; 553 554 case ASTReader::Failure: 555 // Unrecoverable failure: don't even try to process the input file. 556 break; 557 558 case ASTReader::Missing: 559 case ASTReader::OutOfDate: 560 case ASTReader::VersionMismatch: 561 case ASTReader::ConfigurationMismatch: 562 case ASTReader::HadErrors: 563 // No suitable PCH file could be found. Return an error. 564 break; 565 } 566 567 Context.setExternalSource(nullptr); 568 return nullptr; 569 } 570 571 // Code Completion 572 573 static bool EnableCodeCompletion(Preprocessor &PP, 574 StringRef Filename, 575 unsigned Line, 576 unsigned Column) { 577 // Tell the source manager to chop off the given file at a specific 578 // line and column. 579 auto Entry = PP.getFileManager().getFile(Filename); 580 if (!Entry) { 581 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file) 582 << Filename; 583 return true; 584 } 585 586 // Truncate the named file at the given line/column. 587 PP.SetCodeCompletionPoint(*Entry, Line, Column); 588 return false; 589 } 590 591 void CompilerInstance::createCodeCompletionConsumer() { 592 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt; 593 if (!CompletionConsumer) { 594 setCodeCompletionConsumer( 595 createCodeCompletionConsumer(getPreprocessor(), 596 Loc.FileName, Loc.Line, Loc.Column, 597 getFrontendOpts().CodeCompleteOpts, 598 llvm::outs())); 599 if (!CompletionConsumer) 600 return; 601 } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName, 602 Loc.Line, Loc.Column)) { 603 setCodeCompletionConsumer(nullptr); 604 return; 605 } 606 } 607 608 void CompilerInstance::createFrontendTimer() { 609 FrontendTimerGroup.reset( 610 new llvm::TimerGroup("frontend", "Clang front-end time report")); 611 FrontendTimer.reset( 612 new llvm::Timer("frontend", "Clang front-end timer", 613 *FrontendTimerGroup)); 614 } 615 616 CodeCompleteConsumer * 617 CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP, 618 StringRef Filename, 619 unsigned Line, 620 unsigned Column, 621 const CodeCompleteOptions &Opts, 622 raw_ostream &OS) { 623 if (EnableCodeCompletion(PP, Filename, Line, Column)) 624 return nullptr; 625 626 // Set up the creation routine for code-completion. 627 return new PrintingCodeCompleteConsumer(Opts, OS); 628 } 629 630 void CompilerInstance::createSema(TranslationUnitKind TUKind, 631 CodeCompleteConsumer *CompletionConsumer) { 632 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(), 633 TUKind, CompletionConsumer)); 634 // Attach the external sema source if there is any. 635 if (ExternalSemaSrc) { 636 TheSema->addExternalSource(ExternalSemaSrc.get()); 637 ExternalSemaSrc->InitializeSema(*TheSema); 638 } 639 } 640 641 // Output Files 642 643 void CompilerInstance::addOutputFile(OutputFile &&OutFile) { 644 OutputFiles.push_back(std::move(OutFile)); 645 } 646 647 void CompilerInstance::clearOutputFiles(bool EraseFiles) { 648 for (OutputFile &OF : OutputFiles) { 649 if (!OF.TempFilename.empty()) { 650 if (EraseFiles) { 651 llvm::sys::fs::remove(OF.TempFilename); 652 } else { 653 SmallString<128> NewOutFile(OF.Filename); 654 655 // If '-working-directory' was passed, the output filename should be 656 // relative to that. 657 FileMgr->FixupRelativePath(NewOutFile); 658 if (std::error_code ec = 659 llvm::sys::fs::rename(OF.TempFilename, NewOutFile)) { 660 getDiagnostics().Report(diag::err_unable_to_rename_temp) 661 << OF.TempFilename << OF.Filename << ec.message(); 662 663 llvm::sys::fs::remove(OF.TempFilename); 664 } 665 } 666 } else if (!OF.Filename.empty() && EraseFiles) 667 llvm::sys::fs::remove(OF.Filename); 668 } 669 OutputFiles.clear(); 670 if (DeleteBuiltModules) { 671 for (auto &Module : BuiltModules) 672 llvm::sys::fs::remove(Module.second); 673 BuiltModules.clear(); 674 } 675 NonSeekStream.reset(); 676 } 677 678 std::unique_ptr<raw_pwrite_stream> 679 CompilerInstance::createDefaultOutputFile(bool Binary, StringRef InFile, 680 StringRef Extension) { 681 return createOutputFile(getFrontendOpts().OutputFile, Binary, 682 /*RemoveFileOnSignal=*/true, InFile, Extension, 683 getFrontendOpts().UseTemporary); 684 } 685 686 std::unique_ptr<raw_pwrite_stream> CompilerInstance::createNullOutputFile() { 687 return std::make_unique<llvm::raw_null_ostream>(); 688 } 689 690 std::unique_ptr<raw_pwrite_stream> 691 CompilerInstance::createOutputFile(StringRef OutputPath, bool Binary, 692 bool RemoveFileOnSignal, StringRef InFile, 693 StringRef Extension, bool UseTemporary, 694 bool CreateMissingDirectories) { 695 std::string OutputPathName, TempPathName; 696 std::error_code EC; 697 std::unique_ptr<raw_pwrite_stream> OS = createOutputFile( 698 OutputPath, EC, Binary, RemoveFileOnSignal, InFile, Extension, 699 UseTemporary, CreateMissingDirectories, &OutputPathName, &TempPathName); 700 if (!OS) { 701 getDiagnostics().Report(diag::err_fe_unable_to_open_output) << OutputPath 702 << EC.message(); 703 return nullptr; 704 } 705 706 // Add the output file -- but don't try to remove "-", since this means we are 707 // using stdin. 708 addOutputFile( 709 OutputFile((OutputPathName != "-") ? OutputPathName : "", TempPathName)); 710 711 return OS; 712 } 713 714 std::unique_ptr<llvm::raw_pwrite_stream> CompilerInstance::createOutputFile( 715 StringRef OutputPath, std::error_code &Error, bool Binary, 716 bool RemoveFileOnSignal, StringRef InFile, StringRef Extension, 717 bool UseTemporary, bool CreateMissingDirectories, 718 std::string *ResultPathName, std::string *TempPathName) { 719 assert((!CreateMissingDirectories || UseTemporary) && 720 "CreateMissingDirectories is only allowed when using temporary files"); 721 722 std::string OutFile, TempFile; 723 if (!OutputPath.empty()) { 724 OutFile = std::string(OutputPath); 725 } else if (InFile == "-") { 726 OutFile = "-"; 727 } else if (!Extension.empty()) { 728 SmallString<128> Path(InFile); 729 llvm::sys::path::replace_extension(Path, Extension); 730 OutFile = std::string(Path.str()); 731 } else { 732 OutFile = "-"; 733 } 734 735 std::unique_ptr<llvm::raw_fd_ostream> OS; 736 std::string OSFile; 737 738 if (UseTemporary) { 739 if (OutFile == "-") 740 UseTemporary = false; 741 else { 742 llvm::sys::fs::file_status Status; 743 llvm::sys::fs::status(OutputPath, Status); 744 if (llvm::sys::fs::exists(Status)) { 745 // Fail early if we can't write to the final destination. 746 if (!llvm::sys::fs::can_write(OutputPath)) { 747 Error = make_error_code(llvm::errc::operation_not_permitted); 748 return nullptr; 749 } 750 751 // Don't use a temporary if the output is a special file. This handles 752 // things like '-o /dev/null' 753 if (!llvm::sys::fs::is_regular_file(Status)) 754 UseTemporary = false; 755 } 756 } 757 } 758 759 if (UseTemporary) { 760 // Create a temporary file. 761 // Insert -%%%%%%%% before the extension (if any), and because some tools 762 // (noticeable, clang's own GlobalModuleIndex.cpp) glob for build 763 // artifacts, also append .tmp. 764 StringRef OutputExtension = llvm::sys::path::extension(OutFile); 765 SmallString<128> TempPath = 766 StringRef(OutFile).drop_back(OutputExtension.size()); 767 TempPath += "-%%%%%%%%"; 768 TempPath += OutputExtension; 769 TempPath += ".tmp"; 770 int fd; 771 std::error_code EC = 772 llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath); 773 774 if (CreateMissingDirectories && 775 EC == llvm::errc::no_such_file_or_directory) { 776 StringRef Parent = llvm::sys::path::parent_path(OutputPath); 777 EC = llvm::sys::fs::create_directories(Parent); 778 if (!EC) { 779 EC = llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath); 780 } 781 } 782 783 if (!EC) { 784 OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true)); 785 OSFile = TempFile = std::string(TempPath.str()); 786 } 787 // If we failed to create the temporary, fallback to writing to the file 788 // directly. This handles the corner case where we cannot write to the 789 // directory, but can write to the file. 790 } 791 792 if (!OS) { 793 OSFile = OutFile; 794 OS.reset(new llvm::raw_fd_ostream( 795 OSFile, Error, 796 (Binary ? llvm::sys::fs::OF_None : llvm::sys::fs::OF_Text))); 797 if (Error) 798 return nullptr; 799 } 800 801 // Make sure the out stream file gets removed if we crash. 802 if (RemoveFileOnSignal) 803 llvm::sys::RemoveFileOnSignal(OSFile); 804 805 if (ResultPathName) 806 *ResultPathName = OutFile; 807 if (TempPathName) 808 *TempPathName = TempFile; 809 810 if (!Binary || OS->supportsSeeking()) 811 return std::move(OS); 812 813 auto B = std::make_unique<llvm::buffer_ostream>(*OS); 814 assert(!NonSeekStream); 815 NonSeekStream = std::move(OS); 816 return std::move(B); 817 } 818 819 // Initialization Utilities 820 821 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input){ 822 return InitializeSourceManager(Input, getDiagnostics(), getFileManager(), 823 getSourceManager()); 824 } 825 826 // static 827 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input, 828 DiagnosticsEngine &Diags, 829 FileManager &FileMgr, 830 SourceManager &SourceMgr) { 831 SrcMgr::CharacteristicKind Kind = 832 Input.getKind().getFormat() == InputKind::ModuleMap 833 ? Input.isSystem() ? SrcMgr::C_System_ModuleMap 834 : SrcMgr::C_User_ModuleMap 835 : Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User; 836 837 if (Input.isBuffer()) { 838 SourceMgr.setMainFileID(SourceMgr.createFileID(SourceManager::Unowned, 839 Input.getBuffer(), Kind)); 840 assert(SourceMgr.getMainFileID().isValid() && 841 "Couldn't establish MainFileID!"); 842 return true; 843 } 844 845 StringRef InputFile = Input.getFile(); 846 847 // Figure out where to get and map in the main file. 848 if (InputFile != "-") { 849 auto FileOrErr = FileMgr.getFileRef(InputFile, /*OpenFile=*/true); 850 if (!FileOrErr) { 851 // FIXME: include the error in the diagnostic. 852 consumeError(FileOrErr.takeError()); 853 Diags.Report(diag::err_fe_error_reading) << InputFile; 854 return false; 855 } 856 FileEntryRef File = *FileOrErr; 857 858 // The natural SourceManager infrastructure can't currently handle named 859 // pipes, but we would at least like to accept them for the main 860 // file. Detect them here, read them with the volatile flag so FileMgr will 861 // pick up the correct size, and simply override their contents as we do for 862 // STDIN. 863 if (File.getFileEntry().isNamedPipe()) { 864 auto MB = 865 FileMgr.getBufferForFile(&File.getFileEntry(), /*isVolatile=*/true); 866 if (MB) { 867 // Create a new virtual file that will have the correct size. 868 const FileEntry *FE = 869 FileMgr.getVirtualFile(InputFile, (*MB)->getBufferSize(), 0); 870 SourceMgr.overrideFileContents(FE, std::move(*MB)); 871 SourceMgr.setMainFileID( 872 SourceMgr.createFileID(FE, SourceLocation(), Kind)); 873 } else { 874 Diags.Report(diag::err_cannot_open_file) << InputFile 875 << MB.getError().message(); 876 return false; 877 } 878 } else { 879 SourceMgr.setMainFileID( 880 SourceMgr.createFileID(File, SourceLocation(), Kind)); 881 } 882 } else { 883 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> SBOrErr = 884 llvm::MemoryBuffer::getSTDIN(); 885 if (std::error_code EC = SBOrErr.getError()) { 886 Diags.Report(diag::err_fe_error_reading_stdin) << EC.message(); 887 return false; 888 } 889 std::unique_ptr<llvm::MemoryBuffer> SB = std::move(SBOrErr.get()); 890 891 const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(), 892 SB->getBufferSize(), 0); 893 SourceMgr.setMainFileID( 894 SourceMgr.createFileID(File, SourceLocation(), Kind)); 895 SourceMgr.overrideFileContents(File, std::move(SB)); 896 } 897 898 assert(SourceMgr.getMainFileID().isValid() && 899 "Couldn't establish MainFileID!"); 900 return true; 901 } 902 903 // High-Level Operations 904 905 bool CompilerInstance::ExecuteAction(FrontendAction &Act) { 906 assert(hasDiagnostics() && "Diagnostics engine is not initialized!"); 907 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!"); 908 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!"); 909 910 // Mark this point as the bottom of the stack if we don't have somewhere 911 // better. We generally expect frontend actions to be invoked with (nearly) 912 // DesiredStackSpace available. 913 noteBottomOfStack(); 914 915 raw_ostream &OS = getVerboseOutputStream(); 916 917 if (!Act.PrepareToExecute(*this)) 918 return false; 919 920 // Create the target instance. 921 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), 922 getInvocation().TargetOpts)); 923 if (!hasTarget()) 924 return false; 925 926 // Create TargetInfo for the other side of CUDA/OpenMP/SYCL compilation. 927 if ((getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 928 getLangOpts().SYCLIsDevice) && 929 !getFrontendOpts().AuxTriple.empty()) { 930 auto TO = std::make_shared<TargetOptions>(); 931 TO->Triple = llvm::Triple::normalize(getFrontendOpts().AuxTriple); 932 if (getFrontendOpts().AuxTargetCPU) 933 TO->CPU = getFrontendOpts().AuxTargetCPU.getValue(); 934 if (getFrontendOpts().AuxTargetFeatures) 935 TO->FeaturesAsWritten = getFrontendOpts().AuxTargetFeatures.getValue(); 936 TO->HostTriple = getTarget().getTriple().str(); 937 setAuxTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), TO)); 938 } 939 940 if (!getTarget().hasStrictFP() && !getLangOpts().ExpStrictFP) { 941 if (getLangOpts().getFPRoundingMode() != 942 llvm::RoundingMode::NearestTiesToEven) { 943 getDiagnostics().Report(diag::warn_fe_backend_unsupported_fp_rounding); 944 getLangOpts().setFPRoundingMode(llvm::RoundingMode::NearestTiesToEven); 945 } 946 if (getLangOpts().getFPExceptionMode() != LangOptions::FPE_Ignore) { 947 getDiagnostics().Report(diag::warn_fe_backend_unsupported_fp_exceptions); 948 getLangOpts().setFPExceptionMode(LangOptions::FPE_Ignore); 949 } 950 // FIXME: can we disable FEnvAccess? 951 } 952 953 // Inform the target of the language options. 954 // 955 // FIXME: We shouldn't need to do this, the target should be immutable once 956 // created. This complexity should be lifted elsewhere. 957 getTarget().adjust(getLangOpts()); 958 959 // Adjust target options based on codegen options. 960 getTarget().adjustTargetOptions(getCodeGenOpts(), getTargetOpts()); 961 962 if (auto *Aux = getAuxTarget()) 963 getTarget().setAuxTarget(Aux); 964 965 // rewriter project will change target built-in bool type from its default. 966 if (getFrontendOpts().ProgramAction == frontend::RewriteObjC) 967 getTarget().noSignedCharForObjCBool(); 968 969 // Validate/process some options. 970 if (getHeaderSearchOpts().Verbose) 971 OS << "clang -cc1 version " CLANG_VERSION_STRING 972 << " based upon " << BACKEND_PACKAGE_STRING 973 << " default target " << llvm::sys::getDefaultTargetTriple() << "\n"; 974 975 if (getFrontendOpts().ShowTimers) 976 createFrontendTimer(); 977 978 if (getFrontendOpts().ShowStats || !getFrontendOpts().StatsFile.empty()) 979 llvm::EnableStatistics(false); 980 981 for (const FrontendInputFile &FIF : getFrontendOpts().Inputs) { 982 // Reset the ID tables if we are reusing the SourceManager and parsing 983 // regular files. 984 if (hasSourceManager() && !Act.isModelParsingAction()) 985 getSourceManager().clearIDTables(); 986 987 if (Act.BeginSourceFile(*this, FIF)) { 988 if (llvm::Error Err = Act.Execute()) { 989 consumeError(std::move(Err)); // FIXME this drops errors on the floor. 990 } 991 Act.EndSourceFile(); 992 } 993 } 994 995 // Notify the diagnostic client that all files were processed. 996 getDiagnostics().getClient()->finish(); 997 998 if (getDiagnosticOpts().ShowCarets) { 999 // We can have multiple diagnostics sharing one diagnostic client. 1000 // Get the total number of warnings/errors from the client. 1001 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings(); 1002 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors(); 1003 1004 if (NumWarnings) 1005 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s"); 1006 if (NumWarnings && NumErrors) 1007 OS << " and "; 1008 if (NumErrors) 1009 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s"); 1010 if (NumWarnings || NumErrors) { 1011 OS << " generated"; 1012 if (getLangOpts().CUDA) { 1013 if (!getLangOpts().CUDAIsDevice) { 1014 OS << " when compiling for host"; 1015 } else { 1016 OS << " when compiling for " << getTargetOpts().CPU; 1017 } 1018 } 1019 OS << ".\n"; 1020 } 1021 } 1022 1023 if (getFrontendOpts().ShowStats) { 1024 if (hasFileManager()) { 1025 getFileManager().PrintStats(); 1026 OS << '\n'; 1027 } 1028 llvm::PrintStatistics(OS); 1029 } 1030 StringRef StatsFile = getFrontendOpts().StatsFile; 1031 if (!StatsFile.empty()) { 1032 std::error_code EC; 1033 auto StatS = std::make_unique<llvm::raw_fd_ostream>( 1034 StatsFile, EC, llvm::sys::fs::OF_Text); 1035 if (EC) { 1036 getDiagnostics().Report(diag::warn_fe_unable_to_open_stats_file) 1037 << StatsFile << EC.message(); 1038 } else { 1039 llvm::PrintStatisticsJSON(*StatS); 1040 } 1041 } 1042 1043 return !getDiagnostics().getClient()->getNumErrors(); 1044 } 1045 1046 /// Determine the appropriate source input kind based on language 1047 /// options. 1048 static Language getLanguageFromOptions(const LangOptions &LangOpts) { 1049 if (LangOpts.OpenCL) 1050 return Language::OpenCL; 1051 if (LangOpts.CUDA) 1052 return Language::CUDA; 1053 if (LangOpts.ObjC) 1054 return LangOpts.CPlusPlus ? Language::ObjCXX : Language::ObjC; 1055 return LangOpts.CPlusPlus ? Language::CXX : Language::C; 1056 } 1057 1058 /// Compile a module file for the given module, using the options 1059 /// provided by the importing compiler instance. Returns true if the module 1060 /// was built without errors. 1061 static bool 1062 compileModuleImpl(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, 1063 StringRef ModuleName, FrontendInputFile Input, 1064 StringRef OriginalModuleMapFile, StringRef ModuleFileName, 1065 llvm::function_ref<void(CompilerInstance &)> PreBuildStep = 1066 [](CompilerInstance &) {}, 1067 llvm::function_ref<void(CompilerInstance &)> PostBuildStep = 1068 [](CompilerInstance &) {}) { 1069 llvm::TimeTraceScope TimeScope("Module Compile", ModuleName); 1070 ++NumCompiledModules; 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