InitHeaderSearch.cpp revision 79bc57c074cb91f574fba19215f95b63dcf6b04b
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/Frontend/HeaderSearchOptions.h"
18#include "clang/Lex/HeaderSearch.h"
19#include "llvm/ADT/SmallString.h"
20#include "llvm/ADT/SmallPtrSet.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/StringExtras.h"
23#include "llvm/ADT/Triple.h"
24#include "llvm/ADT/Twine.h"
25#include "llvm/Support/raw_ostream.h"
26#include "llvm/System/Path.h"
27#include "llvm/Config/config.h"
28#ifdef _MSC_VER
29  #define WIN32_LEAN_AND_MEAN 1
30  #include <windows.h>
31#endif
32using namespace clang;
33using namespace clang::frontend;
34
35namespace {
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.
40class InitHeaderSearch {
41  std::vector<DirectoryLookup> IncludeGroup[4];
42  HeaderSearch& Headers;
43  bool Verbose;
44  std::string isysroot;
45
46public:
47
48  InitHeaderSearch(HeaderSearch &HS,
49      bool verbose = false, const std::string &iSysroot = "")
50    : Headers(HS), Verbose(verbose), isysroot(iSysroot) {}
51
52  /// AddPath - Add the specified path to the specified group list.
53  void AddPath(const llvm::Twine &Path, IncludeDirGroup Group,
54               bool isCXXAware, bool isUserSupplied,
55               bool isFramework, bool IgnoreSysRoot = false);
56
57  /// AddGnuCPlusPlusIncludePaths - Add the necessary paths to support a gnu
58  ///  libstdc++.
59  void AddGnuCPlusPlusIncludePaths(llvm::StringRef Base,
60                                   llvm::StringRef ArchDir,
61                                   llvm::StringRef Dir32,
62                                   llvm::StringRef Dir64,
63                                   const llvm::Triple &triple);
64
65  /// AddMinGWCPlusPlusIncludePaths - Add the necessary paths to suport a MinGW
66  ///  libstdc++.
67  void AddMinGWCPlusPlusIncludePaths(llvm::StringRef Base,
68                                     llvm::StringRef Arch,
69                                     llvm::StringRef Version);
70
71  /// AddDelimitedPaths - Add a list of paths delimited by the system PATH
72  /// separator. The processing follows that of the CPATH variable for gcc.
73  void AddDelimitedPaths(llvm::StringRef String);
74
75  // AddDefaultCIncludePaths - Add paths that should always be searched.
76  void AddDefaultCIncludePaths(const llvm::Triple &triple,
77                               const HeaderSearchOptions &HSOpts);
78
79  // AddDefaultCPlusPlusIncludePaths -  Add paths that should be searched when
80  //  compiling c++.
81  void AddDefaultCPlusPlusIncludePaths(const llvm::Triple &triple);
82
83  /// AddDefaultSystemIncludePaths - Adds the default system include paths so
84  ///  that e.g. stdio.h is found.
85  void AddDefaultSystemIncludePaths(const LangOptions &Lang,
86                                    const llvm::Triple &triple,
87                                    const HeaderSearchOptions &HSOpts);
88
89  /// Realize - Merges all search path lists into one list and send it to
90  /// HeaderSearch.
91  void Realize();
92};
93
94}
95
96void InitHeaderSearch::AddPath(const llvm::Twine &Path,
97                               IncludeDirGroup Group, bool isCXXAware,
98                               bool isUserSupplied, bool isFramework,
99                               bool IgnoreSysRoot) {
100  assert(!Path.isTriviallyEmpty() && "can't handle empty path here");
101  FileManager &FM = Headers.getFileMgr();
102
103  // Compute the actual path, taking into consideration -isysroot.
104  llvm::SmallString<256> MappedPathStr;
105  llvm::raw_svector_ostream MappedPath(MappedPathStr);
106
107  // Handle isysroot.
108  if (Group == System && !IgnoreSysRoot) {
109    // FIXME: Portability.  This should be a sys::Path interface, this doesn't
110    // handle things like C:\ right, nor win32 \\network\device\blah.
111    if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present.
112      MappedPath << isysroot;
113  }
114
115  Path.print(MappedPath);
116
117  // Compute the DirectoryLookup type.
118  SrcMgr::CharacteristicKind Type;
119  if (Group == Quoted || Group == Angled)
120    Type = SrcMgr::C_User;
121  else if (isCXXAware)
122    Type = SrcMgr::C_System;
123  else
124    Type = SrcMgr::C_ExternCSystem;
125
126
127  // If the directory exists, add it.
128  if (const DirectoryEntry *DE = FM.getDirectory(MappedPath.str())) {
129    IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied,
130                                                  isFramework));
131    return;
132  }
133
134  // Check to see if this is an apple-style headermap (which are not allowed to
135  // be frameworks).
136  if (!isFramework) {
137    if (const FileEntry *FE = FM.getFile(MappedPath.str())) {
138      if (const HeaderMap *HM = Headers.CreateHeaderMap(FE)) {
139        // It is a headermap, add it to the search path.
140        IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied));
141        return;
142      }
143    }
144  }
145
146  if (Verbose)
147    llvm::errs() << "ignoring nonexistent directory \""
148                 << MappedPath.str() << "\"\n";
149}
150
151
152void InitHeaderSearch::AddDelimitedPaths(llvm::StringRef at) {
153  if (at.empty()) // Empty string should not add '.' path.
154    return;
155
156  llvm::StringRef::size_type delim;
157  while ((delim = at.find(llvm::sys::PathSeparator)) != llvm::StringRef::npos) {
158    if (delim == 0)
159      AddPath(".", Angled, false, true, false);
160    else
161      AddPath(at.substr(0, delim), Angled, false, true, false);
162    at = at.substr(delim + 1);
163  }
164
165  if (at.empty())
166    AddPath(".", Angled, false, true, false);
167  else
168    AddPath(at, Angled, false, true, false);
169}
170
171void InitHeaderSearch::AddGnuCPlusPlusIncludePaths(llvm::StringRef Base,
172                                                   llvm::StringRef ArchDir,
173                                                   llvm::StringRef Dir32,
174                                                   llvm::StringRef Dir64,
175                                                   const llvm::Triple &triple) {
176  // Add the base dir
177  AddPath(Base, System, true, false, false);
178
179  // Add the multilib dirs
180  llvm::Triple::ArchType arch = triple.getArch();
181  bool is64bit = arch == llvm::Triple::ppc64 || arch == llvm::Triple::x86_64;
182  if (is64bit)
183    AddPath(Base + "/" + ArchDir + "/" + Dir64, System, true, false, false);
184  else
185    AddPath(Base + "/" + ArchDir + "/" + Dir32, System, true, false, false);
186
187  // Add the backward dir
188  AddPath(Base + "/backward", System, true, false, false);
189}
190
191void InitHeaderSearch::AddMinGWCPlusPlusIncludePaths(llvm::StringRef Base,
192                                                     llvm::StringRef Arch,
193                                                     llvm::StringRef Version) {
194  AddPath(Base + "/" + Arch + "/" + Version + "/include",
195          System, true, false, false);
196  AddPath(Base + "/" + Arch + "/" + Version + "/include/c++",
197          System, true, false, false);
198  AddPath(Base + "/" + Arch + "/" + Version + "/include/c++/backward",
199          System, true, false, false);
200}
201
202  // FIXME: This probably should goto to some platform utils place.
203#ifdef _MSC_VER
204
205  // Read registry string.
206  // This also supports a means to look for high-versioned keys by use
207  // of a $VERSION placeholder in the key path.
208  // $VERSION in the key path is a placeholder for the version number,
209  // causing the highest value path to be searched for and used.
210  // I.e. "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\$VERSION".
211  // There can be additional characters in the component.  Only the numberic
212  // characters are compared.
213static bool getSystemRegistryString(const char *keyPath, const char *valueName,
214                                    char *value, size_t maxLength) {
215  HKEY hRootKey = NULL;
216  HKEY hKey = NULL;
217  const char* subKey = NULL;
218  DWORD valueType;
219  DWORD valueSize = maxLength - 1;
220  long lResult;
221  bool returnValue = false;
222  if (strncmp(keyPath, "HKEY_CLASSES_ROOT\\", 18) == 0) {
223    hRootKey = HKEY_CLASSES_ROOT;
224    subKey = keyPath + 18;
225  }
226  else if (strncmp(keyPath, "HKEY_USERS\\", 11) == 0) {
227    hRootKey = HKEY_USERS;
228    subKey = keyPath + 11;
229  }
230  else if (strncmp(keyPath, "HKEY_LOCAL_MACHINE\\", 19) == 0) {
231    hRootKey = HKEY_LOCAL_MACHINE;
232    subKey = keyPath + 19;
233  }
234  else if (strncmp(keyPath, "HKEY_CURRENT_USER\\", 18) == 0) {
235    hRootKey = HKEY_CURRENT_USER;
236    subKey = keyPath + 18;
237  }
238  else
239    return(false);
240  const char *placeHolder = strstr(subKey, "$VERSION");
241  char bestName[256];
242  bestName[0] = '\0';
243  // If we have a $VERSION placeholder, do the highest-version search.
244  if (placeHolder) {
245    const char *keyEnd = placeHolder - 1;
246    const char *nextKey = placeHolder;
247    // Find end of previous key.
248    while ((keyEnd > subKey) && (*keyEnd != '\\'))
249      keyEnd--;
250    // Find end of key containing $VERSION.
251    while (*nextKey && (*nextKey != '\\'))
252      nextKey++;
253    size_t partialKeyLength = keyEnd - subKey;
254    char partialKey[256];
255    if (partialKeyLength > sizeof(partialKey))
256      partialKeyLength = sizeof(partialKey);
257    strncpy(partialKey, subKey, partialKeyLength);
258    partialKey[partialKeyLength] = '\0';
259    HKEY hTopKey = NULL;
260    lResult = RegOpenKeyEx(hRootKey, partialKey, 0, KEY_READ, &hTopKey);
261    if (lResult == ERROR_SUCCESS) {
262      char keyName[256];
263      int bestIndex = -1;
264      double bestValue = 0.0;
265      DWORD index, size = sizeof(keyName) - 1;
266      for (index = 0; RegEnumKeyEx(hTopKey, index, keyName, &size, NULL,
267          NULL, NULL, NULL) == ERROR_SUCCESS; index++) {
268        const char *sp = keyName;
269        while (*sp && !isdigit(*sp))
270          sp++;
271        if (!*sp)
272          continue;
273        const char *ep = sp + 1;
274        while (*ep && (isdigit(*ep) || (*ep == '.')))
275          ep++;
276        char numBuf[32];
277        strncpy(numBuf, sp, sizeof(numBuf) - 1);
278        numBuf[sizeof(numBuf) - 1] = '\0';
279        double value = strtod(numBuf, NULL);
280        if (value > bestValue) {
281          bestIndex = (int)index;
282          bestValue = value;
283          strcpy(bestName, keyName);
284        }
285        size = sizeof(keyName) - 1;
286      }
287      // If we found the highest versioned key, open the key and get the value.
288      if (bestIndex != -1) {
289        // Append rest of key.
290        strncat(bestName, nextKey, sizeof(bestName) - 1);
291        bestName[sizeof(bestName) - 1] = '\0';
292        // Open the chosen key path remainder.
293        lResult = RegOpenKeyEx(hTopKey, bestName, 0, KEY_READ, &hKey);
294        if (lResult == ERROR_SUCCESS) {
295          lResult = RegQueryValueEx(hKey, valueName, NULL, &valueType,
296            (LPBYTE)value, &valueSize);
297          if (lResult == ERROR_SUCCESS)
298            returnValue = true;
299          RegCloseKey(hKey);
300        }
301      }
302      RegCloseKey(hTopKey);
303    }
304  }
305  else {
306    lResult = RegOpenKeyEx(hRootKey, subKey, 0, KEY_READ, &hKey);
307    if (lResult == ERROR_SUCCESS) {
308      lResult = RegQueryValueEx(hKey, valueName, NULL, &valueType,
309        (LPBYTE)value, &valueSize);
310      if (lResult == ERROR_SUCCESS)
311        returnValue = true;
312      RegCloseKey(hKey);
313    }
314  }
315  return(returnValue);
316}
317#else // _MSC_VER
318  // Read registry string.
319static bool getSystemRegistryString(const char*, const char*, char*, size_t) {
320  return(false);
321}
322#endif // _MSC_VER
323
324  // Get Visual Studio installation directory.
325static bool getVisualStudioDir(std::string &path) {
326  char vsIDEInstallDir[256];
327  // Try the Windows registry first.
328  bool hasVCDir = getSystemRegistryString(
329    "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\$VERSION",
330    "InstallDir", vsIDEInstallDir, sizeof(vsIDEInstallDir) - 1);
331    // If we have both vc80 and vc90, pick version we were compiled with.
332  if (hasVCDir && vsIDEInstallDir[0]) {
333    char *p = (char*)strstr(vsIDEInstallDir, "\\Common7\\IDE");
334    if (p)
335      *p = '\0';
336    path = vsIDEInstallDir;
337    return(true);
338  }
339  else {
340    // Try the environment.
341    const char* vs90comntools = getenv("VS90COMNTOOLS");
342    const char* vs80comntools = getenv("VS80COMNTOOLS");
343    const char* vscomntools = NULL;
344      // If we have both vc80 and vc90, pick version we were compiled with.
345    if (vs90comntools && vs80comntools) {
346      #if (_MSC_VER >= 1500)  // VC90
347          vscomntools = vs90comntools;
348      #elif (_MSC_VER == 1400) // VC80
349          vscomntools = vs80comntools;
350      #else
351          vscomntools = vs90comntools;
352      #endif
353    }
354    else if (vs90comntools)
355      vscomntools = vs90comntools;
356    else if (vs80comntools)
357      vscomntools = vs80comntools;
358    if (vscomntools && *vscomntools) {
359      char *p = const_cast<char *>(strstr(vscomntools, "\\Common7\\Tools"));
360      if (p)
361        *p = '\0';
362      path = vscomntools;
363      return(true);
364    }
365    else
366      return(false);
367  }
368  return(false);
369}
370
371  // Get Windows SDK installation directory.
372static bool getWindowsSDKDir(std::string &path) {
373  char windowsSDKInstallDir[256];
374  // Try the Windows registry.
375  bool hasSDKDir = getSystemRegistryString(
376   "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\$VERSION",
377    "InstallationFolder", windowsSDKInstallDir, sizeof(windowsSDKInstallDir) - 1);
378    // If we have both vc80 and vc90, pick version we were compiled with.
379  if (hasSDKDir && windowsSDKInstallDir[0]) {
380    path = windowsSDKInstallDir;
381    return(true);
382  }
383  return(false);
384}
385
386void InitHeaderSearch::AddDefaultCIncludePaths(const llvm::Triple &triple,
387                                            const HeaderSearchOptions &HSOpts) {
388  // FIXME: temporary hack: hard-coded paths.
389  AddPath("/usr/local/include", System, true, false, false);
390
391  // Builtin includes use #include_next directives and should be positioned
392  // just prior C include dirs.
393  if (HSOpts.UseBuiltinIncludes) {
394    // Ignore the sys root, we *always* look for clang headers relative to
395    // supplied path.
396    llvm::sys::Path P(HSOpts.ResourceDir);
397    P.appendComponent("include");
398    AddPath(P.str(), System, false, false, false, /*IgnoreSysRoot=*/ true);
399  }
400
401  // Add dirs specified via 'configure --with-c-include-dirs'.
402  llvm::StringRef CIncludeDirs(C_INCLUDE_DIRS);
403  if (CIncludeDirs != "") {
404    llvm::SmallVector<llvm::StringRef, 5> dirs;
405    CIncludeDirs.split(dirs, ":");
406    for (llvm::SmallVectorImpl<llvm::StringRef>::iterator i = dirs.begin();
407         i != dirs.end();
408         ++i)
409      AddPath(*i, System, false, false, false);
410    return;
411  }
412  llvm::Triple::OSType os = triple.getOS();
413  switch (os) {
414  case llvm::Triple::Win32:
415    {
416      std::string VSDir;
417      std::string WindowsSDKDir;
418      if (getVisualStudioDir(VSDir)) {
419        AddPath(VSDir + "\\VC\\include", System, false, false, false);
420        if (getWindowsSDKDir(WindowsSDKDir))
421          AddPath(WindowsSDKDir, System, false, false, false);
422        else
423          AddPath(VSDir + "\\VC\\PlatformSDK\\Include",
424            System, false, false, false);
425      }
426      else {
427          // Default install paths.
428        AddPath("C:/Program Files/Microsoft Visual Studio 9.0/VC/include",
429          System, false, false, false);
430        AddPath(
431        "C:/Program Files/Microsoft Visual Studio 9.0/VC/PlatformSDK/Include",
432          System, false, false, false);
433        AddPath("C:/Program Files/Microsoft Visual Studio 8/VC/include",
434          System, false, false, false);
435        AddPath(
436        "C:/Program Files/Microsoft Visual Studio 8/VC/PlatformSDK/Include",
437          System, false, false, false);
438          // For some clang developers.
439        AddPath("G:/Program Files/Microsoft Visual Studio 9.0/VC/include",
440          System, false, false, false);
441        AddPath(
442        "G:/Program Files/Microsoft Visual Studio 9.0/VC/PlatformSDK/Include",
443          System, false, false, false);
444      }
445    }
446    break;
447  case llvm::Triple::Haiku:
448    AddPath("/boot/common/include", System, true, false, false);
449    AddPath("/boot/develop/headers/os", System, true, false, false);
450    AddPath("/boot/develop/headers/os/app", System, true, false, false);
451    AddPath("/boot/develop/headers/os/arch", System, true, false, false);
452    AddPath("/boot/develop/headers/os/device", System, true, false, false);
453    AddPath("/boot/develop/headers/os/drivers", System, true, false, false);
454    AddPath("/boot/develop/headers/os/game", System, true, false, false);
455    AddPath("/boot/develop/headers/os/interface", System, true, false, false);
456    AddPath("/boot/develop/headers/os/kernel", System, true, false, false);
457    AddPath("/boot/develop/headers/os/locale", System, true, false, false);
458    AddPath("/boot/develop/headers/os/mail", System, true, false, false);
459    AddPath("/boot/develop/headers/os/media", System, true, false, false);
460    AddPath("/boot/develop/headers/os/midi", System, true, false, false);
461    AddPath("/boot/develop/headers/os/midi2", System, true, false, false);
462    AddPath("/boot/develop/headers/os/net", System, true, false, false);
463    AddPath("/boot/develop/headers/os/storage", System, true, false, false);
464    AddPath("/boot/develop/headers/os/support", System, true, false, false);
465    AddPath("/boot/develop/headers/os/translation",
466      System, true, false, false);
467    AddPath("/boot/develop/headers/os/add-ons/graphics",
468      System, true, false, false);
469    AddPath("/boot/develop/headers/os/add-ons/input_server",
470      System, true, false, false);
471    AddPath("/boot/develop/headers/os/add-ons/screen_saver",
472      System, true, false, false);
473    AddPath("/boot/develop/headers/os/add-ons/tracker",
474      System, true, false, false);
475    AddPath("/boot/develop/headers/os/be_apps/Deskbar",
476      System, true, false, false);
477    AddPath("/boot/develop/headers/os/be_apps/NetPositive",
478      System, true, false, false);
479    AddPath("/boot/develop/headers/os/be_apps/Tracker",
480      System, true, false, false);
481    AddPath("/boot/develop/headers/cpp", System, true, false, false);
482    AddPath("/boot/develop/headers/cpp/i586-pc-haiku",
483      System, true, false, false);
484    AddPath("/boot/develop/headers/3rdparty", System, true, false, false);
485    AddPath("/boot/develop/headers/bsd", System, true, false, false);
486    AddPath("/boot/develop/headers/glibc", System, true, false, false);
487    AddPath("/boot/develop/headers/posix", System, true, false, false);
488    AddPath("/boot/develop/headers",  System, true, false, false);
489  	break;
490  case llvm::Triple::MinGW64:
491  case llvm::Triple::MinGW32:
492    AddPath("c:/mingw/include", System, true, false, false);
493    break;
494  default:
495    break;
496  }
497
498  AddPath("/usr/include", System, false, false, false);
499}
500
501void InitHeaderSearch::
502AddDefaultCPlusPlusIncludePaths(const llvm::Triple &triple) {
503  llvm::Triple::OSType os = triple.getOS();
504  llvm::StringRef CxxIncludeRoot(CXX_INCLUDE_ROOT);
505  if (CxxIncludeRoot != "") {
506    llvm::StringRef CxxIncludeArch(CXX_INCLUDE_ARCH);
507    if (CxxIncludeArch == "")
508      AddGnuCPlusPlusIncludePaths(CxxIncludeRoot, triple.str().c_str(),
509                                  CXX_INCLUDE_32BIT_DIR, CXX_INCLUDE_64BIT_DIR,
510                                  triple);
511    else
512      AddGnuCPlusPlusIncludePaths(CxxIncludeRoot, CXX_INCLUDE_ARCH,
513                                  CXX_INCLUDE_32BIT_DIR, CXX_INCLUDE_64BIT_DIR,
514                                  triple);
515    return;
516  }
517  // FIXME: temporary hack: hard-coded paths.
518  switch (os) {
519  case llvm::Triple::Cygwin:
520    AddPath("/lib/gcc/i686-pc-cygwin/3.4.4/include",
521        System, true, false, false);
522    AddPath("/lib/gcc/i686-pc-cygwin/3.4.4/include/c++",
523        System, true, false, false);
524    break;
525  case llvm::Triple::MinGW64:
526    // Try gcc 4.4.0
527    AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw64", "4.4.0");
528    // Try gcc 4.3.0
529    AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw64", "4.3.0");
530    // Fall through.
531  case llvm::Triple::MinGW32:
532    // Try gcc 4.4.0
533    AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw32", "4.4.0");
534    // Try gcc 4.3.0
535    AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw32", "4.3.0");
536    break;
537  case llvm::Triple::Darwin:
538    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2.1",
539                                "i686-apple-darwin10", "", "x86_64", triple);
540    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.0.0",
541                                "i686-apple-darwin8", "", "", triple);
542    break;
543  case llvm::Triple::DragonFly:
544    AddPath("/usr/include/c++/4.1", System, true, false, false);
545    break;
546  case llvm::Triple::Linux:
547    //===------------------------------------------------------------------===//
548    // Debian based distros.
549    // Note: these distros symlink /usr/include/c++/X.Y.Z -> X.Y
550    //===------------------------------------------------------------------===//
551    // Ubuntu 10.04 LTS "Lucid Lynx" -- gcc-4.4.3
552    // Ubuntu 9.10 "Karmic Koala"    -- gcc-4.4.1
553    // Debian 6.0 "squeeze"          -- gcc-4.4.2
554    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4",
555                                "x86_64-linux-gnu", "32", "", triple);
556    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4",
557                                "i486-linux-gnu", "", "64", triple);
558    // Ubuntu 9.04 "Jaunty Jackalope" -- gcc-4.3.3
559    // Ubuntu 8.10 "Intrepid Ibex"    -- gcc-4.3.2
560    // Debian 5.0 "lenny"             -- gcc-4.3.2
561    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3",
562                                "x86_64-linux-gnu", "32", "", triple);
563    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3",
564                                "i486-linux-gnu", "", "64", triple);
565    // Ubuntu 8.04.4 LTS "Hardy Heron"     -- gcc-4.2.4
566    // Ubuntu 8.04.[0-3] LTS "Hardy Heron" -- gcc-4.2.3
567    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2",
568                                "x86_64-linux-gnu", "32", "", triple);
569    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2",
570                                "i486-linux-gnu", "", "64", triple);
571    // Ubuntu 7.10 "Gutsy Gibbon" -- gcc-4.1.3
572    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.1",
573                                "x86_64-linux-gnu", "32", "", triple);
574    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.1",
575                                "i486-linux-gnu", "", "64", triple);
576
577    //===------------------------------------------------------------------===//
578    // Redhat based distros.
579    //===------------------------------------------------------------------===//
580    // Fedora 13
581    // Fedora 12
582    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.3",
583                                "x86_64-redhat-linux", "32", "", triple);
584    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.3",
585                                "i686-redhat-linux","", "", triple);
586    // Fedora 12 (pre-FEB-2010)
587    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.2",
588                                "x86_64-redhat-linux", "32", "", triple);
589    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.2",
590                                "i686-redhat-linux","", "", triple);
591    // Fedora 11
592    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.1",
593                                "x86_64-redhat-linux", "32", "", triple);
594    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.1",
595                                "i586-redhat-linux","", "", triple);
596    // Fedora 10
597    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.2",
598                                "x86_64-redhat-linux", "32", "", triple);
599    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.2",
600                                "i386-redhat-linux","", "", triple);
601    // Fedora 9
602    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.0",
603                                "x86_64-redhat-linux", "32", "", triple);
604    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.0",
605                                "i386-redhat-linux", "", "", triple);
606    // Fedora 8
607    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.1.2",
608                                "x86_64-redhat-linux", "", "", triple);
609    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.1.2",
610                                "i386-redhat-linux", "", "", triple);
611
612    //===------------------------------------------------------------------===//
613
614    // Exherbo (2010-01-25)
615    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.3",
616                                "x86_64-pc-linux-gnu", "32", "", triple);
617    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4.3",
618                                "i686-pc-linux-gnu", "", "", triple);
619
620    // openSUSE 11.1 32 bit
621    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3",
622                                "i586-suse-linux", "", "", triple);
623    // openSUSE 11.1 64 bit
624    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3",
625                                "x86_64-suse-linux", "32", "", triple);
626    // openSUSE 11.2
627    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4",
628                                "i586-suse-linux", "", "", triple);
629    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.4",
630                                "x86_64-suse-linux", "", "", triple);
631    // Arch Linux 2008-06-24
632    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.1",
633                                "i686-pc-linux-gnu", "", "", triple);
634    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.3.1",
635                                "x86_64-unknown-linux-gnu", "", "", triple);
636    // Gentoo x86 2009.1 stable
637    AddGnuCPlusPlusIncludePaths(
638      "/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4",
639      "i686-pc-linux-gnu", "", "", triple);
640    // Gentoo x86 2009.0 stable
641    AddGnuCPlusPlusIncludePaths(
642      "/usr/lib/gcc/i686-pc-linux-gnu/4.3.2/include/g++-v4",
643      "i686-pc-linux-gnu", "", "", triple);
644    // Gentoo x86 2008.0 stable
645    AddGnuCPlusPlusIncludePaths(
646      "/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4",
647      "i686-pc-linux-gnu", "", "", triple);
648    // Gentoo amd64 stable
649    AddGnuCPlusPlusIncludePaths(
650        "/usr/lib/gcc/x86_64-pc-linux-gnu/4.1.2/include/g++-v4",
651        "i686-pc-linux-gnu", "", "", triple);
652
653    // Gentoo amd64 gcc 4.3.2
654    AddGnuCPlusPlusIncludePaths(
655        "/usr/lib/gcc/x86_64-pc-linux-gnu/4.3.2/include/g++-v4",
656        "x86_64-pc-linux-gnu", "", "", triple);
657
658    // Gentoo amd64 gcc 4.4.3
659    AddGnuCPlusPlusIncludePaths(
660        "/usr/lib/gcc/x86_64-pc-linux-gnu/4.4.3/include/g++-v4",
661        "x86_64-pc-linux-gnu", "32", "", triple);
662
663    break;
664  case llvm::Triple::FreeBSD:
665    // FreeBSD 8.0
666    // FreeBSD 7.3
667    AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2", "", "", "", triple);
668    break;
669  case llvm::Triple::Solaris:
670    // Solaris - Fall though..
671  case llvm::Triple::AuroraUX:
672    // AuroraUX
673    AddGnuCPlusPlusIncludePaths("/opt/gcc4/include/c++/4.2.4",
674                                "i386-pc-solaris2.11", "", "", triple);
675    break;
676  default:
677    break;
678  }
679}
680
681void InitHeaderSearch::AddDefaultSystemIncludePaths(const LangOptions &Lang,
682                                                    const llvm::Triple &triple,
683                                            const HeaderSearchOptions &HSOpts) {
684  if (Lang.CPlusPlus && HSOpts.UseStandardCXXIncludes)
685    AddDefaultCPlusPlusIncludePaths(triple);
686
687  AddDefaultCIncludePaths(triple, HSOpts);
688
689  // Add the default framework include paths on Darwin.
690  if (triple.getOS() == llvm::Triple::Darwin) {
691    AddPath("/System/Library/Frameworks", System, true, false, true);
692    AddPath("/Library/Frameworks", System, true, false, true);
693  }
694}
695
696/// RemoveDuplicates - If there are duplicate directory entries in the specified
697/// search list, remove the later (dead) ones.
698static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList,
699                             bool Verbose) {
700  llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs;
701  llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs;
702  llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps;
703  for (unsigned i = 0; i != SearchList.size(); ++i) {
704    unsigned DirToRemove = i;
705
706    const DirectoryLookup &CurEntry = SearchList[i];
707
708    if (CurEntry.isNormalDir()) {
709      // If this isn't the first time we've seen this dir, remove it.
710      if (SeenDirs.insert(CurEntry.getDir()))
711        continue;
712    } else if (CurEntry.isFramework()) {
713      // If this isn't the first time we've seen this framework dir, remove it.
714      if (SeenFrameworkDirs.insert(CurEntry.getFrameworkDir()))
715        continue;
716    } else {
717      assert(CurEntry.isHeaderMap() && "Not a headermap or normal dir?");
718      // If this isn't the first time we've seen this headermap, remove it.
719      if (SeenHeaderMaps.insert(CurEntry.getHeaderMap()))
720        continue;
721    }
722
723    // If we have a normal #include dir/framework/headermap that is shadowed
724    // later in the chain by a system include location, we actually want to
725    // ignore the user's request and drop the user dir... keeping the system
726    // dir.  This is weird, but required to emulate GCC's search path correctly.
727    //
728    // Since dupes of system dirs are rare, just rescan to find the original
729    // that we're nuking instead of using a DenseMap.
730    if (CurEntry.getDirCharacteristic() != SrcMgr::C_User) {
731      // Find the dir that this is the same of.
732      unsigned FirstDir;
733      for (FirstDir = 0; ; ++FirstDir) {
734        assert(FirstDir != i && "Didn't find dupe?");
735
736        const DirectoryLookup &SearchEntry = SearchList[FirstDir];
737
738        // If these are different lookup types, then they can't be the dupe.
739        if (SearchEntry.getLookupType() != CurEntry.getLookupType())
740          continue;
741
742        bool isSame;
743        if (CurEntry.isNormalDir())
744          isSame = SearchEntry.getDir() == CurEntry.getDir();
745        else if (CurEntry.isFramework())
746          isSame = SearchEntry.getFrameworkDir() == CurEntry.getFrameworkDir();
747        else {
748          assert(CurEntry.isHeaderMap() && "Not a headermap or normal dir?");
749          isSame = SearchEntry.getHeaderMap() == CurEntry.getHeaderMap();
750        }
751
752        if (isSame)
753          break;
754      }
755
756      // If the first dir in the search path is a non-system dir, zap it
757      // instead of the system one.
758      if (SearchList[FirstDir].getDirCharacteristic() == SrcMgr::C_User)
759        DirToRemove = FirstDir;
760    }
761
762    if (Verbose) {
763      llvm::errs() << "ignoring duplicate directory \""
764                   << CurEntry.getName() << "\"\n";
765      if (DirToRemove != i)
766        llvm::errs() << "  as it is a non-system directory that duplicates "
767                     << "a system directory\n";
768    }
769
770    // This is reached if the current entry is a duplicate.  Remove the
771    // DirToRemove (usually the current dir).
772    SearchList.erase(SearchList.begin()+DirToRemove);
773    --i;
774  }
775}
776
777
778void InitHeaderSearch::Realize() {
779  // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList.
780  std::vector<DirectoryLookup> SearchList;
781  SearchList = IncludeGroup[Angled];
782  SearchList.insert(SearchList.end(), IncludeGroup[System].begin(),
783                    IncludeGroup[System].end());
784  SearchList.insert(SearchList.end(), IncludeGroup[After].begin(),
785                    IncludeGroup[After].end());
786  RemoveDuplicates(SearchList, Verbose);
787  RemoveDuplicates(IncludeGroup[Quoted], Verbose);
788
789  // Prepend QUOTED list on the search list.
790  SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(),
791                    IncludeGroup[Quoted].end());
792
793
794  bool DontSearchCurDir = false;  // TODO: set to true if -I- is set?
795  Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(),
796                         DontSearchCurDir);
797
798  // If verbose, print the list of directories that will be searched.
799  if (Verbose) {
800    llvm::errs() << "#include \"...\" search starts here:\n";
801    unsigned QuotedIdx = IncludeGroup[Quoted].size();
802    for (unsigned i = 0, e = SearchList.size(); i != e; ++i) {
803      if (i == QuotedIdx)
804        llvm::errs() << "#include <...> search starts here:\n";
805      const char *Name = SearchList[i].getName();
806      const char *Suffix;
807      if (SearchList[i].isNormalDir())
808        Suffix = "";
809      else if (SearchList[i].isFramework())
810        Suffix = " (framework directory)";
811      else {
812        assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup");
813        Suffix = " (headermap)";
814      }
815      llvm::errs() << " " << Name << Suffix << "\n";
816    }
817    llvm::errs() << "End of search list.\n";
818  }
819}
820
821void clang::ApplyHeaderSearchOptions(HeaderSearch &HS,
822                                     const HeaderSearchOptions &HSOpts,
823                                     const LangOptions &Lang,
824                                     const llvm::Triple &Triple) {
825  InitHeaderSearch Init(HS, HSOpts.Verbose, HSOpts.Sysroot);
826
827  // Add the user defined entries.
828  for (unsigned i = 0, e = HSOpts.UserEntries.size(); i != e; ++i) {
829    const HeaderSearchOptions::Entry &E = HSOpts.UserEntries[i];
830    Init.AddPath(E.Path, E.Group, false, E.IsUserSupplied, E.IsFramework,
831                 false);
832  }
833
834  // Add entries from CPATH and friends.
835  Init.AddDelimitedPaths(HSOpts.EnvIncPath);
836  if (Lang.CPlusPlus && Lang.ObjC1)
837    Init.AddDelimitedPaths(HSOpts.ObjCXXEnvIncPath);
838  else if (Lang.CPlusPlus)
839    Init.AddDelimitedPaths(HSOpts.CXXEnvIncPath);
840  else if (Lang.ObjC1)
841    Init.AddDelimitedPaths(HSOpts.ObjCEnvIncPath);
842  else
843    Init.AddDelimitedPaths(HSOpts.CEnvIncPath);
844
845  if (HSOpts.UseStandardIncludes)
846    Init.AddDefaultSystemIncludePaths(Lang, Triple, HSOpts);
847
848  Init.Realize();
849}
850