blob: 1d79effc8458e6be19883cccf1aa6568c81100a1 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +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
Chris Lattner4b009652007-07-25 00:24:17 +000014#include "clang/Lex/HeaderSearch.h"
Chris Lattnerc2043bf2007-12-17 06:36:45 +000015#include "clang/Lex/HeaderMap.h"
Chris Lattner2fd1c652007-10-07 08:58:51 +000016#include "clang/Basic/FileManager.h"
17#include "clang/Basic/IdentifierTable.h"
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattnerc2043bf2007-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
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattnerc2043bf2007-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 Lattnerb7426782007-12-17 07:52:39 +000064 // If it ever grows, use of a linear search should be re-evaluated.
Chris Lattnerc2043bf2007-12-17 06:36:45 +000065 if (!HeaderMaps.empty()) {
66 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
Chris Lattnerb7426782007-12-17 07:52:39 +000067 // Pointer equality comparison of FileEntries works because they are
68 // already uniqued by inode.
Chris Lattnerc2043bf2007-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 Lattnerb7426782007-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 Lattner7d0ad4a2007-12-17 08:13:48 +000089 HeaderSearch &HS) const {
Chris Lattnerb7426782007-12-17 07:52:39 +000090 llvm::SmallString<1024> TmpDir;
Chris Lattner7d0ad4a2007-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 Lattnerb7426782007-12-17 07:52:39 +000099
Chris Lattner7d0ad4a2007-12-17 08:13:48 +0000100 if (isFramework())
101 return DoFrameworkLookup(FilenameStart, FilenameEnd, HS);
102
Chris Lattner61349712007-12-17 08:17:39 +0000103 assert(isHeaderMap() && "Unknown directory lookup");
104 return getHeaderMap()->LookupFile(FilenameStart, FilenameEnd,HS.getFileMgr());
Chris Lattnerb7426782007-12-17 07:52:39 +0000105}
106
107
Chris Lattner7d0ad4a2007-12-17 08:13:48 +0000108/// DoFrameworkLookup - Do a lookup of the specified file in the current
109/// DirectoryLookup, which is a framework directory.
110const FileEntry *DirectoryLookup::DoFrameworkLookup(const char *FilenameStart,
111 const char *FilenameEnd,
112 HeaderSearch &HS) const {
113 FileManager &FileMgr = HS.getFileMgr();
114
Chris Lattner4b009652007-07-25 00:24:17 +0000115 // Framework names must have a '/' in the filename.
116 const char *SlashPos = std::find(FilenameStart, FilenameEnd, '/');
117 if (SlashPos == FilenameEnd) return 0;
118
Chris Lattner7d0ad4a2007-12-17 08:13:48 +0000119 // Find out if this is the home for the specified framework, by checking
120 // HeaderSearch. Possible answer are yes/no and unknown.
121 const DirectoryEntry *&FrameworkDirCache =
122 HS.LookupFrameworkCache(FilenameStart, SlashPos);
Chris Lattner4b009652007-07-25 00:24:17 +0000123
Chris Lattner7d0ad4a2007-12-17 08:13:48 +0000124 // If it is known and in some other directory, fail.
125 if (FrameworkDirCache && FrameworkDirCache != getFrameworkDir())
Chris Lattner4b009652007-07-25 00:24:17 +0000126 return 0;
Chris Lattner7d0ad4a2007-12-17 08:13:48 +0000127
128 // Otherwise, construct the path to this framework dir.
129
Chris Lattner4b009652007-07-25 00:24:17 +0000130 // FrameworkName = "/System/Library/Frameworks/"
131 llvm::SmallString<1024> FrameworkName;
Chris Lattner7d0ad4a2007-12-17 08:13:48 +0000132 FrameworkName += getFrameworkDir()->getName();
Chris Lattner4b009652007-07-25 00:24:17 +0000133 if (FrameworkName.empty() || FrameworkName.back() != '/')
134 FrameworkName.push_back('/');
135
136 // FrameworkName = "/System/Library/Frameworks/Cocoa"
137 FrameworkName.append(FilenameStart, SlashPos);
138
139 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
140 FrameworkName += ".framework/";
Chris Lattner7d0ad4a2007-12-17 08:13:48 +0000141
142 // If the cache entry is still unresolved, query to see if the cache entry is
143 // still unresolved. If so, check its existence now.
144 if (FrameworkDirCache == 0) {
145 HS.IncrementFrameworkLookupCount();
Chris Lattner4b009652007-07-25 00:24:17 +0000146
147 // If the framework dir doesn't exist, we fail.
Chris Lattner7d0ad4a2007-12-17 08:13:48 +0000148 // FIXME: It's probably more efficient to query this with FileMgr.getDir.
Chris Lattner4b009652007-07-25 00:24:17 +0000149 if (!llvm::sys::Path(std::string(FrameworkName.begin(),
150 FrameworkName.end())).exists())
151 return 0;
152
153 // Otherwise, if it does, remember that this is the right direntry for this
154 // framework.
Chris Lattner7d0ad4a2007-12-17 08:13:48 +0000155 FrameworkDirCache = getFrameworkDir();
Chris Lattner4b009652007-07-25 00:24:17 +0000156 }
157
158 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
159 unsigned OrigSize = FrameworkName.size();
160
161 FrameworkName += "Headers/";
162 FrameworkName.append(SlashPos+1, FilenameEnd);
163 if (const FileEntry *FE = FileMgr.getFile(FrameworkName.begin(),
164 FrameworkName.end())) {
165 return FE;
166 }
167
168 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
169 const char *Private = "Private";
170 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
171 Private+strlen(Private));
172 return FileMgr.getFile(FrameworkName.begin(), FrameworkName.end());
173}
174
Chris Lattnerb7426782007-12-17 07:52:39 +0000175
Chris Lattner7d0ad4a2007-12-17 08:13:48 +0000176//===----------------------------------------------------------------------===//
177// Header File Location.
178//===----------------------------------------------------------------------===//
179
180
Chris Lattner4b009652007-07-25 00:24:17 +0000181/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
182/// return null on failure. isAngled indicates whether the file reference is
183/// for system #include's or not (i.e. using <> instead of ""). CurFileEnt, if
184/// non-null, indicates where the #including file is, in case a relative search
185/// is needed.
186const FileEntry *HeaderSearch::LookupFile(const char *FilenameStart,
187 const char *FilenameEnd,
188 bool isAngled,
189 const DirectoryLookup *FromDir,
190 const DirectoryLookup *&CurDir,
191 const FileEntry *CurFileEnt) {
192 // If 'Filename' is absolute, check to see if it exists and no searching.
193 // FIXME: Portability. This should be a sys::Path interface, this doesn't
194 // handle things like C:\foo.txt right, nor win32 \\network\device\blah.
195 if (FilenameStart[0] == '/') {
196 CurDir = 0;
197
198 // If this was an #include_next "/absolute/file", fail.
199 if (FromDir) return 0;
200
201 // Otherwise, just return the file.
202 return FileMgr.getFile(FilenameStart, FilenameEnd);
203 }
204
Chris Lattner4b009652007-07-25 00:24:17 +0000205 // Step #0, unless disabled, check to see if the file is in the #includer's
Chris Lattnerb7426782007-12-17 07:52:39 +0000206 // directory. This has to be based on CurFileEnt, not CurDir, because
207 // CurFileEnt could be a #include of a subdirectory (#include "foo/bar.h") and
208 // a subsequent include of "baz.h" should resolve to "whatever/foo/baz.h".
209 // This search is not done for <> headers.
Chris Lattner4b009652007-07-25 00:24:17 +0000210 if (CurFileEnt && !isAngled && !NoCurDirSearch) {
Chris Lattnerb7426782007-12-17 07:52:39 +0000211 llvm::SmallString<1024> TmpDir;
Chris Lattner4b009652007-07-25 00:24:17 +0000212 // Concatenate the requested file onto the directory.
213 // FIXME: Portability. Filename concatenation should be in sys::Path.
214 TmpDir += CurFileEnt->getDir()->getName();
215 TmpDir.push_back('/');
216 TmpDir.append(FilenameStart, FilenameEnd);
217 if (const FileEntry *FE = FileMgr.getFile(TmpDir.begin(), TmpDir.end())) {
218 // Leave CurDir unset.
Chris Lattner4b009652007-07-25 00:24:17 +0000219 // This file is a system header or C++ unfriendly if the old file is.
220 getFileInfo(FE).DirInfo = getFileInfo(CurFileEnt).DirInfo;
221 return FE;
222 }
Chris Lattner4b009652007-07-25 00:24:17 +0000223 }
224
225 CurDir = 0;
226
227 // If this is a system #include, ignore the user #include locs.
228 unsigned i = isAngled ? SystemDirIdx : 0;
229
230 // If this is a #include_next request, start searching after the directory the
231 // file was found in.
232 if (FromDir)
233 i = FromDir-&SearchDirs[0];
234
235 // Cache all of the lookups performed by this method. Many headers are
236 // multiply included, and the "pragma once" optimization prevents them from
237 // being relex/pp'd, but they would still have to search through a
238 // (potentially huge) series of SearchDirs to find it.
239 std::pair<unsigned, unsigned> &CacheLookup =
240 LookupFileCache.GetOrCreateValue(FilenameStart, FilenameEnd).getValue();
241
242 // If the entry has been previously looked up, the first value will be
243 // non-zero. If the value is equal to i (the start point of our search), then
244 // this is a matching hit.
245 if (CacheLookup.first == i+1) {
246 // Skip querying potentially lots of directories for this lookup.
247 i = CacheLookup.second;
248 } else {
249 // Otherwise, this is the first query, or the previous query didn't match
250 // our search start. We will fill in our found location below, so prime the
251 // start point value.
252 CacheLookup.first = i+1;
253 }
Chris Lattnerb7426782007-12-17 07:52:39 +0000254
Chris Lattner4b009652007-07-25 00:24:17 +0000255 // Check each directory in sequence to see if it contains this file.
256 for (; i != SearchDirs.size(); ++i) {
Chris Lattner7d0ad4a2007-12-17 08:13:48 +0000257 const FileEntry *FE =
258 SearchDirs[i].LookupFile(FilenameStart, FilenameEnd, *this);
259 if (!FE) continue;
Chris Lattner4b009652007-07-25 00:24:17 +0000260
Chris Lattner7d0ad4a2007-12-17 08:13:48 +0000261 CurDir = &SearchDirs[i];
262
263 // This file is a system header or C++ unfriendly if the dir is.
264 getFileInfo(FE).DirInfo = CurDir->getDirCharacteristic();
265
266 // Remember this location for the next lookup we do.
267 CacheLookup.second = i;
268 return FE;
Chris Lattner4b009652007-07-25 00:24:17 +0000269 }
270
271 // Otherwise, didn't find it. Remember we didn't find this.
272 CacheLookup.second = SearchDirs.size();
273 return 0;
274}
275
276/// LookupSubframeworkHeader - Look up a subframework for the specified
277/// #include file. For example, if #include'ing <HIToolbox/HIToolbox.h> from
278/// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
279/// is a subframework within Carbon.framework. If so, return the FileEntry
280/// for the designated file, otherwise return null.
281const FileEntry *HeaderSearch::
282LookupSubframeworkHeader(const char *FilenameStart,
283 const char *FilenameEnd,
284 const FileEntry *ContextFileEnt) {
285 // Framework names must have a '/' in the filename. Find it.
286 const char *SlashPos = std::find(FilenameStart, FilenameEnd, '/');
287 if (SlashPos == FilenameEnd) return 0;
288
289 // Look up the base framework name of the ContextFileEnt.
290 const char *ContextName = ContextFileEnt->getName();
291
292 // If the context info wasn't a framework, couldn't be a subframework.
293 const char *FrameworkPos = strstr(ContextName, ".framework/");
294 if (FrameworkPos == 0)
295 return 0;
296
297 llvm::SmallString<1024> FrameworkName(ContextName,
298 FrameworkPos+strlen(".framework/"));
299
300 // Append Frameworks/HIToolbox.framework/
301 FrameworkName += "Frameworks/";
302 FrameworkName.append(FilenameStart, SlashPos);
303 FrameworkName += ".framework/";
304
305 llvm::StringMapEntry<const DirectoryEntry *> &CacheLookup =
306 FrameworkMap.GetOrCreateValue(FilenameStart, SlashPos);
307
308 // Some other location?
309 if (CacheLookup.getValue() &&
310 CacheLookup.getKeyLength() == FrameworkName.size() &&
311 memcmp(CacheLookup.getKeyData(), &FrameworkName[0],
312 CacheLookup.getKeyLength()) != 0)
313 return 0;
314
315 // Cache subframework.
316 if (CacheLookup.getValue() == 0) {
317 ++NumSubFrameworkLookups;
318
319 // If the framework dir doesn't exist, we fail.
320 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.begin(),
321 FrameworkName.end());
322 if (Dir == 0) return 0;
323
324 // Otherwise, if it does, remember that this is the right direntry for this
325 // framework.
326 CacheLookup.setValue(Dir);
327 }
328
329 const FileEntry *FE = 0;
330
331 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
332 llvm::SmallString<1024> HeadersFilename(FrameworkName);
333 HeadersFilename += "Headers/";
334 HeadersFilename.append(SlashPos+1, FilenameEnd);
335 if (!(FE = FileMgr.getFile(HeadersFilename.begin(),
336 HeadersFilename.end()))) {
337
338 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
339 HeadersFilename = FrameworkName;
340 HeadersFilename += "PrivateHeaders/";
341 HeadersFilename.append(SlashPos+1, FilenameEnd);
342 if (!(FE = FileMgr.getFile(HeadersFilename.begin(), HeadersFilename.end())))
343 return 0;
344 }
345
346 // This file is a system header or C++ unfriendly if the old file is.
347 getFileInfo(FE).DirInfo = getFileInfo(ContextFileEnt).DirInfo;
348 return FE;
349}
350
351//===----------------------------------------------------------------------===//
352// File Info Management.
353//===----------------------------------------------------------------------===//
354
355
356/// getFileInfo - Return the PerFileInfo structure for the specified
357/// FileEntry.
358HeaderSearch::PerFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
359 if (FE->getUID() >= FileInfo.size())
360 FileInfo.resize(FE->getUID()+1);
361 return FileInfo[FE->getUID()];
362}
363
364/// ShouldEnterIncludeFile - Mark the specified file as a target of of a
365/// #include, #include_next, or #import directive. Return false if #including
366/// the file will have no effect or true if we should include it.
367bool HeaderSearch::ShouldEnterIncludeFile(const FileEntry *File, bool isImport){
368 ++NumIncluded; // Count # of attempted #includes.
369
370 // Get information about this file.
371 PerFileInfo &FileInfo = getFileInfo(File);
372
373 // If this is a #import directive, check that we have not already imported
374 // this header.
375 if (isImport) {
376 // If this has already been imported, don't import it again.
377 FileInfo.isImport = true;
378
379 // Has this already been #import'ed or #include'd?
380 if (FileInfo.NumIncludes) return false;
381 } else {
382 // Otherwise, if this is a #include of a file that was previously #import'd
383 // or if this is the second #include of a #pragma once file, ignore it.
384 if (FileInfo.isImport)
385 return false;
386 }
387
388 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
389 // if the macro that guards it is defined, we know the #include has no effect.
Chris Lattner4826cbc2007-10-07 07:57:27 +0000390 if (FileInfo.ControllingMacro &&
391 FileInfo.ControllingMacro->hasMacroDefinition()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000392 ++NumMultiIncludeFileOptzn;
393 return false;
394 }
395
396 // Increment the number of times this file has been included.
397 ++FileInfo.NumIncludes;
398
399 return true;
400}
401
402