HeaderSearch.cpp 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389
  1. //===--- HeaderSearch.cpp - Resolve Header File Locations ---===//
  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 implements the DirectoryLookup and HeaderSearch interfaces.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Lex/HeaderSearch.h"
  14. #include "clang/Basic/FileManager.h"
  15. #include "clang/Basic/IdentifierTable.h"
  16. #include "clang/Frontend/PCHContainerOperations.h"
  17. #include "clang/Lex/ExternalPreprocessorSource.h"
  18. #include "clang/Lex/HeaderMap.h"
  19. #include "clang/Lex/HeaderSearchOptions.h"
  20. #include "clang/Lex/LexDiagnostic.h"
  21. #include "clang/Lex/Lexer.h"
  22. #include "clang/Lex/Preprocessor.h"
  23. #include "llvm/ADT/APInt.h"
  24. #include "llvm/ADT/Hashing.h"
  25. #include "llvm/ADT/SmallString.h"
  26. #include "llvm/Support/Capacity.h"
  27. #include "llvm/Support/FileSystem.h"
  28. #include "llvm/Support/Path.h"
  29. #include "llvm/Support/raw_ostream.h"
  30. #include <cstdio>
  31. #if defined(LLVM_ON_UNIX)
  32. #include <limits.h>
  33. #endif
  34. using namespace clang;
  35. const IdentifierInfo *
  36. HeaderFileInfo::getControllingMacro(ExternalPreprocessorSource *External) {
  37. if (ControllingMacro) {
  38. if (ControllingMacro->isOutOfDate())
  39. External->updateOutOfDateIdentifier(
  40. *const_cast<IdentifierInfo *>(ControllingMacro));
  41. return ControllingMacro;
  42. }
  43. if (!ControllingMacroID || !External)
  44. return nullptr;
  45. ControllingMacro = External->GetIdentifier(ControllingMacroID);
  46. return ControllingMacro;
  47. }
  48. ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() {}
  49. HeaderSearch::HeaderSearch(IntrusiveRefCntPtr<HeaderSearchOptions> HSOpts,
  50. SourceManager &SourceMgr, DiagnosticsEngine &Diags,
  51. const LangOptions &LangOpts,
  52. const TargetInfo *Target)
  53. : HSOpts(HSOpts), Diags(Diags), FileMgr(SourceMgr.getFileManager()),
  54. FrameworkMap(64), ModMap(SourceMgr, Diags, LangOpts, Target, *this),
  55. LangOpts(LangOpts) {
  56. AngledDirIdx = 0;
  57. SystemDirIdx = 0;
  58. NoCurDirSearch = false;
  59. ExternalLookup = nullptr;
  60. ExternalSource = nullptr;
  61. NumIncluded = 0;
  62. NumMultiIncludeFileOptzn = 0;
  63. NumFrameworkLookups = NumSubFrameworkLookups = 0;
  64. }
  65. HeaderSearch::~HeaderSearch() {
  66. // Delete headermaps.
  67. for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
  68. delete HeaderMaps[i].second;
  69. }
  70. void HeaderSearch::PrintStats() {
  71. fprintf(stderr, "\n*** HeaderSearch Stats:\n");
  72. fprintf(stderr, "%d files tracked.\n", (int)FileInfo.size());
  73. unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
  74. for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
  75. NumOnceOnlyFiles += FileInfo[i].isImport;
  76. if (MaxNumIncludes < FileInfo[i].NumIncludes)
  77. MaxNumIncludes = FileInfo[i].NumIncludes;
  78. NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
  79. }
  80. fprintf(stderr, " %d #import/#pragma once files.\n", NumOnceOnlyFiles);
  81. fprintf(stderr, " %d included exactly once.\n", NumSingleIncludedFiles);
  82. fprintf(stderr, " %d max times a file is included.\n", MaxNumIncludes);
  83. fprintf(stderr, " %d #include/#include_next/#import.\n", NumIncluded);
  84. fprintf(stderr, " %d #includes skipped due to"
  85. " the multi-include optimization.\n", NumMultiIncludeFileOptzn);
  86. fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups);
  87. fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups);
  88. }
  89. /// CreateHeaderMap - This method returns a HeaderMap for the specified
  90. /// FileEntry, uniquing them through the 'HeaderMaps' datastructure.
  91. const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) {
  92. // We expect the number of headermaps to be small, and almost always empty.
  93. // If it ever grows, use of a linear search should be re-evaluated.
  94. if (!HeaderMaps.empty()) {
  95. for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
  96. // Pointer equality comparison of FileEntries works because they are
  97. // already uniqued by inode.
  98. if (HeaderMaps[i].first == FE)
  99. return HeaderMaps[i].second;
  100. }
  101. if (const HeaderMap *HM = HeaderMap::Create(FE, FileMgr)) {
  102. HeaderMaps.push_back(std::make_pair(FE, HM));
  103. return HM;
  104. }
  105. return nullptr;
  106. }
  107. std::string HeaderSearch::getModuleFileName(Module *Module) {
  108. const FileEntry *ModuleMap =
  109. getModuleMap().getModuleMapFileForUniquing(Module);
  110. return getModuleFileName(Module->Name, ModuleMap->getName());
  111. }
  112. std::string HeaderSearch::getModuleFileName(StringRef ModuleName,
  113. StringRef ModuleMapPath) {
  114. // If we don't have a module cache path, we can't do anything.
  115. if (ModuleCachePath.empty())
  116. return std::string();
  117. SmallString<256> Result(ModuleCachePath);
  118. llvm::sys::fs::make_absolute(Result);
  119. if (HSOpts->DisableModuleHash) {
  120. llvm::sys::path::append(Result, ModuleName + ".pcm");
  121. } else {
  122. // Construct the name <ModuleName>-<hash of ModuleMapPath>.pcm which should
  123. // ideally be globally unique to this particular module. Name collisions
  124. // in the hash are safe (because any translation unit can only import one
  125. // module with each name), but result in a loss of caching.
  126. //
  127. // To avoid false-negatives, we form as canonical a path as we can, and map
  128. // to lower-case in case we're on a case-insensitive file system.
  129. auto *Dir =
  130. FileMgr.getDirectory(llvm::sys::path::parent_path(ModuleMapPath));
  131. if (!Dir)
  132. return std::string();
  133. auto DirName = FileMgr.getCanonicalName(Dir);
  134. auto FileName = llvm::sys::path::filename(ModuleMapPath);
  135. llvm::hash_code Hash =
  136. llvm::hash_combine(DirName.lower(), FileName.lower(),
  137. HSOpts->ModuleFormat);
  138. SmallString<128> HashStr;
  139. llvm::APInt(64, size_t(Hash)).toStringUnsigned(HashStr, /*Radix*/36);
  140. llvm::sys::path::append(Result, ModuleName + "-" + HashStr + ".pcm");
  141. }
  142. return Result.str().str();
  143. }
  144. Module *HeaderSearch::lookupModule(StringRef ModuleName, bool AllowSearch) {
  145. // Look in the module map to determine if there is a module by this name.
  146. Module *Module = ModMap.findModule(ModuleName);
  147. if (Module || !AllowSearch || !HSOpts->ImplicitModuleMaps)
  148. return Module;
  149. // Look through the various header search paths to load any available module
  150. // maps, searching for a module map that describes this module.
  151. for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
  152. if (SearchDirs[Idx].isFramework()) {
  153. // Search for or infer a module map for a framework.
  154. SmallString<128> FrameworkDirName;
  155. FrameworkDirName += SearchDirs[Idx].getFrameworkDir()->getName();
  156. llvm::sys::path::append(FrameworkDirName, ModuleName + ".framework");
  157. if (const DirectoryEntry *FrameworkDir
  158. = FileMgr.getDirectory(FrameworkDirName)) {
  159. bool IsSystem
  160. = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User;
  161. Module = loadFrameworkModule(ModuleName, FrameworkDir, IsSystem);
  162. if (Module)
  163. break;
  164. }
  165. }
  166. // FIXME: Figure out how header maps and module maps will work together.
  167. // Only deal with normal search directories.
  168. if (!SearchDirs[Idx].isNormalDir())
  169. continue;
  170. bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
  171. // Search for a module map file in this directory.
  172. if (loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
  173. /*IsFramework*/false) == LMM_NewlyLoaded) {
  174. // We just loaded a module map file; check whether the module is
  175. // available now.
  176. Module = ModMap.findModule(ModuleName);
  177. if (Module)
  178. break;
  179. }
  180. // Search for a module map in a subdirectory with the same name as the
  181. // module.
  182. SmallString<128> NestedModuleMapDirName;
  183. NestedModuleMapDirName = SearchDirs[Idx].getDir()->getName();
  184. llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
  185. if (loadModuleMapFile(NestedModuleMapDirName, IsSystem,
  186. /*IsFramework*/false) == LMM_NewlyLoaded){
  187. // If we just loaded a module map file, look for the module again.
  188. Module = ModMap.findModule(ModuleName);
  189. if (Module)
  190. break;
  191. }
  192. // If we've already performed the exhaustive search for module maps in this
  193. // search directory, don't do it again.
  194. if (SearchDirs[Idx].haveSearchedAllModuleMaps())
  195. continue;
  196. // Load all module maps in the immediate subdirectories of this search
  197. // directory.
  198. loadSubdirectoryModuleMaps(SearchDirs[Idx]);
  199. // Look again for the module.
  200. Module = ModMap.findModule(ModuleName);
  201. if (Module)
  202. break;
  203. }
  204. return Module;
  205. }
  206. //===----------------------------------------------------------------------===//
  207. // File lookup within a DirectoryLookup scope
  208. //===----------------------------------------------------------------------===//
  209. /// getName - Return the directory or filename corresponding to this lookup
  210. /// object.
  211. const char *DirectoryLookup::getName() const {
  212. if (isNormalDir())
  213. return getDir()->getName();
  214. if (isFramework())
  215. return getFrameworkDir()->getName();
  216. assert(isHeaderMap() && "Unknown DirectoryLookup");
  217. return getHeaderMap()->getFileName();
  218. }
  219. static const FileEntry *
  220. getFileAndSuggestModule(HeaderSearch &HS, StringRef FileName,
  221. const DirectoryEntry *Dir, bool IsSystemHeaderDir,
  222. ModuleMap::KnownHeader *SuggestedModule) {
  223. // If we have a module map that might map this header, load it and
  224. // check whether we'll have a suggestion for a module.
  225. HS.hasModuleMap(FileName, Dir, IsSystemHeaderDir);
  226. if (SuggestedModule) {
  227. const FileEntry *File = HS.getFileMgr().getFile(FileName,
  228. /*OpenFile=*/false);
  229. if (File) {
  230. // If there is a module that corresponds to this header, suggest it.
  231. *SuggestedModule = HS.findModuleForHeader(File);
  232. // FIXME: This appears to be a no-op. We loaded the module map for this
  233. // directory at the start of this function.
  234. if (!SuggestedModule->getModule() &&
  235. HS.hasModuleMap(FileName, Dir, IsSystemHeaderDir))
  236. *SuggestedModule = HS.findModuleForHeader(File);
  237. }
  238. return File;
  239. }
  240. return HS.getFileMgr().getFile(FileName, /*openFile=*/true);
  241. }
  242. /// LookupFile - Lookup the specified file in this search path, returning it
  243. /// if it exists or returning null if not.
  244. const FileEntry *DirectoryLookup::LookupFile(
  245. StringRef &Filename,
  246. HeaderSearch &HS,
  247. SmallVectorImpl<char> *SearchPath,
  248. SmallVectorImpl<char> *RelativePath,
  249. ModuleMap::KnownHeader *SuggestedModule,
  250. bool &InUserSpecifiedSystemFramework,
  251. bool &HasBeenMapped,
  252. SmallVectorImpl<char> &MappedName) const {
  253. InUserSpecifiedSystemFramework = false;
  254. HasBeenMapped = false;
  255. SmallString<1024> TmpDir;
  256. if (isNormalDir()) {
  257. // Concatenate the requested file onto the directory.
  258. TmpDir = getDir()->getName();
  259. llvm::sys::path::append(TmpDir, Filename);
  260. if (SearchPath) {
  261. StringRef SearchPathRef(getDir()->getName());
  262. SearchPath->clear();
  263. SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
  264. }
  265. if (RelativePath) {
  266. RelativePath->clear();
  267. RelativePath->append(Filename.begin(), Filename.end());
  268. }
  269. return getFileAndSuggestModule(HS, TmpDir, getDir(),
  270. isSystemHeaderDirectory(),
  271. SuggestedModule);
  272. }
  273. if (isFramework())
  274. return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
  275. SuggestedModule, InUserSpecifiedSystemFramework);
  276. assert(isHeaderMap() && "Unknown directory lookup");
  277. const HeaderMap *HM = getHeaderMap();
  278. SmallString<1024> Path;
  279. StringRef Dest = HM->lookupFilename(Filename, Path);
  280. if (Dest.empty())
  281. return nullptr;
  282. const FileEntry *Result;
  283. // Check if the headermap maps the filename to a framework include
  284. // ("Foo.h" -> "Foo/Foo.h"), in which case continue header lookup using the
  285. // framework include.
  286. if (llvm::sys::path::is_relative(Dest)) {
  287. MappedName.clear();
  288. MappedName.append(Dest.begin(), Dest.end());
  289. Filename = StringRef(MappedName.begin(), MappedName.size());
  290. HasBeenMapped = true;
  291. Result = HM->LookupFile(Filename, HS.getFileMgr());
  292. } else {
  293. Result = HS.getFileMgr().getFile(Dest);
  294. }
  295. if (Result) {
  296. if (SearchPath) {
  297. StringRef SearchPathRef(getName());
  298. SearchPath->clear();
  299. SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
  300. }
  301. if (RelativePath) {
  302. RelativePath->clear();
  303. RelativePath->append(Filename.begin(), Filename.end());
  304. }
  305. }
  306. return Result;
  307. }
  308. /// \brief Given a framework directory, find the top-most framework directory.
  309. ///
  310. /// \param FileMgr The file manager to use for directory lookups.
  311. /// \param DirName The name of the framework directory.
  312. /// \param SubmodulePath Will be populated with the submodule path from the
  313. /// returned top-level module to the originally named framework.
  314. static const DirectoryEntry *
  315. getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
  316. SmallVectorImpl<std::string> &SubmodulePath) {
  317. assert(llvm::sys::path::extension(DirName) == ".framework" &&
  318. "Not a framework directory");
  319. // Note: as an egregious but useful hack we use the real path here, because
  320. // frameworks moving between top-level frameworks to embedded frameworks tend
  321. // to be symlinked, and we base the logical structure of modules on the
  322. // physical layout. In particular, we need to deal with crazy includes like
  323. //
  324. // #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h>
  325. //
  326. // where 'Bar' used to be embedded in 'Foo', is now a top-level framework
  327. // which one should access with, e.g.,
  328. //
  329. // #include <Bar/Wibble.h>
  330. //
  331. // Similar issues occur when a top-level framework has moved into an
  332. // embedded framework.
  333. const DirectoryEntry *TopFrameworkDir = FileMgr.getDirectory(DirName);
  334. DirName = FileMgr.getCanonicalName(TopFrameworkDir);
  335. do {
  336. // Get the parent directory name.
  337. DirName = llvm::sys::path::parent_path(DirName);
  338. if (DirName.empty())
  339. break;
  340. // Determine whether this directory exists.
  341. const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
  342. if (!Dir)
  343. break;
  344. // If this is a framework directory, then we're a subframework of this
  345. // framework.
  346. if (llvm::sys::path::extension(DirName) == ".framework") {
  347. SubmodulePath.push_back(llvm::sys::path::stem(DirName));
  348. TopFrameworkDir = Dir;
  349. }
  350. } while (true);
  351. return TopFrameworkDir;
  352. }
  353. /// DoFrameworkLookup - Do a lookup of the specified file in the current
  354. /// DirectoryLookup, which is a framework directory.
  355. const FileEntry *DirectoryLookup::DoFrameworkLookup(
  356. StringRef Filename,
  357. HeaderSearch &HS,
  358. SmallVectorImpl<char> *SearchPath,
  359. SmallVectorImpl<char> *RelativePath,
  360. ModuleMap::KnownHeader *SuggestedModule,
  361. bool &InUserSpecifiedSystemFramework) const
  362. {
  363. FileManager &FileMgr = HS.getFileMgr();
  364. // Framework names must have a '/' in the filename.
  365. size_t SlashPos = Filename.find('/');
  366. if (SlashPos == StringRef::npos) return nullptr;
  367. // Find out if this is the home for the specified framework, by checking
  368. // HeaderSearch. Possible answers are yes/no and unknown.
  369. HeaderSearch::FrameworkCacheEntry &CacheEntry =
  370. HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
  371. // If it is known and in some other directory, fail.
  372. if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDir())
  373. return nullptr;
  374. // Otherwise, construct the path to this framework dir.
  375. // FrameworkName = "/System/Library/Frameworks/"
  376. SmallString<1024> FrameworkName;
  377. FrameworkName += getFrameworkDir()->getName();
  378. if (FrameworkName.empty() || FrameworkName.back() != '/')
  379. FrameworkName.push_back('/');
  380. // FrameworkName = "/System/Library/Frameworks/Cocoa"
  381. StringRef ModuleName(Filename.begin(), SlashPos);
  382. FrameworkName += ModuleName;
  383. // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
  384. FrameworkName += ".framework/";
  385. // If the cache entry was unresolved, populate it now.
  386. if (!CacheEntry.Directory) {
  387. HS.IncrementFrameworkLookupCount();
  388. // If the framework dir doesn't exist, we fail.
  389. const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName);
  390. if (!Dir) return nullptr;
  391. // Otherwise, if it does, remember that this is the right direntry for this
  392. // framework.
  393. CacheEntry.Directory = getFrameworkDir();
  394. // If this is a user search directory, check if the framework has been
  395. // user-specified as a system framework.
  396. if (getDirCharacteristic() == SrcMgr::C_User) {
  397. SmallString<1024> SystemFrameworkMarker(FrameworkName);
  398. SystemFrameworkMarker += ".system_framework";
  399. if (llvm::sys::fs::exists(SystemFrameworkMarker)) {
  400. CacheEntry.IsUserSpecifiedSystemFramework = true;
  401. }
  402. }
  403. }
  404. // Set the 'user-specified system framework' flag.
  405. InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
  406. if (RelativePath) {
  407. RelativePath->clear();
  408. RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
  409. }
  410. // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
  411. unsigned OrigSize = FrameworkName.size();
  412. FrameworkName += "Headers/";
  413. if (SearchPath) {
  414. SearchPath->clear();
  415. // Without trailing '/'.
  416. SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
  417. }
  418. FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
  419. const FileEntry *FE = FileMgr.getFile(FrameworkName,
  420. /*openFile=*/!SuggestedModule);
  421. if (!FE) {
  422. // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
  423. const char *Private = "Private";
  424. FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
  425. Private+strlen(Private));
  426. if (SearchPath)
  427. SearchPath->insert(SearchPath->begin()+OrigSize, Private,
  428. Private+strlen(Private));
  429. FE = FileMgr.getFile(FrameworkName, /*openFile=*/!SuggestedModule);
  430. }
  431. // If we found the header and are allowed to suggest a module, do so now.
  432. if (FE && SuggestedModule) {
  433. // Find the framework in which this header occurs.
  434. StringRef FrameworkPath = FE->getDir()->getName();
  435. bool FoundFramework = false;
  436. do {
  437. // Determine whether this directory exists.
  438. const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkPath);
  439. if (!Dir)
  440. break;
  441. // If this is a framework directory, then we're a subframework of this
  442. // framework.
  443. if (llvm::sys::path::extension(FrameworkPath) == ".framework") {
  444. FoundFramework = true;
  445. break;
  446. }
  447. // Get the parent directory name.
  448. FrameworkPath = llvm::sys::path::parent_path(FrameworkPath);
  449. if (FrameworkPath.empty())
  450. break;
  451. } while (true);
  452. if (FoundFramework) {
  453. // Find the top-level framework based on this framework.
  454. SmallVector<std::string, 4> SubmodulePath;
  455. const DirectoryEntry *TopFrameworkDir
  456. = ::getTopFrameworkDir(FileMgr, FrameworkPath, SubmodulePath);
  457. // Determine the name of the top-level framework.
  458. StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
  459. // Load this framework module. If that succeeds, find the suggested module
  460. // for this header, if any.
  461. bool IsSystem = getDirCharacteristic() != SrcMgr::C_User;
  462. HS.loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystem);
  463. // FIXME: This can find a module not part of ModuleName, which is
  464. // important so that we're consistent about whether this header
  465. // corresponds to a module. Possibly we should lock down framework modules
  466. // so that this is not possible.
  467. *SuggestedModule = HS.findModuleForHeader(FE);
  468. } else {
  469. *SuggestedModule = HS.findModuleForHeader(FE);
  470. }
  471. }
  472. return FE;
  473. }
  474. void HeaderSearch::setTarget(const TargetInfo &Target) {
  475. ModMap.setTarget(Target);
  476. }
  477. //===----------------------------------------------------------------------===//
  478. // Header File Location.
  479. //===----------------------------------------------------------------------===//
  480. /// \brief Return true with a diagnostic if the file that MSVC would have found
  481. /// fails to match the one that Clang would have found with MSVC header search
  482. /// disabled.
  483. static bool checkMSVCHeaderSearch(DiagnosticsEngine &Diags,
  484. const FileEntry *MSFE, const FileEntry *FE,
  485. SourceLocation IncludeLoc) {
  486. if (MSFE && FE != MSFE) {
  487. #if 0 // HLSL Change - turn off warnings of MSVC search rules
  488. Diags.Report(IncludeLoc, diag::ext_pp_include_search_ms) << MSFE->getName();
  489. #endif // HLSL Change
  490. return true;
  491. }
  492. return false;
  493. }
  494. static const char *copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc) {
  495. assert(!Str.empty());
  496. char *CopyStr = Alloc.Allocate<char>(Str.size()+1);
  497. std::copy(Str.begin(), Str.end(), CopyStr);
  498. CopyStr[Str.size()] = '\0';
  499. return CopyStr;
  500. }
  501. /// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file,
  502. /// return null on failure. isAngled indicates whether the file reference is
  503. /// for system \#include's or not (i.e. using <> instead of ""). Includers, if
  504. /// non-empty, indicates where the \#including file(s) are, in case a relative
  505. /// search is needed. Microsoft mode will pass all \#including files.
  506. const FileEntry *HeaderSearch::LookupFile(
  507. StringRef Filename, SourceLocation IncludeLoc, bool isAngled,
  508. const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir,
  509. ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>> Includers,
  510. SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath,
  511. ModuleMap::KnownHeader *SuggestedModule, bool SkipCache) {
  512. if (SuggestedModule)
  513. *SuggestedModule = ModuleMap::KnownHeader();
  514. // If 'Filename' is absolute, check to see if it exists and no searching.
  515. if (llvm::sys::path::is_absolute(Filename)) {
  516. CurDir = nullptr;
  517. // If this was an #include_next "/absolute/file", fail.
  518. if (FromDir) return nullptr;
  519. if (SearchPath)
  520. SearchPath->clear();
  521. if (RelativePath) {
  522. RelativePath->clear();
  523. RelativePath->append(Filename.begin(), Filename.end());
  524. }
  525. // Otherwise, just return the file.
  526. const FileEntry *File = FileMgr.getFile(Filename, /*openFile=*/true);
  527. if (File && SuggestedModule) {
  528. // If there is a module that corresponds to this header, suggest it.
  529. hasModuleMap(Filename, File->getDir(), /*SystemHeaderDir*/false);
  530. *SuggestedModule = findModuleForHeader(File);
  531. }
  532. return File;
  533. }
  534. // This is the header that MSVC's header search would have found.
  535. const FileEntry *MSFE = nullptr;
  536. ModuleMap::KnownHeader MSSuggestedModule;
  537. // Unless disabled, check to see if the file is in the #includer's
  538. // directory. This cannot be based on CurDir, because each includer could be
  539. // a #include of a subdirectory (#include "foo/bar.h") and a subsequent
  540. // include of "baz.h" should resolve to "whatever/foo/baz.h".
  541. // This search is not done for <> headers.
  542. if (!Includers.empty() && !isAngled && !NoCurDirSearch) {
  543. SmallString<1024> TmpDir;
  544. bool First = true;
  545. for (const auto &IncluderAndDir : Includers) {
  546. const FileEntry *Includer = IncluderAndDir.first;
  547. // Concatenate the requested file onto the directory.
  548. // FIXME: Portability. Filename concatenation should be in sys::Path.
  549. TmpDir = IncluderAndDir.second->getName();
  550. TmpDir.push_back('/');
  551. TmpDir.append(Filename.begin(), Filename.end());
  552. // FIXME: We don't cache the result of getFileInfo across the call to
  553. // getFileAndSuggestModule, because it's a reference to an element of
  554. // a container that could be reallocated across this call.
  555. //
  556. // FIXME: If we have no includer, that means we're processing a #include
  557. // from a module build. We should treat this as a system header if we're
  558. // building a [system] module.
  559. bool IncluderIsSystemHeader =
  560. Includer && getFileInfo(Includer).DirInfo != SrcMgr::C_User;
  561. if (const FileEntry *FE = getFileAndSuggestModule(
  562. *this, TmpDir, IncluderAndDir.second,
  563. IncluderIsSystemHeader, SuggestedModule)) {
  564. if (!Includer) {
  565. assert(First && "only first includer can have no file");
  566. return FE;
  567. }
  568. // Leave CurDir unset.
  569. // This file is a system header or C++ unfriendly if the old file is.
  570. //
  571. // Note that we only use one of FromHFI/ToHFI at once, due to potential
  572. // reallocation of the underlying vector potentially making the first
  573. // reference binding dangling.
  574. HeaderFileInfo &FromHFI = getFileInfo(Includer);
  575. unsigned DirInfo = FromHFI.DirInfo;
  576. bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader;
  577. StringRef Framework = FromHFI.Framework;
  578. HeaderFileInfo &ToHFI = getFileInfo(FE);
  579. ToHFI.DirInfo = DirInfo;
  580. ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader;
  581. ToHFI.Framework = Framework;
  582. if (SearchPath) {
  583. StringRef SearchPathRef(IncluderAndDir.second->getName());
  584. SearchPath->clear();
  585. SearchPath->append(SearchPathRef.begin(), SearchPathRef.end());
  586. }
  587. if (RelativePath) {
  588. RelativePath->clear();
  589. RelativePath->append(Filename.begin(), Filename.end());
  590. }
  591. if (First)
  592. return FE;
  593. // Otherwise, we found the path via MSVC header search rules. If
  594. // -Wmsvc-include is enabled, we have to keep searching to see if we
  595. // would've found this header in -I or -isystem directories.
  596. if (Diags.isIgnored(diag::ext_pp_include_search_ms, IncludeLoc)) {
  597. return FE;
  598. } else {
  599. MSFE = FE;
  600. if (SuggestedModule) {
  601. MSSuggestedModule = *SuggestedModule;
  602. *SuggestedModule = ModuleMap::KnownHeader();
  603. }
  604. break;
  605. }
  606. }
  607. First = false;
  608. }
  609. }
  610. CurDir = nullptr;
  611. // If this is a system #include, ignore the user #include locs.
  612. unsigned i = isAngled ? AngledDirIdx : 0;
  613. // If this is a #include_next request, start searching after the directory the
  614. // file was found in.
  615. if (FromDir)
  616. i = FromDir-&SearchDirs[0];
  617. // Cache all of the lookups performed by this method. Many headers are
  618. // multiply included, and the "pragma once" optimization prevents them from
  619. // being relex/pp'd, but they would still have to search through a
  620. // (potentially huge) series of SearchDirs to find it.
  621. LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
  622. // If the entry has been previously looked up, the first value will be
  623. // non-zero. If the value is equal to i (the start point of our search), then
  624. // this is a matching hit.
  625. if (!SkipCache && CacheLookup.StartIdx == i+1) {
  626. // Skip querying potentially lots of directories for this lookup.
  627. i = CacheLookup.HitIdx;
  628. if (CacheLookup.MappedName)
  629. Filename = CacheLookup.MappedName;
  630. } else {
  631. // Otherwise, this is the first query, or the previous query didn't match
  632. // our search start. We will fill in our found location below, so prime the
  633. // start point value.
  634. CacheLookup.reset(/*StartIdx=*/i+1);
  635. }
  636. SmallString<64> MappedName;
  637. // Check each directory in sequence to see if it contains this file.
  638. for (; i != SearchDirs.size(); ++i) {
  639. bool InUserSpecifiedSystemFramework = false;
  640. bool HasBeenMapped = false;
  641. const FileEntry *FE =
  642. SearchDirs[i].LookupFile(Filename, *this, SearchPath, RelativePath,
  643. SuggestedModule, InUserSpecifiedSystemFramework,
  644. HasBeenMapped, MappedName);
  645. if (HasBeenMapped) {
  646. CacheLookup.MappedName =
  647. copyString(Filename, LookupFileCache.getAllocator());
  648. }
  649. if (!FE) continue;
  650. CurDir = &SearchDirs[i];
  651. // This file is a system header or C++ unfriendly if the dir is.
  652. HeaderFileInfo &HFI = getFileInfo(FE);
  653. HFI.DirInfo = CurDir->getDirCharacteristic();
  654. // If the directory characteristic is User but this framework was
  655. // user-specified to be treated as a system framework, promote the
  656. // characteristic.
  657. if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework)
  658. HFI.DirInfo = SrcMgr::C_System;
  659. // If the filename matches a known system header prefix, override
  660. // whether the file is a system header.
  661. for (unsigned j = SystemHeaderPrefixes.size(); j; --j) {
  662. if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) {
  663. HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System
  664. : SrcMgr::C_User;
  665. break;
  666. }
  667. }
  668. // If this file is found in a header map and uses the framework style of
  669. // includes, then this header is part of a framework we're building.
  670. if (CurDir->isIndexHeaderMap()) {
  671. size_t SlashPos = Filename.find('/');
  672. if (SlashPos != StringRef::npos) {
  673. HFI.IndexHeaderMapHeader = 1;
  674. HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(),
  675. SlashPos));
  676. }
  677. }
  678. if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
  679. if (SuggestedModule)
  680. *SuggestedModule = MSSuggestedModule;
  681. return MSFE;
  682. }
  683. // Remember this location for the next lookup we do.
  684. CacheLookup.HitIdx = i;
  685. return FE;
  686. }
  687. // If we are including a file with a quoted include "foo.h" from inside
  688. // a header in a framework that is currently being built, and we couldn't
  689. // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where
  690. // "Foo" is the name of the framework in which the including header was found.
  691. if (!Includers.empty() && Includers.front().first && !isAngled &&
  692. Filename.find('/') == StringRef::npos) {
  693. HeaderFileInfo &IncludingHFI = getFileInfo(Includers.front().first);
  694. if (IncludingHFI.IndexHeaderMapHeader) {
  695. SmallString<128> ScratchFilename;
  696. ScratchFilename += IncludingHFI.Framework;
  697. ScratchFilename += '/';
  698. ScratchFilename += Filename;
  699. const FileEntry *FE = LookupFile(
  700. ScratchFilename, IncludeLoc, /*isAngled=*/true, FromDir, CurDir,
  701. Includers.front(), SearchPath, RelativePath, SuggestedModule);
  702. if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) {
  703. if (SuggestedModule)
  704. *SuggestedModule = MSSuggestedModule;
  705. return MSFE;
  706. }
  707. LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename];
  708. CacheLookup.HitIdx = LookupFileCache[ScratchFilename].HitIdx;
  709. // FIXME: SuggestedModule.
  710. return FE;
  711. }
  712. }
  713. if (checkMSVCHeaderSearch(Diags, MSFE, nullptr, IncludeLoc)) {
  714. if (SuggestedModule)
  715. *SuggestedModule = MSSuggestedModule;
  716. return MSFE;
  717. }
  718. // Otherwise, didn't find it. Remember we didn't find this.
  719. CacheLookup.HitIdx = SearchDirs.size();
  720. return nullptr;
  721. }
  722. /// LookupSubframeworkHeader - Look up a subframework for the specified
  723. /// \#include file. For example, if \#include'ing <HIToolbox/HIToolbox.h> from
  724. /// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
  725. /// is a subframework within Carbon.framework. If so, return the FileEntry
  726. /// for the designated file, otherwise return null.
  727. const FileEntry *HeaderSearch::
  728. LookupSubframeworkHeader(StringRef Filename,
  729. const FileEntry *ContextFileEnt,
  730. SmallVectorImpl<char> *SearchPath,
  731. SmallVectorImpl<char> *RelativePath,
  732. ModuleMap::KnownHeader *SuggestedModule) {
  733. assert(ContextFileEnt && "No context file?");
  734. // Framework names must have a '/' in the filename. Find it.
  735. // FIXME: Should we permit '\' on Windows?
  736. size_t SlashPos = Filename.find('/');
  737. if (SlashPos == StringRef::npos) return nullptr;
  738. // Look up the base framework name of the ContextFileEnt.
  739. const char *ContextName = ContextFileEnt->getName();
  740. // If the context info wasn't a framework, couldn't be a subframework.
  741. const unsigned DotFrameworkLen = 10;
  742. const char *FrameworkPos = strstr(ContextName, ".framework");
  743. if (FrameworkPos == nullptr ||
  744. (FrameworkPos[DotFrameworkLen] != '/' &&
  745. FrameworkPos[DotFrameworkLen] != '\\'))
  746. return nullptr;
  747. SmallString<1024> FrameworkName(ContextName, FrameworkPos+DotFrameworkLen+1);
  748. // Append Frameworks/HIToolbox.framework/
  749. FrameworkName += "Frameworks/";
  750. FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
  751. FrameworkName += ".framework/";
  752. auto &CacheLookup =
  753. *FrameworkMap.insert(std::make_pair(Filename.substr(0, SlashPos),
  754. FrameworkCacheEntry())).first;
  755. // Some other location?
  756. if (CacheLookup.second.Directory &&
  757. CacheLookup.first().size() == FrameworkName.size() &&
  758. memcmp(CacheLookup.first().data(), &FrameworkName[0],
  759. CacheLookup.first().size()) != 0)
  760. return nullptr;
  761. // Cache subframework.
  762. if (!CacheLookup.second.Directory) {
  763. ++NumSubFrameworkLookups;
  764. // If the framework dir doesn't exist, we fail.
  765. const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName);
  766. if (!Dir) return nullptr;
  767. // Otherwise, if it does, remember that this is the right direntry for this
  768. // framework.
  769. CacheLookup.second.Directory = Dir;
  770. }
  771. const FileEntry *FE = nullptr;
  772. if (RelativePath) {
  773. RelativePath->clear();
  774. RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
  775. }
  776. // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
  777. SmallString<1024> HeadersFilename(FrameworkName);
  778. HeadersFilename += "Headers/";
  779. if (SearchPath) {
  780. SearchPath->clear();
  781. // Without trailing '/'.
  782. SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
  783. }
  784. HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
  785. if (!(FE = FileMgr.getFile(HeadersFilename, /*openFile=*/true))) {
  786. // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
  787. HeadersFilename = FrameworkName;
  788. HeadersFilename += "PrivateHeaders/";
  789. if (SearchPath) {
  790. SearchPath->clear();
  791. // Without trailing '/'.
  792. SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1);
  793. }
  794. HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end());
  795. if (!(FE = FileMgr.getFile(HeadersFilename, /*openFile=*/true)))
  796. return nullptr;
  797. }
  798. // This file is a system header or C++ unfriendly if the old file is.
  799. //
  800. // Note that the temporary 'DirInfo' is required here, as either call to
  801. // getFileInfo could resize the vector and we don't want to rely on order
  802. // of evaluation.
  803. unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo;
  804. getFileInfo(FE).DirInfo = DirInfo;
  805. // If we're supposed to suggest a module, look for one now.
  806. if (SuggestedModule) {
  807. // Find the top-level framework based on this framework.
  808. FrameworkName.pop_back(); // remove the trailing '/'
  809. SmallVector<std::string, 4> SubmodulePath;
  810. const DirectoryEntry *TopFrameworkDir
  811. = ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
  812. // Determine the name of the top-level framework.
  813. StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
  814. // Load this framework module. If that succeeds, find the suggested module
  815. // for this header, if any.
  816. bool IsSystem = false;
  817. if (loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystem)) {
  818. *SuggestedModule = findModuleForHeader(FE);
  819. }
  820. }
  821. return FE;
  822. }
  823. //===----------------------------------------------------------------------===//
  824. // File Info Management.
  825. //===----------------------------------------------------------------------===//
  826. /// \brief Merge the header file info provided by \p OtherHFI into the current
  827. /// header file info (\p HFI)
  828. static void mergeHeaderFileInfo(HeaderFileInfo &HFI,
  829. const HeaderFileInfo &OtherHFI) {
  830. HFI.isImport |= OtherHFI.isImport;
  831. HFI.isPragmaOnce |= OtherHFI.isPragmaOnce;
  832. HFI.isModuleHeader |= OtherHFI.isModuleHeader;
  833. HFI.NumIncludes += OtherHFI.NumIncludes;
  834. if (!HFI.ControllingMacro && !HFI.ControllingMacroID) {
  835. HFI.ControllingMacro = OtherHFI.ControllingMacro;
  836. HFI.ControllingMacroID = OtherHFI.ControllingMacroID;
  837. }
  838. if (OtherHFI.External) {
  839. HFI.DirInfo = OtherHFI.DirInfo;
  840. HFI.External = OtherHFI.External;
  841. HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader;
  842. }
  843. if (HFI.Framework.empty())
  844. HFI.Framework = OtherHFI.Framework;
  845. HFI.Resolved = true;
  846. }
  847. /// getFileInfo - Return the HeaderFileInfo structure for the specified
  848. /// FileEntry.
  849. HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
  850. if (FE->getUID() >= FileInfo.size())
  851. FileInfo.resize(FE->getUID()+1);
  852. HeaderFileInfo &HFI = FileInfo[FE->getUID()];
  853. if (ExternalSource && !HFI.Resolved)
  854. mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(FE));
  855. HFI.IsValid = 1;
  856. return HFI;
  857. }
  858. bool HeaderSearch::tryGetFileInfo(const FileEntry *FE,
  859. HeaderFileInfo &Result) const {
  860. if (FE->getUID() >= FileInfo.size())
  861. return false;
  862. const HeaderFileInfo &HFI = FileInfo[FE->getUID()];
  863. if (HFI.IsValid) {
  864. Result = HFI;
  865. return true;
  866. }
  867. return false;
  868. }
  869. bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) {
  870. // Check if we've ever seen this file as a header.
  871. if (File->getUID() >= FileInfo.size())
  872. return false;
  873. // Resolve header file info from the external source, if needed.
  874. HeaderFileInfo &HFI = FileInfo[File->getUID()];
  875. if (ExternalSource && !HFI.Resolved)
  876. mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(File));
  877. return HFI.isPragmaOnce || HFI.isImport ||
  878. HFI.ControllingMacro || HFI.ControllingMacroID;
  879. }
  880. void HeaderSearch::MarkFileModuleHeader(const FileEntry *FE,
  881. ModuleMap::ModuleHeaderRole Role,
  882. bool isCompilingModuleHeader) {
  883. if (FE->getUID() >= FileInfo.size())
  884. FileInfo.resize(FE->getUID()+1);
  885. HeaderFileInfo &HFI = FileInfo[FE->getUID()];
  886. HFI.isModuleHeader = true;
  887. HFI.isCompilingModuleHeader |= isCompilingModuleHeader;
  888. HFI.setHeaderRole(Role);
  889. }
  890. bool HeaderSearch::ShouldEnterIncludeFile(Preprocessor &PP,
  891. const FileEntry *File,
  892. bool isImport, Module *M) {
  893. ++NumIncluded; // Count # of attempted #includes.
  894. // Get information about this file.
  895. HeaderFileInfo &FileInfo = getFileInfo(File);
  896. // If this is a #import directive, check that we have not already imported
  897. // this header.
  898. if (isImport) {
  899. // If this has already been imported, don't import it again.
  900. FileInfo.isImport = true;
  901. // Has this already been #import'ed or #include'd?
  902. if (FileInfo.NumIncludes) return false;
  903. } else {
  904. // Otherwise, if this is a #include of a file that was previously #import'd
  905. // or if this is the second #include of a #pragma once file, ignore it.
  906. if (FileInfo.isImport)
  907. return false;
  908. }
  909. // Next, check to see if the file is wrapped with #ifndef guards. If so, and
  910. // if the macro that guards it is defined, we know the #include has no effect.
  911. if (const IdentifierInfo *ControllingMacro
  912. = FileInfo.getControllingMacro(ExternalLookup)) {
  913. // If the header corresponds to a module, check whether the macro is already
  914. // defined in that module rather than checking in the current set of visible
  915. // modules.
  916. if (M ? PP.isMacroDefinedInLocalModule(ControllingMacro, M)
  917. : PP.isMacroDefined(ControllingMacro)) {
  918. ++NumMultiIncludeFileOptzn;
  919. return false;
  920. }
  921. }
  922. // Increment the number of times this file has been included.
  923. ++FileInfo.NumIncludes;
  924. return true;
  925. }
  926. size_t HeaderSearch::getTotalMemory() const {
  927. return SearchDirs.capacity()
  928. + llvm::capacity_in_bytes(FileInfo)
  929. + llvm::capacity_in_bytes(HeaderMaps)
  930. + LookupFileCache.getAllocator().getTotalMemory()
  931. + FrameworkMap.getAllocator().getTotalMemory();
  932. }
  933. StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
  934. return FrameworkNames.insert(Framework).first->first();
  935. }
  936. bool HeaderSearch::hasModuleMap(StringRef FileName,
  937. const DirectoryEntry *Root,
  938. bool IsSystem) {
  939. if (!HSOpts->ImplicitModuleMaps)
  940. return false;
  941. SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
  942. StringRef DirName = FileName;
  943. do {
  944. // Get the parent directory name.
  945. DirName = llvm::sys::path::parent_path(DirName);
  946. if (DirName.empty())
  947. return false;
  948. // Determine whether this directory exists.
  949. const DirectoryEntry *Dir = FileMgr.getDirectory(DirName);
  950. if (!Dir)
  951. return false;
  952. // Try to load the module map file in this directory.
  953. switch (loadModuleMapFile(Dir, IsSystem,
  954. llvm::sys::path::extension(Dir->getName()) ==
  955. ".framework")) {
  956. case LMM_NewlyLoaded:
  957. case LMM_AlreadyLoaded:
  958. // Success. All of the directories we stepped through inherit this module
  959. // map file.
  960. for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I)
  961. DirectoryHasModuleMap[FixUpDirectories[I]] = true;
  962. return true;
  963. case LMM_NoDirectory:
  964. case LMM_InvalidModuleMap:
  965. break;
  966. }
  967. // If we hit the top of our search, we're done.
  968. if (Dir == Root)
  969. return false;
  970. // Keep track of all of the directories we checked, so we can mark them as
  971. // having module maps if we eventually do find a module map.
  972. FixUpDirectories.push_back(Dir);
  973. } while (true);
  974. }
  975. ModuleMap::KnownHeader
  976. HeaderSearch::findModuleForHeader(const FileEntry *File) const {
  977. if (ExternalSource) {
  978. // Make sure the external source has handled header info about this file,
  979. // which includes whether the file is part of a module.
  980. (void)getFileInfo(File);
  981. }
  982. return ModMap.findModuleForHeader(File);
  983. }
  984. static const FileEntry *getPrivateModuleMap(const FileEntry *File,
  985. FileManager &FileMgr) {
  986. StringRef Filename = llvm::sys::path::filename(File->getName());
  987. SmallString<128> PrivateFilename(File->getDir()->getName());
  988. if (Filename == "module.map")
  989. llvm::sys::path::append(PrivateFilename, "module_private.map");
  990. else if (Filename == "module.modulemap")
  991. llvm::sys::path::append(PrivateFilename, "module.private.modulemap");
  992. else
  993. return nullptr;
  994. return FileMgr.getFile(PrivateFilename);
  995. }
  996. bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem) {
  997. // Find the directory for the module. For frameworks, that may require going
  998. // up from the 'Modules' directory.
  999. const DirectoryEntry *Dir = nullptr;
  1000. if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd)
  1001. Dir = FileMgr.getDirectory(".");
  1002. else {
  1003. Dir = File->getDir();
  1004. StringRef DirName(Dir->getName());
  1005. if (llvm::sys::path::filename(DirName) == "Modules") {
  1006. DirName = llvm::sys::path::parent_path(DirName);
  1007. if (DirName.endswith(".framework"))
  1008. Dir = FileMgr.getDirectory(DirName);
  1009. // FIXME: This assert can fail if there's a race between the above check
  1010. // and the removal of the directory.
  1011. assert(Dir && "parent must exist");
  1012. }
  1013. }
  1014. switch (loadModuleMapFileImpl(File, IsSystem, Dir)) {
  1015. case LMM_AlreadyLoaded:
  1016. case LMM_NewlyLoaded:
  1017. return false;
  1018. case LMM_NoDirectory:
  1019. case LMM_InvalidModuleMap:
  1020. return true;
  1021. }
  1022. llvm_unreachable("Unknown load module map result");
  1023. }
  1024. HeaderSearch::LoadModuleMapResult
  1025. HeaderSearch::loadModuleMapFileImpl(const FileEntry *File, bool IsSystem,
  1026. const DirectoryEntry *Dir) {
  1027. assert(File && "expected FileEntry");
  1028. // Check whether we've already loaded this module map, and mark it as being
  1029. // loaded in case we recursively try to load it from itself.
  1030. auto AddResult = LoadedModuleMaps.insert(std::make_pair(File, true));
  1031. if (!AddResult.second)
  1032. return AddResult.first->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
  1033. if (ModMap.parseModuleMapFile(File, IsSystem, Dir)) {
  1034. LoadedModuleMaps[File] = false;
  1035. return LMM_InvalidModuleMap;
  1036. }
  1037. // Try to load a corresponding private module map.
  1038. if (const FileEntry *PMMFile = getPrivateModuleMap(File, FileMgr)) {
  1039. if (ModMap.parseModuleMapFile(PMMFile, IsSystem, Dir)) {
  1040. LoadedModuleMaps[File] = false;
  1041. return LMM_InvalidModuleMap;
  1042. }
  1043. }
  1044. // This directory has a module map.
  1045. return LMM_NewlyLoaded;
  1046. }
  1047. const FileEntry *
  1048. HeaderSearch::lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework) {
  1049. if (!HSOpts->ImplicitModuleMaps)
  1050. return nullptr;
  1051. // For frameworks, the preferred spelling is Modules/module.modulemap, but
  1052. // module.map at the framework root is also accepted.
  1053. SmallString<128> ModuleMapFileName(Dir->getName());
  1054. if (IsFramework)
  1055. llvm::sys::path::append(ModuleMapFileName, "Modules");
  1056. llvm::sys::path::append(ModuleMapFileName, "module.modulemap");
  1057. if (const FileEntry *F = FileMgr.getFile(ModuleMapFileName))
  1058. return F;
  1059. // Continue to allow module.map
  1060. ModuleMapFileName = Dir->getName();
  1061. llvm::sys::path::append(ModuleMapFileName, "module.map");
  1062. return FileMgr.getFile(ModuleMapFileName);
  1063. }
  1064. Module *HeaderSearch::loadFrameworkModule(StringRef Name,
  1065. const DirectoryEntry *Dir,
  1066. bool IsSystem) {
  1067. if (Module *Module = ModMap.findModule(Name))
  1068. return Module;
  1069. // Try to load a module map file.
  1070. switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/true)) {
  1071. case LMM_InvalidModuleMap:
  1072. // Try to infer a module map from the framework directory.
  1073. if (HSOpts->ImplicitModuleMaps)
  1074. ModMap.inferFrameworkModule(Dir, IsSystem, /*Parent=*/nullptr);
  1075. break;
  1076. case LMM_AlreadyLoaded:
  1077. case LMM_NoDirectory:
  1078. return nullptr;
  1079. case LMM_NewlyLoaded:
  1080. break;
  1081. }
  1082. return ModMap.findModule(Name);
  1083. }
  1084. HeaderSearch::LoadModuleMapResult
  1085. HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem,
  1086. bool IsFramework) {
  1087. if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName))
  1088. return loadModuleMapFile(Dir, IsSystem, IsFramework);
  1089. return LMM_NoDirectory;
  1090. }
  1091. HeaderSearch::LoadModuleMapResult
  1092. HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir, bool IsSystem,
  1093. bool IsFramework) {
  1094. auto KnownDir = DirectoryHasModuleMap.find(Dir);
  1095. if (KnownDir != DirectoryHasModuleMap.end())
  1096. return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
  1097. if (const FileEntry *ModuleMapFile = lookupModuleMapFile(Dir, IsFramework)) {
  1098. LoadModuleMapResult Result =
  1099. loadModuleMapFileImpl(ModuleMapFile, IsSystem, Dir);
  1100. // Add Dir explicitly in case ModuleMapFile is in a subdirectory.
  1101. // E.g. Foo.framework/Modules/module.modulemap
  1102. // ^Dir ^ModuleMapFile
  1103. if (Result == LMM_NewlyLoaded)
  1104. DirectoryHasModuleMap[Dir] = true;
  1105. else if (Result == LMM_InvalidModuleMap)
  1106. DirectoryHasModuleMap[Dir] = false;
  1107. return Result;
  1108. }
  1109. return LMM_InvalidModuleMap;
  1110. }
  1111. void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) {
  1112. Modules.clear();
  1113. if (HSOpts->ImplicitModuleMaps) {
  1114. // Load module maps for each of the header search directories.
  1115. for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
  1116. bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory();
  1117. if (SearchDirs[Idx].isFramework()) {
  1118. std::error_code EC;
  1119. SmallString<128> DirNative;
  1120. llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
  1121. DirNative);
  1122. // Search each of the ".framework" directories to load them as modules.
  1123. for (llvm::sys::fs::directory_iterator Dir(DirNative, EC), DirEnd;
  1124. Dir != DirEnd && !EC; Dir.increment(EC)) {
  1125. if (llvm::sys::path::extension(Dir->path()) != ".framework")
  1126. continue;
  1127. const DirectoryEntry *FrameworkDir =
  1128. FileMgr.getDirectory(Dir->path());
  1129. if (!FrameworkDir)
  1130. continue;
  1131. // Load this framework module.
  1132. loadFrameworkModule(llvm::sys::path::stem(Dir->path()), FrameworkDir,
  1133. IsSystem);
  1134. }
  1135. continue;
  1136. }
  1137. // FIXME: Deal with header maps.
  1138. if (SearchDirs[Idx].isHeaderMap())
  1139. continue;
  1140. // Try to load a module map file for the search directory.
  1141. loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem,
  1142. /*IsFramework*/ false);
  1143. // Try to load module map files for immediate subdirectories of this
  1144. // search directory.
  1145. loadSubdirectoryModuleMaps(SearchDirs[Idx]);
  1146. }
  1147. }
  1148. // Populate the list of modules.
  1149. for (ModuleMap::module_iterator M = ModMap.module_begin(),
  1150. MEnd = ModMap.module_end();
  1151. M != MEnd; ++M) {
  1152. Modules.push_back(M->getValue());
  1153. }
  1154. }
  1155. void HeaderSearch::loadTopLevelSystemModules() {
  1156. if (!HSOpts->ImplicitModuleMaps)
  1157. return;
  1158. // Load module maps for each of the header search directories.
  1159. for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) {
  1160. // We only care about normal header directories.
  1161. if (!SearchDirs[Idx].isNormalDir()) {
  1162. continue;
  1163. }
  1164. // Try to load a module map file for the search directory.
  1165. loadModuleMapFile(SearchDirs[Idx].getDir(),
  1166. SearchDirs[Idx].isSystemHeaderDirectory(),
  1167. SearchDirs[Idx].isFramework());
  1168. }
  1169. }
  1170. void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) {
  1171. assert(HSOpts->ImplicitModuleMaps &&
  1172. "Should not be loading subdirectory module maps");
  1173. if (SearchDir.haveSearchedAllModuleMaps())
  1174. return;
  1175. std::error_code EC;
  1176. SmallString<128> DirNative;
  1177. llvm::sys::path::native(SearchDir.getDir()->getName(), DirNative);
  1178. for (llvm::sys::fs::directory_iterator Dir(DirNative, EC), DirEnd;
  1179. Dir != DirEnd && !EC; Dir.increment(EC)) {
  1180. bool IsFramework = llvm::sys::path::extension(Dir->path()) == ".framework";
  1181. if (IsFramework == SearchDir.isFramework())
  1182. loadModuleMapFile(Dir->path(), SearchDir.isSystemHeaderDirectory(),
  1183. SearchDir.isFramework());
  1184. }
  1185. SearchDir.setSearchedAllModuleMaps(true);
  1186. }