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