Home | History | Annotate | Download | only in Frontend
      1 //===--- InitHeaderSearch.cpp - Initialize header search paths ------------===//
      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 InitHeaderSearch class.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "clang/Frontend/Utils.h"
     15 #include "clang/Basic/FileManager.h"
     16 #include "clang/Basic/LangOptions.h"
     17 #include "clang/Config/config.h" // C_INCLUDE_DIRS
     18 #include "clang/Lex/HeaderSearch.h"
     19 #include "clang/Lex/HeaderSearchOptions.h"
     20 #include "llvm/ADT/SmallPtrSet.h"
     21 #include "llvm/ADT/SmallString.h"
     22 #include "llvm/ADT/SmallVector.h"
     23 #include "llvm/ADT/StringExtras.h"
     24 #include "llvm/ADT/Triple.h"
     25 #include "llvm/ADT/Twine.h"
     26 #include "llvm/Support/ErrorHandling.h"
     27 #include "llvm/Support/Path.h"
     28 #include "llvm/Support/raw_ostream.h"
     29 
     30 using namespace clang;
     31 using namespace clang::frontend;
     32 
     33 namespace {
     34 
     35 /// InitHeaderSearch - This class makes it easier to set the search paths of
     36 ///  a HeaderSearch object. InitHeaderSearch stores several search path lists
     37 ///  internally, which can be sent to a HeaderSearch object in one swoop.
     38 class InitHeaderSearch {
     39   std::vector<std::pair<IncludeDirGroup, DirectoryLookup> > IncludePath;
     40   typedef std::vector<std::pair<IncludeDirGroup,
     41                       DirectoryLookup> >::const_iterator path_iterator;
     42   std::vector<std::pair<std::string, bool> > SystemHeaderPrefixes;
     43   HeaderSearch &Headers;
     44   bool Verbose;
     45   std::string IncludeSysroot;
     46   bool HasSysroot;
     47 
     48 public:
     49 
     50   InitHeaderSearch(HeaderSearch &HS, bool verbose, StringRef sysroot)
     51     : Headers(HS), Verbose(verbose), IncludeSysroot(sysroot),
     52       HasSysroot(!(sysroot.empty() || sysroot == "/")) {
     53   }
     54 
     55   /// AddPath - Add the specified path to the specified group list, prefixing
     56   /// the sysroot if used.
     57   void AddPath(const Twine &Path, IncludeDirGroup Group, bool isFramework);
     58 
     59   /// AddUnmappedPath - Add the specified path to the specified group list,
     60   /// without performing any sysroot remapping.
     61   void AddUnmappedPath(const Twine &Path, IncludeDirGroup Group,
     62                        bool isFramework);
     63 
     64   /// AddSystemHeaderPrefix - Add the specified prefix to the system header
     65   /// prefix list.
     66   void AddSystemHeaderPrefix(StringRef Prefix, bool IsSystemHeader) {
     67     SystemHeaderPrefixes.push_back(std::make_pair(Prefix, IsSystemHeader));
     68   }
     69 
     70   /// AddGnuCPlusPlusIncludePaths - Add the necessary paths to support a gnu
     71   ///  libstdc++.
     72   void AddGnuCPlusPlusIncludePaths(StringRef Base,
     73                                    StringRef ArchDir,
     74                                    StringRef Dir32,
     75                                    StringRef Dir64,
     76                                    const llvm::Triple &triple);
     77 
     78   /// AddMinGWCPlusPlusIncludePaths - Add the necessary paths to support a MinGW
     79   ///  libstdc++.
     80   void AddMinGWCPlusPlusIncludePaths(StringRef Base,
     81                                      StringRef Arch,
     82                                      StringRef Version);
     83 
     84   /// AddMinGW64CXXPaths - Add the necessary paths to support
     85   /// libstdc++ of x86_64-w64-mingw32 aka mingw-w64.
     86   void AddMinGW64CXXPaths(StringRef Base,
     87                           StringRef Version);
     88 
     89   // AddDefaultCIncludePaths - Add paths that should always be searched.
     90   void AddDefaultCIncludePaths(const llvm::Triple &triple,
     91                                const HeaderSearchOptions &HSOpts);
     92 
     93   // AddDefaultCPlusPlusIncludePaths -  Add paths that should be searched when
     94   //  compiling c++.
     95   void AddDefaultCPlusPlusIncludePaths(const llvm::Triple &triple,
     96                                        const HeaderSearchOptions &HSOpts);
     97 
     98   /// AddDefaultSystemIncludePaths - Adds the default system include paths so
     99   ///  that e.g. stdio.h is found.
    100   void AddDefaultIncludePaths(const LangOptions &Lang,
    101                               const llvm::Triple &triple,
    102                               const HeaderSearchOptions &HSOpts);
    103 
    104   /// Realize - Merges all search path lists into one list and send it to
    105   /// HeaderSearch.
    106   void Realize(const LangOptions &Lang);
    107 };
    108 
    109 }  // end anonymous namespace.
    110 
    111 static bool CanPrefixSysroot(StringRef Path) {
    112 #if defined(_WIN32)
    113   return !Path.empty() && llvm::sys::path::is_separator(Path[0]);
    114 #else
    115   return llvm::sys::path::is_absolute(Path);
    116 #endif
    117 }
    118 
    119 void InitHeaderSearch::AddPath(const Twine &Path, IncludeDirGroup Group,
    120                                bool isFramework) {
    121   // Add the path with sysroot prepended, if desired and this is a system header
    122   // group.
    123   if (HasSysroot) {
    124     SmallString<256> MappedPathStorage;
    125     StringRef MappedPathStr = Path.toStringRef(MappedPathStorage);
    126     if (CanPrefixSysroot(MappedPathStr)) {
    127       AddUnmappedPath(IncludeSysroot + Path, Group, isFramework);
    128       return;
    129     }
    130   }
    131 
    132   AddUnmappedPath(Path, Group, isFramework);
    133 }
    134 
    135 void InitHeaderSearch::AddUnmappedPath(const Twine &Path, IncludeDirGroup Group,
    136                                        bool isFramework) {
    137   assert(!Path.isTriviallyEmpty() && "can't handle empty path here");
    138 
    139   FileManager &FM = Headers.getFileMgr();
    140   SmallString<256> MappedPathStorage;
    141   StringRef MappedPathStr = Path.toStringRef(MappedPathStorage);
    142 
    143   // Compute the DirectoryLookup type.
    144   SrcMgr::CharacteristicKind Type;
    145   if (Group == Quoted || Group == Angled || Group == IndexHeaderMap) {
    146     Type = SrcMgr::C_User;
    147   } else if (Group == ExternCSystem) {
    148     Type = SrcMgr::C_ExternCSystem;
    149   } else {
    150     Type = SrcMgr::C_System;
    151   }
    152 
    153   // If the directory exists, add it.
    154   if (const DirectoryEntry *DE = FM.getDirectory(MappedPathStr)) {
    155     IncludePath.push_back(
    156       std::make_pair(Group, DirectoryLookup(DE, Type, isFramework)));
    157     return;
    158   }
    159 
    160   // Check to see if this is an apple-style headermap (which are not allowed to
    161   // be frameworks).
    162   if (!isFramework) {
    163     if (const FileEntry *FE = FM.getFile(MappedPathStr)) {
    164       if (const HeaderMap *HM = Headers.CreateHeaderMap(FE)) {
    165         // It is a headermap, add it to the search path.
    166         IncludePath.push_back(
    167           std::make_pair(Group,
    168                          DirectoryLookup(HM, Type, Group == IndexHeaderMap)));
    169         return;
    170       }
    171     }
    172   }
    173 
    174   if (Verbose)
    175     llvm::errs() << "ignoring nonexistent directory \""
    176                  << MappedPathStr << "\"\n";
    177 }
    178 
    179 void InitHeaderSearch::AddGnuCPlusPlusIncludePaths(StringRef Base,
    180                                                    StringRef ArchDir,
    181                                                    StringRef Dir32,
    182                                                    StringRef Dir64,
    183                                                    const llvm::Triple &triple) {
    184   // Add the base dir
    185   AddPath(Base, CXXSystem, false);
    186 
    187   // Add the multilib dirs
    188   llvm::Triple::ArchType arch = triple.getArch();
    189   bool is64bit = arch == llvm::Triple::ppc64 || arch == llvm::Triple::x86_64;
    190   if (is64bit)
    191     AddPath(Base + "/" + ArchDir + "/" + Dir64, CXXSystem, false);
    192   else
    193     AddPath(Base + "/" + ArchDir + "/" + Dir32, CXXSystem, false);
    194 
    195   // Add the backward dir
    196   AddPath(Base + "/backward", CXXSystem, false);
    197 }
    198 
    199 void InitHeaderSearch::AddMinGWCPlusPlusIncludePaths(StringRef Base,
    200                                                      StringRef Arch,
    201                                                      StringRef Version) {
    202   AddPath(Base + "/" + Arch + "/" + Version + "/include/c++",
    203           CXXSystem, false);
    204   AddPath(Base + "/" + Arch + "/" + Version + "/include/c++/" + Arch,
    205           CXXSystem, false);
    206   AddPath(Base + "/" + Arch + "/" + Version + "/include/c++/backward",
    207           CXXSystem, false);
    208 }
    209 
    210 void InitHeaderSearch::AddMinGW64CXXPaths(StringRef Base,
    211                                           StringRef Version) {
    212   // Assumes Base is HeaderSearchOpts' ResourceDir
    213   AddPath(Base + "/../../../include/c++/" + Version,
    214           CXXSystem, false);
    215   AddPath(Base + "/../../../include/c++/" + Version + "/x86_64-w64-mingw32",
    216           CXXSystem, false);
    217   AddPath(Base + "/../../../include/c++/" + Version + "/i686-w64-mingw32",
    218           CXXSystem, false);
    219   AddPath(Base + "/../../../include/c++/" + Version + "/backward",
    220           CXXSystem, false);
    221 }
    222 
    223 void InitHeaderSearch::AddDefaultCIncludePaths(const llvm::Triple &triple,
    224                                             const HeaderSearchOptions &HSOpts) {
    225   llvm::Triple::OSType os = triple.getOS();
    226 
    227   if (HSOpts.UseStandardSystemIncludes) {
    228     switch (os) {
    229     case llvm::Triple::FreeBSD:
    230     case llvm::Triple::NetBSD:
    231     case llvm::Triple::OpenBSD:
    232     case llvm::Triple::Bitrig:
    233       break;
    234     default:
    235       // FIXME: temporary hack: hard-coded paths.
    236       AddPath("/usr/local/include", System, false);
    237       break;
    238     }
    239   }
    240 
    241   // Builtin includes use #include_next directives and should be positioned
    242   // just prior C include dirs.
    243   if (HSOpts.UseBuiltinIncludes) {
    244     // Ignore the sys root, we *always* look for clang headers relative to
    245     // supplied path.
    246     llvm::sys::Path P(HSOpts.ResourceDir);
    247     P.appendComponent("include");
    248     AddUnmappedPath(P.str(), ExternCSystem, false);
    249   }
    250 
    251   // All remaining additions are for system include directories, early exit if
    252   // we aren't using them.
    253   if (!HSOpts.UseStandardSystemIncludes)
    254     return;
    255 
    256   // Add dirs specified via 'configure --with-c-include-dirs'.
    257   StringRef CIncludeDirs(C_INCLUDE_DIRS);
    258   if (CIncludeDirs != "") {
    259     SmallVector<StringRef, 5> dirs;
    260     CIncludeDirs.split(dirs, ":");
    261     for (SmallVectorImpl<StringRef>::iterator i = dirs.begin();
    262          i != dirs.end();
    263          ++i)
    264       AddPath(*i, ExternCSystem, false);
    265     return;
    266   }
    267 
    268   switch (os) {
    269   case llvm::Triple::Linux:
    270   case llvm::Triple::Win32:
    271     llvm_unreachable("Include management is handled in the driver.");
    272 
    273   case llvm::Triple::Haiku:
    274     AddPath("/boot/common/include", System, false);
    275     AddPath("/boot/develop/headers/os", System, false);
    276     AddPath("/boot/develop/headers/os/app", System, false);
    277     AddPath("/boot/develop/headers/os/arch", System, false);
    278     AddPath("/boot/develop/headers/os/device", System, false);
    279     AddPath("/boot/develop/headers/os/drivers", System, false);
    280     AddPath("/boot/develop/headers/os/game", System, false);
    281     AddPath("/boot/develop/headers/os/interface", System, false);
    282     AddPath("/boot/develop/headers/os/kernel", System, false);
    283     AddPath("/boot/develop/headers/os/locale", System, false);
    284     AddPath("/boot/develop/headers/os/mail", System, false);
    285     AddPath("/boot/develop/headers/os/media", System, false);
    286     AddPath("/boot/develop/headers/os/midi", System, false);
    287     AddPath("/boot/develop/headers/os/midi2", System, false);
    288     AddPath("/boot/develop/headers/os/net", System, false);
    289     AddPath("/boot/develop/headers/os/storage", System, false);
    290     AddPath("/boot/develop/headers/os/support", System, false);
    291     AddPath("/boot/develop/headers/os/translation", System, false);
    292     AddPath("/boot/develop/headers/os/add-ons/graphics", System, false);
    293     AddPath("/boot/develop/headers/os/add-ons/input_server", System, false);
    294     AddPath("/boot/develop/headers/os/add-ons/screen_saver", System, false);
    295     AddPath("/boot/develop/headers/os/add-ons/tracker", System, false);
    296     AddPath("/boot/develop/headers/os/be_apps/Deskbar", System, false);
    297     AddPath("/boot/develop/headers/os/be_apps/NetPositive", System, false);
    298     AddPath("/boot/develop/headers/os/be_apps/Tracker", System, false);
    299     AddPath("/boot/develop/headers/cpp", System, false);
    300     AddPath("/boot/develop/headers/cpp/i586-pc-haiku", System, false);
    301     AddPath("/boot/develop/headers/3rdparty", System, false);
    302     AddPath("/boot/develop/headers/bsd", System, false);
    303     AddPath("/boot/develop/headers/glibc", System, false);
    304     AddPath("/boot/develop/headers/posix", System, false);
    305     AddPath("/boot/develop/headers",  System, false);
    306     break;
    307   case llvm::Triple::RTEMS:
    308     break;
    309   case llvm::Triple::Cygwin:
    310     AddPath("/usr/include/w32api", System, false);
    311     break;
    312   case llvm::Triple::MinGW32: {
    313       // mingw-w64 crt include paths
    314       llvm::sys::Path P(HSOpts.ResourceDir);
    315       P.appendComponent("../../../i686-w64-mingw32/include"); // <sysroot>/i686-w64-mingw32/include
    316       AddPath(P.str(), System, false);
    317       P = llvm::sys::Path(HSOpts.ResourceDir);
    318       P.appendComponent("../../../x86_64-w64-mingw32/include"); // <sysroot>/x86_64-w64-mingw32/include
    319       AddPath(P.str(), System, false);
    320       // mingw.org crt include paths
    321       P = llvm::sys::Path(HSOpts.ResourceDir);
    322       P.appendComponent("../../../include"); // <sysroot>/include
    323       AddPath(P.str(), System, false);
    324       AddPath("/mingw/include", System, false);
    325 #if defined(_WIN32)
    326       AddPath("c:/mingw/include", System, false);
    327 #endif
    328     }
    329     break;
    330 
    331   default:
    332     break;
    333   }
    334 
    335   if ( os != llvm::Triple::RTEMS )
    336     AddPath("/usr/include", ExternCSystem, false);
    337 }
    338 
    339 void InitHeaderSearch::
    340 AddDefaultCPlusPlusIncludePaths(const llvm::Triple &triple, const HeaderSearchOptions &HSOpts) {
    341   llvm::Triple::OSType os = triple.getOS();
    342   // FIXME: temporary hack: hard-coded paths.
    343 
    344   if (triple.isOSDarwin()) {
    345     switch (triple.getArch()) {
    346     default: break;
    347 
    348     case llvm::Triple::ppc:
    349     case llvm::Triple::ppc64:
    350       AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2.1",
    351                                   "powerpc-apple-darwin10", "", "ppc64",
    352                                   triple);
    353       AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.0.0",
    354                                   "powerpc-apple-darwin10", "", "ppc64",
    355                                   triple);
    356       break;
    357 
    358     case llvm::Triple::x86:
    359     case llvm::Triple::x86_64:
    360       AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2.1",
    361                                   "i686-apple-darwin10", "", "x86_64", triple);
    362       AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.0.0",
    363                                   "i686-apple-darwin8", "", "", triple);
    364       break;
    365 
    366     case llvm::Triple::arm:
    367     case llvm::Triple::thumb:
    368       AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2.1",
    369                                   "arm-apple-darwin10", "v7", "", triple);
    370       AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2.1",
    371                                   "arm-apple-darwin10", "v6", "", triple);
    372       break;
    373     }
    374     return;
    375   }
    376 
    377   switch (os) {
    378   case llvm::Triple::Linux:
    379   case llvm::Triple::Win32:
    380     llvm_unreachable("Include management is handled in the driver.");
    381 
    382   case llvm::Triple::Cygwin:
    383     // Cygwin-1.7
    384     AddMinGWCPlusPlusIncludePaths("/usr/lib/gcc", "i686-pc-cygwin", "4.5.3");
    385     AddMinGWCPlusPlusIncludePaths("/usr/lib/gcc", "i686-pc-cygwin", "4.3.4");
    386     // g++-4 / Cygwin-1.5
    387     AddMinGWCPlusPlusIncludePaths("/usr/lib/gcc", "i686-pc-cygwin", "4.3.2");
    388     break;
    389   case llvm::Triple::MinGW32:
    390     // mingw-w64 C++ include paths (i686-w64-mingw32 and x86_64-w64-mingw32)
    391     AddMinGW64CXXPaths(HSOpts.ResourceDir, "4.5.0");
    392     AddMinGW64CXXPaths(HSOpts.ResourceDir, "4.5.1");
    393     AddMinGW64CXXPaths(HSOpts.ResourceDir, "4.5.2");
    394     AddMinGW64CXXPaths(HSOpts.ResourceDir, "4.5.3");
    395     AddMinGW64CXXPaths(HSOpts.ResourceDir, "4.5.4");
    396     AddMinGW64CXXPaths(HSOpts.ResourceDir, "4.6.0");
    397     AddMinGW64CXXPaths(HSOpts.ResourceDir, "4.6.1");
    398     AddMinGW64CXXPaths(HSOpts.ResourceDir, "4.6.2");
    399     AddMinGW64CXXPaths(HSOpts.ResourceDir, "4.6.3");
    400     AddMinGW64CXXPaths(HSOpts.ResourceDir, "4.7.0");
    401     // mingw.org C++ include paths
    402     AddMinGWCPlusPlusIncludePaths("/mingw/lib/gcc", "mingw32", "4.5.2"); //MSYS
    403 #if defined(_WIN32)
    404     AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw32", "4.6.2");
    405     AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw32", "4.6.1");
    406     AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw32", "4.5.2");
    407     AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw32", "4.5.0");
    408     AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw32", "4.4.0");
    409     AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw32", "4.3.0");
    410 #endif
    411     break;
    412   case llvm::Triple::DragonFly:
    413     AddPath("/usr/include/c++/4.1", CXXSystem, false);
    414     break;
    415   case llvm::Triple::FreeBSD:
    416     // FreeBSD 8.0
    417     // FreeBSD 7.3
    418     AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2", "", "", "", triple);
    419     break;
    420   case llvm::Triple::NetBSD:
    421     AddGnuCPlusPlusIncludePaths("/usr/include/g++", "", "", "", triple);
    422     break;
    423   case llvm::Triple::OpenBSD: {
    424     std::string t = triple.getTriple();
    425     if (t.substr(0, 6) == "x86_64")
    426       t.replace(0, 6, "amd64");
    427     AddGnuCPlusPlusIncludePaths("/usr/include/g++",
    428                                 t, "", "", triple);
    429     break;
    430   }
    431   case llvm::Triple::Minix:
    432     AddGnuCPlusPlusIncludePaths("/usr/gnu/include/c++/4.4.3",
    433                                 "", "", "", triple);
    434     break;
    435   case llvm::Triple::Solaris:
    436     AddGnuCPlusPlusIncludePaths("/usr/gcc/4.5/include/c++/4.5.2/",
    437                                 "i386-pc-solaris2.11", "", "", triple);
    438     // Solaris - Fall though..
    439   case llvm::Triple::AuroraUX:
    440     // AuroraUX
    441     AddGnuCPlusPlusIncludePaths("/opt/gcc4/include/c++/4.2.4",
    442                                 "i386-pc-solaris2.11", "", "", triple);
    443     break;
    444   default:
    445     break;
    446   }
    447 }
    448 
    449 void InitHeaderSearch::AddDefaultIncludePaths(const LangOptions &Lang,
    450                                               const llvm::Triple &triple,
    451                                             const HeaderSearchOptions &HSOpts) {
    452   // NB: This code path is going away. All of the logic is moving into the
    453   // driver which has the information necessary to do target-specific
    454   // selections of default include paths. Each target which moves there will be
    455   // exempted from this logic here until we can delete the entire pile of code.
    456   switch (triple.getOS()) {
    457   default:
    458     break; // Everything else continues to use this routine's logic.
    459 
    460   case llvm::Triple::Linux:
    461   case llvm::Triple::Win32:
    462     return;
    463   }
    464 
    465   if (Lang.CPlusPlus && HSOpts.UseStandardCXXIncludes &&
    466       HSOpts.UseStandardSystemIncludes) {
    467     if (HSOpts.UseLibcxx) {
    468       if (triple.isOSDarwin()) {
    469         // On Darwin, libc++ may be installed alongside the compiler in
    470         // lib/c++/v1.
    471         llvm::sys::Path P(HSOpts.ResourceDir);
    472         if (!P.isEmpty()) {
    473           P.eraseComponent();  // Remove version from foo/lib/clang/version
    474           P.eraseComponent();  // Remove clang from foo/lib/clang
    475 
    476           // Get foo/lib/c++/v1
    477           P.appendComponent("c++");
    478           P.appendComponent("v1");
    479           AddUnmappedPath(P.str(), CXXSystem, false);
    480         }
    481       }
    482       // On Solaris, include the support directory for things like xlocale and
    483       // fudged system headers.
    484       if (triple.getOS() == llvm::Triple::Solaris)
    485         AddPath("/usr/include/c++/v1/support/solaris", CXXSystem, false);
    486 
    487       AddPath("/usr/include/c++/v1", CXXSystem, false);
    488     } else {
    489       AddDefaultCPlusPlusIncludePaths(triple, HSOpts);
    490     }
    491   }
    492 
    493   AddDefaultCIncludePaths(triple, HSOpts);
    494 
    495   // Add the default framework include paths on Darwin.
    496   if (HSOpts.UseStandardSystemIncludes) {
    497     if (triple.isOSDarwin()) {
    498       AddPath("/System/Library/Frameworks", System, true);
    499       AddPath("/Library/Frameworks", System, true);
    500     }
    501   }
    502 }
    503 
    504 /// RemoveDuplicates - If there are duplicate directory entries in the specified
    505 /// search list, remove the later (dead) ones.  Returns the number of non-system
    506 /// headers removed, which is used to update NumAngled.
    507 static unsigned RemoveDuplicates(std::vector<DirectoryLookup> &SearchList,
    508                                  unsigned First, bool Verbose) {
    509   llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
    510   llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
    511   llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
    512   unsigned NonSystemRemoved = 0;
    513   for (unsigned i = First; i != SearchList.size(); ++i) {
    514     unsigned DirToRemove = i;
    515 
    516     const DirectoryLookup &CurEntry = SearchList[i];
    517 
    518     if (CurEntry.isNormalDir()) {
    519       // If this isn't the first time we've seen this dir, remove it.
    520       if (SeenDirs.insert(CurEntry.getDir()))
    521         continue;
    522     } else if (CurEntry.isFramework()) {
    523       // If this isn't the first time we've seen this framework dir, remove it.
    524       if (SeenFrameworkDirs.insert(CurEntry.getFrameworkDir()))
    525         continue;
    526     } else {
    527       assert(CurEntry.isHeaderMap() && "Not a headermap or normal dir?");
    528       // If this isn't the first time we've seen this headermap, remove it.
    529       if (SeenHeaderMaps.insert(CurEntry.getHeaderMap()))
    530         continue;
    531     }
    532 
    533     // If we have a normal #include dir/framework/headermap that is shadowed
    534     // later in the chain by a system include location, we actually want to
    535     // ignore the user's request and drop the user dir... keeping the system
    536     // dir.  This is weird, but required to emulate GCC's search path correctly.
    537     //
    538     // Since dupes of system dirs are rare, just rescan to find the original
    539     // that we're nuking instead of using a DenseMap.
    540     if (CurEntry.getDirCharacteristic() != SrcMgr::C_User) {
    541       // Find the dir that this is the same of.
    542       unsigned FirstDir;
    543       for (FirstDir = 0; ; ++FirstDir) {
    544         assert(FirstDir != i && "Didn't find dupe?");
    545 
    546         const DirectoryLookup &SearchEntry = SearchList[FirstDir];
    547 
    548         // If these are different lookup types, then they can't be the dupe.
    549         if (SearchEntry.getLookupType() != CurEntry.getLookupType())
    550           continue;
    551 
    552         bool isSame;
    553         if (CurEntry.isNormalDir())
    554           isSame = SearchEntry.getDir() == CurEntry.getDir();
    555         else if (CurEntry.isFramework())
    556           isSame = SearchEntry.getFrameworkDir() == CurEntry.getFrameworkDir();
    557         else {
    558           assert(CurEntry.isHeaderMap() && "Not a headermap or normal dir?");
    559           isSame = SearchEntry.getHeaderMap() == CurEntry.getHeaderMap();
    560         }
    561 
    562         if (isSame)
    563           break;
    564       }
    565 
    566       // If the first dir in the search path is a non-system dir, zap it
    567       // instead of the system one.
    568       if (SearchList[FirstDir].getDirCharacteristic() == SrcMgr::C_User)
    569         DirToRemove = FirstDir;
    570     }
    571 
    572     if (Verbose) {
    573       llvm::errs() << "ignoring duplicate directory \""
    574                    << CurEntry.getName() << "\"\n";
    575       if (DirToRemove != i)
    576         llvm::errs() << "  as it is a non-system directory that duplicates "
    577                      << "a system directory\n";
    578     }
    579     if (DirToRemove != i)
    580       ++NonSystemRemoved;
    581 
    582     // This is reached if the current entry is a duplicate.  Remove the
    583     // DirToRemove (usually the current dir).
    584     SearchList.erase(SearchList.begin()+DirToRemove);
    585     --i;
    586   }
    587   return NonSystemRemoved;
    588 }
    589 
    590 
    591 void InitHeaderSearch::Realize(const LangOptions &Lang) {
    592   // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
    593   std::vector<DirectoryLookup> SearchList;
    594   SearchList.reserve(IncludePath.size());
    595 
    596   // Quoted arguments go first.
    597   for (path_iterator it = IncludePath.begin(), ie = IncludePath.end();
    598        it != ie; ++it) {
    599     if (it->first == Quoted)
    600       SearchList.push_back(it->second);
    601   }
    602   // Deduplicate and remember index.
    603   RemoveDuplicates(SearchList, 0, Verbose);
    604   unsigned NumQuoted = SearchList.size();
    605 
    606   for (path_iterator it = IncludePath.begin(), ie = IncludePath.end();
    607        it != ie; ++it) {
    608     if (it->first == Angled || it->first == IndexHeaderMap)
    609       SearchList.push_back(it->second);
    610   }
    611 
    612   RemoveDuplicates(SearchList, NumQuoted, Verbose);
    613   unsigned NumAngled = SearchList.size();
    614 
    615   for (path_iterator it = IncludePath.begin(), ie = IncludePath.end();
    616        it != ie; ++it) {
    617     if (it->first == System || it->first == ExternCSystem ||
    618         (!Lang.ObjC1 && !Lang.CPlusPlus && it->first == CSystem)    ||
    619         (/*FIXME !Lang.ObjC1 && */Lang.CPlusPlus  && it->first == CXXSystem)  ||
    620         (Lang.ObjC1  && !Lang.CPlusPlus && it->first == ObjCSystem) ||
    621         (Lang.ObjC1  && Lang.CPlusPlus  && it->first == ObjCXXSystem))
    622       SearchList.push_back(it->second);
    623   }
    624 
    625   for (path_iterator it = IncludePath.begin(), ie = IncludePath.end();
    626        it != ie; ++it) {
    627     if (it->first == After)
    628       SearchList.push_back(it->second);
    629   }
    630 
    631   // Remove duplicates across both the Angled and System directories.  GCC does
    632   // this and failing to remove duplicates across these two groups breaks
    633   // #include_next.
    634   unsigned NonSystemRemoved = RemoveDuplicates(SearchList, NumQuoted, Verbose);
    635   NumAngled -= NonSystemRemoved;
    636 
    637   bool DontSearchCurDir = false;  // TODO: set to true if -I- is set?
    638   Headers.SetSearchPaths(SearchList, NumQuoted, NumAngled, DontSearchCurDir);
    639 
    640   Headers.SetSystemHeaderPrefixes(SystemHeaderPrefixes);
    641 
    642   // If verbose, print the list of directories that will be searched.
    643   if (Verbose) {
    644     llvm::errs() << "#include \"...\" search starts here:\n";
    645     for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
    646       if (i == NumQuoted)
    647         llvm::errs() << "#include <...> search starts here:\n";
    648       const char *Name = SearchList[i].getName();
    649       const char *Suffix;
    650       if (SearchList[i].isNormalDir())
    651         Suffix = "";
    652       else if (SearchList[i].isFramework())
    653         Suffix = " (framework directory)";
    654       else {
    655         assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
    656         Suffix = " (headermap)";
    657       }
    658       llvm::errs() << " " << Name << Suffix << "\n";
    659     }
    660     llvm::errs() << "End of search list.\n";
    661   }
    662 }
    663 
    664 void clang::ApplyHeaderSearchOptions(HeaderSearch &HS,
    665                                      const HeaderSearchOptions &HSOpts,
    666                                      const LangOptions &Lang,
    667                                      const llvm::Triple &Triple) {
    668   InitHeaderSearch Init(HS, HSOpts.Verbose, HSOpts.Sysroot);
    669 
    670   // Add the user defined entries.
    671   for (unsigned i = 0, e = HSOpts.UserEntries.size(); i != e; ++i) {
    672     const HeaderSearchOptions::Entry &E = HSOpts.UserEntries[i];
    673     if (E.IgnoreSysRoot) {
    674       Init.AddUnmappedPath(E.Path, E.Group, E.IsFramework);
    675     } else {
    676       Init.AddPath(E.Path, E.Group, E.IsFramework);
    677     }
    678   }
    679 
    680   Init.AddDefaultIncludePaths(Lang, Triple, HSOpts);
    681 
    682   for (unsigned i = 0, e = HSOpts.SystemHeaderPrefixes.size(); i != e; ++i)
    683     Init.AddSystemHeaderPrefix(HSOpts.SystemHeaderPrefixes[i].Prefix,
    684                                HSOpts.SystemHeaderPrefixes[i].IsSystemHeader);
    685 
    686   if (HSOpts.UseBuiltinIncludes) {
    687     // Set up the builtin include directory in the module map.
    688     llvm::sys::Path P(HSOpts.ResourceDir);
    689     P.appendComponent("include");
    690     if (const DirectoryEntry *Dir = HS.getFileMgr().getDirectory(P.str()))
    691       HS.getModuleMap().setBuiltinIncludeDir(Dir);
    692   }
    693 
    694   Init.Realize(Lang);
    695 }
    696