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