1 //===- ModuleMap.cpp - Describe the layout of modules ---------------------===// 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 // This file defines the ModuleMap implementation, which describes the layout 10 // of a module as it relates to headers. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Lex/ModuleMap.h" 15 #include "clang/Basic/CharInfo.h" 16 #include "clang/Basic/Diagnostic.h" 17 #include "clang/Basic/FileManager.h" 18 #include "clang/Basic/LLVM.h" 19 #include "clang/Basic/LangOptions.h" 20 #include "clang/Basic/Module.h" 21 #include "clang/Basic/SourceLocation.h" 22 #include "clang/Basic/SourceManager.h" 23 #include "clang/Basic/TargetInfo.h" 24 #include "clang/Lex/HeaderSearch.h" 25 #include "clang/Lex/HeaderSearchOptions.h" 26 #include "clang/Lex/LexDiagnostic.h" 27 #include "clang/Lex/ModuleMapFile.h" 28 #include "llvm/ADT/DenseMap.h" 29 #include "llvm/ADT/STLExtras.h" 30 #include "llvm/ADT/SmallPtrSet.h" 31 #include "llvm/ADT/SmallVector.h" 32 #include "llvm/ADT/StringMap.h" 33 #include "llvm/ADT/StringRef.h" 34 #include "llvm/ADT/StringSwitch.h" 35 #include "llvm/Support/Compiler.h" 36 #include "llvm/Support/ErrorHandling.h" 37 #include "llvm/Support/Path.h" 38 #include "llvm/Support/VirtualFileSystem.h" 39 #include "llvm/Support/raw_ostream.h" 40 #include <cassert> 41 #include <cstring> 42 #include <optional> 43 #include <string> 44 #include <system_error> 45 #include <utility> 46 47 using namespace clang; 48 49 void ModuleMapCallbacks::anchor() {} 50 51 void ModuleMap::resolveLinkAsDependencies(Module *Mod) { 52 auto PendingLinkAs = PendingLinkAsModule.find(Mod->Name); 53 if (PendingLinkAs != PendingLinkAsModule.end()) { 54 for (auto &Name : PendingLinkAs->second) { 55 auto *M = findModule(Name.getKey()); 56 if (M) 57 M->UseExportAsModuleLinkName = true; 58 } 59 } 60 } 61 62 void ModuleMap::addLinkAsDependency(Module *Mod) { 63 if (findModule(Mod->ExportAsModule)) 64 Mod->UseExportAsModuleLinkName = true; 65 else 66 PendingLinkAsModule[Mod->ExportAsModule].insert(Mod->Name); 67 } 68 69 Module::HeaderKind ModuleMap::headerRoleToKind(ModuleHeaderRole Role) { 70 switch ((int)Role) { 71 case NormalHeader: 72 return Module::HK_Normal; 73 case PrivateHeader: 74 return Module::HK_Private; 75 case TextualHeader: 76 return Module::HK_Textual; 77 case PrivateHeader | TextualHeader: 78 return Module::HK_PrivateTextual; 79 case ExcludedHeader: 80 return Module::HK_Excluded; 81 } 82 llvm_unreachable("unknown header role"); 83 } 84 85 ModuleMap::ModuleHeaderRole 86 ModuleMap::headerKindToRole(Module::HeaderKind Kind) { 87 switch ((int)Kind) { 88 case Module::HK_Normal: 89 return NormalHeader; 90 case Module::HK_Private: 91 return PrivateHeader; 92 case Module::HK_Textual: 93 return TextualHeader; 94 case Module::HK_PrivateTextual: 95 return ModuleHeaderRole(PrivateHeader | TextualHeader); 96 case Module::HK_Excluded: 97 return ExcludedHeader; 98 } 99 llvm_unreachable("unknown header kind"); 100 } 101 102 bool ModuleMap::isModular(ModuleHeaderRole Role) { 103 return !(Role & (ModuleMap::TextualHeader | ModuleMap::ExcludedHeader)); 104 } 105 106 Module::ExportDecl 107 ModuleMap::resolveExport(Module *Mod, 108 const Module::UnresolvedExportDecl &Unresolved, 109 bool Complain) const { 110 // We may have just a wildcard. 111 if (Unresolved.Id.empty()) { 112 assert(Unresolved.Wildcard && "Invalid unresolved export"); 113 return Module::ExportDecl(nullptr, true); 114 } 115 116 // Resolve the module-id. 117 Module *Context = resolveModuleId(Unresolved.Id, Mod, Complain); 118 if (!Context) 119 return {}; 120 121 return Module::ExportDecl(Context, Unresolved.Wildcard); 122 } 123 124 Module *ModuleMap::resolveModuleId(const ModuleId &Id, Module *Mod, 125 bool Complain) const { 126 // Find the starting module. 127 Module *Context = lookupModuleUnqualified(Id[0].first, Mod); 128 if (!Context) { 129 if (Complain) 130 Diags.Report(Id[0].second, diag::err_mmap_missing_module_unqualified) 131 << Id[0].first << Mod->getFullModuleName(); 132 133 return nullptr; 134 } 135 136 // Dig into the module path. 137 for (unsigned I = 1, N = Id.size(); I != N; ++I) { 138 Module *Sub = lookupModuleQualified(Id[I].first, Context); 139 if (!Sub) { 140 if (Complain) 141 Diags.Report(Id[I].second, diag::err_mmap_missing_module_qualified) 142 << Id[I].first << Context->getFullModuleName() 143 << SourceRange(Id[0].second, Id[I-1].second); 144 145 return nullptr; 146 } 147 148 Context = Sub; 149 } 150 151 return Context; 152 } 153 154 /// Append to \p Paths the set of paths needed to get to the 155 /// subframework in which the given module lives. 156 static void appendSubframeworkPaths(Module *Mod, 157 SmallVectorImpl<char> &Path) { 158 // Collect the framework names from the given module to the top-level module. 159 SmallVector<StringRef, 2> Paths; 160 for (; Mod; Mod = Mod->Parent) { 161 if (Mod->IsFramework) 162 Paths.push_back(Mod->Name); 163 } 164 165 if (Paths.empty()) 166 return; 167 168 // Add Frameworks/Name.framework for each subframework. 169 for (StringRef Framework : llvm::drop_begin(llvm::reverse(Paths))) 170 llvm::sys::path::append(Path, "Frameworks", Framework + ".framework"); 171 } 172 173 OptionalFileEntryRef ModuleMap::findHeader( 174 Module *M, const Module::UnresolvedHeaderDirective &Header, 175 SmallVectorImpl<char> &RelativePathName, bool &NeedsFramework) { 176 // Search for the header file within the module's home directory. 177 auto Directory = M->Directory; 178 SmallString<128> FullPathName(Directory->getName()); 179 180 auto GetFile = [&](StringRef Filename) -> OptionalFileEntryRef { 181 auto File = 182 expectedToOptional(SourceMgr.getFileManager().getFileRef(Filename)); 183 if (!File || (Header.Size && File->getSize() != *Header.Size) || 184 (Header.ModTime && File->getModificationTime() != *Header.ModTime)) 185 return std::nullopt; 186 return *File; 187 }; 188 189 auto GetFrameworkFile = [&]() -> OptionalFileEntryRef { 190 unsigned FullPathLength = FullPathName.size(); 191 appendSubframeworkPaths(M, RelativePathName); 192 unsigned RelativePathLength = RelativePathName.size(); 193 194 // Check whether this file is in the public headers. 195 llvm::sys::path::append(RelativePathName, "Headers", Header.FileName); 196 llvm::sys::path::append(FullPathName, RelativePathName); 197 if (auto File = GetFile(FullPathName)) 198 return File; 199 200 // Check whether this file is in the private headers. 201 // Ideally, private modules in the form 'FrameworkName.Private' should 202 // be defined as 'module FrameworkName.Private', and not as 203 // 'framework module FrameworkName.Private', since a 'Private.Framework' 204 // does not usually exist. However, since both are currently widely used 205 // for private modules, make sure we find the right path in both cases. 206 if (M->IsFramework && M->Name == "Private") 207 RelativePathName.clear(); 208 else 209 RelativePathName.resize(RelativePathLength); 210 FullPathName.resize(FullPathLength); 211 llvm::sys::path::append(RelativePathName, "PrivateHeaders", 212 Header.FileName); 213 llvm::sys::path::append(FullPathName, RelativePathName); 214 return GetFile(FullPathName); 215 }; 216 217 if (llvm::sys::path::is_absolute(Header.FileName)) { 218 RelativePathName.clear(); 219 RelativePathName.append(Header.FileName.begin(), Header.FileName.end()); 220 return GetFile(Header.FileName); 221 } 222 223 if (M->isPartOfFramework()) 224 return GetFrameworkFile(); 225 226 // Lookup for normal headers. 227 llvm::sys::path::append(RelativePathName, Header.FileName); 228 llvm::sys::path::append(FullPathName, RelativePathName); 229 auto NormalHdrFile = GetFile(FullPathName); 230 231 if (!NormalHdrFile && Directory->getName().ends_with(".framework")) { 232 // The lack of 'framework' keyword in a module declaration it's a simple 233 // mistake we can diagnose when the header exists within the proper 234 // framework style path. 235 FullPathName.assign(Directory->getName()); 236 RelativePathName.clear(); 237 if (GetFrameworkFile()) { 238 Diags.Report(Header.FileNameLoc, 239 diag::warn_mmap_incomplete_framework_module_declaration) 240 << Header.FileName << M->getFullModuleName(); 241 NeedsFramework = true; 242 } 243 return std::nullopt; 244 } 245 246 return NormalHdrFile; 247 } 248 249 /// Determine whether the given file name is the name of a builtin 250 /// header, supplied by Clang to replace, override, or augment existing system 251 /// headers. 252 static bool isBuiltinHeaderName(StringRef FileName) { 253 return llvm::StringSwitch<bool>(FileName) 254 .Case("float.h", true) 255 .Case("iso646.h", true) 256 .Case("limits.h", true) 257 .Case("stdalign.h", true) 258 .Case("stdarg.h", true) 259 .Case("stdatomic.h", true) 260 .Case("stdbool.h", true) 261 .Case("stdcountof.h", true) 262 .Case("stddef.h", true) 263 .Case("stdint.h", true) 264 .Case("tgmath.h", true) 265 .Case("unwind.h", true) 266 .Default(false); 267 } 268 269 /// Determine whether the given module name is the name of a builtin 270 /// module that is cyclic with a system module on some platforms. 271 static bool isBuiltInModuleName(StringRef ModuleName) { 272 return llvm::StringSwitch<bool>(ModuleName) 273 .Case("_Builtin_float", true) 274 .Case("_Builtin_inttypes", true) 275 .Case("_Builtin_iso646", true) 276 .Case("_Builtin_limits", true) 277 .Case("_Builtin_stdalign", true) 278 .Case("_Builtin_stdarg", true) 279 .Case("_Builtin_stdatomic", true) 280 .Case("_Builtin_stdbool", true) 281 .Case("_Builtin_stddef", true) 282 .Case("_Builtin_stdint", true) 283 .Case("_Builtin_stdnoreturn", true) 284 .Case("_Builtin_tgmath", true) 285 .Case("_Builtin_unwind", true) 286 .Default(false); 287 } 288 289 void ModuleMap::resolveHeader(Module *Mod, 290 const Module::UnresolvedHeaderDirective &Header, 291 bool &NeedsFramework) { 292 SmallString<128> RelativePathName; 293 if (OptionalFileEntryRef File = 294 findHeader(Mod, Header, RelativePathName, NeedsFramework)) { 295 if (Header.IsUmbrella) { 296 const DirectoryEntry *UmbrellaDir = &File->getDir().getDirEntry(); 297 if (Module *UmbrellaMod = UmbrellaDirs[UmbrellaDir]) 298 Diags.Report(Header.FileNameLoc, diag::err_mmap_umbrella_clash) 299 << UmbrellaMod->getFullModuleName(); 300 else 301 // Record this umbrella header. 302 setUmbrellaHeaderAsWritten(Mod, *File, Header.FileName, 303 RelativePathName.str()); 304 } else { 305 Module::Header H = {Header.FileName, std::string(RelativePathName), 306 *File}; 307 addHeader(Mod, H, headerKindToRole(Header.Kind)); 308 } 309 } else if (Header.HasBuiltinHeader && !Header.Size && !Header.ModTime) { 310 // There's a builtin header but no corresponding on-disk header. Assume 311 // this was supposed to modularize the builtin header alone. 312 } else if (Header.Kind == Module::HK_Excluded) { 313 // Ignore missing excluded header files. They're optional anyway. 314 } else { 315 // If we find a module that has a missing header, we mark this module as 316 // unavailable and store the header directive for displaying diagnostics. 317 Mod->MissingHeaders.push_back(Header); 318 // A missing header with stat information doesn't make the module 319 // unavailable; this keeps our behavior consistent as headers are lazily 320 // resolved. (Such a module still can't be built though, except from 321 // preprocessed source.) 322 if (!Header.Size && !Header.ModTime) 323 Mod->markUnavailable(/*Unimportable=*/false); 324 } 325 } 326 327 bool ModuleMap::resolveAsBuiltinHeader( 328 Module *Mod, const Module::UnresolvedHeaderDirective &Header) { 329 if (Header.Kind == Module::HK_Excluded || 330 llvm::sys::path::is_absolute(Header.FileName) || 331 Mod->isPartOfFramework() || !Mod->IsSystem || Header.IsUmbrella || 332 !BuiltinIncludeDir || BuiltinIncludeDir == Mod->Directory || 333 !LangOpts.BuiltinHeadersInSystemModules || !isBuiltinHeaderName(Header.FileName)) 334 return false; 335 336 // This is a system module with a top-level header. This header 337 // may have a counterpart (or replacement) in the set of headers 338 // supplied by Clang. Find that builtin header. 339 SmallString<128> Path; 340 llvm::sys::path::append(Path, BuiltinIncludeDir->getName(), Header.FileName); 341 auto File = SourceMgr.getFileManager().getOptionalFileRef(Path); 342 if (!File) 343 return false; 344 345 Module::Header H = {Header.FileName, Header.FileName, *File}; 346 auto Role = headerKindToRole(Header.Kind); 347 addHeader(Mod, H, Role); 348 return true; 349 } 350 351 ModuleMap::ModuleMap(SourceManager &SourceMgr, DiagnosticsEngine &Diags, 352 const LangOptions &LangOpts, const TargetInfo *Target, 353 HeaderSearch &HeaderInfo) 354 : SourceMgr(SourceMgr), Diags(Diags), LangOpts(LangOpts), Target(Target), 355 HeaderInfo(HeaderInfo) { 356 } 357 358 ModuleMap::~ModuleMap() = default; 359 360 void ModuleMap::setTarget(const TargetInfo &Target) { 361 assert((!this->Target || this->Target == &Target) && 362 "Improper target override"); 363 this->Target = &Target; 364 } 365 366 /// "Sanitize" a filename so that it can be used as an identifier. 367 static StringRef sanitizeFilenameAsIdentifier(StringRef Name, 368 SmallVectorImpl<char> &Buffer) { 369 if (Name.empty()) 370 return Name; 371 372 if (!isValidAsciiIdentifier(Name)) { 373 // If we don't already have something with the form of an identifier, 374 // create a buffer with the sanitized name. 375 Buffer.clear(); 376 if (isDigit(Name[0])) 377 Buffer.push_back('_'); 378 Buffer.reserve(Buffer.size() + Name.size()); 379 for (unsigned I = 0, N = Name.size(); I != N; ++I) { 380 if (isAsciiIdentifierContinue(Name[I])) 381 Buffer.push_back(Name[I]); 382 else 383 Buffer.push_back('_'); 384 } 385 386 Name = StringRef(Buffer.data(), Buffer.size()); 387 } 388 389 while (llvm::StringSwitch<bool>(Name) 390 #define KEYWORD(Keyword,Conditions) .Case(#Keyword, true) 391 #define ALIAS(Keyword, AliasOf, Conditions) .Case(Keyword, true) 392 #include "clang/Basic/TokenKinds.def" 393 .Default(false)) { 394 if (Name.data() != Buffer.data()) 395 Buffer.append(Name.begin(), Name.end()); 396 Buffer.push_back('_'); 397 Name = StringRef(Buffer.data(), Buffer.size()); 398 } 399 400 return Name; 401 } 402 403 bool ModuleMap::isBuiltinHeader(FileEntryRef File) { 404 return File.getDir() == BuiltinIncludeDir && LangOpts.BuiltinHeadersInSystemModules && 405 isBuiltinHeaderName(llvm::sys::path::filename(File.getName())); 406 } 407 408 bool ModuleMap::shouldImportRelativeToBuiltinIncludeDir(StringRef FileName, 409 Module *Module) const { 410 return LangOpts.BuiltinHeadersInSystemModules && BuiltinIncludeDir && 411 Module->IsSystem && !Module->isPartOfFramework() && 412 isBuiltinHeaderName(FileName); 413 } 414 415 ModuleMap::HeadersMap::iterator ModuleMap::findKnownHeader(FileEntryRef File) { 416 resolveHeaderDirectives(File); 417 HeadersMap::iterator Known = Headers.find(File); 418 if (HeaderInfo.getHeaderSearchOpts().ImplicitModuleMaps && 419 Known == Headers.end() && ModuleMap::isBuiltinHeader(File)) { 420 HeaderInfo.loadTopLevelSystemModules(); 421 return Headers.find(File); 422 } 423 return Known; 424 } 425 426 ModuleMap::KnownHeader ModuleMap::findHeaderInUmbrellaDirs( 427 FileEntryRef File, SmallVectorImpl<DirectoryEntryRef> &IntermediateDirs) { 428 if (UmbrellaDirs.empty()) 429 return {}; 430 431 OptionalDirectoryEntryRef Dir = File.getDir(); 432 433 // Note: as an egregious but useful hack we use the real path here, because 434 // frameworks moving from top-level frameworks to embedded frameworks tend 435 // to be symlinked from the top-level location to the embedded location, 436 // and we need to resolve lookups as if we had found the embedded location. 437 StringRef DirName = SourceMgr.getFileManager().getCanonicalName(*Dir); 438 439 // Keep walking up the directory hierarchy, looking for a directory with 440 // an umbrella header. 441 do { 442 auto KnownDir = UmbrellaDirs.find(*Dir); 443 if (KnownDir != UmbrellaDirs.end()) 444 return KnownHeader(KnownDir->second, NormalHeader); 445 446 IntermediateDirs.push_back(*Dir); 447 448 // Retrieve our parent path. 449 DirName = llvm::sys::path::parent_path(DirName); 450 if (DirName.empty()) 451 break; 452 453 // Resolve the parent path to a directory entry. 454 Dir = SourceMgr.getFileManager().getOptionalDirectoryRef(DirName); 455 } while (Dir); 456 return {}; 457 } 458 459 static bool violatesPrivateInclude(Module *RequestingModule, 460 const FileEntry *IncFileEnt, 461 ModuleMap::KnownHeader Header) { 462 #ifndef NDEBUG 463 if (Header.getRole() & ModuleMap::PrivateHeader) { 464 // Check for consistency between the module header role 465 // as obtained from the lookup and as obtained from the module. 466 // This check is not cheap, so enable it only for debugging. 467 bool IsPrivate = false; 468 ArrayRef<Module::Header> HeaderList[] = { 469 Header.getModule()->getHeaders(Module::HK_Private), 470 Header.getModule()->getHeaders(Module::HK_PrivateTextual)}; 471 for (auto Hs : HeaderList) 472 IsPrivate |= llvm::any_of( 473 Hs, [&](const Module::Header &H) { return H.Entry == IncFileEnt; }); 474 assert(IsPrivate && "inconsistent headers and roles"); 475 } 476 #endif 477 return !Header.isAccessibleFrom(RequestingModule); 478 } 479 480 static Module *getTopLevelOrNull(Module *M) { 481 return M ? M->getTopLevelModule() : nullptr; 482 } 483 484 void ModuleMap::diagnoseHeaderInclusion(Module *RequestingModule, 485 bool RequestingModuleIsModuleInterface, 486 SourceLocation FilenameLoc, 487 StringRef Filename, FileEntryRef File) { 488 // No errors for indirect modules. This may be a bit of a problem for modules 489 // with no source files. 490 if (getTopLevelOrNull(RequestingModule) != getTopLevelOrNull(SourceModule)) 491 return; 492 493 if (RequestingModule) { 494 resolveUses(RequestingModule, /*Complain=*/false); 495 resolveHeaderDirectives(RequestingModule, /*File=*/std::nullopt); 496 } 497 498 bool Excluded = false; 499 Module *Private = nullptr; 500 Module *NotUsed = nullptr; 501 502 HeadersMap::iterator Known = findKnownHeader(File); 503 if (Known != Headers.end()) { 504 for (const KnownHeader &Header : Known->second) { 505 // Excluded headers don't really belong to a module. 506 if (Header.getRole() == ModuleMap::ExcludedHeader) { 507 Excluded = true; 508 continue; 509 } 510 511 // Remember private headers for later printing of a diagnostic. 512 if (violatesPrivateInclude(RequestingModule, File, Header)) { 513 Private = Header.getModule(); 514 continue; 515 } 516 517 // If uses need to be specified explicitly, we are only allowed to return 518 // modules that are explicitly used by the requesting module. 519 if (RequestingModule && LangOpts.ModulesDeclUse && 520 !RequestingModule->directlyUses(Header.getModule())) { 521 NotUsed = Header.getModule(); 522 continue; 523 } 524 525 // We have found a module that we can happily use. 526 return; 527 } 528 529 Excluded = true; 530 } 531 532 // We have found a header, but it is private. 533 if (Private) { 534 Diags.Report(FilenameLoc, diag::warn_use_of_private_header_outside_module) 535 << Filename; 536 return; 537 } 538 539 // We have found a module, but we don't use it. 540 if (NotUsed) { 541 Diags.Report(FilenameLoc, diag::err_undeclared_use_of_module_indirect) 542 << RequestingModule->getTopLevelModule()->Name << Filename 543 << NotUsed->Name; 544 return; 545 } 546 547 if (Excluded || isHeaderInUmbrellaDirs(File)) 548 return; 549 550 // At this point, only non-modular includes remain. 551 552 if (RequestingModule && LangOpts.ModulesStrictDeclUse) { 553 Diags.Report(FilenameLoc, diag::err_undeclared_use_of_module) 554 << RequestingModule->getTopLevelModule()->Name << Filename; 555 } else if (RequestingModule && RequestingModuleIsModuleInterface && 556 LangOpts.isCompilingModule()) { 557 // Do not diagnose when we are not compiling a module. 558 diag::kind DiagID = RequestingModule->getTopLevelModule()->IsFramework ? 559 diag::warn_non_modular_include_in_framework_module : 560 diag::warn_non_modular_include_in_module; 561 Diags.Report(FilenameLoc, DiagID) << RequestingModule->getFullModuleName() 562 << File.getName(); 563 } 564 } 565 566 static bool isBetterKnownHeader(const ModuleMap::KnownHeader &New, 567 const ModuleMap::KnownHeader &Old) { 568 // Prefer available modules. 569 // FIXME: Considering whether the module is available rather than merely 570 // importable is non-hermetic and can result in surprising behavior for 571 // prebuilt modules. Consider only checking for importability here. 572 if (New.getModule()->isAvailable() && !Old.getModule()->isAvailable()) 573 return true; 574 575 // Prefer a public header over a private header. 576 if ((New.getRole() & ModuleMap::PrivateHeader) != 577 (Old.getRole() & ModuleMap::PrivateHeader)) 578 return !(New.getRole() & ModuleMap::PrivateHeader); 579 580 // Prefer a non-textual header over a textual header. 581 if ((New.getRole() & ModuleMap::TextualHeader) != 582 (Old.getRole() & ModuleMap::TextualHeader)) 583 return !(New.getRole() & ModuleMap::TextualHeader); 584 585 // Prefer a non-excluded header over an excluded header. 586 if ((New.getRole() == ModuleMap::ExcludedHeader) != 587 (Old.getRole() == ModuleMap::ExcludedHeader)) 588 return New.getRole() != ModuleMap::ExcludedHeader; 589 590 // Don't have a reason to choose between these. Just keep the first one. 591 return false; 592 } 593 594 ModuleMap::KnownHeader ModuleMap::findModuleForHeader(FileEntryRef File, 595 bool AllowTextual, 596 bool AllowExcluded) { 597 auto MakeResult = [&](ModuleMap::KnownHeader R) -> ModuleMap::KnownHeader { 598 if (!AllowTextual && R.getRole() & ModuleMap::TextualHeader) 599 return {}; 600 return R; 601 }; 602 603 HeadersMap::iterator Known = findKnownHeader(File); 604 if (Known != Headers.end()) { 605 ModuleMap::KnownHeader Result; 606 // Iterate over all modules that 'File' is part of to find the best fit. 607 for (KnownHeader &H : Known->second) { 608 // Cannot use a module if the header is excluded in it. 609 if (!AllowExcluded && H.getRole() == ModuleMap::ExcludedHeader) 610 continue; 611 // Prefer a header from the source module over all others. 612 if (H.getModule()->getTopLevelModule() == SourceModule) 613 return MakeResult(H); 614 if (!Result || isBetterKnownHeader(H, Result)) 615 Result = H; 616 } 617 return MakeResult(Result); 618 } 619 620 return MakeResult(findOrCreateModuleForHeaderInUmbrellaDir(File)); 621 } 622 623 ModuleMap::KnownHeader 624 ModuleMap::findOrCreateModuleForHeaderInUmbrellaDir(FileEntryRef File) { 625 assert(!Headers.count(File) && "already have a module for this header"); 626 627 SmallVector<DirectoryEntryRef, 2> SkippedDirs; 628 KnownHeader H = findHeaderInUmbrellaDirs(File, SkippedDirs); 629 if (H) { 630 Module *Result = H.getModule(); 631 632 // Search up the module stack until we find a module with an umbrella 633 // directory. 634 Module *UmbrellaModule = Result; 635 while (!UmbrellaModule->getEffectiveUmbrellaDir() && UmbrellaModule->Parent) 636 UmbrellaModule = UmbrellaModule->Parent; 637 638 if (UmbrellaModule->InferSubmodules) { 639 FileID UmbrellaModuleMap = getModuleMapFileIDForUniquing(UmbrellaModule); 640 641 // Infer submodules for each of the directories we found between 642 // the directory of the umbrella header and the directory where 643 // the actual header is located. 644 bool Explicit = UmbrellaModule->InferExplicitSubmodules; 645 646 for (DirectoryEntryRef SkippedDir : llvm::reverse(SkippedDirs)) { 647 // Find or create the module that corresponds to this directory name. 648 SmallString<32> NameBuf; 649 StringRef Name = sanitizeFilenameAsIdentifier( 650 llvm::sys::path::stem(SkippedDir.getName()), NameBuf); 651 Result = findOrCreateModuleFirst(Name, Result, /*IsFramework=*/false, 652 Explicit); 653 setInferredModuleAllowedBy(Result, UmbrellaModuleMap); 654 655 // Associate the module and the directory. 656 UmbrellaDirs[SkippedDir] = Result; 657 658 // If inferred submodules export everything they import, add a 659 // wildcard to the set of exports. 660 if (UmbrellaModule->InferExportWildcard && Result->Exports.empty()) 661 Result->Exports.push_back(Module::ExportDecl(nullptr, true)); 662 } 663 664 // Infer a submodule with the same name as this header file. 665 SmallString<32> NameBuf; 666 StringRef Name = sanitizeFilenameAsIdentifier( 667 llvm::sys::path::stem(File.getName()), NameBuf); 668 Result = findOrCreateModuleFirst(Name, Result, /*IsFramework=*/false, 669 Explicit); 670 setInferredModuleAllowedBy(Result, UmbrellaModuleMap); 671 Result->addTopHeader(File); 672 673 // If inferred submodules export everything they import, add a 674 // wildcard to the set of exports. 675 if (UmbrellaModule->InferExportWildcard && Result->Exports.empty()) 676 Result->Exports.push_back(Module::ExportDecl(nullptr, true)); 677 } else { 678 // Record each of the directories we stepped through as being part of 679 // the module we found, since the umbrella header covers them all. 680 for (unsigned I = 0, N = SkippedDirs.size(); I != N; ++I) 681 UmbrellaDirs[SkippedDirs[I]] = Result; 682 } 683 684 KnownHeader Header(Result, NormalHeader); 685 Headers[File].push_back(Header); 686 return Header; 687 } 688 689 return {}; 690 } 691 692 ArrayRef<ModuleMap::KnownHeader> 693 ModuleMap::findAllModulesForHeader(FileEntryRef File) { 694 HeadersMap::iterator Known = findKnownHeader(File); 695 if (Known != Headers.end()) 696 return Known->second; 697 698 if (findOrCreateModuleForHeaderInUmbrellaDir(File)) 699 return Headers.find(File)->second; 700 701 return {}; 702 } 703 704 ArrayRef<ModuleMap::KnownHeader> 705 ModuleMap::findResolvedModulesForHeader(FileEntryRef File) const { 706 // FIXME: Is this necessary? 707 resolveHeaderDirectives(File); 708 auto It = Headers.find(File); 709 if (It == Headers.end()) 710 return {}; 711 return It->second; 712 } 713 714 bool ModuleMap::isHeaderInUnavailableModule(FileEntryRef Header) const { 715 return isHeaderUnavailableInModule(Header, nullptr); 716 } 717 718 bool ModuleMap::isHeaderUnavailableInModule( 719 FileEntryRef Header, const Module *RequestingModule) const { 720 resolveHeaderDirectives(Header); 721 HeadersMap::const_iterator Known = Headers.find(Header); 722 if (Known != Headers.end()) { 723 for (SmallVectorImpl<KnownHeader>::const_iterator 724 I = Known->second.begin(), 725 E = Known->second.end(); 726 I != E; ++I) { 727 728 if (I->getRole() == ModuleMap::ExcludedHeader) 729 continue; 730 731 if (I->isAvailable() && 732 (!RequestingModule || 733 I->getModule()->isSubModuleOf(RequestingModule))) { 734 // When no requesting module is available, the caller is looking if a 735 // header is part a module by only looking into the module map. This is 736 // done by warn_uncovered_module_header checks; don't consider textual 737 // headers part of it in this mode, otherwise we get misleading warnings 738 // that a umbrella header is not including a textual header. 739 if (!RequestingModule && I->getRole() == ModuleMap::TextualHeader) 740 continue; 741 return false; 742 } 743 } 744 return true; 745 } 746 747 OptionalDirectoryEntryRef Dir = Header.getDir(); 748 SmallVector<DirectoryEntryRef, 2> SkippedDirs; 749 StringRef DirName = Dir->getName(); 750 751 auto IsUnavailable = [&](const Module *M) { 752 return !M->isAvailable() && (!RequestingModule || 753 M->isSubModuleOf(RequestingModule)); 754 }; 755 756 // Keep walking up the directory hierarchy, looking for a directory with 757 // an umbrella header. 758 do { 759 auto KnownDir = UmbrellaDirs.find(*Dir); 760 if (KnownDir != UmbrellaDirs.end()) { 761 Module *Found = KnownDir->second; 762 if (IsUnavailable(Found)) 763 return true; 764 765 // Search up the module stack until we find a module with an umbrella 766 // directory. 767 Module *UmbrellaModule = Found; 768 while (!UmbrellaModule->getEffectiveUmbrellaDir() && 769 UmbrellaModule->Parent) 770 UmbrellaModule = UmbrellaModule->Parent; 771 772 if (UmbrellaModule->InferSubmodules) { 773 for (DirectoryEntryRef SkippedDir : llvm::reverse(SkippedDirs)) { 774 // Find or create the module that corresponds to this directory name. 775 SmallString<32> NameBuf; 776 StringRef Name = sanitizeFilenameAsIdentifier( 777 llvm::sys::path::stem(SkippedDir.getName()), NameBuf); 778 Found = lookupModuleQualified(Name, Found); 779 if (!Found) 780 return false; 781 if (IsUnavailable(Found)) 782 return true; 783 } 784 785 // Infer a submodule with the same name as this header file. 786 SmallString<32> NameBuf; 787 StringRef Name = sanitizeFilenameAsIdentifier( 788 llvm::sys::path::stem(Header.getName()), 789 NameBuf); 790 Found = lookupModuleQualified(Name, Found); 791 if (!Found) 792 return false; 793 } 794 795 return IsUnavailable(Found); 796 } 797 798 SkippedDirs.push_back(*Dir); 799 800 // Retrieve our parent path. 801 DirName = llvm::sys::path::parent_path(DirName); 802 if (DirName.empty()) 803 break; 804 805 // Resolve the parent path to a directory entry. 806 Dir = SourceMgr.getFileManager().getOptionalDirectoryRef(DirName); 807 } while (Dir); 808 809 return false; 810 } 811 812 Module *ModuleMap::findModule(StringRef Name) const { 813 llvm::StringMap<Module *>::const_iterator Known = Modules.find(Name); 814 if (Known != Modules.end()) 815 return Known->getValue(); 816 817 return nullptr; 818 } 819 820 Module *ModuleMap::findOrInferSubmodule(Module *Parent, StringRef Name) { 821 if (Module *SubM = Parent->findSubmodule(Name)) 822 return SubM; 823 if (!Parent->InferSubmodules) 824 return nullptr; 825 Module *Result = new (ModulesAlloc.Allocate()) 826 Module(ModuleConstructorTag{}, Name, SourceLocation(), Parent, false, 827 Parent->InferExplicitSubmodules, 0); 828 Result->InferExplicitSubmodules = Parent->InferExplicitSubmodules; 829 Result->InferSubmodules = Parent->InferSubmodules; 830 Result->InferExportWildcard = Parent->InferExportWildcard; 831 if (Result->InferExportWildcard) 832 Result->Exports.push_back(Module::ExportDecl(nullptr, true)); 833 return Result; 834 } 835 836 Module *ModuleMap::lookupModuleUnqualified(StringRef Name, 837 Module *Context) const { 838 for(; Context; Context = Context->Parent) { 839 if (Module *Sub = lookupModuleQualified(Name, Context)) 840 return Sub; 841 } 842 843 return findModule(Name); 844 } 845 846 Module *ModuleMap::lookupModuleQualified(StringRef Name, Module *Context) const{ 847 if (!Context) 848 return findModule(Name); 849 850 return Context->findSubmodule(Name); 851 } 852 853 std::pair<Module *, bool> ModuleMap::findOrCreateModule(StringRef Name, 854 Module *Parent, 855 bool IsFramework, 856 bool IsExplicit) { 857 // Try to find an existing module with this name. 858 if (Module *Sub = lookupModuleQualified(Name, Parent)) 859 return std::make_pair(Sub, false); 860 861 // Create a new module with this name. 862 Module *M = createModule(Name, Parent, IsFramework, IsExplicit); 863 return std::make_pair(M, true); 864 } 865 866 Module *ModuleMap::createModule(StringRef Name, Module *Parent, 867 bool IsFramework, bool IsExplicit) { 868 assert(lookupModuleQualified(Name, Parent) == nullptr && 869 "Creating duplicate submodule"); 870 871 Module *Result = new (ModulesAlloc.Allocate()) 872 Module(ModuleConstructorTag{}, Name, SourceLocation(), Parent, 873 IsFramework, IsExplicit, NumCreatedModules++); 874 if (!Parent) { 875 if (LangOpts.CurrentModule == Name) 876 SourceModule = Result; 877 Modules[Name] = Result; 878 ModuleScopeIDs[Result] = CurrentModuleScopeID; 879 } 880 return Result; 881 } 882 883 Module *ModuleMap::createGlobalModuleFragmentForModuleUnit(SourceLocation Loc, 884 Module *Parent) { 885 auto *Result = new (ModulesAlloc.Allocate()) Module( 886 ModuleConstructorTag{}, "<global>", Loc, Parent, /*IsFramework=*/false, 887 /*IsExplicit=*/true, NumCreatedModules++); 888 Result->Kind = Module::ExplicitGlobalModuleFragment; 889 // If the created module isn't owned by a parent, send it to PendingSubmodules 890 // to wait for its parent. 891 if (!Result->Parent) 892 PendingSubmodules.emplace_back(Result); 893 return Result; 894 } 895 896 Module * 897 ModuleMap::createImplicitGlobalModuleFragmentForModuleUnit(SourceLocation Loc, 898 Module *Parent) { 899 assert(Parent && "We should only create an implicit global module fragment " 900 "in a module purview"); 901 // Note: Here the `IsExplicit` parameter refers to the semantics in clang 902 // modules. All the non-explicit submodules in clang modules will be exported 903 // too. Here we simplify the implementation by using the concept. 904 auto *Result = new (ModulesAlloc.Allocate()) 905 Module(ModuleConstructorTag{}, "<implicit global>", Loc, Parent, 906 /*IsFramework=*/false, /*IsExplicit=*/false, NumCreatedModules++); 907 Result->Kind = Module::ImplicitGlobalModuleFragment; 908 return Result; 909 } 910 911 Module * 912 ModuleMap::createPrivateModuleFragmentForInterfaceUnit(Module *Parent, 913 SourceLocation Loc) { 914 auto *Result = new (ModulesAlloc.Allocate()) Module( 915 ModuleConstructorTag{}, "<private>", Loc, Parent, /*IsFramework=*/false, 916 /*IsExplicit=*/true, NumCreatedModules++); 917 Result->Kind = Module::PrivateModuleFragment; 918 return Result; 919 } 920 921 Module *ModuleMap::createModuleUnitWithKind(SourceLocation Loc, StringRef Name, 922 Module::ModuleKind Kind) { 923 auto *Result = new (ModulesAlloc.Allocate()) 924 Module(ModuleConstructorTag{}, Name, Loc, nullptr, /*IsFramework=*/false, 925 /*IsExplicit=*/false, NumCreatedModules++); 926 Result->Kind = Kind; 927 928 // Reparent any current global module fragment as a submodule of this module. 929 for (auto &Submodule : PendingSubmodules) 930 Submodule->setParent(Result); 931 PendingSubmodules.clear(); 932 return Result; 933 } 934 935 Module *ModuleMap::createModuleForInterfaceUnit(SourceLocation Loc, 936 StringRef Name) { 937 assert(LangOpts.CurrentModule == Name && "module name mismatch"); 938 assert(!Modules[Name] && "redefining existing module"); 939 940 auto *Result = 941 createModuleUnitWithKind(Loc, Name, Module::ModuleInterfaceUnit); 942 Modules[Name] = SourceModule = Result; 943 944 // Mark the main source file as being within the newly-created module so that 945 // declarations and macros are properly visibility-restricted to it. 946 auto MainFile = SourceMgr.getFileEntryRefForID(SourceMgr.getMainFileID()); 947 assert(MainFile && "no input file for module interface"); 948 Headers[*MainFile].push_back(KnownHeader(Result, PrivateHeader)); 949 950 return Result; 951 } 952 953 Module *ModuleMap::createModuleForImplementationUnit(SourceLocation Loc, 954 StringRef Name) { 955 assert(LangOpts.CurrentModule == Name && "module name mismatch"); 956 // The interface for this implementation must exist and be loaded. 957 assert(Modules[Name] && Modules[Name]->Kind == Module::ModuleInterfaceUnit && 958 "creating implementation module without an interface"); 959 960 // Create an entry in the modules map to own the implementation unit module. 961 // User module names must not start with a period (so that this cannot clash 962 // with any legal user-defined module name). 963 StringRef IName = ".ImplementationUnit"; 964 assert(!Modules[IName] && "multiple implementation units?"); 965 966 auto *Result = 967 createModuleUnitWithKind(Loc, Name, Module::ModuleImplementationUnit); 968 Modules[IName] = SourceModule = Result; 969 970 // Check that the main file is present. 971 assert(SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()) && 972 "no input file for module implementation"); 973 974 return Result; 975 } 976 977 Module *ModuleMap::createHeaderUnit(SourceLocation Loc, StringRef Name, 978 Module::Header H) { 979 assert(LangOpts.CurrentModule == Name && "module name mismatch"); 980 assert(!Modules[Name] && "redefining existing module"); 981 982 auto *Result = new (ModulesAlloc.Allocate()) 983 Module(ModuleConstructorTag{}, Name, Loc, nullptr, /*IsFramework=*/false, 984 /*IsExplicit=*/false, NumCreatedModules++); 985 Result->Kind = Module::ModuleHeaderUnit; 986 Modules[Name] = SourceModule = Result; 987 addHeader(Result, H, NormalHeader); 988 return Result; 989 } 990 991 /// For a framework module, infer the framework against which we 992 /// should link. 993 static void inferFrameworkLink(Module *Mod) { 994 assert(Mod->IsFramework && "Can only infer linking for framework modules"); 995 assert(!Mod->isSubFramework() && 996 "Can only infer linking for top-level frameworks"); 997 998 StringRef FrameworkName(Mod->Name); 999 FrameworkName.consume_back("_Private"); 1000 Mod->LinkLibraries.push_back(Module::LinkLibrary(FrameworkName.str(), 1001 /*IsFramework=*/true)); 1002 } 1003 1004 Module *ModuleMap::inferFrameworkModule(DirectoryEntryRef FrameworkDir, 1005 bool IsSystem, Module *Parent) { 1006 Attributes Attrs; 1007 Attrs.IsSystem = IsSystem; 1008 return inferFrameworkModule(FrameworkDir, Attrs, Parent); 1009 } 1010 1011 Module *ModuleMap::inferFrameworkModule(DirectoryEntryRef FrameworkDir, 1012 Attributes Attrs, Module *Parent) { 1013 // Note: as an egregious but useful hack we use the real path here, because 1014 // we might be looking at an embedded framework that symlinks out to a 1015 // top-level framework, and we need to infer as if we were naming the 1016 // top-level framework. 1017 StringRef FrameworkDirName = 1018 SourceMgr.getFileManager().getCanonicalName(FrameworkDir); 1019 1020 // In case this is a case-insensitive filesystem, use the canonical 1021 // directory name as the ModuleName, since modules are case-sensitive. 1022 // FIXME: we should be able to give a fix-it hint for the correct spelling. 1023 SmallString<32> ModuleNameStorage; 1024 StringRef ModuleName = sanitizeFilenameAsIdentifier( 1025 llvm::sys::path::stem(FrameworkDirName), ModuleNameStorage); 1026 1027 // Check whether we've already found this module. 1028 if (Module *Mod = lookupModuleQualified(ModuleName, Parent)) 1029 return Mod; 1030 1031 FileManager &FileMgr = SourceMgr.getFileManager(); 1032 1033 // If the framework has a parent path from which we're allowed to infer 1034 // a framework module, do so. 1035 FileID ModuleMapFID; 1036 if (!Parent) { 1037 // Determine whether we're allowed to infer a module map. 1038 bool canInfer = false; 1039 if (llvm::sys::path::has_parent_path(FrameworkDirName)) { 1040 // Figure out the parent path. 1041 StringRef Parent = llvm::sys::path::parent_path(FrameworkDirName); 1042 if (auto ParentDir = FileMgr.getOptionalDirectoryRef(Parent)) { 1043 // Check whether we have already looked into the parent directory 1044 // for a module map. 1045 llvm::DenseMap<const DirectoryEntry *, InferredDirectory>::const_iterator 1046 inferred = InferredDirectories.find(*ParentDir); 1047 if (inferred == InferredDirectories.end()) { 1048 // We haven't looked here before. Load a module map, if there is 1049 // one. 1050 bool IsFrameworkDir = Parent.ends_with(".framework"); 1051 if (OptionalFileEntryRef ModMapFile = 1052 HeaderInfo.lookupModuleMapFile(*ParentDir, IsFrameworkDir)) { 1053 // TODO: Parsing a module map should populate `InferredDirectories` 1054 // so we don't need to do a full load here. 1055 parseAndLoadModuleMapFile(*ModMapFile, Attrs.IsSystem, *ParentDir); 1056 inferred = InferredDirectories.find(*ParentDir); 1057 } 1058 1059 if (inferred == InferredDirectories.end()) 1060 inferred = InferredDirectories.insert( 1061 std::make_pair(*ParentDir, InferredDirectory())).first; 1062 } 1063 1064 if (inferred->second.InferModules) { 1065 // We're allowed to infer for this directory, but make sure it's okay 1066 // to infer this particular module. 1067 StringRef Name = llvm::sys::path::stem(FrameworkDirName); 1068 canInfer = 1069 !llvm::is_contained(inferred->second.ExcludedModules, Name); 1070 1071 Attrs.IsSystem |= inferred->second.Attrs.IsSystem; 1072 Attrs.IsExternC |= inferred->second.Attrs.IsExternC; 1073 Attrs.IsExhaustive |= inferred->second.Attrs.IsExhaustive; 1074 Attrs.NoUndeclaredIncludes |= 1075 inferred->second.Attrs.NoUndeclaredIncludes; 1076 ModuleMapFID = inferred->second.ModuleMapFID; 1077 } 1078 } 1079 } 1080 1081 // If we're not allowed to infer a framework module, don't. 1082 if (!canInfer) 1083 return nullptr; 1084 } else { 1085 ModuleMapFID = getModuleMapFileIDForUniquing(Parent); 1086 } 1087 1088 // Look for an umbrella header. 1089 SmallString<128> UmbrellaName = FrameworkDir.getName(); 1090 llvm::sys::path::append(UmbrellaName, "Headers", ModuleName + ".h"); 1091 auto UmbrellaHeader = FileMgr.getOptionalFileRef(UmbrellaName); 1092 1093 // FIXME: If there's no umbrella header, we could probably scan the 1094 // framework to load *everything*. But, it's not clear that this is a good 1095 // idea. 1096 if (!UmbrellaHeader) 1097 return nullptr; 1098 1099 Module *Result = new (ModulesAlloc.Allocate()) 1100 Module(ModuleConstructorTag{}, ModuleName, SourceLocation(), Parent, 1101 /*IsFramework=*/true, /*IsExplicit=*/false, NumCreatedModules++); 1102 setInferredModuleAllowedBy(Result, ModuleMapFID); 1103 if (!Parent) { 1104 if (LangOpts.CurrentModule == ModuleName) 1105 SourceModule = Result; 1106 Modules[ModuleName] = Result; 1107 ModuleScopeIDs[Result] = CurrentModuleScopeID; 1108 } 1109 1110 Result->IsSystem |= Attrs.IsSystem; 1111 Result->IsExternC |= Attrs.IsExternC; 1112 Result->ConfigMacrosExhaustive |= Attrs.IsExhaustive; 1113 Result->NoUndeclaredIncludes |= Attrs.NoUndeclaredIncludes; 1114 Result->Directory = FrameworkDir; 1115 1116 // Chop off the first framework bit, as that is implied. 1117 StringRef RelativePath = UmbrellaName.str().substr( 1118 Result->getTopLevelModule()->Directory->getName().size()); 1119 RelativePath = llvm::sys::path::relative_path(RelativePath); 1120 1121 // umbrella header "umbrella-header-name" 1122 setUmbrellaHeaderAsWritten(Result, *UmbrellaHeader, ModuleName + ".h", 1123 RelativePath); 1124 1125 // export * 1126 Result->Exports.push_back(Module::ExportDecl(nullptr, true)); 1127 1128 // module * { export * } 1129 Result->InferSubmodules = true; 1130 Result->InferExportWildcard = true; 1131 1132 // Look for subframeworks. 1133 std::error_code EC; 1134 SmallString<128> SubframeworksDirName = FrameworkDir.getName(); 1135 llvm::sys::path::append(SubframeworksDirName, "Frameworks"); 1136 llvm::sys::path::native(SubframeworksDirName); 1137 llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem(); 1138 for (llvm::vfs::directory_iterator 1139 Dir = FS.dir_begin(SubframeworksDirName, EC), 1140 DirEnd; 1141 Dir != DirEnd && !EC; Dir.increment(EC)) { 1142 if (!StringRef(Dir->path()).ends_with(".framework")) 1143 continue; 1144 1145 if (auto SubframeworkDir = FileMgr.getOptionalDirectoryRef(Dir->path())) { 1146 // Note: as an egregious but useful hack, we use the real path here and 1147 // check whether it is actually a subdirectory of the parent directory. 1148 // This will not be the case if the 'subframework' is actually a symlink 1149 // out to a top-level framework. 1150 StringRef SubframeworkDirName = 1151 FileMgr.getCanonicalName(*SubframeworkDir); 1152 bool FoundParent = false; 1153 do { 1154 // Get the parent directory name. 1155 SubframeworkDirName 1156 = llvm::sys::path::parent_path(SubframeworkDirName); 1157 if (SubframeworkDirName.empty()) 1158 break; 1159 1160 if (auto SubDir = 1161 FileMgr.getOptionalDirectoryRef(SubframeworkDirName)) { 1162 if (*SubDir == FrameworkDir) { 1163 FoundParent = true; 1164 break; 1165 } 1166 } 1167 } while (true); 1168 1169 if (!FoundParent) 1170 continue; 1171 1172 // FIXME: Do we want to warn about subframeworks without umbrella headers? 1173 inferFrameworkModule(*SubframeworkDir, Attrs, Result); 1174 } 1175 } 1176 1177 // If the module is a top-level framework, automatically link against the 1178 // framework. 1179 if (!Result->isSubFramework()) 1180 inferFrameworkLink(Result); 1181 1182 return Result; 1183 } 1184 1185 Module *ModuleMap::createShadowedModule(StringRef Name, bool IsFramework, 1186 Module *ShadowingModule) { 1187 1188 // Create a new module with this name. 1189 Module *Result = new (ModulesAlloc.Allocate()) 1190 Module(ModuleConstructorTag{}, Name, SourceLocation(), /*Parent=*/nullptr, 1191 IsFramework, /*IsExplicit=*/false, NumCreatedModules++); 1192 Result->ShadowingModule = ShadowingModule; 1193 Result->markUnavailable(/*Unimportable*/true); 1194 ModuleScopeIDs[Result] = CurrentModuleScopeID; 1195 ShadowModules.push_back(Result); 1196 1197 return Result; 1198 } 1199 1200 void ModuleMap::setUmbrellaHeaderAsWritten( 1201 Module *Mod, FileEntryRef UmbrellaHeader, const Twine &NameAsWritten, 1202 const Twine &PathRelativeToRootModuleDirectory) { 1203 Headers[UmbrellaHeader].push_back(KnownHeader(Mod, NormalHeader)); 1204 Mod->Umbrella = UmbrellaHeader; 1205 Mod->UmbrellaAsWritten = NameAsWritten.str(); 1206 Mod->UmbrellaRelativeToRootModuleDirectory = 1207 PathRelativeToRootModuleDirectory.str(); 1208 UmbrellaDirs[UmbrellaHeader.getDir()] = Mod; 1209 1210 // Notify callbacks that we just added a new header. 1211 for (const auto &Cb : Callbacks) 1212 Cb->moduleMapAddUmbrellaHeader(UmbrellaHeader); 1213 } 1214 1215 void ModuleMap::setUmbrellaDirAsWritten( 1216 Module *Mod, DirectoryEntryRef UmbrellaDir, const Twine &NameAsWritten, 1217 const Twine &PathRelativeToRootModuleDirectory) { 1218 Mod->Umbrella = UmbrellaDir; 1219 Mod->UmbrellaAsWritten = NameAsWritten.str(); 1220 Mod->UmbrellaRelativeToRootModuleDirectory = 1221 PathRelativeToRootModuleDirectory.str(); 1222 UmbrellaDirs[UmbrellaDir] = Mod; 1223 } 1224 1225 void ModuleMap::addUnresolvedHeader(Module *Mod, 1226 Module::UnresolvedHeaderDirective Header, 1227 bool &NeedsFramework) { 1228 // If there is a builtin counterpart to this file, add it now so it can 1229 // wrap the system header. 1230 if (resolveAsBuiltinHeader(Mod, Header)) { 1231 // If we have both a builtin and system version of the file, the 1232 // builtin version may want to inject macros into the system header, so 1233 // force the system header to be treated as a textual header in this 1234 // case. 1235 Header.Kind = headerRoleToKind(ModuleMap::ModuleHeaderRole( 1236 headerKindToRole(Header.Kind) | ModuleMap::TextualHeader)); 1237 Header.HasBuiltinHeader = true; 1238 } 1239 1240 // If possible, don't stat the header until we need to. This requires the 1241 // user to have provided us with some stat information about the file. 1242 // FIXME: Add support for lazily stat'ing umbrella headers and excluded 1243 // headers. 1244 if ((Header.Size || Header.ModTime) && !Header.IsUmbrella && 1245 Header.Kind != Module::HK_Excluded) { 1246 // We expect more variation in mtime than size, so if we're given both, 1247 // use the mtime as the key. 1248 if (Header.ModTime) 1249 LazyHeadersByModTime[*Header.ModTime].push_back(Mod); 1250 else 1251 LazyHeadersBySize[*Header.Size].push_back(Mod); 1252 Mod->UnresolvedHeaders.push_back(Header); 1253 return; 1254 } 1255 1256 // We don't have stat information or can't defer looking this file up. 1257 // Perform the lookup now. 1258 resolveHeader(Mod, Header, NeedsFramework); 1259 } 1260 1261 void ModuleMap::resolveHeaderDirectives(const FileEntry *File) const { 1262 auto BySize = LazyHeadersBySize.find(File->getSize()); 1263 if (BySize != LazyHeadersBySize.end()) { 1264 for (auto *M : BySize->second) 1265 resolveHeaderDirectives(M, File); 1266 LazyHeadersBySize.erase(BySize); 1267 } 1268 1269 auto ByModTime = LazyHeadersByModTime.find(File->getModificationTime()); 1270 if (ByModTime != LazyHeadersByModTime.end()) { 1271 for (auto *M : ByModTime->second) 1272 resolveHeaderDirectives(M, File); 1273 LazyHeadersByModTime.erase(ByModTime); 1274 } 1275 } 1276 1277 void ModuleMap::resolveHeaderDirectives( 1278 Module *Mod, std::optional<const FileEntry *> File) const { 1279 bool NeedsFramework = false; 1280 SmallVector<Module::UnresolvedHeaderDirective, 1> NewHeaders; 1281 const auto Size = File ? (*File)->getSize() : 0; 1282 const auto ModTime = File ? (*File)->getModificationTime() : 0; 1283 1284 for (auto &Header : Mod->UnresolvedHeaders) { 1285 if (File && ((Header.ModTime && Header.ModTime != ModTime) || 1286 (Header.Size && Header.Size != Size))) 1287 NewHeaders.push_back(Header); 1288 else 1289 // This operation is logically const; we're just changing how we represent 1290 // the header information for this file. 1291 const_cast<ModuleMap *>(this)->resolveHeader(Mod, Header, NeedsFramework); 1292 } 1293 Mod->UnresolvedHeaders.swap(NewHeaders); 1294 } 1295 1296 void ModuleMap::addHeader(Module *Mod, Module::Header Header, 1297 ModuleHeaderRole Role, bool Imported) { 1298 KnownHeader KH(Mod, Role); 1299 1300 FileEntryRef HeaderEntry = Header.Entry; 1301 1302 // Only add each header to the headers list once. 1303 // FIXME: Should we diagnose if a header is listed twice in the 1304 // same module definition? 1305 auto &HeaderList = Headers[HeaderEntry]; 1306 if (llvm::is_contained(HeaderList, KH)) 1307 return; 1308 1309 HeaderList.push_back(KH); 1310 Mod->addHeader(headerRoleToKind(Role), std::move(Header)); 1311 1312 bool isCompilingModuleHeader = Mod->isForBuilding(LangOpts); 1313 if (!Imported || isCompilingModuleHeader) { 1314 // When we import HeaderFileInfo, the external source is expected to 1315 // set the isModuleHeader flag itself. 1316 HeaderInfo.MarkFileModuleHeader(HeaderEntry, Role, isCompilingModuleHeader); 1317 } 1318 1319 // Notify callbacks that we just added a new header. 1320 for (const auto &Cb : Callbacks) 1321 Cb->moduleMapAddHeader(HeaderEntry.getName()); 1322 } 1323 1324 bool ModuleMap::parseModuleMapFile(FileEntryRef File, bool IsSystem, 1325 DirectoryEntryRef Dir, FileID ID, 1326 SourceLocation ExternModuleLoc) { 1327 llvm::DenseMap<const FileEntry *, const modulemap::ModuleMapFile *>::iterator 1328 Known = ParsedModuleMap.find(File); 1329 if (Known != ParsedModuleMap.end()) 1330 return Known->second == nullptr; 1331 1332 // If the module map file wasn't already entered, do so now. 1333 if (ID.isInvalid()) { 1334 ID = SourceMgr.translateFile(File); 1335 if (ID.isInvalid() || SourceMgr.isLoadedFileID(ID)) { 1336 auto FileCharacter = 1337 IsSystem ? SrcMgr::C_System_ModuleMap : SrcMgr::C_User_ModuleMap; 1338 ID = SourceMgr.createFileID(File, ExternModuleLoc, FileCharacter); 1339 } 1340 } 1341 1342 std::optional<llvm::MemoryBufferRef> Buffer = SourceMgr.getBufferOrNone(ID); 1343 if (!Buffer) { 1344 ParsedModuleMap[File] = nullptr; 1345 return true; 1346 } 1347 1348 Diags.Report(diag::remark_mmap_parse) << File.getName(); 1349 std::optional<modulemap::ModuleMapFile> MaybeMMF = 1350 modulemap::parseModuleMap(ID, Dir, SourceMgr, Diags, IsSystem, nullptr); 1351 1352 if (!MaybeMMF) { 1353 ParsedModuleMap[File] = nullptr; 1354 return true; 1355 } 1356 1357 ParsedModuleMaps.push_back( 1358 std::make_unique<modulemap::ModuleMapFile>(std::move(*MaybeMMF))); 1359 const modulemap::ModuleMapFile &MMF = *ParsedModuleMaps.back(); 1360 std::vector<const modulemap::ExternModuleDecl *> PendingExternalModuleMaps; 1361 for (const auto &Decl : MMF.Decls) { 1362 std::visit(llvm::makeVisitor( 1363 [&](const modulemap::ModuleDecl &MD) { 1364 // Only use the first part of the name even for submodules. 1365 // This will correctly load the submodule declarations when 1366 // the module is loaded. 1367 auto &ModuleDecls = 1368 ParsedModules[StringRef(MD.Id.front().first)]; 1369 ModuleDecls.push_back(std::pair(&MMF, &MD)); 1370 }, 1371 [&](const modulemap::ExternModuleDecl &EMD) { 1372 PendingExternalModuleMaps.push_back(&EMD); 1373 }), 1374 Decl); 1375 } 1376 1377 for (const modulemap::ExternModuleDecl *EMD : PendingExternalModuleMaps) { 1378 StringRef FileNameRef = EMD->Path; 1379 SmallString<128> ModuleMapFileName; 1380 if (llvm::sys::path::is_relative(FileNameRef)) { 1381 ModuleMapFileName += Dir.getName(); 1382 llvm::sys::path::append(ModuleMapFileName, EMD->Path); 1383 FileNameRef = ModuleMapFileName; 1384 } 1385 1386 if (auto EFile = 1387 SourceMgr.getFileManager().getOptionalFileRef(FileNameRef)) { 1388 parseModuleMapFile(*EFile, IsSystem, EFile->getDir(), FileID(), 1389 ExternModuleLoc); 1390 } 1391 } 1392 1393 ParsedModuleMap[File] = &MMF; 1394 1395 for (const auto &Cb : Callbacks) 1396 Cb->moduleMapFileRead(SourceLocation(), File, IsSystem); 1397 1398 return false; 1399 } 1400 1401 FileID ModuleMap::getContainingModuleMapFileID(const Module *Module) const { 1402 if (Module->DefinitionLoc.isInvalid()) 1403 return {}; 1404 1405 return SourceMgr.getFileID(Module->DefinitionLoc); 1406 } 1407 1408 OptionalFileEntryRef 1409 ModuleMap::getContainingModuleMapFile(const Module *Module) const { 1410 return SourceMgr.getFileEntryRefForID(getContainingModuleMapFileID(Module)); 1411 } 1412 1413 FileID ModuleMap::getModuleMapFileIDForUniquing(const Module *M) const { 1414 if (M->IsInferred) { 1415 assert(InferredModuleAllowedBy.count(M) && "missing inferred module map"); 1416 return InferredModuleAllowedBy.find(M)->second; 1417 } 1418 return getContainingModuleMapFileID(M); 1419 } 1420 1421 OptionalFileEntryRef 1422 ModuleMap::getModuleMapFileForUniquing(const Module *M) const { 1423 return SourceMgr.getFileEntryRefForID(getModuleMapFileIDForUniquing(M)); 1424 } 1425 1426 void ModuleMap::setInferredModuleAllowedBy(Module *M, FileID ModMapFID) { 1427 M->IsInferred = true; 1428 InferredModuleAllowedBy[M] = ModMapFID; 1429 } 1430 1431 std::error_code 1432 ModuleMap::canonicalizeModuleMapPath(SmallVectorImpl<char> &Path) { 1433 StringRef Dir = llvm::sys::path::parent_path({Path.data(), Path.size()}); 1434 1435 // Do not canonicalize within the framework; the module map loader expects 1436 // Modules/ not Versions/A/Modules. 1437 if (llvm::sys::path::filename(Dir) == "Modules") { 1438 StringRef Parent = llvm::sys::path::parent_path(Dir); 1439 if (Parent.ends_with(".framework")) 1440 Dir = Parent; 1441 } 1442 1443 FileManager &FM = SourceMgr.getFileManager(); 1444 auto DirEntry = FM.getDirectoryRef(Dir.empty() ? "." : Dir); 1445 if (!DirEntry) 1446 return llvm::errorToErrorCode(DirEntry.takeError()); 1447 1448 // Canonicalize the directory. 1449 StringRef CanonicalDir = FM.getCanonicalName(*DirEntry); 1450 if (CanonicalDir != Dir) 1451 llvm::sys::path::replace_path_prefix(Path, Dir, CanonicalDir); 1452 1453 // In theory, the filename component should also be canonicalized if it 1454 // on a case-insensitive filesystem. However, the extra canonicalization is 1455 // expensive and if clang looked up the filename it will always be lowercase. 1456 1457 // Remove ., remove redundant separators, and switch to native separators. 1458 // This is needed for separators between CanonicalDir and the filename. 1459 llvm::sys::path::remove_dots(Path); 1460 1461 return std::error_code(); 1462 } 1463 1464 void ModuleMap::addAdditionalModuleMapFile(const Module *M, 1465 FileEntryRef ModuleMap) { 1466 AdditionalModMaps[M].insert(ModuleMap); 1467 } 1468 1469 LLVM_DUMP_METHOD void ModuleMap::dump() { 1470 llvm::errs() << "Modules:"; 1471 for (llvm::StringMap<Module *>::iterator M = Modules.begin(), 1472 MEnd = Modules.end(); 1473 M != MEnd; ++M) 1474 M->getValue()->print(llvm::errs(), 2); 1475 1476 llvm::errs() << "Headers:"; 1477 for (HeadersMap::iterator H = Headers.begin(), HEnd = Headers.end(); 1478 H != HEnd; ++H) { 1479 llvm::errs() << " \"" << H->first.getName() << "\" -> "; 1480 for (SmallVectorImpl<KnownHeader>::const_iterator I = H->second.begin(), 1481 E = H->second.end(); 1482 I != E; ++I) { 1483 if (I != H->second.begin()) 1484 llvm::errs() << ","; 1485 llvm::errs() << I->getModule()->getFullModuleName(); 1486 } 1487 llvm::errs() << "\n"; 1488 } 1489 } 1490 1491 bool ModuleMap::resolveExports(Module *Mod, bool Complain) { 1492 auto Unresolved = std::move(Mod->UnresolvedExports); 1493 Mod->UnresolvedExports.clear(); 1494 for (auto &UE : Unresolved) { 1495 Module::ExportDecl Export = resolveExport(Mod, UE, Complain); 1496 if (Export.getPointer() || Export.getInt()) 1497 Mod->Exports.push_back(Export); 1498 else 1499 Mod->UnresolvedExports.push_back(UE); 1500 } 1501 return !Mod->UnresolvedExports.empty(); 1502 } 1503 1504 bool ModuleMap::resolveUses(Module *Mod, bool Complain) { 1505 auto *Top = Mod->getTopLevelModule(); 1506 auto Unresolved = std::move(Top->UnresolvedDirectUses); 1507 Top->UnresolvedDirectUses.clear(); 1508 for (auto &UDU : Unresolved) { 1509 Module *DirectUse = resolveModuleId(UDU, Top, Complain); 1510 if (DirectUse) 1511 Top->DirectUses.push_back(DirectUse); 1512 else 1513 Top->UnresolvedDirectUses.push_back(UDU); 1514 } 1515 return !Top->UnresolvedDirectUses.empty(); 1516 } 1517 1518 bool ModuleMap::resolveConflicts(Module *Mod, bool Complain) { 1519 auto Unresolved = std::move(Mod->UnresolvedConflicts); 1520 Mod->UnresolvedConflicts.clear(); 1521 for (auto &UC : Unresolved) { 1522 if (Module *OtherMod = resolveModuleId(UC.Id, Mod, Complain)) { 1523 Module::Conflict Conflict; 1524 Conflict.Other = OtherMod; 1525 Conflict.Message = UC.Message; 1526 Mod->Conflicts.push_back(Conflict); 1527 } else 1528 Mod->UnresolvedConflicts.push_back(UC); 1529 } 1530 return !Mod->UnresolvedConflicts.empty(); 1531 } 1532 1533 //----------------------------------------------------------------------------// 1534 // Module map file loader 1535 //----------------------------------------------------------------------------// 1536 1537 namespace clang { 1538 class ModuleMapLoader { 1539 SourceManager &SourceMgr; 1540 1541 DiagnosticsEngine &Diags; 1542 ModuleMap ⤅ 1543 1544 /// The current module map file. 1545 FileID ModuleMapFID; 1546 1547 /// Source location of most recent loaded module declaration 1548 SourceLocation CurrModuleDeclLoc; 1549 1550 /// The directory that file names in this module map file should 1551 /// be resolved relative to. 1552 DirectoryEntryRef Directory; 1553 1554 /// Whether this module map is in a system header directory. 1555 bool IsSystem; 1556 1557 /// Whether an error occurred. 1558 bool HadError = false; 1559 1560 /// The active module. 1561 Module *ActiveModule = nullptr; 1562 1563 /// Whether a module uses the 'requires excluded' hack to mark its 1564 /// contents as 'textual'. 1565 /// 1566 /// On older Darwin SDK versions, 'requires excluded' is used to mark the 1567 /// contents of the Darwin.C.excluded (assert.h) and Tcl.Private modules as 1568 /// non-modular headers. For backwards compatibility, we continue to 1569 /// support this idiom for just these modules, and map the headers to 1570 /// 'textual' to match the original intent. 1571 llvm::SmallPtrSet<Module *, 2> UsesRequiresExcludedHack; 1572 1573 void handleModuleDecl(const modulemap::ModuleDecl &MD); 1574 void handleExternModuleDecl(const modulemap::ExternModuleDecl &EMD); 1575 void handleRequiresDecl(const modulemap::RequiresDecl &RD); 1576 void handleHeaderDecl(const modulemap::HeaderDecl &HD); 1577 void handleUmbrellaDirDecl(const modulemap::UmbrellaDirDecl &UDD); 1578 void handleExportDecl(const modulemap::ExportDecl &ED); 1579 void handleExportAsDecl(const modulemap::ExportAsDecl &EAD); 1580 void handleUseDecl(const modulemap::UseDecl &UD); 1581 void handleLinkDecl(const modulemap::LinkDecl &LD); 1582 void handleConfigMacros(const modulemap::ConfigMacrosDecl &CMD); 1583 void handleConflict(const modulemap::ConflictDecl &CD); 1584 void handleInferredModuleDecl(const modulemap::ModuleDecl &MD); 1585 1586 /// Private modules are canonicalized as Foo_Private. Clang provides extra 1587 /// module map search logic to find the appropriate private module when PCH 1588 /// is used with implicit module maps. Warn when private modules are written 1589 /// in other ways (FooPrivate and Foo.Private), providing notes and fixits. 1590 void diagnosePrivateModules(SourceLocation StartLoc); 1591 1592 using Attributes = ModuleMap::Attributes; 1593 1594 public: 1595 ModuleMapLoader(SourceManager &SourceMgr, DiagnosticsEngine &Diags, 1596 ModuleMap &Map, FileID ModuleMapFID, 1597 DirectoryEntryRef Directory, bool IsSystem) 1598 : SourceMgr(SourceMgr), Diags(Diags), Map(Map), 1599 ModuleMapFID(ModuleMapFID), Directory(Directory), IsSystem(IsSystem) {} 1600 1601 bool loadModuleDecl(const modulemap::ModuleDecl &MD); 1602 bool loadExternModuleDecl(const modulemap::ExternModuleDecl &EMD); 1603 bool parseAndLoadModuleMapFile(const modulemap::ModuleMapFile &MMF); 1604 }; 1605 1606 } // namespace clang 1607 1608 /// Private modules are canonicalized as Foo_Private. Clang provides extra 1609 /// module map search logic to find the appropriate private module when PCH 1610 /// is used with implicit module maps. Warn when private modules are written 1611 /// in other ways (FooPrivate and Foo.Private), providing notes and fixits. 1612 void ModuleMapLoader::diagnosePrivateModules(SourceLocation StartLoc) { 1613 auto GenNoteAndFixIt = [&](StringRef BadName, StringRef Canonical, 1614 const Module *M, SourceRange ReplLoc) { 1615 auto D = Diags.Report(ActiveModule->DefinitionLoc, 1616 diag::note_mmap_rename_top_level_private_module); 1617 D << BadName << M->Name; 1618 D << FixItHint::CreateReplacement(ReplLoc, Canonical); 1619 }; 1620 1621 for (auto E = Map.module_begin(); E != Map.module_end(); ++E) { 1622 auto const *M = E->getValue(); 1623 if (M->Directory != ActiveModule->Directory) 1624 continue; 1625 1626 SmallString<128> FullName(ActiveModule->getFullModuleName()); 1627 if (!FullName.starts_with(M->Name) && !FullName.ends_with("Private")) 1628 continue; 1629 SmallString<128> FixedPrivModDecl; 1630 SmallString<128> Canonical(M->Name); 1631 Canonical.append("_Private"); 1632 1633 // Foo.Private -> Foo_Private 1634 if (ActiveModule->Parent && ActiveModule->Name == "Private" && !M->Parent && 1635 M->Name == ActiveModule->Parent->Name) { 1636 Diags.Report(ActiveModule->DefinitionLoc, 1637 diag::warn_mmap_mismatched_private_submodule) 1638 << FullName; 1639 1640 SourceLocation FixItInitBegin = CurrModuleDeclLoc; 1641 if (StartLoc.isValid()) 1642 FixItInitBegin = StartLoc; 1643 1644 if (ActiveModule->Parent->IsFramework) 1645 FixedPrivModDecl.append("framework "); 1646 FixedPrivModDecl.append("module "); 1647 FixedPrivModDecl.append(Canonical); 1648 1649 GenNoteAndFixIt(FullName, FixedPrivModDecl, M, 1650 SourceRange(FixItInitBegin, ActiveModule->DefinitionLoc)); 1651 continue; 1652 } 1653 1654 // FooPrivate and whatnots -> Foo_Private 1655 if (!ActiveModule->Parent && !M->Parent && M->Name != ActiveModule->Name && 1656 ActiveModule->Name != Canonical) { 1657 Diags.Report(ActiveModule->DefinitionLoc, 1658 diag::warn_mmap_mismatched_private_module_name) 1659 << ActiveModule->Name; 1660 GenNoteAndFixIt(ActiveModule->Name, Canonical, M, 1661 SourceRange(ActiveModule->DefinitionLoc)); 1662 } 1663 } 1664 } 1665 1666 void ModuleMapLoader::handleModuleDecl(const modulemap::ModuleDecl &MD) { 1667 if (MD.Id.front().first == "*") 1668 return handleInferredModuleDecl(MD); 1669 1670 CurrModuleDeclLoc = MD.Location; 1671 1672 Module *PreviousActiveModule = ActiveModule; 1673 if (MD.Id.size() > 1) { 1674 // This module map defines a submodule. Go find the module of which it 1675 // is a submodule. 1676 ActiveModule = nullptr; 1677 const Module *TopLevelModule = nullptr; 1678 for (unsigned I = 0, N = MD.Id.size() - 1; I != N; ++I) { 1679 if (Module *Next = 1680 Map.lookupModuleQualified(MD.Id[I].first, ActiveModule)) { 1681 if (I == 0) 1682 TopLevelModule = Next; 1683 ActiveModule = Next; 1684 continue; 1685 } 1686 1687 Diags.Report(MD.Id[I].second, diag::err_mmap_missing_parent_module) 1688 << MD.Id[I].first << (ActiveModule != nullptr) 1689 << (ActiveModule 1690 ? ActiveModule->getTopLevelModule()->getFullModuleName() 1691 : ""); 1692 HadError = true; 1693 } 1694 1695 if (TopLevelModule && 1696 ModuleMapFID != Map.getContainingModuleMapFileID(TopLevelModule)) { 1697 assert(ModuleMapFID != 1698 Map.getModuleMapFileIDForUniquing(TopLevelModule) && 1699 "submodule defined in same file as 'module *' that allowed its " 1700 "top-level module"); 1701 Map.addAdditionalModuleMapFile( 1702 TopLevelModule, *SourceMgr.getFileEntryRefForID(ModuleMapFID)); 1703 } 1704 } 1705 1706 StringRef ModuleName = MD.Id.back().first; 1707 SourceLocation ModuleNameLoc = MD.Id.back().second; 1708 1709 // Determine whether this (sub)module has already been defined. 1710 Module *ShadowingModule = nullptr; 1711 if (Module *Existing = Map.lookupModuleQualified(ModuleName, ActiveModule)) { 1712 // We might see a (re)definition of a module that we already have a 1713 // definition for in four cases: 1714 // - If we loaded one definition from an AST file and we've just found a 1715 // corresponding definition in a module map file, or 1716 bool LoadedFromASTFile = Existing->IsFromModuleFile; 1717 // - If we previously inferred this module from different module map file. 1718 bool Inferred = Existing->IsInferred; 1719 // - If we're building a framework that vends a module map, we might've 1720 // previously seen the one in intermediate products and now the system 1721 // one. 1722 // FIXME: If we're parsing module map file that looks like this: 1723 // framework module FW { ... } 1724 // module FW.Sub { ... } 1725 // We can't check the framework qualifier, since it's not attached to 1726 // the definition of Sub. Checking that qualifier on \c Existing is 1727 // not correct either, since we might've previously seen: 1728 // module FW { ... } 1729 // module FW.Sub { ... } 1730 // We should enforce consistency of redefinitions so that we can rely 1731 // that \c Existing is part of a framework iff the redefinition of FW 1732 // we have just skipped had it too. Once we do that, stop checking 1733 // the local framework qualifier and only rely on \c Existing. 1734 bool PartOfFramework = MD.Framework || Existing->isPartOfFramework(); 1735 // - If we're building a (preprocessed) module and we've just loaded the 1736 // module map file from which it was created. 1737 bool ParsedAsMainInput = 1738 Map.LangOpts.getCompilingModule() == LangOptions::CMK_ModuleMap && 1739 Map.LangOpts.CurrentModule == ModuleName && 1740 SourceMgr.getDecomposedLoc(ModuleNameLoc).first != 1741 SourceMgr.getDecomposedLoc(Existing->DefinitionLoc).first; 1742 // TODO: Remove this check when we can avoid loading module maps multiple 1743 // times. 1744 bool SameModuleDecl = ModuleNameLoc == Existing->DefinitionLoc; 1745 if (LoadedFromASTFile || Inferred || PartOfFramework || ParsedAsMainInput || 1746 SameModuleDecl) { 1747 ActiveModule = PreviousActiveModule; 1748 // Skip the module definition. 1749 return; 1750 } 1751 1752 if (!Existing->Parent && Map.mayShadowNewModule(Existing)) { 1753 ShadowingModule = Existing; 1754 } else { 1755 // This is not a shawdowed module decl, it is an illegal redefinition. 1756 Diags.Report(ModuleNameLoc, diag::err_mmap_module_redefinition) 1757 << ModuleName; 1758 Diags.Report(Existing->DefinitionLoc, diag::note_mmap_prev_definition); 1759 HadError = true; 1760 return; 1761 } 1762 } 1763 1764 // Start defining this module. 1765 if (ShadowingModule) { 1766 ActiveModule = 1767 Map.createShadowedModule(ModuleName, MD.Framework, ShadowingModule); 1768 } else { 1769 ActiveModule = Map.findOrCreateModuleFirst(ModuleName, ActiveModule, 1770 MD.Framework, MD.Explicit); 1771 } 1772 1773 ActiveModule->DefinitionLoc = ModuleNameLoc; 1774 if (MD.Attrs.IsSystem || IsSystem) 1775 ActiveModule->IsSystem = true; 1776 if (MD.Attrs.IsExternC) 1777 ActiveModule->IsExternC = true; 1778 if (MD.Attrs.NoUndeclaredIncludes) 1779 ActiveModule->NoUndeclaredIncludes = true; 1780 ActiveModule->Directory = Directory; 1781 1782 StringRef MapFileName( 1783 SourceMgr.getFileEntryRefForID(ModuleMapFID)->getName()); 1784 if (MapFileName.ends_with("module.private.modulemap") || 1785 MapFileName.ends_with("module_private.map")) { 1786 ActiveModule->ModuleMapIsPrivate = true; 1787 } 1788 1789 // Private modules named as FooPrivate, Foo.Private or similar are likely a 1790 // user error; provide warnings, notes and fixits to direct users to use 1791 // Foo_Private instead. 1792 SourceLocation StartLoc = 1793 SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID()); 1794 if (Map.HeaderInfo.getHeaderSearchOpts().ImplicitModuleMaps && 1795 !Diags.isIgnored(diag::warn_mmap_mismatched_private_submodule, 1796 StartLoc) && 1797 !Diags.isIgnored(diag::warn_mmap_mismatched_private_module_name, 1798 StartLoc) && 1799 ActiveModule->ModuleMapIsPrivate) 1800 diagnosePrivateModules(MD.Location); 1801 1802 for (const modulemap::Decl &Decl : MD.Decls) { 1803 std::visit( 1804 llvm::makeVisitor( 1805 [&](const modulemap::RequiresDecl &RD) { handleRequiresDecl(RD); }, 1806 [&](const modulemap::HeaderDecl &HD) { handleHeaderDecl(HD); }, 1807 [&](const modulemap::UmbrellaDirDecl &UDD) { 1808 handleUmbrellaDirDecl(UDD); 1809 }, 1810 [&](const modulemap::ModuleDecl &MD) { handleModuleDecl(MD); }, 1811 [&](const modulemap::ExportDecl &ED) { handleExportDecl(ED); }, 1812 [&](const modulemap::ExportAsDecl &EAD) { 1813 handleExportAsDecl(EAD); 1814 }, 1815 [&](const modulemap::ExternModuleDecl &EMD) { 1816 handleExternModuleDecl(EMD); 1817 }, 1818 [&](const modulemap::UseDecl &UD) { handleUseDecl(UD); }, 1819 [&](const modulemap::LinkDecl &LD) { handleLinkDecl(LD); }, 1820 [&](const modulemap::ConfigMacrosDecl &CMD) { 1821 handleConfigMacros(CMD); 1822 }, 1823 [&](const modulemap::ConflictDecl &CD) { handleConflict(CD); }, 1824 [&](const modulemap::ExcludeDecl &ED) { 1825 Diags.Report(ED.Location, diag::err_mmap_expected_member); 1826 }), 1827 Decl); 1828 } 1829 1830 // If the active module is a top-level framework, and there are no link 1831 // libraries, automatically link against the framework. 1832 if (ActiveModule->IsFramework && !ActiveModule->isSubFramework() && 1833 ActiveModule->LinkLibraries.empty()) 1834 inferFrameworkLink(ActiveModule); 1835 1836 // If the module meets all requirements but is still unavailable, mark the 1837 // whole tree as unavailable to prevent it from building. 1838 if (!ActiveModule->IsAvailable && !ActiveModule->IsUnimportable && 1839 ActiveModule->Parent) { 1840 ActiveModule->getTopLevelModule()->markUnavailable(/*Unimportable=*/false); 1841 ActiveModule->getTopLevelModule()->MissingHeaders.append( 1842 ActiveModule->MissingHeaders.begin(), ActiveModule->MissingHeaders.end()); 1843 } 1844 1845 // We're done parsing this module. Pop back to the previous module. 1846 ActiveModule = PreviousActiveModule; 1847 } 1848 1849 void ModuleMapLoader::handleExternModuleDecl( 1850 const modulemap::ExternModuleDecl &EMD) { 1851 StringRef FileNameRef = EMD.Path; 1852 SmallString<128> ModuleMapFileName; 1853 if (llvm::sys::path::is_relative(FileNameRef)) { 1854 ModuleMapFileName += Directory.getName(); 1855 llvm::sys::path::append(ModuleMapFileName, EMD.Path); 1856 FileNameRef = ModuleMapFileName; 1857 } 1858 if (auto File = SourceMgr.getFileManager().getOptionalFileRef(FileNameRef)) 1859 Map.parseAndLoadModuleMapFile( 1860 *File, IsSystem, 1861 Map.HeaderInfo.getHeaderSearchOpts().ModuleMapFileHomeIsCwd 1862 ? Directory 1863 : File->getDir(), 1864 FileID(), nullptr, EMD.Location); 1865 } 1866 1867 /// Whether to add the requirement \p Feature to the module \p M. 1868 /// 1869 /// This preserves backwards compatibility for two hacks in the Darwin system 1870 /// module map files: 1871 /// 1872 /// 1. The use of 'requires excluded' to make headers non-modular, which 1873 /// should really be mapped to 'textual' now that we have this feature. We 1874 /// drop the 'excluded' requirement, and set \p IsRequiresExcludedHack to 1875 /// true. Later, this bit will be used to map all the headers inside this 1876 /// module to 'textual'. 1877 /// 1878 /// This affects Darwin.C.excluded (for assert.h) and Tcl.Private. 1879 /// 1880 /// 2. Removes a bogus cplusplus requirement from IOKit.avc. This requirement 1881 /// was never correct and causes issues now that we check it, so drop it. 1882 static bool shouldAddRequirement(Module *M, StringRef Feature, 1883 bool &IsRequiresExcludedHack) { 1884 if (Feature == "excluded" && 1885 (M->fullModuleNameIs({"Darwin", "C", "excluded"}) || 1886 M->fullModuleNameIs({"Tcl", "Private"}))) { 1887 IsRequiresExcludedHack = true; 1888 return false; 1889 } else if (Feature == "cplusplus" && M->fullModuleNameIs({"IOKit", "avc"})) { 1890 return false; 1891 } 1892 1893 return true; 1894 } 1895 1896 void ModuleMapLoader::handleRequiresDecl(const modulemap::RequiresDecl &RD) { 1897 1898 for (const modulemap::RequiresFeature &RF : RD.Features) { 1899 bool IsRequiresExcludedHack = false; 1900 bool ShouldAddRequirement = 1901 shouldAddRequirement(ActiveModule, RF.Feature, IsRequiresExcludedHack); 1902 1903 if (IsRequiresExcludedHack) 1904 UsesRequiresExcludedHack.insert(ActiveModule); 1905 1906 if (ShouldAddRequirement) { 1907 // Add this feature. 1908 ActiveModule->addRequirement(RF.Feature, RF.RequiredState, Map.LangOpts, 1909 *Map.Target); 1910 } 1911 } 1912 } 1913 1914 void ModuleMapLoader::handleHeaderDecl(const modulemap::HeaderDecl &HD) { 1915 // We've already consumed the first token. 1916 ModuleMap::ModuleHeaderRole Role = ModuleMap::NormalHeader; 1917 1918 if (HD.Private) { 1919 Role = ModuleMap::PrivateHeader; 1920 } else if (HD.Excluded) { 1921 Role = ModuleMap::ExcludedHeader; 1922 } 1923 1924 if (HD.Textual) 1925 Role = ModuleMap::ModuleHeaderRole(Role | ModuleMap::TextualHeader); 1926 1927 if (UsesRequiresExcludedHack.count(ActiveModule)) { 1928 // Mark this header 'textual' (see doc comment for 1929 // Module::UsesRequiresExcludedHack). 1930 Role = ModuleMap::ModuleHeaderRole(Role | ModuleMap::TextualHeader); 1931 } 1932 1933 Module::UnresolvedHeaderDirective Header; 1934 Header.FileName = HD.Path; 1935 Header.FileNameLoc = HD.PathLoc; 1936 Header.IsUmbrella = HD.Umbrella; 1937 Header.Kind = Map.headerRoleToKind(Role); 1938 1939 // Check whether we already have an umbrella. 1940 if (Header.IsUmbrella && 1941 !std::holds_alternative<std::monostate>(ActiveModule->Umbrella)) { 1942 Diags.Report(Header.FileNameLoc, diag::err_mmap_umbrella_clash) 1943 << ActiveModule->getFullModuleName(); 1944 HadError = true; 1945 return; 1946 } 1947 1948 if (HD.Size) 1949 Header.Size = HD.Size; 1950 if (HD.MTime) 1951 Header.ModTime = HD.MTime; 1952 1953 bool NeedsFramework = false; 1954 // Don't add headers to the builtin modules if the builtin headers belong to 1955 // the system modules, with the exception of __stddef_max_align_t.h which 1956 // always had its own module. 1957 if (!Map.LangOpts.BuiltinHeadersInSystemModules || 1958 !isBuiltInModuleName(ActiveModule->getTopLevelModuleName()) || 1959 ActiveModule->fullModuleNameIs({"_Builtin_stddef", "max_align_t"})) 1960 Map.addUnresolvedHeader(ActiveModule, std::move(Header), NeedsFramework); 1961 1962 if (NeedsFramework) 1963 Diags.Report(CurrModuleDeclLoc, diag::note_mmap_add_framework_keyword) 1964 << ActiveModule->getFullModuleName() 1965 << FixItHint::CreateReplacement(CurrModuleDeclLoc, "framework module"); 1966 } 1967 1968 static bool compareModuleHeaders(const Module::Header &A, 1969 const Module::Header &B) { 1970 return A.NameAsWritten < B.NameAsWritten; 1971 } 1972 1973 void ModuleMapLoader::handleUmbrellaDirDecl( 1974 const modulemap::UmbrellaDirDecl &UDD) { 1975 std::string DirName = std::string(UDD.Path); 1976 std::string DirNameAsWritten = DirName; 1977 1978 // Check whether we already have an umbrella. 1979 if (!std::holds_alternative<std::monostate>(ActiveModule->Umbrella)) { 1980 Diags.Report(UDD.Location, diag::err_mmap_umbrella_clash) 1981 << ActiveModule->getFullModuleName(); 1982 HadError = true; 1983 return; 1984 } 1985 1986 // Look for this file. 1987 OptionalDirectoryEntryRef Dir; 1988 if (llvm::sys::path::is_absolute(DirName)) { 1989 Dir = SourceMgr.getFileManager().getOptionalDirectoryRef(DirName); 1990 } else { 1991 SmallString<128> PathName; 1992 PathName = Directory.getName(); 1993 llvm::sys::path::append(PathName, DirName); 1994 Dir = SourceMgr.getFileManager().getOptionalDirectoryRef(PathName); 1995 } 1996 1997 if (!Dir) { 1998 Diags.Report(UDD.Location, diag::warn_mmap_umbrella_dir_not_found) 1999 << DirName; 2000 return; 2001 } 2002 2003 if (UsesRequiresExcludedHack.count(ActiveModule)) { 2004 // Mark this header 'textual' (see doc comment for 2005 // ModuleMapLoader::UsesRequiresExcludedHack). Although iterating over the 2006 // directory is relatively expensive, in practice this only applies to the 2007 // uncommonly used Tcl module on Darwin platforms. 2008 std::error_code EC; 2009 SmallVector<Module::Header, 6> Headers; 2010 llvm::vfs::FileSystem &FS = 2011 SourceMgr.getFileManager().getVirtualFileSystem(); 2012 for (llvm::vfs::recursive_directory_iterator I(FS, Dir->getName(), EC), E; 2013 I != E && !EC; I.increment(EC)) { 2014 if (auto FE = SourceMgr.getFileManager().getOptionalFileRef(I->path())) { 2015 Module::Header Header = {"", std::string(I->path()), *FE}; 2016 Headers.push_back(std::move(Header)); 2017 } 2018 } 2019 2020 // Sort header paths so that the pcm doesn't depend on iteration order. 2021 llvm::stable_sort(Headers, compareModuleHeaders); 2022 2023 for (auto &Header : Headers) 2024 Map.addHeader(ActiveModule, std::move(Header), ModuleMap::TextualHeader); 2025 return; 2026 } 2027 2028 if (Module *OwningModule = Map.UmbrellaDirs[*Dir]) { 2029 Diags.Report(UDD.Location, diag::err_mmap_umbrella_clash) 2030 << OwningModule->getFullModuleName(); 2031 HadError = true; 2032 return; 2033 } 2034 2035 // Record this umbrella directory. 2036 Map.setUmbrellaDirAsWritten(ActiveModule, *Dir, DirNameAsWritten, DirName); 2037 } 2038 2039 void ModuleMapLoader::handleExportDecl(const modulemap::ExportDecl &ED) { 2040 Module::UnresolvedExportDecl Unresolved = {ED.Location, ED.Id, ED.Wildcard}; 2041 ActiveModule->UnresolvedExports.push_back(Unresolved); 2042 } 2043 2044 void ModuleMapLoader::handleExportAsDecl(const modulemap::ExportAsDecl &EAD) { 2045 const auto &ModName = EAD.Id.front(); 2046 2047 if (!ActiveModule->ExportAsModule.empty()) { 2048 if (ActiveModule->ExportAsModule == ModName.first) { 2049 Diags.Report(ModName.second, diag::warn_mmap_redundant_export_as) 2050 << ActiveModule->Name << ModName.first; 2051 } else { 2052 Diags.Report(ModName.second, diag::err_mmap_conflicting_export_as) 2053 << ActiveModule->Name << ActiveModule->ExportAsModule 2054 << ModName.first; 2055 } 2056 } 2057 2058 ActiveModule->ExportAsModule = ModName.first; 2059 Map.addLinkAsDependency(ActiveModule); 2060 } 2061 2062 void ModuleMapLoader::handleUseDecl(const modulemap::UseDecl &UD) { 2063 if (ActiveModule->Parent) 2064 Diags.Report(UD.Location, diag::err_mmap_use_decl_submodule); 2065 else 2066 ActiveModule->UnresolvedDirectUses.push_back(UD.Id); 2067 } 2068 2069 void ModuleMapLoader::handleLinkDecl(const modulemap::LinkDecl &LD) { 2070 ActiveModule->LinkLibraries.push_back( 2071 Module::LinkLibrary(std::string{LD.Library}, LD.Framework)); 2072 } 2073 2074 void ModuleMapLoader::handleConfigMacros( 2075 const modulemap::ConfigMacrosDecl &CMD) { 2076 if (ActiveModule->Parent) { 2077 Diags.Report(CMD.Location, diag::err_mmap_config_macro_submodule); 2078 return; 2079 } 2080 2081 // TODO: Is this really the behavior we want for multiple config_macros 2082 // declarations? If any of them are exhaustive then all of them are. 2083 if (CMD.Exhaustive) { 2084 ActiveModule->ConfigMacrosExhaustive = true; 2085 } 2086 ActiveModule->ConfigMacros.insert(ActiveModule->ConfigMacros.end(), 2087 CMD.Macros.begin(), CMD.Macros.end()); 2088 } 2089 2090 void ModuleMapLoader::handleConflict(const modulemap::ConflictDecl &CD) { 2091 Module::UnresolvedConflict Conflict; 2092 2093 Conflict.Id = CD.Id; 2094 Conflict.Message = CD.Message; 2095 2096 // FIXME: when we move to C++20 we should consider using emplace_back 2097 ActiveModule->UnresolvedConflicts.push_back(std::move(Conflict)); 2098 } 2099 2100 void ModuleMapLoader::handleInferredModuleDecl( 2101 const modulemap::ModuleDecl &MD) { 2102 SourceLocation StarLoc = MD.Id.front().second; 2103 2104 // Inferred modules must be submodules. 2105 if (!ActiveModule && !MD.Framework) { 2106 Diags.Report(StarLoc, diag::err_mmap_top_level_inferred_submodule); 2107 return; 2108 } 2109 2110 if (ActiveModule) { 2111 // Inferred modules must have umbrella directories. 2112 if (ActiveModule->IsAvailable && !ActiveModule->getEffectiveUmbrellaDir()) { 2113 Diags.Report(StarLoc, diag::err_mmap_inferred_no_umbrella); 2114 return; 2115 } 2116 2117 // Check for redefinition of an inferred module. 2118 if (ActiveModule->InferSubmodules) { 2119 Diags.Report(StarLoc, diag::err_mmap_inferred_redef); 2120 if (ActiveModule->InferredSubmoduleLoc.isValid()) 2121 Diags.Report(ActiveModule->InferredSubmoduleLoc, 2122 diag::note_mmap_prev_definition); 2123 return; 2124 } 2125 2126 // Check for the 'framework' keyword, which is not permitted here. 2127 if (MD.Framework) { 2128 Diags.Report(StarLoc, diag::err_mmap_inferred_framework_submodule); 2129 return; 2130 } 2131 } else if (MD.Explicit) { 2132 Diags.Report(StarLoc, diag::err_mmap_explicit_inferred_framework); 2133 return; 2134 } 2135 2136 if (ActiveModule) { 2137 // Note that we have an inferred submodule. 2138 ActiveModule->InferSubmodules = true; 2139 ActiveModule->InferredSubmoduleLoc = StarLoc; 2140 ActiveModule->InferExplicitSubmodules = MD.Explicit; 2141 } else { 2142 // We'll be inferring framework modules for this directory. 2143 auto &InfDir = Map.InferredDirectories[Directory]; 2144 InfDir.InferModules = true; 2145 InfDir.Attrs = MD.Attrs; 2146 InfDir.ModuleMapFID = ModuleMapFID; 2147 // FIXME: Handle the 'framework' keyword. 2148 } 2149 2150 for (const modulemap::Decl &Decl : MD.Decls) { 2151 std::visit( 2152 llvm::makeVisitor( 2153 [&](const auto &Other) { 2154 Diags.Report(Other.Location, 2155 diag::err_mmap_expected_inferred_member) 2156 << (ActiveModule != nullptr); 2157 }, 2158 [&](const modulemap::ExcludeDecl &ED) { 2159 // Only inferred frameworks can have exclude decls 2160 if (ActiveModule) { 2161 Diags.Report(ED.Location, 2162 diag::err_mmap_expected_inferred_member) 2163 << (ActiveModule != nullptr); 2164 HadError = true; 2165 return; 2166 } 2167 Map.InferredDirectories[Directory].ExcludedModules.emplace_back( 2168 ED.Module); 2169 }, 2170 [&](const modulemap::ExportDecl &ED) { 2171 // Only inferred submodules can have export decls 2172 if (!ActiveModule) { 2173 Diags.Report(ED.Location, 2174 diag::err_mmap_expected_inferred_member) 2175 << (ActiveModule != nullptr); 2176 HadError = true; 2177 return; 2178 } 2179 2180 if (ED.Wildcard && ED.Id.size() == 0) 2181 ActiveModule->InferExportWildcard = true; 2182 else 2183 Diags.Report(ED.Id.front().second, 2184 diag::err_mmap_expected_export_wildcard); 2185 }), 2186 Decl); 2187 } 2188 } 2189 2190 bool ModuleMapLoader::loadModuleDecl(const modulemap::ModuleDecl &MD) { 2191 handleModuleDecl(MD); 2192 return HadError; 2193 } 2194 2195 bool ModuleMapLoader::loadExternModuleDecl( 2196 const modulemap::ExternModuleDecl &EMD) { 2197 handleExternModuleDecl(EMD); 2198 return HadError; 2199 } 2200 2201 bool ModuleMapLoader::parseAndLoadModuleMapFile( 2202 const modulemap::ModuleMapFile &MMF) { 2203 for (const auto &Decl : MMF.Decls) { 2204 std::visit( 2205 llvm::makeVisitor( 2206 [&](const modulemap::ModuleDecl &MD) { handleModuleDecl(MD); }, 2207 [&](const modulemap::ExternModuleDecl &EMD) { 2208 handleExternModuleDecl(EMD); 2209 }), 2210 Decl); 2211 } 2212 return HadError; 2213 } 2214 2215 Module *ModuleMap::findOrLoadModule(StringRef Name) { 2216 llvm::StringMap<Module *>::const_iterator Known = Modules.find(Name); 2217 if (Known != Modules.end()) 2218 return Known->getValue(); 2219 2220 auto ParsedMod = ParsedModules.find(Name); 2221 if (ParsedMod == ParsedModules.end()) 2222 return nullptr; 2223 2224 Diags.Report(diag::remark_mmap_load_module) << Name; 2225 2226 for (const auto &ModuleDecl : ParsedMod->second) { 2227 const modulemap::ModuleMapFile &MMF = *ModuleDecl.first; 2228 ModuleMapLoader Loader(SourceMgr, Diags, const_cast<ModuleMap &>(*this), 2229 MMF.ID, *MMF.Dir, MMF.IsSystem); 2230 if (Loader.loadModuleDecl(*ModuleDecl.second)) 2231 return nullptr; 2232 } 2233 2234 return findModule(Name); 2235 } 2236 2237 bool ModuleMap::parseAndLoadModuleMapFile(FileEntryRef File, bool IsSystem, 2238 DirectoryEntryRef Dir, FileID ID, 2239 unsigned *Offset, 2240 SourceLocation ExternModuleLoc) { 2241 assert(Target && "Missing target information"); 2242 llvm::DenseMap<const FileEntry *, bool>::iterator Known = 2243 LoadedModuleMap.find(File); 2244 if (Known != LoadedModuleMap.end()) 2245 return Known->second; 2246 2247 // If the module map file wasn't already entered, do so now. 2248 if (ID.isInvalid()) { 2249 ID = SourceMgr.translateFile(File); 2250 // TODO: The way we compute affecting module maps requires this to be a 2251 // local FileID. This should be changed to reuse loaded FileIDs when 2252 // available, and change the way that affecting module maps are 2253 // computed to not require this. 2254 if (ID.isInvalid() || SourceMgr.isLoadedFileID(ID)) { 2255 auto FileCharacter = 2256 IsSystem ? SrcMgr::C_System_ModuleMap : SrcMgr::C_User_ModuleMap; 2257 ID = SourceMgr.createFileID(File, ExternModuleLoc, FileCharacter); 2258 } 2259 } 2260 2261 assert(Target && "Missing target information"); 2262 std::optional<llvm::MemoryBufferRef> Buffer = SourceMgr.getBufferOrNone(ID); 2263 if (!Buffer) 2264 return LoadedModuleMap[File] = true; 2265 assert((!Offset || *Offset <= Buffer->getBufferSize()) && 2266 "invalid buffer offset"); 2267 2268 std::optional<modulemap::ModuleMapFile> MMF = 2269 modulemap::parseModuleMap(ID, Dir, SourceMgr, Diags, IsSystem, Offset); 2270 bool Result = false; 2271 if (MMF) { 2272 Diags.Report(diag::remark_mmap_load) << File.getName(); 2273 ModuleMapLoader Loader(SourceMgr, Diags, *this, ID, Dir, IsSystem); 2274 Result = Loader.parseAndLoadModuleMapFile(*MMF); 2275 } 2276 LoadedModuleMap[File] = Result; 2277 2278 // Notify callbacks that we observed it. 2279 // FIXME: We should only report module maps that were actually used. 2280 for (const auto &Cb : Callbacks) 2281 Cb->moduleMapFileRead(MMF ? MMF->Start : SourceLocation(), File, IsSystem); 2282 2283 return Result; 2284 } 2285