Clang Project

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