clang API Documentation

Basic/Module.cpp
Go to the documentation of this file.
00001 //===--- Module.cpp - Describe a module -----------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file defines the Module class, which describes a module in the source
00011 // code.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "clang/Basic/Module.h"
00016 #include "clang/Basic/FileManager.h"
00017 #include "clang/Basic/LangOptions.h"
00018 #include "clang/Basic/TargetInfo.h"
00019 #include "llvm/ADT/ArrayRef.h"
00020 #include "llvm/ADT/SmallVector.h"
00021 #include "llvm/ADT/StringSwitch.h"
00022 #include "llvm/Support/ErrorHandling.h"
00023 #include "llvm/Support/raw_ostream.h"
00024 
00025 using namespace clang;
00026 
00027 Module::Module(StringRef Name, SourceLocation DefinitionLoc, Module *Parent,
00028                bool IsFramework, bool IsExplicit)
00029     : Name(Name), DefinitionLoc(DefinitionLoc), Parent(Parent),
00030       Umbrella(), ASTFile(nullptr), IsMissingRequirement(false),
00031       IsAvailable(true), IsFromModuleFile(false), IsFramework(IsFramework),
00032       IsExplicit(IsExplicit), IsSystem(false), IsExternC(false),
00033       IsInferred(false), InferSubmodules(false), InferExplicitSubmodules(false),
00034       InferExportWildcard(false), ConfigMacrosExhaustive(false),
00035       NameVisibility(Hidden) {
00036   if (Parent) {
00037     if (!Parent->isAvailable())
00038       IsAvailable = false;
00039     if (Parent->IsSystem)
00040       IsSystem = true;
00041     if (Parent->IsExternC)
00042       IsExternC = true;
00043     IsMissingRequirement = Parent->IsMissingRequirement;
00044     
00045     Parent->SubModuleIndex[Name] = Parent->SubModules.size();
00046     Parent->SubModules.push_back(this);
00047   }
00048 }
00049 
00050 Module::~Module() {
00051   for (submodule_iterator I = submodule_begin(), IEnd = submodule_end();
00052        I != IEnd; ++I) {
00053     delete *I;
00054   }
00055 }
00056 
00057 /// \brief Determine whether a translation unit built using the current
00058 /// language options has the given feature.
00059 static bool hasFeature(StringRef Feature, const LangOptions &LangOpts,
00060                        const TargetInfo &Target) {
00061   return llvm::StringSwitch<bool>(Feature)
00062            .Case("altivec", LangOpts.AltiVec)
00063            .Case("blocks", LangOpts.Blocks)
00064            .Case("cplusplus", LangOpts.CPlusPlus)
00065            .Case("cplusplus11", LangOpts.CPlusPlus11)
00066            .Case("objc", LangOpts.ObjC1)
00067            .Case("objc_arc", LangOpts.ObjCAutoRefCount)
00068            .Case("opencl", LangOpts.OpenCL)
00069            .Case("tls", Target.isTLSSupported())
00070            .Default(Target.hasFeature(Feature));
00071 }
00072 
00073 bool
00074 Module::isAvailable(const LangOptions &LangOpts, const TargetInfo &Target,
00075                     Requirement &Req, HeaderDirective &MissingHeader) const {
00076   if (IsAvailable)
00077     return true;
00078 
00079   for (const Module *Current = this; Current; Current = Current->Parent) {
00080     if (!Current->MissingHeaders.empty()) {
00081       MissingHeader = Current->MissingHeaders.front();
00082       return false;
00083     }
00084     for (unsigned I = 0, N = Current->Requirements.size(); I != N; ++I) {
00085       if (hasFeature(Current->Requirements[I].first, LangOpts, Target) !=
00086               Current->Requirements[I].second) {
00087         Req = Current->Requirements[I];
00088         return false;
00089       }
00090     }
00091   }
00092 
00093   llvm_unreachable("could not find a reason why module is unavailable");
00094 }
00095 
00096 bool Module::isSubModuleOf(const Module *Other) const {
00097   const Module *This = this;
00098   do {
00099     if (This == Other)
00100       return true;
00101     
00102     This = This->Parent;
00103   } while (This);
00104   
00105   return false;
00106 }
00107 
00108 const Module *Module::getTopLevelModule() const {
00109   const Module *Result = this;
00110   while (Result->Parent)
00111     Result = Result->Parent;
00112   
00113   return Result;
00114 }
00115 
00116 std::string Module::getFullModuleName() const {
00117   SmallVector<StringRef, 2> Names;
00118   
00119   // Build up the set of module names (from innermost to outermost).
00120   for (const Module *M = this; M; M = M->Parent)
00121     Names.push_back(M->Name);
00122   
00123   std::string Result;
00124   for (SmallVectorImpl<StringRef>::reverse_iterator I = Names.rbegin(),
00125                                                  IEnd = Names.rend();
00126        I != IEnd; ++I) {
00127     if (!Result.empty())
00128       Result += '.';
00129     
00130     Result += *I;
00131   }
00132   
00133   return Result;
00134 }
00135 
00136 const DirectoryEntry *Module::getUmbrellaDir() const {
00137   if (const FileEntry *Header = getUmbrellaHeader())
00138     return Header->getDir();
00139   
00140   return Umbrella.dyn_cast<const DirectoryEntry *>();
00141 }
00142 
00143 ArrayRef<const FileEntry *> Module::getTopHeaders(FileManager &FileMgr) {
00144   if (!TopHeaderNames.empty()) {
00145     for (std::vector<std::string>::iterator
00146            I = TopHeaderNames.begin(), E = TopHeaderNames.end(); I != E; ++I) {
00147       if (const FileEntry *FE = FileMgr.getFile(*I))
00148         TopHeaders.insert(FE);
00149     }
00150     TopHeaderNames.clear();
00151   }
00152 
00153   return llvm::makeArrayRef(TopHeaders.begin(), TopHeaders.end());
00154 }
00155 
00156 void Module::addRequirement(StringRef Feature, bool RequiredState,
00157                             const LangOptions &LangOpts,
00158                             const TargetInfo &Target) {
00159   Requirements.push_back(Requirement(Feature, RequiredState));
00160 
00161   // If this feature is currently available, we're done.
00162   if (hasFeature(Feature, LangOpts, Target) == RequiredState)
00163     return;
00164 
00165   markUnavailable(/*MissingRequirement*/true);
00166 }
00167 
00168 void Module::markUnavailable(bool MissingRequirement) {
00169   if (!IsAvailable)
00170     return;
00171 
00172   SmallVector<Module *, 2> Stack;
00173   Stack.push_back(this);
00174   while (!Stack.empty()) {
00175     Module *Current = Stack.back();
00176     Stack.pop_back();
00177 
00178     if (!Current->IsAvailable)
00179       continue;
00180 
00181     Current->IsAvailable = false;
00182     Current->IsMissingRequirement |= MissingRequirement;
00183     for (submodule_iterator Sub = Current->submodule_begin(),
00184                          SubEnd = Current->submodule_end();
00185          Sub != SubEnd; ++Sub) {
00186       if ((*Sub)->IsAvailable)
00187         Stack.push_back(*Sub);
00188     }
00189   }
00190 }
00191 
00192 Module *Module::findSubmodule(StringRef Name) const {
00193   llvm::StringMap<unsigned>::const_iterator Pos = SubModuleIndex.find(Name);
00194   if (Pos == SubModuleIndex.end())
00195     return nullptr;
00196 
00197   return SubModules[Pos->getValue()];
00198 }
00199 
00200 static void printModuleId(raw_ostream &OS, const ModuleId &Id) {
00201   for (unsigned I = 0, N = Id.size(); I != N; ++I) {
00202     if (I)
00203       OS << ".";
00204     OS << Id[I].first;
00205   }
00206 }
00207 
00208 void Module::getExportedModules(SmallVectorImpl<Module *> &Exported) const {
00209   // All non-explicit submodules are exported.
00210   for (std::vector<Module *>::const_iterator I = SubModules.begin(),
00211                                              E = SubModules.end();
00212        I != E; ++I) {
00213     Module *Mod = *I;
00214     if (!Mod->IsExplicit)
00215       Exported.push_back(Mod);
00216   }
00217 
00218   // Find re-exported modules by filtering the list of imported modules.
00219   bool AnyWildcard = false;
00220   bool UnrestrictedWildcard = false;
00221   SmallVector<Module *, 4> WildcardRestrictions;
00222   for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
00223     Module *Mod = Exports[I].getPointer();
00224     if (!Exports[I].getInt()) {
00225       // Export a named module directly; no wildcards involved.
00226       Exported.push_back(Mod);
00227 
00228       continue;
00229     }
00230 
00231     // Wildcard export: export all of the imported modules that match
00232     // the given pattern.
00233     AnyWildcard = true;
00234     if (UnrestrictedWildcard)
00235       continue;
00236 
00237     if (Module *Restriction = Exports[I].getPointer())
00238       WildcardRestrictions.push_back(Restriction);
00239     else {
00240       WildcardRestrictions.clear();
00241       UnrestrictedWildcard = true;
00242     }
00243   }
00244 
00245   // If there were any wildcards, push any imported modules that were
00246   // re-exported by the wildcard restriction.
00247   if (!AnyWildcard)
00248     return;
00249 
00250   for (unsigned I = 0, N = Imports.size(); I != N; ++I) {
00251     Module *Mod = Imports[I];
00252     bool Acceptable = UnrestrictedWildcard;
00253     if (!Acceptable) {
00254       // Check whether this module meets one of the restrictions.
00255       for (unsigned R = 0, NR = WildcardRestrictions.size(); R != NR; ++R) {
00256         Module *Restriction = WildcardRestrictions[R];
00257         if (Mod == Restriction || Mod->isSubModuleOf(Restriction)) {
00258           Acceptable = true;
00259           break;
00260         }
00261       }
00262     }
00263 
00264     if (!Acceptable)
00265       continue;
00266 
00267     Exported.push_back(Mod);
00268   }
00269 }
00270 
00271 void Module::buildVisibleModulesCache() const {
00272   assert(VisibleModulesCache.empty() && "cache does not need building");
00273 
00274   // This module is visible to itself.
00275   VisibleModulesCache.insert(this);
00276 
00277   // Every imported module is visible.
00278   SmallVector<Module *, 16> Stack(Imports.begin(), Imports.end());
00279   while (!Stack.empty()) {
00280     Module *CurrModule = Stack.pop_back_val();
00281 
00282     // Every module transitively exported by an imported module is visible.
00283     if (VisibleModulesCache.insert(CurrModule).second)
00284       CurrModule->getExportedModules(Stack);
00285   }
00286 }
00287 
00288 void Module::print(raw_ostream &OS, unsigned Indent) const {
00289   OS.indent(Indent);
00290   if (IsFramework)
00291     OS << "framework ";
00292   if (IsExplicit)
00293     OS << "explicit ";
00294   OS << "module " << Name;
00295 
00296   if (IsSystem) {
00297     OS.indent(Indent + 2);
00298     OS << " [system]";
00299   }
00300 
00301   OS << " {\n";
00302   
00303   if (!Requirements.empty()) {
00304     OS.indent(Indent + 2);
00305     OS << "requires ";
00306     for (unsigned I = 0, N = Requirements.size(); I != N; ++I) {
00307       if (I)
00308         OS << ", ";
00309       if (!Requirements[I].second)
00310         OS << "!";
00311       OS << Requirements[I].first;
00312     }
00313     OS << "\n";
00314   }
00315   
00316   if (const FileEntry *UmbrellaHeader = getUmbrellaHeader()) {
00317     OS.indent(Indent + 2);
00318     OS << "umbrella header \"";
00319     OS.write_escaped(UmbrellaHeader->getName());
00320     OS << "\"\n";
00321   } else if (const DirectoryEntry *UmbrellaDir = getUmbrellaDir()) {
00322     OS.indent(Indent + 2);
00323     OS << "umbrella \"";
00324     OS.write_escaped(UmbrellaDir->getName());
00325     OS << "\"\n";    
00326   }
00327 
00328   if (!ConfigMacros.empty() || ConfigMacrosExhaustive) {
00329     OS.indent(Indent + 2);
00330     OS << "config_macros ";
00331     if (ConfigMacrosExhaustive)
00332       OS << "[exhaustive]";
00333     for (unsigned I = 0, N = ConfigMacros.size(); I != N; ++I) {
00334       if (I)
00335         OS << ", ";
00336       OS << ConfigMacros[I];
00337     }
00338     OS << "\n";
00339   }
00340 
00341   struct HeaderKind {
00342     StringRef Prefix;
00343     const SmallVectorImpl<const FileEntry *> &Headers;
00344   } Kinds[] = {{"", NormalHeaders},
00345                {"exclude ", ExcludedHeaders},
00346                {"textual ", TextualHeaders},
00347                {"private ", PrivateHeaders}};
00348 
00349   for (auto &K : Kinds) {
00350     for (auto *H : K.Headers) {
00351       OS.indent(Indent + 2);
00352       OS << K.Prefix << "header \"";
00353       OS.write_escaped(H->getName());
00354       OS << "\"\n";
00355     }
00356   }
00357 
00358   for (submodule_const_iterator MI = submodule_begin(), MIEnd = submodule_end();
00359        MI != MIEnd; ++MI)
00360     // Print inferred subframework modules so that we don't need to re-infer
00361     // them (requires expensive directory iteration + stat calls) when we build
00362     // the module. Regular inferred submodules are OK, as we need to look at all
00363     // those header files anyway.
00364     if (!(*MI)->IsInferred || (*MI)->IsFramework)
00365       (*MI)->print(OS, Indent + 2);
00366   
00367   for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
00368     OS.indent(Indent + 2);
00369     OS << "export ";
00370     if (Module *Restriction = Exports[I].getPointer()) {
00371       OS << Restriction->getFullModuleName();
00372       if (Exports[I].getInt())
00373         OS << ".*";
00374     } else {
00375       OS << "*";
00376     }
00377     OS << "\n";
00378   }
00379 
00380   for (unsigned I = 0, N = UnresolvedExports.size(); I != N; ++I) {
00381     OS.indent(Indent + 2);
00382     OS << "export ";
00383     printModuleId(OS, UnresolvedExports[I].Id);
00384     if (UnresolvedExports[I].Wildcard) {
00385       if (UnresolvedExports[I].Id.empty())
00386         OS << "*";
00387       else
00388         OS << ".*";
00389     }
00390     OS << "\n";
00391   }
00392 
00393   for (unsigned I = 0, N = DirectUses.size(); I != N; ++I) {
00394     OS.indent(Indent + 2);
00395     OS << "use ";
00396     OS << DirectUses[I]->getFullModuleName();
00397     OS << "\n";
00398   }
00399 
00400   for (unsigned I = 0, N = UnresolvedDirectUses.size(); I != N; ++I) {
00401     OS.indent(Indent + 2);
00402     OS << "use ";
00403     printModuleId(OS, UnresolvedDirectUses[I]);
00404     OS << "\n";
00405   }
00406 
00407   for (unsigned I = 0, N = LinkLibraries.size(); I != N; ++I) {
00408     OS.indent(Indent + 2);
00409     OS << "link ";
00410     if (LinkLibraries[I].IsFramework)
00411       OS << "framework ";
00412     OS << "\"";
00413     OS.write_escaped(LinkLibraries[I].Library);
00414     OS << "\"";
00415   }
00416 
00417   for (unsigned I = 0, N = UnresolvedConflicts.size(); I != N; ++I) {
00418     OS.indent(Indent + 2);
00419     OS << "conflict ";
00420     printModuleId(OS, UnresolvedConflicts[I].Id);
00421     OS << ", \"";
00422     OS.write_escaped(UnresolvedConflicts[I].Message);
00423     OS << "\"\n";
00424   }
00425 
00426   for (unsigned I = 0, N = Conflicts.size(); I != N; ++I) {
00427     OS.indent(Indent + 2);
00428     OS << "conflict ";
00429     OS << Conflicts[I].Other->getFullModuleName();
00430     OS << ", \"";
00431     OS.write_escaped(Conflicts[I].Message);
00432     OS << "\"\n";
00433   }
00434 
00435   if (InferSubmodules) {
00436     OS.indent(Indent + 2);
00437     if (InferExplicitSubmodules)
00438       OS << "explicit ";
00439     OS << "module * {\n";
00440     if (InferExportWildcard) {
00441       OS.indent(Indent + 4);
00442       OS << "export *\n";
00443     }
00444     OS.indent(Indent + 2);
00445     OS << "}\n";
00446   }
00447   
00448   OS.indent(Indent);
00449   OS << "}\n";
00450 }
00451 
00452 void Module::dump() const {
00453   print(llvm::errs());
00454 }
00455 
00456