blob: 3489de560512d28142ba45bbf506b03502886baf [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- HeaderSearch.cpp - Resolve Header File Locations ---===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the DirectoryLookup and HeaderSearch interfaces.
11//
12//===----------------------------------------------------------------------===//
13
Reid Spencer5f016e22007-07-11 17:01:13 +000014#include "clang/Lex/HeaderSearch.h"
Chris Lattner822da612007-12-17 06:36:45 +000015#include "clang/Lex/HeaderMap.h"
Chris Lattnerc7229c32007-10-07 08:58:51 +000016#include "clang/Basic/FileManager.h"
17#include "clang/Basic/IdentifierTable.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000018#include "llvm/System/Path.h"
19#include "llvm/ADT/SmallString.h"
20using namespace clang;
21
22HeaderSearch::HeaderSearch(FileManager &FM) : FileMgr(FM), FrameworkMap(64) {
23 SystemDirIdx = 0;
24 NoCurDirSearch = false;
25
26 NumIncluded = 0;
27 NumMultiIncludeFileOptzn = 0;
28 NumFrameworkLookups = NumSubFrameworkLookups = 0;
29}
30
Chris Lattner822da612007-12-17 06:36:45 +000031HeaderSearch::~HeaderSearch() {
32 // Delete headermaps.
33 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
34 delete HeaderMaps[i].second;
35}
36
Reid Spencer5f016e22007-07-11 17:01:13 +000037void HeaderSearch::PrintStats() {
38 fprintf(stderr, "\n*** HeaderSearch Stats:\n");
39 fprintf(stderr, "%d files tracked.\n", (int)FileInfo.size());
40 unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0;
41 for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) {
42 NumOnceOnlyFiles += FileInfo[i].isImport;
43 if (MaxNumIncludes < FileInfo[i].NumIncludes)
44 MaxNumIncludes = FileInfo[i].NumIncludes;
45 NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1;
46 }
47 fprintf(stderr, " %d #import/#pragma once files.\n", NumOnceOnlyFiles);
48 fprintf(stderr, " %d included exactly once.\n", NumSingleIncludedFiles);
49 fprintf(stderr, " %d max times a file is included.\n", MaxNumIncludes);
50
51 fprintf(stderr, " %d #include/#include_next/#import.\n", NumIncluded);
52 fprintf(stderr, " %d #includes skipped due to"
53 " the multi-include optimization.\n", NumMultiIncludeFileOptzn);
54
55 fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups);
56 fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups);
57}
58
Chris Lattner822da612007-12-17 06:36:45 +000059/// CreateHeaderMap - This method returns a HeaderMap for the specified
60/// FileEntry, uniquing them through the the 'HeaderMaps' datastructure.
61const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE,
62 std::string &ErrorInfo) {
63 // We expect the number of headermaps to be small, and almost always empty.
Chris Lattnerdf772332007-12-17 07:52:39 +000064 // If it ever grows, use of a linear search should be re-evaluated.
Chris Lattner822da612007-12-17 06:36:45 +000065 if (!HeaderMaps.empty()) {
66 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
Chris Lattnerdf772332007-12-17 07:52:39 +000067 // Pointer equality comparison of FileEntries works because they are
68 // already uniqued by inode.
Chris Lattner822da612007-12-17 06:36:45 +000069 if (HeaderMaps[i].first == FE)
70 return HeaderMaps[i].second;
71 }
72
73 if (const HeaderMap *HM = HeaderMap::Create(FE, ErrorInfo)) {
74 HeaderMaps.push_back(std::make_pair(FE, HM));
75 return HM;
76 }
77
78 return 0;
79}
80
Chris Lattnerdf772332007-12-17 07:52:39 +000081//===----------------------------------------------------------------------===//
82// File lookup within a DirectoryLookup scope
83//===----------------------------------------------------------------------===//
84
85/// LookupFile - Lookup the specified file in this search path, returning it
86/// if it exists or returning null if not.
87const FileEntry *DirectoryLookup::LookupFile(const char *FilenameStart,
88 const char *FilenameEnd,
Chris Lattnerafded5b2007-12-17 08:13:48 +000089 HeaderSearch &HS) const {
Chris Lattnerdf772332007-12-17 07:52:39 +000090 llvm::SmallString<1024> TmpDir;
Chris Lattnerafded5b2007-12-17 08:13:48 +000091 if (isNormalDir()) {
92 // Concatenate the requested file onto the directory.
93 // FIXME: Portability. Filename concatenation should be in sys::Path.
94 TmpDir += getDir()->getName();
95 TmpDir.push_back('/');
96 TmpDir.append(FilenameStart, FilenameEnd);
97 return HS.getFileMgr().getFile(TmpDir.begin(), TmpDir.end());
98 }
Chris Lattnerdf772332007-12-17 07:52:39 +000099
Chris Lattnerafded5b2007-12-17 08:13:48 +0000100 if (isFramework())
101 return DoFrameworkLookup(FilenameStart, FilenameEnd, HS);
102
103 assert(0 && "headermap unimp");
Chris Lattnerdf772332007-12-17 07:52:39 +0000104}
105
106
Chris Lattnerafded5b2007-12-17 08:13:48 +0000107/// DoFrameworkLookup - Do a lookup of the specified file in the current
108/// DirectoryLookup, which is a framework directory.
109const FileEntry *DirectoryLookup::DoFrameworkLookup(const char *FilenameStart,
110 const char *FilenameEnd,
111 HeaderSearch &HS) const {
112 FileManager &FileMgr = HS.getFileMgr();
113
Reid Spencer5f016e22007-07-11 17:01:13 +0000114 // Framework names must have a '/' in the filename.
115 const char *SlashPos = std::find(FilenameStart, FilenameEnd, '/');
116 if (SlashPos == FilenameEnd) return 0;
117
Chris Lattnerafded5b2007-12-17 08:13:48 +0000118 // Find out if this is the home for the specified framework, by checking
119 // HeaderSearch. Possible answer are yes/no and unknown.
120 const DirectoryEntry *&FrameworkDirCache =
121 HS.LookupFrameworkCache(FilenameStart, SlashPos);
Reid Spencer5f016e22007-07-11 17:01:13 +0000122
Chris Lattnerafded5b2007-12-17 08:13:48 +0000123 // If it is known and in some other directory, fail.
124 if (FrameworkDirCache && FrameworkDirCache != getFrameworkDir())
Reid Spencer5f016e22007-07-11 17:01:13 +0000125 return 0;
Chris Lattnerafded5b2007-12-17 08:13:48 +0000126
127 // Otherwise, construct the path to this framework dir.
128
Reid Spencer5f016e22007-07-11 17:01:13 +0000129 // FrameworkName = "/System/Library/Frameworks/"
130 llvm::SmallString<1024> FrameworkName;
Chris Lattnerafded5b2007-12-17 08:13:48 +0000131 FrameworkName += getFrameworkDir()->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +0000132 if (FrameworkName.empty() || FrameworkName.back() != '/')
133 FrameworkName.push_back('/');
134
135 // FrameworkName = "/System/Library/Frameworks/Cocoa"
136 FrameworkName.append(FilenameStart, SlashPos);
137
138 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
139 FrameworkName += ".framework/";
Chris Lattnerafded5b2007-12-17 08:13:48 +0000140
141 // If the cache entry is still unresolved, query to see if the cache entry is
142 // still unresolved. If so, check its existence now.
143 if (FrameworkDirCache == 0) {
144 HS.IncrementFrameworkLookupCount();
Reid Spencer5f016e22007-07-11 17:01:13 +0000145
146 // If the framework dir doesn't exist, we fail.
Chris Lattnerafded5b2007-12-17 08:13:48 +0000147 // FIXME: It's probably more efficient to query this with FileMgr.getDir.
Reid Spencer5f016e22007-07-11 17:01:13 +0000148 if (!llvm::sys::Path(std::string(FrameworkName.begin(),
149 FrameworkName.end())).exists())
150 return 0;
151
152 // Otherwise, if it does, remember that this is the right direntry for this
153 // framework.
Chris Lattnerafded5b2007-12-17 08:13:48 +0000154 FrameworkDirCache = getFrameworkDir();
Reid Spencer5f016e22007-07-11 17:01:13 +0000155 }
156
157 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
158 unsigned OrigSize = FrameworkName.size();
159
160 FrameworkName += "Headers/";
161 FrameworkName.append(SlashPos+1, FilenameEnd);
162 if (const FileEntry *FE = FileMgr.getFile(FrameworkName.begin(),
163 FrameworkName.end())) {
164 return FE;
165 }
166
167 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
168 const char *Private = "Private";
169 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
170 Private+strlen(Private));
171 return FileMgr.getFile(FrameworkName.begin(), FrameworkName.end());
172}
173
Chris Lattnerdf772332007-12-17 07:52:39 +0000174
Chris Lattnerafded5b2007-12-17 08:13:48 +0000175//===----------------------------------------------------------------------===//
176// Header File Location.
177//===----------------------------------------------------------------------===//
178
179
Reid Spencer5f016e22007-07-11 17:01:13 +0000180/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
181/// return null on failure. isAngled indicates whether the file reference is
182/// for system #include's or not (i.e. using <> instead of ""). CurFileEnt, if
183/// non-null, indicates where the #including file is, in case a relative search
184/// is needed.
185const FileEntry *HeaderSearch::LookupFile(const char *FilenameStart,
186 const char *FilenameEnd,
187 bool isAngled,
188 const DirectoryLookup *FromDir,
189 const DirectoryLookup *&CurDir,
190 const FileEntry *CurFileEnt) {
191 // If 'Filename' is absolute, check to see if it exists and no searching.
192 // FIXME: Portability. This should be a sys::Path interface, this doesn't
193 // handle things like C:\foo.txt right, nor win32 \\network\device\blah.
194 if (FilenameStart[0] == '/') {
195 CurDir = 0;
196
197 // If this was an #include_next "/absolute/file", fail.
198 if (FromDir) return 0;
199
200 // Otherwise, just return the file.
201 return FileMgr.getFile(FilenameStart, FilenameEnd);
202 }
203
Reid Spencer5f016e22007-07-11 17:01:13 +0000204 // Step #0, unless disabled, check to see if the file is in the #includer's
Chris Lattnerdf772332007-12-17 07:52:39 +0000205 // directory. This has to be based on CurFileEnt, not CurDir, because
206 // CurFileEnt could be a #include of a subdirectory (#include "foo/bar.h") and
207 // a subsequent include of "baz.h" should resolve to "whatever/foo/baz.h".
208 // This search is not done for <> headers.
Reid Spencer5f016e22007-07-11 17:01:13 +0000209 if (CurFileEnt && !isAngled && !NoCurDirSearch) {
Chris Lattnerdf772332007-12-17 07:52:39 +0000210 llvm::SmallString<1024> TmpDir;
Reid Spencer5f016e22007-07-11 17:01:13 +0000211 // Concatenate the requested file onto the directory.
212 // FIXME: Portability. Filename concatenation should be in sys::Path.
213 TmpDir += CurFileEnt->getDir()->getName();
214 TmpDir.push_back('/');
215 TmpDir.append(FilenameStart, FilenameEnd);
216 if (const FileEntry *FE = FileMgr.getFile(TmpDir.begin(), TmpDir.end())) {
217 // Leave CurDir unset.
Reid Spencer5f016e22007-07-11 17:01:13 +0000218 // This file is a system header or C++ unfriendly if the old file is.
219 getFileInfo(FE).DirInfo = getFileInfo(CurFileEnt).DirInfo;
220 return FE;
221 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000222 }
223
224 CurDir = 0;
225
226 // If this is a system #include, ignore the user #include locs.
227 unsigned i = isAngled ? SystemDirIdx : 0;
228
229 // If this is a #include_next request, start searching after the directory the
230 // file was found in.
231 if (FromDir)
232 i = FromDir-&SearchDirs[0];
233
Chris Lattner9960ae82007-07-22 07:28:00 +0000234 // Cache all of the lookups performed by this method. Many headers are
235 // multiply included, and the "pragma once" optimization prevents them from
236 // being relex/pp'd, but they would still have to search through a
237 // (potentially huge) series of SearchDirs to find it.
238 std::pair<unsigned, unsigned> &CacheLookup =
239 LookupFileCache.GetOrCreateValue(FilenameStart, FilenameEnd).getValue();
240
241 // If the entry has been previously looked up, the first value will be
242 // non-zero. If the value is equal to i (the start point of our search), then
243 // this is a matching hit.
244 if (CacheLookup.first == i+1) {
245 // Skip querying potentially lots of directories for this lookup.
246 i = CacheLookup.second;
247 } else {
248 // Otherwise, this is the first query, or the previous query didn't match
249 // our search start. We will fill in our found location below, so prime the
250 // start point value.
251 CacheLookup.first = i+1;
252 }
Chris Lattnerdf772332007-12-17 07:52:39 +0000253
Reid Spencer5f016e22007-07-11 17:01:13 +0000254 // Check each directory in sequence to see if it contains this file.
255 for (; i != SearchDirs.size(); ++i) {
Chris Lattnerafded5b2007-12-17 08:13:48 +0000256 const FileEntry *FE =
257 SearchDirs[i].LookupFile(FilenameStart, FilenameEnd, *this);
258 if (!FE) continue;
Reid Spencer5f016e22007-07-11 17:01:13 +0000259
Chris Lattnerafded5b2007-12-17 08:13:48 +0000260 CurDir = &SearchDirs[i];
261
262 // This file is a system header or C++ unfriendly if the dir is.
263 getFileInfo(FE).DirInfo = CurDir->getDirCharacteristic();
264
265 // Remember this location for the next lookup we do.
266 CacheLookup.second = i;
267 return FE;
Reid Spencer5f016e22007-07-11 17:01:13 +0000268 }
269
Chris Lattner9960ae82007-07-22 07:28:00 +0000270 // Otherwise, didn't find it. Remember we didn't find this.
271 CacheLookup.second = SearchDirs.size();
Reid Spencer5f016e22007-07-11 17:01:13 +0000272 return 0;
273}
274
275/// LookupSubframeworkHeader - Look up a subframework for the specified
276/// #include file. For example, if #include'ing <HIToolbox/HIToolbox.h> from
277/// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
278/// is a subframework within Carbon.framework. If so, return the FileEntry
279/// for the designated file, otherwise return null.
280const FileEntry *HeaderSearch::
281LookupSubframeworkHeader(const char *FilenameStart,
282 const char *FilenameEnd,
283 const FileEntry *ContextFileEnt) {
284 // Framework names must have a '/' in the filename. Find it.
285 const char *SlashPos = std::find(FilenameStart, FilenameEnd, '/');
286 if (SlashPos == FilenameEnd) return 0;
287
288 // Look up the base framework name of the ContextFileEnt.
289 const char *ContextName = ContextFileEnt->getName();
290
291 // If the context info wasn't a framework, couldn't be a subframework.
292 const char *FrameworkPos = strstr(ContextName, ".framework/");
293 if (FrameworkPos == 0)
294 return 0;
295
296 llvm::SmallString<1024> FrameworkName(ContextName,
297 FrameworkPos+strlen(".framework/"));
298
299 // Append Frameworks/HIToolbox.framework/
300 FrameworkName += "Frameworks/";
301 FrameworkName.append(FilenameStart, SlashPos);
302 FrameworkName += ".framework/";
303
304 llvm::StringMapEntry<const DirectoryEntry *> &CacheLookup =
305 FrameworkMap.GetOrCreateValue(FilenameStart, SlashPos);
306
307 // Some other location?
308 if (CacheLookup.getValue() &&
309 CacheLookup.getKeyLength() == FrameworkName.size() &&
310 memcmp(CacheLookup.getKeyData(), &FrameworkName[0],
311 CacheLookup.getKeyLength()) != 0)
312 return 0;
313
314 // Cache subframework.
315 if (CacheLookup.getValue() == 0) {
316 ++NumSubFrameworkLookups;
317
318 // If the framework dir doesn't exist, we fail.
319 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.begin(),
320 FrameworkName.end());
321 if (Dir == 0) return 0;
322
323 // Otherwise, if it does, remember that this is the right direntry for this
324 // framework.
325 CacheLookup.setValue(Dir);
326 }
327
328 const FileEntry *FE = 0;
329
330 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
331 llvm::SmallString<1024> HeadersFilename(FrameworkName);
332 HeadersFilename += "Headers/";
333 HeadersFilename.append(SlashPos+1, FilenameEnd);
334 if (!(FE = FileMgr.getFile(HeadersFilename.begin(),
335 HeadersFilename.end()))) {
336
337 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
338 HeadersFilename = FrameworkName;
339 HeadersFilename += "PrivateHeaders/";
340 HeadersFilename.append(SlashPos+1, FilenameEnd);
341 if (!(FE = FileMgr.getFile(HeadersFilename.begin(), HeadersFilename.end())))
342 return 0;
343 }
344
345 // This file is a system header or C++ unfriendly if the old file is.
346 getFileInfo(FE).DirInfo = getFileInfo(ContextFileEnt).DirInfo;
347 return FE;
348}
349
350//===----------------------------------------------------------------------===//
351// File Info Management.
352//===----------------------------------------------------------------------===//
353
354
355/// getFileInfo - Return the PerFileInfo structure for the specified
356/// FileEntry.
357HeaderSearch::PerFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
358 if (FE->getUID() >= FileInfo.size())
359 FileInfo.resize(FE->getUID()+1);
360 return FileInfo[FE->getUID()];
361}
362
363/// ShouldEnterIncludeFile - Mark the specified file as a target of of a
364/// #include, #include_next, or #import directive. Return false if #including
365/// the file will have no effect or true if we should include it.
366bool HeaderSearch::ShouldEnterIncludeFile(const FileEntry *File, bool isImport){
367 ++NumIncluded; // Count # of attempted #includes.
368
369 // Get information about this file.
370 PerFileInfo &FileInfo = getFileInfo(File);
371
372 // If this is a #import directive, check that we have not already imported
373 // this header.
374 if (isImport) {
375 // If this has already been imported, don't import it again.
376 FileInfo.isImport = true;
377
378 // Has this already been #import'ed or #include'd?
379 if (FileInfo.NumIncludes) return false;
380 } else {
381 // Otherwise, if this is a #include of a file that was previously #import'd
382 // or if this is the second #include of a #pragma once file, ignore it.
383 if (FileInfo.isImport)
384 return false;
385 }
386
387 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
388 // if the macro that guards it is defined, we know the #include has no effect.
Chris Lattner9c46de42007-10-07 07:57:27 +0000389 if (FileInfo.ControllingMacro &&
390 FileInfo.ControllingMacro->hasMacroDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000391 ++NumMultiIncludeFileOptzn;
392 return false;
393 }
394
395 // Increment the number of times this file has been included.
396 ++FileInfo.NumIncludes;
397
398 return true;
399}
400
401