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