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