blob: c91c4f9ba4e67a8667139271e0ed695721e6cb42 [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.
64 // If it ever grows, use of a linear search should be reevaluated.
65 if (!HeaderMaps.empty()) {
66 for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i)
67 if (HeaderMaps[i].first == FE)
68 return HeaderMaps[i].second;
69 }
70
71 if (const HeaderMap *HM = HeaderMap::Create(FE, ErrorInfo)) {
72 HeaderMaps.push_back(std::make_pair(FE, HM));
73 return HM;
74 }
75
76 return 0;
77}
78
79
Chris Lattner4b009652007-07-25 00:24:17 +000080//===----------------------------------------------------------------------===//
81// Header File Location.
82//===----------------------------------------------------------------------===//
83
84const FileEntry *HeaderSearch::DoFrameworkLookup(const DirectoryEntry *Dir,
85 const char *FilenameStart,
86 const char *FilenameEnd) {
87 // Framework names must have a '/' in the filename.
88 const char *SlashPos = std::find(FilenameStart, FilenameEnd, '/');
89 if (SlashPos == FilenameEnd) return 0;
90
91 llvm::StringMapEntry<const DirectoryEntry *> &CacheLookup =
92 FrameworkMap.GetOrCreateValue(FilenameStart, SlashPos);
93
94 // If it is some other directory, fail.
95 if (CacheLookup.getValue() && CacheLookup.getValue() != Dir)
96 return 0;
97
98 // FrameworkName = "/System/Library/Frameworks/"
99 llvm::SmallString<1024> FrameworkName;
100 FrameworkName += Dir->getName();
101 if (FrameworkName.empty() || FrameworkName.back() != '/')
102 FrameworkName.push_back('/');
103
104 // FrameworkName = "/System/Library/Frameworks/Cocoa"
105 FrameworkName.append(FilenameStart, SlashPos);
106
107 // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/"
108 FrameworkName += ".framework/";
109
110 if (CacheLookup.getValue() == 0) {
111 ++NumFrameworkLookups;
112
113 // If the framework dir doesn't exist, we fail.
114 if (!llvm::sys::Path(std::string(FrameworkName.begin(),
115 FrameworkName.end())).exists())
116 return 0;
117
118 // Otherwise, if it does, remember that this is the right direntry for this
119 // framework.
120 CacheLookup.setValue(Dir);
121 }
122
123 // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
124 unsigned OrigSize = FrameworkName.size();
125
126 FrameworkName += "Headers/";
127 FrameworkName.append(SlashPos+1, FilenameEnd);
128 if (const FileEntry *FE = FileMgr.getFile(FrameworkName.begin(),
129 FrameworkName.end())) {
130 return FE;
131 }
132
133 // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h"
134 const char *Private = "Private";
135 FrameworkName.insert(FrameworkName.begin()+OrigSize, Private,
136 Private+strlen(Private));
137 return FileMgr.getFile(FrameworkName.begin(), FrameworkName.end());
138}
139
140/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
141/// return null on failure. isAngled indicates whether the file reference is
142/// for system #include's or not (i.e. using <> instead of ""). CurFileEnt, if
143/// non-null, indicates where the #including file is, in case a relative search
144/// is needed.
145const FileEntry *HeaderSearch::LookupFile(const char *FilenameStart,
146 const char *FilenameEnd,
147 bool isAngled,
148 const DirectoryLookup *FromDir,
149 const DirectoryLookup *&CurDir,
150 const FileEntry *CurFileEnt) {
151 // If 'Filename' is absolute, check to see if it exists and no searching.
152 // FIXME: Portability. This should be a sys::Path interface, this doesn't
153 // handle things like C:\foo.txt right, nor win32 \\network\device\blah.
154 if (FilenameStart[0] == '/') {
155 CurDir = 0;
156
157 // If this was an #include_next "/absolute/file", fail.
158 if (FromDir) return 0;
159
160 // Otherwise, just return the file.
161 return FileMgr.getFile(FilenameStart, FilenameEnd);
162 }
163
164 llvm::SmallString<1024> TmpDir;
165
166 // Step #0, unless disabled, check to see if the file is in the #includer's
167 // directory. This search is not done for <> headers.
168 if (CurFileEnt && !isAngled && !NoCurDirSearch) {
169 // Concatenate the requested file onto the directory.
170 // FIXME: Portability. Filename concatenation should be in sys::Path.
171 TmpDir += CurFileEnt->getDir()->getName();
172 TmpDir.push_back('/');
173 TmpDir.append(FilenameStart, FilenameEnd);
174 if (const FileEntry *FE = FileMgr.getFile(TmpDir.begin(), TmpDir.end())) {
175 // Leave CurDir unset.
176
177 // This file is a system header or C++ unfriendly if the old file is.
178 getFileInfo(FE).DirInfo = getFileInfo(CurFileEnt).DirInfo;
179 return FE;
180 }
181 TmpDir.clear();
182 }
183
184 CurDir = 0;
185
186 // If this is a system #include, ignore the user #include locs.
187 unsigned i = isAngled ? SystemDirIdx : 0;
188
189 // If this is a #include_next request, start searching after the directory the
190 // file was found in.
191 if (FromDir)
192 i = FromDir-&SearchDirs[0];
193
194 // Cache all of the lookups performed by this method. Many headers are
195 // multiply included, and the "pragma once" optimization prevents them from
196 // being relex/pp'd, but they would still have to search through a
197 // (potentially huge) series of SearchDirs to find it.
198 std::pair<unsigned, unsigned> &CacheLookup =
199 LookupFileCache.GetOrCreateValue(FilenameStart, FilenameEnd).getValue();
200
201 // If the entry has been previously looked up, the first value will be
202 // non-zero. If the value is equal to i (the start point of our search), then
203 // this is a matching hit.
204 if (CacheLookup.first == i+1) {
205 // Skip querying potentially lots of directories for this lookup.
206 i = CacheLookup.second;
207 } else {
208 // Otherwise, this is the first query, or the previous query didn't match
209 // our search start. We will fill in our found location below, so prime the
210 // start point value.
211 CacheLookup.first = i+1;
212 }
213
214 // Check each directory in sequence to see if it contains this file.
215 for (; i != SearchDirs.size(); ++i) {
216 const FileEntry *FE = 0;
217 if (!SearchDirs[i].isFramework()) {
218 // FIXME: Portability. Adding file to dir should be in sys::Path.
219 // Concatenate the requested file onto the directory.
220 TmpDir.clear();
221 TmpDir += SearchDirs[i].getDir()->getName();
222 TmpDir.push_back('/');
223 TmpDir.append(FilenameStart, FilenameEnd);
224 FE = FileMgr.getFile(TmpDir.begin(), TmpDir.end());
225 } else {
226 FE = DoFrameworkLookup(SearchDirs[i].getDir(), FilenameStart,FilenameEnd);
227 }
228
229 if (FE) {
230 CurDir = &SearchDirs[i];
231
232 // This file is a system header or C++ unfriendly if the dir is.
233 getFileInfo(FE).DirInfo = CurDir->getDirCharacteristic();
234
235 // Remember this location for the next lookup we do.
236 CacheLookup.second = i;
237 return FE;
238 }
239 }
240
241 // Otherwise, didn't find it. Remember we didn't find this.
242 CacheLookup.second = SearchDirs.size();
243 return 0;
244}
245
246/// LookupSubframeworkHeader - Look up a subframework for the specified
247/// #include file. For example, if #include'ing <HIToolbox/HIToolbox.h> from
248/// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox
249/// is a subframework within Carbon.framework. If so, return the FileEntry
250/// for the designated file, otherwise return null.
251const FileEntry *HeaderSearch::
252LookupSubframeworkHeader(const char *FilenameStart,
253 const char *FilenameEnd,
254 const FileEntry *ContextFileEnt) {
255 // Framework names must have a '/' in the filename. Find it.
256 const char *SlashPos = std::find(FilenameStart, FilenameEnd, '/');
257 if (SlashPos == FilenameEnd) return 0;
258
259 // Look up the base framework name of the ContextFileEnt.
260 const char *ContextName = ContextFileEnt->getName();
261
262 // If the context info wasn't a framework, couldn't be a subframework.
263 const char *FrameworkPos = strstr(ContextName, ".framework/");
264 if (FrameworkPos == 0)
265 return 0;
266
267 llvm::SmallString<1024> FrameworkName(ContextName,
268 FrameworkPos+strlen(".framework/"));
269
270 // Append Frameworks/HIToolbox.framework/
271 FrameworkName += "Frameworks/";
272 FrameworkName.append(FilenameStart, SlashPos);
273 FrameworkName += ".framework/";
274
275 llvm::StringMapEntry<const DirectoryEntry *> &CacheLookup =
276 FrameworkMap.GetOrCreateValue(FilenameStart, SlashPos);
277
278 // Some other location?
279 if (CacheLookup.getValue() &&
280 CacheLookup.getKeyLength() == FrameworkName.size() &&
281 memcmp(CacheLookup.getKeyData(), &FrameworkName[0],
282 CacheLookup.getKeyLength()) != 0)
283 return 0;
284
285 // Cache subframework.
286 if (CacheLookup.getValue() == 0) {
287 ++NumSubFrameworkLookups;
288
289 // If the framework dir doesn't exist, we fail.
290 const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName.begin(),
291 FrameworkName.end());
292 if (Dir == 0) return 0;
293
294 // Otherwise, if it does, remember that this is the right direntry for this
295 // framework.
296 CacheLookup.setValue(Dir);
297 }
298
299 const FileEntry *FE = 0;
300
301 // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
302 llvm::SmallString<1024> HeadersFilename(FrameworkName);
303 HeadersFilename += "Headers/";
304 HeadersFilename.append(SlashPos+1, FilenameEnd);
305 if (!(FE = FileMgr.getFile(HeadersFilename.begin(),
306 HeadersFilename.end()))) {
307
308 // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h"
309 HeadersFilename = FrameworkName;
310 HeadersFilename += "PrivateHeaders/";
311 HeadersFilename.append(SlashPos+1, FilenameEnd);
312 if (!(FE = FileMgr.getFile(HeadersFilename.begin(), HeadersFilename.end())))
313 return 0;
314 }
315
316 // This file is a system header or C++ unfriendly if the old file is.
317 getFileInfo(FE).DirInfo = getFileInfo(ContextFileEnt).DirInfo;
318 return FE;
319}
320
321//===----------------------------------------------------------------------===//
322// File Info Management.
323//===----------------------------------------------------------------------===//
324
325
326/// getFileInfo - Return the PerFileInfo structure for the specified
327/// FileEntry.
328HeaderSearch::PerFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) {
329 if (FE->getUID() >= FileInfo.size())
330 FileInfo.resize(FE->getUID()+1);
331 return FileInfo[FE->getUID()];
332}
333
334/// ShouldEnterIncludeFile - Mark the specified file as a target of of a
335/// #include, #include_next, or #import directive. Return false if #including
336/// the file will have no effect or true if we should include it.
337bool HeaderSearch::ShouldEnterIncludeFile(const FileEntry *File, bool isImport){
338 ++NumIncluded; // Count # of attempted #includes.
339
340 // Get information about this file.
341 PerFileInfo &FileInfo = getFileInfo(File);
342
343 // If this is a #import directive, check that we have not already imported
344 // this header.
345 if (isImport) {
346 // If this has already been imported, don't import it again.
347 FileInfo.isImport = true;
348
349 // Has this already been #import'ed or #include'd?
350 if (FileInfo.NumIncludes) return false;
351 } else {
352 // Otherwise, if this is a #include of a file that was previously #import'd
353 // or if this is the second #include of a #pragma once file, ignore it.
354 if (FileInfo.isImport)
355 return false;
356 }
357
358 // Next, check to see if the file is wrapped with #ifndef guards. If so, and
359 // if the macro that guards it is defined, we know the #include has no effect.
Chris Lattner4826cbc2007-10-07 07:57:27 +0000360 if (FileInfo.ControllingMacro &&
361 FileInfo.ControllingMacro->hasMacroDefinition()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000362 ++NumMultiIncludeFileOptzn;
363 return false;
364 }
365
366 // Increment the number of times this file has been included.
367 ++FileInfo.NumIncludes;
368
369 return true;
370}
371
372