blob: 2a9a553fccac87302de261a5e225a148a831fc38 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SourceManager.cpp - Track and cache source files -----------------===//
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 SourceManager interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Basic/SourceManager.h"
15#include "clang/Basic/FileManager.h"
16#include "llvm/Support/MemoryBuffer.h"
17#include "llvm/System/Path.h"
18#include <algorithm>
19#include <iostream>
Gabor Greif15012182007-07-12 16:00:00 +000020#include <fcntl.h>
21
Reid Spencer5f016e22007-07-11 17:01:13 +000022using namespace clang;
23using namespace SrcMgr;
24using llvm::MemoryBuffer;
25
26SourceManager::~SourceManager() {
27 for (std::map<const FileEntry *, FileInfo>::iterator I = FileInfos.begin(),
28 E = FileInfos.end(); I != E; ++I) {
29 delete I->second.Buffer;
30 delete[] I->second.SourceLineCache;
31 }
32
33 for (std::list<InfoRec>::iterator I = MemBufferInfos.begin(),
34 E = MemBufferInfos.end(); I != E; ++I) {
35 delete I->second.Buffer;
36 delete[] I->second.SourceLineCache;
37 }
38}
39
40
41// FIXME: REMOVE THESE
42#include <unistd.h>
43#include <sys/types.h>
44#include <sys/uio.h>
45#include <sys/fcntl.h>
46#include <cerrno>
47
48static const MemoryBuffer *ReadFileFast(const FileEntry *FileEnt) {
49#if 0
50 // FIXME: Reintroduce this and zap this function once the common llvm stuff
51 // is fast for the small case.
52 return MemoryBuffer::getFile(FileEnt->getName(), strlen(FileEnt->getName()),
53 FileEnt->getSize());
54#endif
55
56 // If the file is larger than some threshold, use 'read', otherwise use mmap.
57 if (FileEnt->getSize() >= 4096*4)
58 return MemoryBuffer::getFile(FileEnt->getName(), strlen(FileEnt->getName()),
59 0, FileEnt->getSize());
60
61 MemoryBuffer *SB = MemoryBuffer::getNewUninitMemBuffer(FileEnt->getSize(),
62 FileEnt->getName());
63 char *BufPtr = const_cast<char*>(SB->getBufferStart());
64
65 int FD = ::open(FileEnt->getName(), O_RDONLY);
66 if (FD == -1) {
67 delete SB;
68 return 0;
69 }
70
71 unsigned BytesLeft = FileEnt->getSize();
72 while (BytesLeft) {
73 ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);
74 if (NumRead != -1) {
75 BytesLeft -= NumRead;
76 BufPtr += NumRead;
77 } else if (errno == EINTR) {
78 // try again
79 } else {
80 // error reading.
81 close(FD);
82 delete SB;
83 return 0;
84 }
85 }
86 close(FD);
87
88 return SB;
89}
90
91
92/// getFileInfo - Create or return a cached FileInfo for the specified file.
93///
94const InfoRec *
95SourceManager::getInfoRec(const FileEntry *FileEnt) {
96 assert(FileEnt && "Didn't specify a file entry to use?");
97 // Do we already have information about this file?
98 std::map<const FileEntry *, FileInfo>::iterator I =
99 FileInfos.lower_bound(FileEnt);
100 if (I != FileInfos.end() && I->first == FileEnt)
101 return &*I;
102
103 // Nope, get information.
104 const MemoryBuffer *File = ReadFileFast(FileEnt);
105 if (File == 0)
106 return 0;
107
108 const InfoRec &Entry =
109 *FileInfos.insert(I, std::make_pair(FileEnt, FileInfo()));
110 FileInfo &Info = const_cast<FileInfo &>(Entry.second);
111
112 Info.Buffer = File;
113 Info.SourceLineCache = 0;
114 Info.NumLines = 0;
115 return &Entry;
116}
117
118
119/// createMemBufferInfoRec - Create a new info record for the specified memory
120/// buffer. This does no caching.
121const InfoRec *
122SourceManager::createMemBufferInfoRec(const MemoryBuffer *Buffer) {
123 // Add a new info record to the MemBufferInfos list and return it.
124 FileInfo FI;
125 FI.Buffer = Buffer;
126 FI.SourceLineCache = 0;
127 FI.NumLines = 0;
128 MemBufferInfos.push_back(InfoRec(0, FI));
129 return &MemBufferInfos.back();
130}
131
132
133/// createFileID - Create a new fileID for the specified InfoRec and include
134/// position. This works regardless of whether the InfoRec corresponds to a
135/// file or some other input source.
136unsigned SourceManager::createFileID(const InfoRec *File,
137 SourceLocation IncludePos) {
138 // If FileEnt is really large (e.g. it's a large .i file), we may not be able
139 // to fit an arbitrary position in the file in the FilePos field. To handle
140 // this, we create one FileID for each chunk of the file that fits in a
141 // FilePos field.
142 unsigned FileSize = File->second.Buffer->getBufferSize();
143 if (FileSize+1 < (1 << SourceLocation::FilePosBits)) {
144 FileIDs.push_back(FileIDInfo::getNormalBuffer(IncludePos, 0, File));
145 assert(FileIDs.size() < (1 << SourceLocation::FileIDBits) &&
146 "Ran out of file ID's!");
147 return FileIDs.size();
148 }
149
150 // Create one FileID for each chunk of the file.
151 unsigned Result = FileIDs.size()+1;
152
153 unsigned ChunkNo = 0;
154 while (1) {
155 FileIDs.push_back(FileIDInfo::getNormalBuffer(IncludePos, ChunkNo++, File));
156
157 if (FileSize+1 < (1 << SourceLocation::FilePosBits)) break;
158 FileSize -= (1 << SourceLocation::FilePosBits);
159 }
160
161 assert(FileIDs.size() < (1 << SourceLocation::FileIDBits) &&
162 "Ran out of file ID's!");
163 return Result;
164}
165
166/// getInstantiationLoc - Return a new SourceLocation that encodes the fact
167/// that a token from physloc PhysLoc should actually be referenced from
168/// InstantiationLoc.
169SourceLocation SourceManager::getInstantiationLoc(SourceLocation PhysLoc,
170 SourceLocation InstantLoc) {
171 assert(getFIDInfo(PhysLoc.getFileID())->IDType !=
172 SrcMgr::FileIDInfo::MacroExpansion &&
173 "Location instantiated in a macro?");
174
175 // Resolve InstantLoc down to a real logical location.
176 InstantLoc = getLogicalLoc(InstantLoc);
177
178 unsigned InstantiationFileID;
179 // If this is the same instantiation as was requested last time, return this
180 // immediately.
181 if (PhysLoc.getFileID() == LastInstantiationLoc_MacroFID &&
182 InstantLoc == LastInstantiationLoc_InstantLoc) {
183 InstantiationFileID = LastInstantiationLoc_Result;
184 } else {
185 // Add a FileID for this. FIXME: should cache these!
186 FileIDs.push_back(FileIDInfo::getMacroExpansion(InstantLoc,
187 PhysLoc.getFileID()));
188 InstantiationFileID = FileIDs.size();
189
190 // Remember this in the single-entry cache for next time.
191 LastInstantiationLoc_MacroFID = PhysLoc.getFileID();
192 LastInstantiationLoc_InstantLoc = InstantLoc;
193 LastInstantiationLoc_Result = InstantiationFileID;
194 }
195 return SourceLocation(InstantiationFileID, PhysLoc.getRawFilePos());
196}
197
198
199
200/// getCharacterData - Return a pointer to the start of the specified location
201/// in the appropriate MemoryBuffer.
202const char *SourceManager::getCharacterData(SourceLocation SL) const {
203 // Note that this is a hot function in the getSpelling() path, which is
204 // heavily used by -E mode.
205 unsigned FileID = SL.getFileID();
206 assert(FileID && "Invalid source location!");
207
208 return getFileInfo(FileID)->Buffer->getBufferStart() + getFilePos(SL);
209}
210
211/// getIncludeLoc - Return the location of the #include for the specified
212/// FileID.
213SourceLocation SourceManager::getIncludeLoc(unsigned FileID) const {
214 const SrcMgr::FileIDInfo *FIDInfo = getFIDInfo(FileID);
215
216 // For Macros, the physical loc is specified by the MacroTokenFileID.
217 if (FIDInfo->IDType == SrcMgr::FileIDInfo::MacroExpansion)
218 FIDInfo = &FileIDs[FIDInfo->u.MacroTokenFileID-1];
219
220 return FIDInfo->IncludeLoc;
221}
222
223
224/// getColumnNumber - Return the column # for the specified include position.
225/// this is significantly cheaper to compute than the line number. This returns
226/// zero if the column number isn't known.
227unsigned SourceManager::getColumnNumber(SourceLocation Loc) const {
228 Loc = getLogicalLoc(Loc);
229 unsigned FileID = Loc.getFileID();
230 if (FileID == 0) return 0;
231
232 unsigned FilePos = getFilePos(Loc);
233 const MemoryBuffer *Buffer = getBuffer(FileID);
234 const char *Buf = Buffer->getBufferStart();
235
236 unsigned LineStart = FilePos;
237 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
238 --LineStart;
239 return FilePos-LineStart+1;
240}
241
242/// getSourceName - This method returns the name of the file or buffer that
243/// the SourceLocation specifies. This can be modified with #line directives,
244/// etc.
245std::string SourceManager::getSourceName(SourceLocation Loc) {
246 Loc = getLogicalLoc(Loc);
247 unsigned FileID = Loc.getFileID();
248 if (FileID == 0) return "";
249 return getFileInfo(FileID)->Buffer->getBufferIdentifier();
250}
251
252
253/// getLineNumber - Given a SourceLocation, return the physical line number
254/// for the position indicated. This requires building and caching a table of
255/// line offsets for the MemoryBuffer, so this is not cheap: use only when
256/// about to emit a diagnostic.
257unsigned SourceManager::getLineNumber(SourceLocation Loc) {
258 Loc = getLogicalLoc(Loc);
259 unsigned FileID = Loc.getFileID();
260 if (FileID == 0) return 0;
261 FileInfo *FileInfo = getFileInfo(FileID);
262
263 // If this is the first use of line information for this buffer, compute the
264 /// SourceLineCache for it on demand.
265 if (FileInfo->SourceLineCache == 0) {
266 const MemoryBuffer *Buffer = FileInfo->Buffer;
267
268 // Find the file offsets of all of the *physical* source lines. This does
269 // not look at trigraphs, escaped newlines, or anything else tricky.
270 std::vector<unsigned> LineOffsets;
271
272 // Line #1 starts at char 0.
273 LineOffsets.push_back(0);
274
275 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
276 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
277 unsigned Offs = 0;
278 while (1) {
279 // Skip over the contents of the line.
280 // TODO: Vectorize this? This is very performance sensitive for programs
281 // with lots of diagnostics and in -E mode.
282 const unsigned char *NextBuf = (const unsigned char *)Buf;
283 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
284 ++NextBuf;
285 Offs += NextBuf-Buf;
286 Buf = NextBuf;
287
288 if (Buf[0] == '\n' || Buf[0] == '\r') {
289 // If this is \n\r or \r\n, skip both characters.
290 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
291 ++Offs, ++Buf;
292 ++Offs, ++Buf;
293 LineOffsets.push_back(Offs);
294 } else {
295 // Otherwise, this is a null. If end of file, exit.
296 if (Buf == End) break;
297 // Otherwise, skip the null.
298 ++Offs, ++Buf;
299 }
300 }
301 LineOffsets.push_back(Offs);
302
303 // Copy the offsets into the FileInfo structure.
304 FileInfo->NumLines = LineOffsets.size();
305 FileInfo->SourceLineCache = new unsigned[LineOffsets.size()];
306 std::copy(LineOffsets.begin(), LineOffsets.end(),
307 FileInfo->SourceLineCache);
308 }
309
310 // Okay, we know we have a line number table. Do a binary search to find the
311 // line number that this character position lands on.
312 unsigned NumLines = FileInfo->NumLines;
313 unsigned *SourceLineCache = FileInfo->SourceLineCache;
314
315 // TODO: If this is performance sensitive, we could try doing simple radix
316 // type approaches to make good (tight?) initial guesses based on the
317 // assumption that all lines are the same average size.
318 unsigned *Pos = std::lower_bound(SourceLineCache, SourceLineCache+NumLines,
319 getFilePos(Loc)+1);
320 return Pos-SourceLineCache;
321}
322
323/// getSourceFilePos - This method returns the *logical* offset from the start
324/// of the file that the specified SourceLocation represents. This returns
325/// the location of the *logical* character data, not the physical file
326/// position. In the case of macros, for example, this returns where the
327/// macro was instantiated, not where the characters for the macro can be
328/// found.
329unsigned SourceManager::getSourceFilePos(SourceLocation Loc) const {
330
331 // If this is a macro, we need to get the instantiation location.
332 const SrcMgr::FileIDInfo *FIDInfo = getFIDInfo(Loc.getFileID());
333 while (FIDInfo->IDType == SrcMgr::FileIDInfo::MacroExpansion) {
334 Loc = FIDInfo->IncludeLoc;
335 FIDInfo = getFIDInfo(Loc.getFileID());
336 }
337
338 return getFilePos(Loc);
339}
340
341
342/// PrintStats - Print statistics to stderr.
343///
344void SourceManager::PrintStats() const {
345 std::cerr << "\n*** Source Manager Stats:\n";
346 std::cerr << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
347 << " mem buffers mapped, " << FileIDs.size()
348 << " file ID's allocated.\n";
349 unsigned NumBuffers = 0, NumMacros = 0;
350 for (unsigned i = 0, e = FileIDs.size(); i != e; ++i) {
351 if (FileIDs[i].IDType == FileIDInfo::NormalBuffer)
352 ++NumBuffers;
353 else if (FileIDs[i].IDType == FileIDInfo::MacroExpansion)
354 ++NumMacros;
355 else
356 assert(0 && "Unknown FileID!");
357 }
358 std::cerr << " " << NumBuffers << " normal buffer FileID's, "
359 << NumMacros << " macro expansion FileID's.\n";
360
361
362
363 unsigned NumLineNumsComputed = 0;
364 unsigned NumFileBytesMapped = 0;
365 for (std::map<const FileEntry *, FileInfo>::const_iterator I =
366 FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
367 NumLineNumsComputed += I->second.SourceLineCache != 0;
368 NumFileBytesMapped += I->second.Buffer->getBufferSize();
369 }
370 std::cerr << NumFileBytesMapped << " bytes of files mapped, "
371 << NumLineNumsComputed << " files with line #'s computed.\n";
372}