1 //===--- Module.cpp - Describe a module -----------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines the Module class, which describes a module in the source 11 // code. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "clang/Basic/Module.h" 16 #include "clang/Basic/FileManager.h" 17 #include "clang/Basic/LangOptions.h" 18 #include "clang/Basic/TargetInfo.h" 19 #include "llvm/ADT/ArrayRef.h" 20 #include "llvm/ADT/SmallVector.h" 21 #include "llvm/ADT/StringSwitch.h" 22 #include "llvm/Support/ErrorHandling.h" 23 #include "llvm/Support/raw_ostream.h" 24 25 using namespace clang; 26 27 Module::Module(StringRef Name, SourceLocation DefinitionLoc, Module *Parent, 28 bool IsFramework, bool IsExplicit, unsigned VisibilityID) 29 : Name(Name), DefinitionLoc(DefinitionLoc), Parent(Parent), Directory(), 30 Umbrella(), ASTFile(nullptr), VisibilityID(VisibilityID), 31 IsMissingRequirement(false), HasIncompatibleModuleFile(false), 32 IsAvailable(true), IsFromModuleFile(false), IsFramework(IsFramework), 33 IsExplicit(IsExplicit), IsSystem(false), IsExternC(false), 34 IsInferred(false), InferSubmodules(false), InferExplicitSubmodules(false), 35 InferExportWildcard(false), ConfigMacrosExhaustive(false), 36 NoUndeclaredIncludes(false), NameVisibility(Hidden) { 37 if (Parent) { 38 if (!Parent->isAvailable()) 39 IsAvailable = false; 40 if (Parent->IsSystem) 41 IsSystem = true; 42 if (Parent->IsExternC) 43 IsExternC = true; 44 if (Parent->NoUndeclaredIncludes) 45 NoUndeclaredIncludes = true; 46 IsMissingRequirement = Parent->IsMissingRequirement; 47 48 Parent->SubModuleIndex[Name] = Parent->SubModules.size(); 49 Parent->SubModules.push_back(this); 50 } 51 } 52 53 Module::~Module() { 54 for (submodule_iterator I = submodule_begin(), IEnd = submodule_end(); 55 I != IEnd; ++I) { 56 delete *I; 57 } 58 } 59 60 /// \brief Determine whether a translation unit built using the current 61 /// language options has the given feature. 62 static bool hasFeature(StringRef Feature, const LangOptions &LangOpts, 63 const TargetInfo &Target) { 64 bool HasFeature = llvm::StringSwitch<bool>(Feature) 65 .Case("altivec", LangOpts.AltiVec) 66 .Case("blocks", LangOpts.Blocks) 67 .Case("coroutines", LangOpts.CoroutinesTS) 68 .Case("cplusplus", LangOpts.CPlusPlus) 69 .Case("cplusplus11", LangOpts.CPlusPlus11) 70 .Case("freestanding", LangOpts.Freestanding) 71 .Case("gnuinlineasm", LangOpts.GNUAsm) 72 .Case("objc", LangOpts.ObjC1) 73 .Case("objc_arc", LangOpts.ObjCAutoRefCount) 74 .Case("opencl", LangOpts.OpenCL) 75 .Case("tls", Target.isTLSSupported()) 76 .Case("zvector", LangOpts.ZVector) 77 .Default(Target.hasFeature(Feature)); 78 if (!HasFeature) 79 HasFeature = std::find(LangOpts.ModuleFeatures.begin(), 80 LangOpts.ModuleFeatures.end(), 81 Feature) != LangOpts.ModuleFeatures.end(); 82 return HasFeature; 83 } 84 85 bool Module::isAvailable(const LangOptions &LangOpts, const TargetInfo &Target, 86 Requirement &Req, 87 UnresolvedHeaderDirective &MissingHeader) const { 88 if (IsAvailable) 89 return true; 90 91 for (const Module *Current = this; Current; Current = Current->Parent) { 92 for (unsigned I = 0, N = Current->Requirements.size(); I != N; ++I) { 93 if (hasFeature(Current->Requirements[I].first, LangOpts, Target) != 94 Current->Requirements[I].second) { 95 Req = Current->Requirements[I]; 96 return false; 97 } 98 } 99 if (!Current->MissingHeaders.empty()) { 100 MissingHeader = Current->MissingHeaders.front(); 101 return false; 102 } 103 } 104 105 llvm_unreachable("could not find a reason why module is unavailable"); 106 } 107 108 bool Module::isSubModuleOf(const Module *Other) const { 109 const Module *This = this; 110 do { 111 if (This == Other) 112 return true; 113 114 This = This->Parent; 115 } while (This); 116 117 return false; 118 } 119 120 const Module *Module::getTopLevelModule() const { 121 const Module *Result = this; 122 while (Result->Parent) 123 Result = Result->Parent; 124 125 return Result; 126 } 127 128 std::string Module::getFullModuleName() const { 129 SmallVector<StringRef, 2> Names; 130 131 // Build up the set of module names (from innermost to outermost). 132 for (const Module *M = this; M; M = M->Parent) 133 Names.push_back(M->Name); 134 135 std::string Result; 136 for (SmallVectorImpl<StringRef>::reverse_iterator I = Names.rbegin(), 137 IEnd = Names.rend(); 138 I != IEnd; ++I) { 139 if (!Result.empty()) 140 Result += '.'; 141 142 Result += *I; 143 } 144 145 return Result; 146 } 147 148 bool Module::fullModuleNameIs(ArrayRef<StringRef> nameParts) const { 149 for (const Module *M = this; M; M = M->Parent) { 150 if (nameParts.empty() || M->Name != nameParts.back()) 151 return false; 152 nameParts = nameParts.drop_back(); 153 } 154 return nameParts.empty(); 155 } 156 157 Module::DirectoryName Module::getUmbrellaDir() const { 158 if (Header U = getUmbrellaHeader()) 159 return {"", U.Entry->getDir()}; 160 161 return {UmbrellaAsWritten, Umbrella.dyn_cast<const DirectoryEntry *>()}; 162 } 163 164 ArrayRef<const FileEntry *> Module::getTopHeaders(FileManager &FileMgr) { 165 if (!TopHeaderNames.empty()) { 166 for (std::vector<std::string>::iterator 167 I = TopHeaderNames.begin(), E = TopHeaderNames.end(); I != E; ++I) { 168 if (const FileEntry *FE = FileMgr.getFile(*I)) 169 TopHeaders.insert(FE); 170 } 171 TopHeaderNames.clear(); 172 } 173 174 return llvm::makeArrayRef(TopHeaders.begin(), TopHeaders.end()); 175 } 176 177 bool Module::directlyUses(const Module *Requested) const { 178 auto *Top = getTopLevelModule(); 179 180 // A top-level module implicitly uses itself. 181 if (Requested->isSubModuleOf(Top)) 182 return true; 183 184 for (auto *Use : Top->DirectUses) 185 if (Requested->isSubModuleOf(Use)) 186 return true; 187 188 // Anyone is allowed to use our builtin stddef.h and its accompanying module. 189 if (!Requested->Parent && Requested->Name == "_Builtin_stddef_max_align_t") 190 return true; 191 192 return false; 193 } 194 195 void Module::addRequirement(StringRef Feature, bool RequiredState, 196 const LangOptions &LangOpts, 197 const TargetInfo &Target) { 198 Requirements.push_back(Requirement(Feature, RequiredState)); 199 200 // If this feature is currently available, we're done. 201 if (hasFeature(Feature, LangOpts, Target) == RequiredState) 202 return; 203 204 markUnavailable(/*MissingRequirement*/true); 205 } 206 207 void Module::markUnavailable(bool MissingRequirement) { 208 auto needUpdate = [MissingRequirement](Module *M) { 209 return M->IsAvailable || (!M->IsMissingRequirement && MissingRequirement); 210 }; 211 212 if (!needUpdate(this)) 213 return; 214 215 SmallVector<Module *, 2> Stack; 216 Stack.push_back(this); 217 while (!Stack.empty()) { 218 Module *Current = Stack.back(); 219 Stack.pop_back(); 220 221 if (!needUpdate(Current)) 222 continue; 223 224 Current->IsAvailable = false; 225 Current->IsMissingRequirement |= MissingRequirement; 226 for (submodule_iterator Sub = Current->submodule_begin(), 227 SubEnd = Current->submodule_end(); 228 Sub != SubEnd; ++Sub) { 229 if (needUpdate(*Sub)) 230 Stack.push_back(*Sub); 231 } 232 } 233 } 234 235 Module *Module::findSubmodule(StringRef Name) const { 236 llvm::StringMap<unsigned>::const_iterator Pos = SubModuleIndex.find(Name); 237 if (Pos == SubModuleIndex.end()) 238 return nullptr; 239 240 return SubModules[Pos->getValue()]; 241 } 242 243 static void printModuleId(raw_ostream &OS, const ModuleId &Id) { 244 for (unsigned I = 0, N = Id.size(); I != N; ++I) { 245 if (I) 246 OS << "."; 247 OS << Id[I].first; 248 } 249 } 250 251 void Module::getExportedModules(SmallVectorImpl<Module *> &Exported) const { 252 // All non-explicit submodules are exported. 253 for (std::vector<Module *>::const_iterator I = SubModules.begin(), 254 E = SubModules.end(); 255 I != E; ++I) { 256 Module *Mod = *I; 257 if (!Mod->IsExplicit) 258 Exported.push_back(Mod); 259 } 260 261 // Find re-exported modules by filtering the list of imported modules. 262 bool AnyWildcard = false; 263 bool UnrestrictedWildcard = false; 264 SmallVector<Module *, 4> WildcardRestrictions; 265 for (unsigned I = 0, N = Exports.size(); I != N; ++I) { 266 Module *Mod = Exports[I].getPointer(); 267 if (!Exports[I].getInt()) { 268 // Export a named module directly; no wildcards involved. 269 Exported.push_back(Mod); 270 271 continue; 272 } 273 274 // Wildcard export: export all of the imported modules that match 275 // the given pattern. 276 AnyWildcard = true; 277 if (UnrestrictedWildcard) 278 continue; 279 280 if (Module *Restriction = Exports[I].getPointer()) 281 WildcardRestrictions.push_back(Restriction); 282 else { 283 WildcardRestrictions.clear(); 284 UnrestrictedWildcard = true; 285 } 286 } 287 288 // If there were any wildcards, push any imported modules that were 289 // re-exported by the wildcard restriction. 290 if (!AnyWildcard) 291 return; 292 293 for (unsigned I = 0, N = Imports.size(); I != N; ++I) { 294 Module *Mod = Imports[I]; 295 bool Acceptable = UnrestrictedWildcard; 296 if (!Acceptable) { 297 // Check whether this module meets one of the restrictions. 298 for (unsigned R = 0, NR = WildcardRestrictions.size(); R != NR; ++R) { 299 Module *Restriction = WildcardRestrictions[R]; 300 if (Mod == Restriction || Mod->isSubModuleOf(Restriction)) { 301 Acceptable = true; 302 break; 303 } 304 } 305 } 306 307 if (!Acceptable) 308 continue; 309 310 Exported.push_back(Mod); 311 } 312 } 313 314 void Module::buildVisibleModulesCache() const { 315 assert(VisibleModulesCache.empty() && "cache does not need building"); 316 317 // This module is visible to itself. 318 VisibleModulesCache.insert(this); 319 320 // Every imported module is visible. 321 SmallVector<Module *, 16> Stack(Imports.begin(), Imports.end()); 322 while (!Stack.empty()) { 323 Module *CurrModule = Stack.pop_back_val(); 324 325 // Every module transitively exported by an imported module is visible. 326 if (VisibleModulesCache.insert(CurrModule).second) 327 CurrModule->getExportedModules(Stack); 328 } 329 } 330 331 void Module::print(raw_ostream &OS, unsigned Indent) const { 332 OS.indent(Indent); 333 if (IsFramework) 334 OS << "framework "; 335 if (IsExplicit) 336 OS << "explicit "; 337 OS << "module " << Name; 338 339 if (IsSystem || IsExternC) { 340 OS.indent(Indent + 2); 341 if (IsSystem) 342 OS << " [system]"; 343 if (IsExternC) 344 OS << " [extern_c]"; 345 } 346 347 OS << " {\n"; 348 349 if (!Requirements.empty()) { 350 OS.indent(Indent + 2); 351 OS << "requires "; 352 for (unsigned I = 0, N = Requirements.size(); I != N; ++I) { 353 if (I) 354 OS << ", "; 355 if (!Requirements[I].second) 356 OS << "!"; 357 OS << Requirements[I].first; 358 } 359 OS << "\n"; 360 } 361 362 if (Header H = getUmbrellaHeader()) { 363 OS.indent(Indent + 2); 364 OS << "umbrella header \""; 365 OS.write_escaped(H.NameAsWritten); 366 OS << "\"\n"; 367 } else if (DirectoryName D = getUmbrellaDir()) { 368 OS.indent(Indent + 2); 369 OS << "umbrella \""; 370 OS.write_escaped(D.NameAsWritten); 371 OS << "\"\n"; 372 } 373 374 if (!ConfigMacros.empty() || ConfigMacrosExhaustive) { 375 OS.indent(Indent + 2); 376 OS << "config_macros "; 377 if (ConfigMacrosExhaustive) 378 OS << "[exhaustive]"; 379 for (unsigned I = 0, N = ConfigMacros.size(); I != N; ++I) { 380 if (I) 381 OS << ", "; 382 OS << ConfigMacros[I]; 383 } 384 OS << "\n"; 385 } 386 387 struct { 388 StringRef Prefix; 389 HeaderKind Kind; 390 } Kinds[] = {{"", HK_Normal}, 391 {"textual ", HK_Textual}, 392 {"private ", HK_Private}, 393 {"private textual ", HK_PrivateTextual}, 394 {"exclude ", HK_Excluded}}; 395 396 for (auto &K : Kinds) { 397 for (auto &H : Headers[K.Kind]) { 398 OS.indent(Indent + 2); 399 OS << K.Prefix << "header \""; 400 OS.write_escaped(H.NameAsWritten); 401 OS << "\"\n"; 402 } 403 } 404 405 for (submodule_const_iterator MI = submodule_begin(), MIEnd = submodule_end(); 406 MI != MIEnd; ++MI) 407 // Print inferred subframework modules so that we don't need to re-infer 408 // them (requires expensive directory iteration + stat calls) when we build 409 // the module. Regular inferred submodules are OK, as we need to look at all 410 // those header files anyway. 411 if (!(*MI)->IsInferred || (*MI)->IsFramework) 412 (*MI)->print(OS, Indent + 2); 413 414 for (unsigned I = 0, N = Exports.size(); I != N; ++I) { 415 OS.indent(Indent + 2); 416 OS << "export "; 417 if (Module *Restriction = Exports[I].getPointer()) { 418 OS << Restriction->getFullModuleName(); 419 if (Exports[I].getInt()) 420 OS << ".*"; 421 } else { 422 OS << "*"; 423 } 424 OS << "\n"; 425 } 426 427 for (unsigned I = 0, N = UnresolvedExports.size(); I != N; ++I) { 428 OS.indent(Indent + 2); 429 OS << "export "; 430 printModuleId(OS, UnresolvedExports[I].Id); 431 if (UnresolvedExports[I].Wildcard) 432 OS << (UnresolvedExports[I].Id.empty() ? "*" : ".*"); 433 OS << "\n"; 434 } 435 436 for (unsigned I = 0, N = DirectUses.size(); I != N; ++I) { 437 OS.indent(Indent + 2); 438 OS << "use "; 439 OS << DirectUses[I]->getFullModuleName(); 440 OS << "\n"; 441 } 442 443 for (unsigned I = 0, N = UnresolvedDirectUses.size(); I != N; ++I) { 444 OS.indent(Indent + 2); 445 OS << "use "; 446 printModuleId(OS, UnresolvedDirectUses[I]); 447 OS << "\n"; 448 } 449 450 for (unsigned I = 0, N = LinkLibraries.size(); I != N; ++I) { 451 OS.indent(Indent + 2); 452 OS << "link "; 453 if (LinkLibraries[I].IsFramework) 454 OS << "framework "; 455 OS << "\""; 456 OS.write_escaped(LinkLibraries[I].Library); 457 OS << "\""; 458 } 459 460 for (unsigned I = 0, N = UnresolvedConflicts.size(); I != N; ++I) { 461 OS.indent(Indent + 2); 462 OS << "conflict "; 463 printModuleId(OS, UnresolvedConflicts[I].Id); 464 OS << ", \""; 465 OS.write_escaped(UnresolvedConflicts[I].Message); 466 OS << "\"\n"; 467 } 468 469 for (unsigned I = 0, N = Conflicts.size(); I != N; ++I) { 470 OS.indent(Indent + 2); 471 OS << "conflict "; 472 OS << Conflicts[I].Other->getFullModuleName(); 473 OS << ", \""; 474 OS.write_escaped(Conflicts[I].Message); 475 OS << "\"\n"; 476 } 477 478 if (InferSubmodules) { 479 OS.indent(Indent + 2); 480 if (InferExplicitSubmodules) 481 OS << "explicit "; 482 OS << "module * {\n"; 483 if (InferExportWildcard) { 484 OS.indent(Indent + 4); 485 OS << "export *\n"; 486 } 487 OS.indent(Indent + 2); 488 OS << "}\n"; 489 } 490 491 OS.indent(Indent); 492 OS << "}\n"; 493 } 494 495 LLVM_DUMP_METHOD void Module::dump() const { 496 print(llvm::errs()); 497 } 498 499 void VisibleModuleSet::setVisible(Module *M, SourceLocation Loc, 500 VisibleCallback Vis, ConflictCallback Cb) { 501 assert(Loc.isValid() && "setVisible expects a valid import location"); 502 if (isVisible(M)) 503 return; 504 505 ++Generation; 506 507 struct Visiting { 508 Module *M; 509 Visiting *ExportedBy; 510 }; 511 512 std::function<void(Visiting)> VisitModule = [&](Visiting V) { 513 // Modules that aren't available cannot be made visible. 514 if (!V.M->isAvailable()) 515 return; 516 517 // Nothing to do for a module that's already visible. 518 unsigned ID = V.M->getVisibilityID(); 519 if (ImportLocs.size() <= ID) 520 ImportLocs.resize(ID + 1); 521 else if (ImportLocs[ID].isValid()) 522 return; 523 524 ImportLocs[ID] = Loc; 525 Vis(M); 526 527 // Make any exported modules visible. 528 SmallVector<Module *, 16> Exports; 529 V.M->getExportedModules(Exports); 530 for (Module *E : Exports) 531 VisitModule({E, &V}); 532 533 for (auto &C : V.M->Conflicts) { 534 if (isVisible(C.Other)) { 535 llvm::SmallVector<Module*, 8> Path; 536 for (Visiting *I = &V; I; I = I->ExportedBy) 537 Path.push_back(I->M); 538 Cb(Path, C.Other, C.Message); 539 } 540 } 541 }; 542 VisitModule({M, nullptr}); 543 } 544