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