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 14 #include "clang/Lex/HeaderSearch.h" 15 #include "clang/Lex/HeaderMap.h" 16 #include "clang/Basic/Diagnostic.h" 17 #include "clang/Basic/FileManager.h" 18 #include "clang/Basic/IdentifierTable.h" 19 #include "llvm/Support/FileSystem.h" 20 #include "llvm/Support/Path.h" 21 #include "llvm/ADT/SmallString.h" 22 #include "llvm/Support/Capacity.h" 23 #include <cstdio> 24 using namespace clang; 25 26 const IdentifierInfo * 27 HeaderFileInfo::getControllingMacro(ExternalIdentifierLookup *External) { 28 if (ControllingMacro) 29 return ControllingMacro; 30 31 if (!ControllingMacroID || !External) 32 return 0; 33 34 ControllingMacro = External->GetIdentifier(ControllingMacroID); 35 return ControllingMacro; 36 } 37 38 ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() {} 39 40 HeaderSearch::HeaderSearch(FileManager &FM, DiagnosticsEngine &Diags) 41 : FileMgr(FM), Diags(Diags), FrameworkMap(64), 42 ModMap(FileMgr, *Diags.getClient()) 43 { 44 AngledDirIdx = 0; 45 SystemDirIdx = 0; 46 NoCurDirSearch = false; 47 48 ExternalLookup = 0; 49 ExternalSource = 0; 50 NumIncluded = 0; 51 NumMultiIncludeFileOptzn = 0; 52 NumFrameworkLookups = NumSubFrameworkLookups = 0; 53 } 54 55 HeaderSearch::~HeaderSearch() { 56 // Delete headermaps. 57 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i) 58 delete HeaderMaps[i].second; 59 } 60 61 void HeaderSearch::PrintStats() { 62 fprintf(stderr, "\n*** HeaderSearch Stats:\n"); 63 fprintf(stderr, "%d files tracked.\n", (int)FileInfo.size()); 64 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0; 65 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) { 66 NumOnceOnlyFiles += FileInfo[i].isImport; 67 if (MaxNumIncludes < FileInfo[i].NumIncludes) 68 MaxNumIncludes = FileInfo[i].NumIncludes; 69 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1; 70 } 71 fprintf(stderr, " %d #import/#pragma once files.\n", NumOnceOnlyFiles); 72 fprintf(stderr, " %d included exactly once.\n", NumSingleIncludedFiles); 73 fprintf(stderr, " %d max times a file is included.\n", MaxNumIncludes); 74 75 fprintf(stderr, " %d #include/#include_next/#import.\n", NumIncluded); 76 fprintf(stderr, " %d #includes skipped due to" 77 " the multi-include optimization.\n", NumMultiIncludeFileOptzn); 78 79 fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups); 80 fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups); 81 } 82 83 /// CreateHeaderMap - This method returns a HeaderMap for the specified 84 /// FileEntry, uniquing them through the the 'HeaderMaps' datastructure. 85 const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) { 86 // We expect the number of headermaps to be small, and almost always empty. 87 // If it ever grows, use of a linear search should be re-evaluated. 88 if (!HeaderMaps.empty()) { 89 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i) 90 // Pointer equality comparison of FileEntries works because they are 91 // already uniqued by inode. 92 if (HeaderMaps[i].first == FE) 93 return HeaderMaps[i].second; 94 } 95 96 if (const HeaderMap *HM = HeaderMap::Create(FE, FileMgr)) { 97 HeaderMaps.push_back(std::make_pair(FE, HM)); 98 return HM; 99 } 100 101 return 0; 102 } 103 104 const FileEntry *HeaderSearch::lookupModule(StringRef ModuleName, 105 std::string *ModuleFileName, 106 std::string *UmbrellaHeader) { 107 // If we don't have a module cache path, we can't do anything. 108 if (ModuleCachePath.empty()) { 109 if (ModuleFileName) 110 ModuleFileName->clear(); 111 return 0; 112 } 113 114 // Try to find the module path. 115 llvm::SmallString<256> FileName(ModuleCachePath); 116 llvm::sys::path::append(FileName, ModuleName + ".pcm"); 117 if (ModuleFileName) 118 *ModuleFileName = FileName.str(); 119 120 if (const FileEntry *ModuleFile 121 = getFileMgr().getFile(FileName, /*OpenFile=*/false, 122 /*CacheFailure=*/false)) 123 return ModuleFile; 124 125 // We didn't find the module. If we're not supposed to look for an 126 // umbrella header, this is the end of the road. 127 if (!UmbrellaHeader) 128 return 0; 129 130 // Look in the module map to determine if there is a module by this name. 131 ModuleMap::Module *Module = ModMap.findModule(ModuleName); 132 if (!Module) { 133 // Look through the various header search paths to load any avaiable module 134 // maps, searching for a module map that describes this module. 135 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) { 136 // Skip non-normal include paths 137 if (!SearchDirs[Idx].isNormalDir()) 138 continue; 139 140 // Search for a module map file in this directory. 141 if (loadModuleMapFile(SearchDirs[Idx].getDir()) == LMM_NewlyLoaded) { 142 // We just loaded a module map file; check whether the module is 143 // available now. 144 Module = ModMap.findModule(ModuleName); 145 if (Module) 146 break; 147 } 148 149 // Search for a module map in a subdirectory with the same name as the 150 // module. 151 llvm::SmallString<128> NestedModuleMapDirName; 152 NestedModuleMapDirName = SearchDirs[Idx].getDir()->getName(); 153 llvm::sys::path::append(NestedModuleMapDirName, ModuleName); 154 if (loadModuleMapFile(NestedModuleMapDirName) == LMM_NewlyLoaded) { 155 // If we just loaded a module map file, look for the module again. 156 Module = ModMap.findModule(ModuleName); 157 if (Module) 158 break; 159 } 160 } 161 } 162 163 // If we have a module with an umbrella header 164 // FIXME: Even if it doesn't have an umbrella header, we should be able to 165 // handle the module. However, the caller isn't ready for that yet. 166 if (Module && Module->UmbrellaHeader) { 167 *UmbrellaHeader = Module->UmbrellaHeader->getName(); 168 return 0; 169 } 170 171 // Look in each of the framework directories for an umbrella header with 172 // the same name as the module. 173 llvm::SmallString<128> UmbrellaHeaderName; 174 UmbrellaHeaderName = ModuleName; 175 UmbrellaHeaderName += '/'; 176 UmbrellaHeaderName += ModuleName; 177 UmbrellaHeaderName += ".h"; 178 for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) { 179 // Skip non-framework include paths 180 if (!SearchDirs[Idx].isFramework()) 181 continue; 182 183 // Look for the umbrella header in this directory. 184 if (const FileEntry *HeaderFile 185 = SearchDirs[Idx].LookupFile(UmbrellaHeaderName, *this, 0, 0, 186 StringRef(), 0)) { 187 *UmbrellaHeader = HeaderFile->getName(); 188 return 0; 189 } 190 } 191 192 // We did not find an umbrella header. Clear out the UmbrellaHeader pointee 193 // so our caller knows that we failed. 194 UmbrellaHeader->clear(); 195 return 0; 196 } 197 198 //===----------------------------------------------------------------------===// 199 // File lookup within a DirectoryLookup scope 200 //===----------------------------------------------------------------------===// 201 202 /// getName - Return the directory or filename corresponding to this lookup 203 /// object. 204 const char *DirectoryLookup::getName() const { 205 if (isNormalDir()) 206 return getDir()->getName(); 207 if (isFramework()) 208 return getFrameworkDir()->getName(); 209 assert(isHeaderMap() && "Unknown DirectoryLookup"); 210 return getHeaderMap()->getFileName(); 211 } 212 213 214 /// LookupFile - Lookup the specified file in this search path, returning it 215 /// if it exists or returning null if not. 216 const FileEntry *DirectoryLookup::LookupFile( 217 StringRef Filename, 218 HeaderSearch &HS, 219 SmallVectorImpl<char> *SearchPath, 220 SmallVectorImpl<char> *RelativePath, 221 StringRef BuildingModule, 222 StringRef *SuggestedModule) const { 223 llvm::SmallString<1024> TmpDir; 224 if (isNormalDir()) { 225 // Concatenate the requested file onto the directory. 226 TmpDir = getDir()->getName(); 227 llvm::sys::path::append(TmpDir, Filename); 228 if (SearchPath != NULL) { 229 StringRef SearchPathRef(getDir()->getName()); 230 SearchPath->clear(); 231 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end()); 232 } 233 if (RelativePath != NULL) { 234 RelativePath->clear(); 235 RelativePath->append(Filename.begin(), Filename.end()); 236 } 237 238 // If we have a module map that might map this header, load it and 239 // check whether we'll have a suggestion for a module. 240 if (SuggestedModule && HS.hasModuleMap(TmpDir, getDir())) { 241 const FileEntry *File = HS.getFileMgr().getFile(TmpDir.str(), 242 /*openFile=*/false); 243 if (!File) 244 return File; 245 246 // If there is a module that corresponds to this header, 247 // suggest it. 248 StringRef Module = HS.findModuleForHeader(File); 249 if (!Module.empty() && Module != BuildingModule) 250 *SuggestedModule = Module; 251 252 return File; 253 } 254 255 return HS.getFileMgr().getFile(TmpDir.str(), /*openFile=*/true); 256 } 257 258 if (isFramework()) 259 return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath, 260 BuildingModule, SuggestedModule); 261 262 assert(isHeaderMap() && "Unknown directory lookup"); 263 const FileEntry * const Result = getHeaderMap()->LookupFile( 264 Filename, HS.getFileMgr()); 265 if (Result) { 266 if (SearchPath != NULL) { 267 StringRef SearchPathRef(getName()); 268 SearchPath->clear(); 269 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end()); 270 } 271 if (RelativePath != NULL) { 272 RelativePath->clear(); 273 RelativePath->append(Filename.begin(), Filename.end()); 274 } 275 } 276 return Result; 277 } 278 279 280 /// DoFrameworkLookup - Do a lookup of the specified file in the current 281 /// DirectoryLookup, which is a framework directory. 282 const FileEntry *DirectoryLookup::DoFrameworkLookup( 283 StringRef Filename, 284 HeaderSearch &HS, 285 SmallVectorImpl<char> *SearchPath, 286 SmallVectorImpl<char> *RelativePath, 287 StringRef BuildingModule, 288 StringRef *SuggestedModule) const 289 { 290 FileManager &FileMgr = HS.getFileMgr(); 291 292 // Framework names must have a '/' in the filename. 293 size_t SlashPos = Filename.find('/'); 294 if (SlashPos == StringRef::npos) return 0; 295 296 // Find out if this is the home for the specified framework, by checking 297 // HeaderSearch. Possible answer are yes/no and unknown. 298 const DirectoryEntry *&FrameworkDirCache = 299 HS.LookupFrameworkCache(Filename.substr(0, SlashPos)); 300 301 // If it is known and in some other directory, fail. 302 if (FrameworkDirCache && FrameworkDirCache != getFrameworkDir()) 303 return 0; 304 305 // Otherwise, construct the path to this framework dir. 306 307 // FrameworkName = "/System/Library/Frameworks/" 308 llvm::SmallString<1024> FrameworkName; 309 FrameworkName += getFrameworkDir()->getName(); 310 if (FrameworkName.empty() || FrameworkName.back() != '/') 311 FrameworkName.push_back('/'); 312 313 // FrameworkName = "/System/Library/Frameworks/Cocoa" 314 StringRef ModuleName(Filename.begin(), SlashPos); 315 FrameworkName += ModuleName; 316 317 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/" 318 FrameworkName += ".framework/"; 319 320 // If the cache entry is still unresolved, query to see if the cache entry is 321 // still unresolved. If so, check its existence now. 322 if (FrameworkDirCache == 0) { 323 HS.IncrementFrameworkLookupCount(); 324 325 // If the framework dir doesn't exist, we fail. 326 // FIXME: It's probably more efficient to query this with FileMgr.getDir. 327 bool Exists; 328 if (llvm::sys::fs::exists(FrameworkName.str(), Exists) || !Exists) 329 return 0; 330 331 // Otherwise, if it does, remember that this is the right direntry for this 332 // framework. 333 FrameworkDirCache = getFrameworkDir(); 334 } 335 336 if (RelativePath != NULL) { 337 RelativePath->clear(); 338 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end()); 339 } 340 341 // If we're allowed to look for modules, try to load or create the module 342 // corresponding to this framework. 343 ModuleMap::Module *Module = 0; 344 if (SuggestedModule) { 345 if (const DirectoryEntry *FrameworkDir 346 = FileMgr.getDirectory(FrameworkName)) { 347 if ((Module = HS.getFrameworkModule(ModuleName, FrameworkDir)) && 348 Module->Name == BuildingModule) 349 Module = 0; 350 } 351 } 352 353 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h" 354 unsigned OrigSize = FrameworkName.size(); 355 356 FrameworkName += "Headers/"; 357 358 if (SearchPath != NULL) { 359 SearchPath->clear(); 360 // Without trailing '/'. 361 SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1); 362 } 363 364 // Determine whether this is the module we're building or not. 365 // FIXME: Do we still need the ".." hack? 366 bool AutomaticImport = Module && 367 !Filename.substr(SlashPos + 1).startswith(".."); 368 369 FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end()); 370 if (const FileEntry *FE = FileMgr.getFile(FrameworkName.str(), 371 /*openFile=*/!AutomaticImport)) { 372 if (AutomaticImport) 373 *SuggestedModule = Module->Name; 374 return FE; 375 } 376 377 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h" 378 const char *Private = "Private"; 379 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private, 380 Private+strlen(Private)); 381 if (SearchPath != NULL) 382 SearchPath->insert(SearchPath->begin()+OrigSize, Private, 383 Private+strlen(Private)); 384 385 const FileEntry *FE = FileMgr.getFile(FrameworkName.str(), 386 /*openFile=*/!AutomaticImport); 387 if (FE && AutomaticImport) 388 *SuggestedModule = Module->Name; 389 return FE; 390 } 391 392 393 //===----------------------------------------------------------------------===// 394 // Header File Location. 395 //===----------------------------------------------------------------------===// 396 397 398 /// LookupFile - Given a "foo" or <foo> reference, look up the indicated file, 399 /// return null on failure. isAngled indicates whether the file reference is 400 /// for system #include's or not (i.e. using <> instead of ""). CurFileEnt, if 401 /// non-null, indicates where the #including file is, in case a relative search 402 /// is needed. 403 const FileEntry *HeaderSearch::LookupFile( 404 StringRef Filename, 405 bool isAngled, 406 const DirectoryLookup *FromDir, 407 const DirectoryLookup *&CurDir, 408 const FileEntry *CurFileEnt, 409 SmallVectorImpl<char> *SearchPath, 410 SmallVectorImpl<char> *RelativePath, 411 StringRef *SuggestedModule) 412 { 413 if (SuggestedModule) 414 *SuggestedModule = StringRef(); 415 416 // If 'Filename' is absolute, check to see if it exists and no searching. 417 if (llvm::sys::path::is_absolute(Filename)) { 418 CurDir = 0; 419 420 // If this was an #include_next "/absolute/file", fail. 421 if (FromDir) return 0; 422 423 if (SearchPath != NULL) 424 SearchPath->clear(); 425 if (RelativePath != NULL) { 426 RelativePath->clear(); 427 RelativePath->append(Filename.begin(), Filename.end()); 428 } 429 // Otherwise, just return the file. 430 return FileMgr.getFile(Filename, /*openFile=*/true); 431 } 432 433 // Unless disabled, check to see if the file is in the #includer's 434 // directory. This has to be based on CurFileEnt, not CurDir, because 435 // CurFileEnt could be a #include of a subdirectory (#include "foo/bar.h") and 436 // a subsequent include of "baz.h" should resolve to "whatever/foo/baz.h". 437 // This search is not done for <> headers. 438 if (CurFileEnt && !isAngled && !NoCurDirSearch) { 439 llvm::SmallString<1024> TmpDir; 440 // Concatenate the requested file onto the directory. 441 // FIXME: Portability. Filename concatenation should be in sys::Path. 442 TmpDir += CurFileEnt->getDir()->getName(); 443 TmpDir.push_back('/'); 444 TmpDir.append(Filename.begin(), Filename.end()); 445 if (const FileEntry *FE = FileMgr.getFile(TmpDir.str(),/*openFile=*/true)) { 446 // Leave CurDir unset. 447 // This file is a system header or C++ unfriendly if the old file is. 448 // 449 // Note that the temporary 'DirInfo' is required here, as either call to 450 // getFileInfo could resize the vector and we don't want to rely on order 451 // of evaluation. 452 unsigned DirInfo = getFileInfo(CurFileEnt).DirInfo; 453 getFileInfo(FE).DirInfo = DirInfo; 454 if (SearchPath != NULL) { 455 StringRef SearchPathRef(CurFileEnt->getDir()->getName()); 456 SearchPath->clear(); 457 SearchPath->append(SearchPathRef.begin(), SearchPathRef.end()); 458 } 459 if (RelativePath != NULL) { 460 RelativePath->clear(); 461 RelativePath->append(Filename.begin(), Filename.end()); 462 } 463 return FE; 464 } 465 } 466 467 CurDir = 0; 468 469 // If this is a system #include, ignore the user #include locs. 470 unsigned i = isAngled ? AngledDirIdx : 0; 471 472 // If this is a #include_next request, start searching after the directory the 473 // file was found in. 474 if (FromDir) 475 i = FromDir-&SearchDirs[0]; 476 477 // Cache all of the lookups performed by this method. Many headers are 478 // multiply included, and the "pragma once" optimization prevents them from 479 // being relex/pp'd, but they would still have to search through a 480 // (potentially huge) series of SearchDirs to find it. 481 std::pair<unsigned, unsigned> &CacheLookup = 482 LookupFileCache.GetOrCreateValue(Filename).getValue(); 483 484 // If the entry has been previously looked up, the first value will be 485 // non-zero. If the value is equal to i (the start point of our search), then 486 // this is a matching hit. 487 if (CacheLookup.first == i+1) { 488 // Skip querying potentially lots of directories for this lookup. 489 i = CacheLookup.second; 490 } else { 491 // Otherwise, this is the first query, or the previous query didn't match 492 // our search start. We will fill in our found location below, so prime the 493 // start point value. 494 CacheLookup.first = i+1; 495 } 496 497 // Check each directory in sequence to see if it contains this file. 498 for (; i != SearchDirs.size(); ++i) { 499 const FileEntry *FE = 500 SearchDirs[i].LookupFile(Filename, *this, SearchPath, RelativePath, 501 BuildingModule, SuggestedModule); 502 if (!FE) continue; 503 504 CurDir = &SearchDirs[i]; 505 506 // This file is a system header or C++ unfriendly if the dir is. 507 HeaderFileInfo &HFI = getFileInfo(FE); 508 HFI.DirInfo = CurDir->getDirCharacteristic(); 509 510 // If this file is found in a header map and uses the framework style of 511 // includes, then this header is part of a framework we're building. 512 if (CurDir->isIndexHeaderMap()) { 513 size_t SlashPos = Filename.find('/'); 514 if (SlashPos != StringRef::npos) { 515 HFI.IndexHeaderMapHeader = 1; 516 HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(), 517 SlashPos)); 518 } 519 } 520 521 // Remember this location for the next lookup we do. 522 CacheLookup.second = i; 523 return FE; 524 } 525 526 // If we are including a file with a quoted include "foo.h" from inside 527 // a header in a framework that is currently being built, and we couldn't 528 // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where 529 // "Foo" is the name of the framework in which the including header was found. 530 if (CurFileEnt && !isAngled && Filename.find('/') == StringRef::npos) { 531 HeaderFileInfo &IncludingHFI = getFileInfo(CurFileEnt); 532 if (IncludingHFI.IndexHeaderMapHeader) { 533 llvm::SmallString<128> ScratchFilename; 534 ScratchFilename += IncludingHFI.Framework; 535 ScratchFilename += '/'; 536 ScratchFilename += Filename; 537 538 const FileEntry *Result = LookupFile(ScratchFilename, /*isAngled=*/true, 539 FromDir, CurDir, CurFileEnt, 540 SearchPath, RelativePath, 541 SuggestedModule); 542 std::pair<unsigned, unsigned> &CacheLookup 543 = LookupFileCache.GetOrCreateValue(Filename).getValue(); 544 CacheLookup.second 545 = LookupFileCache.GetOrCreateValue(ScratchFilename).getValue().second; 546 return Result; 547 } 548 } 549 550 // Otherwise, didn't find it. Remember we didn't find this. 551 CacheLookup.second = SearchDirs.size(); 552 return 0; 553 } 554 555 /// LookupSubframeworkHeader - Look up a subframework for the specified 556 /// #include file. For example, if #include'ing <HIToolbox/HIToolbox.h> from 557 /// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox 558 /// is a subframework within Carbon.framework. If so, return the FileEntry 559 /// for the designated file, otherwise return null. 560 const FileEntry *HeaderSearch:: 561 LookupSubframeworkHeader(StringRef Filename, 562 const FileEntry *ContextFileEnt, 563 SmallVectorImpl<char> *SearchPath, 564 SmallVectorImpl<char> *RelativePath) { 565 assert(ContextFileEnt && "No context file?"); 566 567 // Framework names must have a '/' in the filename. Find it. 568 size_t SlashPos = Filename.find('/'); 569 if (SlashPos == StringRef::npos) return 0; 570 571 // Look up the base framework name of the ContextFileEnt. 572 const char *ContextName = ContextFileEnt->getName(); 573 574 // If the context info wasn't a framework, couldn't be a subframework. 575 const char *FrameworkPos = strstr(ContextName, ".framework/"); 576 if (FrameworkPos == 0) 577 return 0; 578 579 llvm::SmallString<1024> FrameworkName(ContextName, 580 FrameworkPos+strlen(".framework/")); 581 582 // Append Frameworks/HIToolbox.framework/ 583 FrameworkName += "Frameworks/"; 584 FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos); 585 FrameworkName += ".framework/"; 586 587 llvm::StringMapEntry<const DirectoryEntry *> &CacheLookup = 588 FrameworkMap.GetOrCreateValue(Filename.substr(0, SlashPos)); 589 590 // Some other location? 591 if (CacheLookup.getValue() && 592 CacheLookup.getKeyLength() == FrameworkName.size() && 593 memcmp(CacheLookup.getKeyData(), &FrameworkName[0], 594 CacheLookup.getKeyLength()) != 0) 595 return 0; 596 597 // Cache subframework. 598 if (CacheLookup.getValue() == 0) { 599 ++NumSubFrameworkLookups; 600 601 // If the framework dir doesn't exist, we fail. 602 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.str()); 603 if (Dir == 0) return 0; 604 605 // Otherwise, if it does, remember that this is the right direntry for this 606 // framework. 607 CacheLookup.setValue(Dir); 608 } 609 610 const FileEntry *FE = 0; 611 612 if (RelativePath != NULL) { 613 RelativePath->clear(); 614 RelativePath->append(Filename.begin()+SlashPos+1, Filename.end()); 615 } 616 617 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h" 618 llvm::SmallString<1024> HeadersFilename(FrameworkName); 619 HeadersFilename += "Headers/"; 620 if (SearchPath != NULL) { 621 SearchPath->clear(); 622 // Without trailing '/'. 623 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1); 624 } 625 626 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end()); 627 if (!(FE = FileMgr.getFile(HeadersFilename.str(), /*openFile=*/true))) { 628 629 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h" 630 HeadersFilename = FrameworkName; 631 HeadersFilename += "PrivateHeaders/"; 632 if (SearchPath != NULL) { 633 SearchPath->clear(); 634 // Without trailing '/'. 635 SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1); 636 } 637 638 HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end()); 639 if (!(FE = FileMgr.getFile(HeadersFilename.str(), /*openFile=*/true))) 640 return 0; 641 } 642 643 // This file is a system header or C++ unfriendly if the old file is. 644 // 645 // Note that the temporary 'DirInfo' is required here, as either call to 646 // getFileInfo could resize the vector and we don't want to rely on order 647 // of evaluation. 648 unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo; 649 getFileInfo(FE).DirInfo = DirInfo; 650 return FE; 651 } 652 653 //===----------------------------------------------------------------------===// 654 // File Info Management. 655 //===----------------------------------------------------------------------===// 656 657 /// \brief Merge the header file info provided by \p OtherHFI into the current 658 /// header file info (\p HFI) 659 static void mergeHeaderFileInfo(HeaderFileInfo &HFI, 660 const HeaderFileInfo &OtherHFI) { 661 HFI.isImport |= OtherHFI.isImport; 662 HFI.isPragmaOnce |= OtherHFI.isPragmaOnce; 663 HFI.NumIncludes += OtherHFI.NumIncludes; 664 665 if (!HFI.ControllingMacro && !HFI.ControllingMacroID) { 666 HFI.ControllingMacro = OtherHFI.ControllingMacro; 667 HFI.ControllingMacroID = OtherHFI.ControllingMacroID; 668 } 669 670 if (OtherHFI.External) { 671 HFI.DirInfo = OtherHFI.DirInfo; 672 HFI.External = OtherHFI.External; 673 HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader; 674 } 675 676 if (HFI.Framework.empty()) 677 HFI.Framework = OtherHFI.Framework; 678 679 HFI.Resolved = true; 680 } 681 682 /// getFileInfo - Return the HeaderFileInfo structure for the specified 683 /// FileEntry. 684 HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) { 685 if (FE->getUID() >= FileInfo.size()) 686 FileInfo.resize(FE->getUID()+1); 687 688 HeaderFileInfo &HFI = FileInfo[FE->getUID()]; 689 if (ExternalSource && !HFI.Resolved) 690 mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(FE)); 691 return HFI; 692 } 693 694 bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) { 695 // Check if we've ever seen this file as a header. 696 if (File->getUID() >= FileInfo.size()) 697 return false; 698 699 // Resolve header file info from the external source, if needed. 700 HeaderFileInfo &HFI = FileInfo[File->getUID()]; 701 if (ExternalSource && !HFI.Resolved) 702 mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(File)); 703 704 return HFI.isPragmaOnce || HFI.ControllingMacro || HFI.ControllingMacroID; 705 } 706 707 void HeaderSearch::setHeaderFileInfoForUID(HeaderFileInfo HFI, unsigned UID) { 708 if (UID >= FileInfo.size()) 709 FileInfo.resize(UID+1); 710 HFI.Resolved = true; 711 FileInfo[UID] = HFI; 712 } 713 714 /// ShouldEnterIncludeFile - Mark the specified file as a target of of a 715 /// #include, #include_next, or #import directive. Return false if #including 716 /// the file will have no effect or true if we should include it. 717 bool HeaderSearch::ShouldEnterIncludeFile(const FileEntry *File, bool isImport){ 718 ++NumIncluded; // Count # of attempted #includes. 719 720 // Get information about this file. 721 HeaderFileInfo &FileInfo = getFileInfo(File); 722 723 // If this is a #import directive, check that we have not already imported 724 // this header. 725 if (isImport) { 726 // If this has already been imported, don't import it again. 727 FileInfo.isImport = true; 728 729 // Has this already been #import'ed or #include'd? 730 if (FileInfo.NumIncludes) return false; 731 } else { 732 // Otherwise, if this is a #include of a file that was previously #import'd 733 // or if this is the second #include of a #pragma once file, ignore it. 734 if (FileInfo.isImport) 735 return false; 736 } 737 738 // Next, check to see if the file is wrapped with #ifndef guards. If so, and 739 // if the macro that guards it is defined, we know the #include has no effect. 740 if (const IdentifierInfo *ControllingMacro 741 = FileInfo.getControllingMacro(ExternalLookup)) 742 if (ControllingMacro->hasMacroDefinition()) { 743 ++NumMultiIncludeFileOptzn; 744 return false; 745 } 746 747 // Increment the number of times this file has been included. 748 ++FileInfo.NumIncludes; 749 750 return true; 751 } 752 753 size_t HeaderSearch::getTotalMemory() const { 754 return SearchDirs.capacity() 755 + llvm::capacity_in_bytes(FileInfo) 756 + llvm::capacity_in_bytes(HeaderMaps) 757 + LookupFileCache.getAllocator().getTotalMemory() 758 + FrameworkMap.getAllocator().getTotalMemory(); 759 } 760 761 StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) { 762 return FrameworkNames.GetOrCreateValue(Framework).getKey(); 763 } 764 765 bool HeaderSearch::hasModuleMap(StringRef FileName, 766 const DirectoryEntry *Root) { 767 llvm::SmallVector<const DirectoryEntry *, 2> FixUpDirectories; 768 769 StringRef DirName = FileName; 770 do { 771 // Get the parent directory name. 772 DirName = llvm::sys::path::parent_path(DirName); 773 if (DirName.empty()) 774 return false; 775 776 // Determine whether this directory exists. 777 const DirectoryEntry *Dir = FileMgr.getDirectory(DirName); 778 if (!Dir) 779 return false; 780 781 // Try to load the module map file in this directory. 782 switch (loadModuleMapFile(Dir)) { 783 case LMM_NewlyLoaded: 784 case LMM_AlreadyLoaded: 785 // Success. All of the directories we stepped through inherit this module 786 // map file. 787 for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I) 788 DirectoryHasModuleMap[FixUpDirectories[I]] = true; 789 790 return true; 791 792 case LMM_NoDirectory: 793 case LMM_InvalidModuleMap: 794 break; 795 } 796 797 // If we hit the top of our search, we're done. 798 if (Dir == Root) 799 return false; 800 801 // Keep track of all of the directories we checked, so we can mark them as 802 // having module maps if we eventually do find a module map. 803 FixUpDirectories.push_back(Dir); 804 } while (true); 805 806 return false; 807 } 808 809 StringRef HeaderSearch::findModuleForHeader(const FileEntry *File) { 810 if (ModuleMap::Module *Module = ModMap.findModuleForHeader(File)) 811 return Module->getTopLevelModuleName(); 812 813 return StringRef(); 814 } 815 816 bool HeaderSearch::loadModuleMapFile(const FileEntry *File) { 817 const DirectoryEntry *Dir = File->getDir(); 818 819 llvm::DenseMap<const DirectoryEntry *, bool>::iterator KnownDir 820 = DirectoryHasModuleMap.find(Dir); 821 if (KnownDir != DirectoryHasModuleMap.end()) 822 return !KnownDir->second; 823 824 bool Result = ModMap.parseModuleMapFile(File); 825 DirectoryHasModuleMap[Dir] = !Result; 826 return Result; 827 } 828 829 ModuleMap::Module *HeaderSearch::getModule(StringRef Name, bool AllowSearch) { 830 if (ModuleMap::Module *Module = ModMap.findModule(Name)) 831 return Module; 832 833 if (!AllowSearch) 834 return 0; 835 836 for (unsigned I = 0, N = SearchDirs.size(); I != N; ++I) { 837 if (!SearchDirs[I].isNormalDir()) 838 continue; 839 840 switch (loadModuleMapFile(SearchDirs[I].getDir())) { 841 case LMM_AlreadyLoaded: 842 case LMM_InvalidModuleMap: 843 case LMM_NoDirectory: 844 break; 845 846 case LMM_NewlyLoaded: 847 if (ModuleMap::Module *Module = ModMap.findModule(Name)) 848 return Module; 849 break; 850 } 851 } 852 853 return 0; 854 } 855 856 ModuleMap::Module *HeaderSearch::getFrameworkModule(StringRef Name, 857 const DirectoryEntry *Dir) { 858 if (ModuleMap::Module *Module = ModMap.findModule(Name)) 859 return Module; 860 861 // Try to load a module map file. 862 switch (loadModuleMapFile(Dir)) { 863 case LMM_InvalidModuleMap: 864 break; 865 866 case LMM_AlreadyLoaded: 867 case LMM_NoDirectory: 868 return 0; 869 870 case LMM_NewlyLoaded: 871 return ModMap.findModule(Name); 872 } 873 874 // Try to infer a module map. 875 return ModMap.inferFrameworkModule(Name, Dir); 876 } 877 878 879 HeaderSearch::LoadModuleMapResult 880 HeaderSearch::loadModuleMapFile(StringRef DirName) { 881 if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName)) 882 return loadModuleMapFile(Dir); 883 884 return LMM_NoDirectory; 885 } 886 887 HeaderSearch::LoadModuleMapResult 888 HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir) { 889 llvm::DenseMap<const DirectoryEntry *, bool>::iterator KnownDir 890 = DirectoryHasModuleMap.find(Dir); 891 if (KnownDir != DirectoryHasModuleMap.end()) 892 return KnownDir->second? LMM_AlreadyLoaded : LMM_InvalidModuleMap; 893 894 llvm::SmallString<128> ModuleMapFileName; 895 ModuleMapFileName += Dir->getName(); 896 llvm::sys::path::append(ModuleMapFileName, "module.map"); 897 if (const FileEntry *ModuleMapFile = FileMgr.getFile(ModuleMapFileName)) { 898 // We have found a module map file. Try to parse it. 899 if (!ModMap.parseModuleMapFile(ModuleMapFile)) { 900 // This directory has a module map. 901 DirectoryHasModuleMap[Dir] = true; 902 903 return LMM_NewlyLoaded; 904 } 905 } 906 907 // No suitable module map. 908 DirectoryHasModuleMap[Dir] = false; 909 return LMM_InvalidModuleMap; 910 } 911 912