blob: f00f2bddfa01278fa34c37f1005ca3508c4cbf94 [file] [log] [blame]
Chris Lattner22eb9722006-06-18 05:43:12 +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 "clang/Basic/SourceBuffer.h"
17#include "llvm/System/Path.h"
18#include <algorithm>
19#include <iostream>
20using namespace llvm;
21using namespace clang;
Chris Lattner5f4b1ff2006-06-20 05:02:40 +000022using namespace SrcMgr;
Chris Lattner22eb9722006-06-18 05:43:12 +000023
24SourceManager::~SourceManager() {
25 for (std::map<const FileEntry *, FileInfo>::iterator I = FileInfos.begin(),
26 E = FileInfos.end(); I != E; ++I) {
27 delete I->second.Buffer;
28 delete[] I->second.SourceLineCache;
29 }
30
31 for (std::list<InfoRec>::iterator I = MemBufferInfos.begin(),
32 E = MemBufferInfos.end(); I != E; ++I) {
33 delete I->second.Buffer;
34 delete[] I->second.SourceLineCache;
35 }
36}
37
38/// getFileInfo - Create or return a cached FileInfo for the specified file.
39///
Chris Lattner5f4b1ff2006-06-20 05:02:40 +000040const InfoRec *
Chris Lattner22eb9722006-06-18 05:43:12 +000041SourceManager::getInfoRec(const FileEntry *FileEnt) {
42 assert(FileEnt && "Didn't specify a file entry to use?");
43 // Do we already have information about this file?
44 std::map<const FileEntry *, FileInfo>::iterator I =
45 FileInfos.lower_bound(FileEnt);
46 if (I != FileInfos.end() && I->first == FileEnt)
47 return &*I;
48
49 // Nope, get information.
50 const SourceBuffer *File;
51 try {
52 File = clang::SourceBuffer::getFile(FileEnt);
53 if (File == 0)
54 return 0;
55 } catch (...) {
56 return 0;
57 }
58
59 const InfoRec &Entry =
60 *FileInfos.insert(I, std::make_pair(FileEnt, FileInfo()));
61 FileInfo &Info = const_cast<FileInfo &>(Entry.second);
62
63 Info.Buffer = File;
64 Info.SourceLineCache = 0;
65 Info.NumLines = 0;
66 return &Entry;
67}
68
69
70/// createMemBufferInfoRec - Create a new info record for the specified memory
71/// buffer. This does no caching.
Chris Lattner5f4b1ff2006-06-20 05:02:40 +000072const InfoRec *
Chris Lattner22eb9722006-06-18 05:43:12 +000073SourceManager::createMemBufferInfoRec(const SourceBuffer *Buffer) {
74 // Add a new info record to the MemBufferInfos list and return it.
75 FileInfo FI;
76 FI.Buffer = Buffer;
77 FI.SourceLineCache = 0;
78 FI.NumLines = 0;
79 MemBufferInfos.push_back(InfoRec(0, FI));
80 return &MemBufferInfos.back();
81}
82
83
84/// createFileID - Create a new fileID for the specified InfoRec and include
85/// position. This works regardless of whether the InfoRec corresponds to a
86/// file or some other input source.
87unsigned SourceManager::createFileID(const InfoRec *File,
88 SourceLocation IncludePos) {
89 // If FileEnt is really large (e.g. it's a large .i file), we may not be able
90 // to fit an arbitrary position in the file in the FilePos field. To handle
91 // this, we create one FileID for each chunk of the file that fits in a
92 // FilePos field.
93 unsigned FileSize = File->second.Buffer->getBufferSize();
94 if (FileSize+1 < (1 << SourceLocation::FilePosBits)) {
Chris Lattner5f4b1ff2006-06-20 05:02:40 +000095 FileIDs.push_back(FileIDInfo::getNormalBuffer(IncludePos, 0, File));
Chris Lattner2a904d02006-10-22 06:33:42 +000096 assert(FileIDs.size() < (1 << SourceLocation::FileIDBits) &&
97 "Ran out of file ID's!");
Chris Lattner22eb9722006-06-18 05:43:12 +000098 return FileIDs.size();
99 }
100
101 // Create one FileID for each chunk of the file.
102 unsigned Result = FileIDs.size()+1;
103
104 unsigned ChunkNo = 0;
105 while (1) {
Chris Lattner5f4b1ff2006-06-20 05:02:40 +0000106 FileIDs.push_back(FileIDInfo::getNormalBuffer(IncludePos, ChunkNo++, File));
Chris Lattner22eb9722006-06-18 05:43:12 +0000107
108 if (FileSize+1 < (1 << SourceLocation::FilePosBits)) break;
109 FileSize -= (1 << SourceLocation::FilePosBits);
110 }
111
Chris Lattner2a904d02006-10-22 06:33:42 +0000112 assert(FileIDs.size() < (1 << SourceLocation::FileIDBits) &&
113 "Ran out of file ID's!");
Chris Lattner22eb9722006-06-18 05:43:12 +0000114 return Result;
115}
116
Chris Lattner7d6a4f62006-06-30 06:10:08 +0000117/// getInstantiationLoc - Return a new SourceLocation that encodes the fact
118/// that a token from physloc PhysLoc should actually be referenced from
119/// InstantiationLoc.
120SourceLocation SourceManager::getInstantiationLoc(SourceLocation PhysLoc,
121 SourceLocation InstantLoc) {
Chris Lattner351050b2006-07-16 18:05:08 +0000122 assert(getFIDInfo(PhysLoc.getFileID())->IDType !=
123 SrcMgr::FileIDInfo::MacroExpansion &&
124 "Location instantiated in a macro?");
125
Chris Lattner4c37a8c2006-06-30 06:15:08 +0000126 // Resolve InstantLoc down to a real logical location.
127 InstantLoc = getLogicalLoc(InstantLoc);
Chris Lattner7fa8c882006-07-20 06:48:52 +0000128
129 unsigned InstantiationFileID;
130 // If this is the same instantiation as was requested last time, return this
131 // immediately.
132 if (PhysLoc.getFileID() == LastInstantiationLoc_MacroFID &&
133 InstantLoc == LastInstantiationLoc_InstantLoc) {
134 InstantiationFileID = LastInstantiationLoc_Result;
135 } else {
136 // Add a FileID for this. FIXME: should cache these!
137 FileIDs.push_back(FileIDInfo::getMacroExpansion(InstantLoc,
138 PhysLoc.getFileID()));
139 InstantiationFileID = FileIDs.size();
140
141 // Remember this in the single-entry cache for next time.
142 LastInstantiationLoc_MacroFID = PhysLoc.getFileID();
143 LastInstantiationLoc_InstantLoc = InstantLoc;
144 LastInstantiationLoc_Result = InstantiationFileID;
145 }
Chris Lattner4c37a8c2006-06-30 06:15:08 +0000146 return SourceLocation(InstantiationFileID, PhysLoc.getRawFilePos());
Chris Lattner7d6a4f62006-06-30 06:10:08 +0000147}
148
149
Chris Lattner30709b032006-06-21 03:01:55 +0000150
Chris Lattnerd01e2912006-06-18 16:22:51 +0000151/// getCharacterData - Return a pointer to the start of the specified location
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000152/// in the appropriate SourceBuffer.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000153const char *SourceManager::getCharacterData(SourceLocation SL) const {
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000154 // Note that this is a hot function in the getSpelling() path, which is
155 // heavily used by -E mode.
156 unsigned FileID = SL.getFileID();
157 assert(FileID && "Invalid source location!");
158
159 return getFileInfo(FileID)->Buffer->getBufferStart() + getFilePos(SL);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000160}
161
Chris Lattner685730f2006-06-26 01:36:22 +0000162/// getIncludeLoc - Return the location of the #include for the specified
163/// FileID.
164SourceLocation SourceManager::getIncludeLoc(unsigned FileID) const {
165 const SrcMgr::FileIDInfo *FIDInfo = getFIDInfo(FileID);
166
167 // For Macros, the physical loc is specified by the MacroTokenFileID.
Chris Lattner2dffd2b2006-06-29 16:44:08 +0000168 if (FIDInfo->IDType == SrcMgr::FileIDInfo::MacroExpansion)
Chris Lattner685730f2006-06-26 01:36:22 +0000169 FIDInfo = &FileIDs[FIDInfo->u.MacroTokenFileID-1];
170
171 return FIDInfo->IncludeLoc;
172}
173
Chris Lattnerd01e2912006-06-18 16:22:51 +0000174
Chris Lattner22eb9722006-06-18 05:43:12 +0000175/// getColumnNumber - Return the column # for the specified include position.
176/// this is significantly cheaper to compute than the line number. This returns
177/// zero if the column number isn't known.
Chris Lattner9a13bde2006-06-21 04:57:09 +0000178unsigned SourceManager::getColumnNumber(SourceLocation Loc) const {
Chris Lattner2dffd2b2006-06-29 16:44:08 +0000179 Loc = getLogicalLoc(Loc);
Chris Lattner9a13bde2006-06-21 04:57:09 +0000180 unsigned FileID = Loc.getFileID();
Chris Lattner22eb9722006-06-18 05:43:12 +0000181 if (FileID == 0) return 0;
Chris Lattner30709b032006-06-21 03:01:55 +0000182
Chris Lattner9a13bde2006-06-21 04:57:09 +0000183 unsigned FilePos = getFilePos(Loc);
Chris Lattner30709b032006-06-21 03:01:55 +0000184 const SourceBuffer *Buffer = getBuffer(FileID);
Chris Lattner22eb9722006-06-18 05:43:12 +0000185 const char *Buf = Buffer->getBufferStart();
186
187 unsigned LineStart = FilePos;
188 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
189 --LineStart;
190 return FilePos-LineStart+1;
191}
192
Chris Lattner9a13bde2006-06-21 04:57:09 +0000193/// getSourceName - This method returns the name of the file or buffer that
194/// the SourceLocation specifies. This can be modified with #line directives,
195/// etc.
196std::string SourceManager::getSourceName(SourceLocation Loc) {
Chris Lattner2dffd2b2006-06-29 16:44:08 +0000197 Loc = getLogicalLoc(Loc);
Chris Lattner9a13bde2006-06-21 04:57:09 +0000198 unsigned FileID = Loc.getFileID();
199 if (FileID == 0) return "";
Chris Lattner2dffd2b2006-06-29 16:44:08 +0000200 return getFileInfo(FileID)->Buffer->getBufferIdentifier();
Chris Lattner9a13bde2006-06-21 04:57:09 +0000201}
202
203
Chris Lattner22eb9722006-06-18 05:43:12 +0000204/// getLineNumber - Given a SourceLocation, return the physical line number
205/// for the position indicated. This requires building and caching a table of
206/// line offsets for the SourceBuffer, so this is not cheap: use only when
207/// about to emit a diagnostic.
Chris Lattner9a13bde2006-06-21 04:57:09 +0000208unsigned SourceManager::getLineNumber(SourceLocation Loc) {
Chris Lattner2dffd2b2006-06-29 16:44:08 +0000209 Loc = getLogicalLoc(Loc);
Chris Lattnera85a9d22006-07-02 20:07:52 +0000210 unsigned FileID = Loc.getFileID();
211 if (FileID == 0) return 0;
212 FileInfo *FileInfo = getFileInfo(FileID);
Chris Lattner22eb9722006-06-18 05:43:12 +0000213
214 // If this is the first use of line information for this buffer, compute the
215 /// SourceLineCache for it on demand.
216 if (FileInfo->SourceLineCache == 0) {
217 const SourceBuffer *Buffer = FileInfo->Buffer;
218
219 // Find the file offsets of all of the *physical* source lines. This does
220 // not look at trigraphs, escaped newlines, or anything else tricky.
221 std::vector<unsigned> LineOffsets;
222
223 // Line #1 starts at char 0.
224 LineOffsets.push_back(0);
225
226 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
227 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
228 unsigned Offs = 0;
229 while (1) {
230 // Skip over the contents of the line.
231 // TODO: Vectorize this? This is very performance sensitive for programs
Chris Lattnerd5da3ea2006-07-04 21:11:41 +0000232 // with lots of diagnostics and in -E mode.
Chris Lattner22eb9722006-06-18 05:43:12 +0000233 const unsigned char *NextBuf = (const unsigned char *)Buf;
234 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
235 ++NextBuf;
236 Offs += NextBuf-Buf;
237 Buf = NextBuf;
238
239 if (Buf[0] == '\n' || Buf[0] == '\r') {
240 // If this is \n\r or \r\n, skip both characters.
241 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
242 ++Offs, ++Buf;
243 ++Offs, ++Buf;
244 LineOffsets.push_back(Offs);
245 } else {
246 // Otherwise, this is a null. If end of file, exit.
247 if (Buf == End) break;
248 // Otherwise, skip the null.
249 ++Offs, ++Buf;
250 }
251 }
252 LineOffsets.push_back(Offs);
253
254 // Copy the offsets into the FileInfo structure.
255 FileInfo->NumLines = LineOffsets.size();
256 FileInfo->SourceLineCache = new unsigned[LineOffsets.size()];
257 std::copy(LineOffsets.begin(), LineOffsets.end(),
258 FileInfo->SourceLineCache);
259 }
260
261 // Okay, we know we have a line number table. Do a binary search to find the
262 // line number that this character position lands on.
263 unsigned NumLines = FileInfo->NumLines;
264 unsigned *SourceLineCache = FileInfo->SourceLineCache;
265
266 // TODO: If this is performance sensitive, we could try doing simple radix
267 // type approaches to make good (tight?) initial guesses based on the
268 // assumption that all lines are the same average size.
269 unsigned *Pos = std::lower_bound(SourceLineCache, SourceLineCache+NumLines,
Chris Lattner9a13bde2006-06-21 04:57:09 +0000270 getFilePos(Loc)+1);
Chris Lattner22eb9722006-06-18 05:43:12 +0000271 return Pos-SourceLineCache;
272}
273
Chris Lattnerf6fd68a2006-06-26 01:48:23 +0000274/// getSourceFilePos - This method returns the *logical* offset from the start
275/// of the file that the specified SourceLocation represents. This returns
276/// the location of the *logical* character data, not the physical file
277/// position. In the case of macros, for example, this returns where the
278/// macro was instantiated, not where the characters for the macro can be
279/// found.
280unsigned SourceManager::getSourceFilePos(SourceLocation Loc) const {
281
282 // If this is a macro, we need to get the instantiation location.
283 const SrcMgr::FileIDInfo *FIDInfo = getFIDInfo(Loc.getFileID());
Chris Lattnerdc9f9bf2006-06-29 06:33:42 +0000284 while (FIDInfo->IDType == SrcMgr::FileIDInfo::MacroExpansion) {
285 Loc = FIDInfo->IncludeLoc;
286 FIDInfo = getFIDInfo(Loc.getFileID());
287 }
Chris Lattnerf6fd68a2006-06-26 01:48:23 +0000288
289 return getFilePos(Loc);
290}
291
292
Chris Lattner22eb9722006-06-18 05:43:12 +0000293/// PrintStats - Print statistics to stderr.
294///
295void SourceManager::PrintStats() const {
296 std::cerr << "\n*** Source Manager Stats:\n";
297 std::cerr << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
298 << " mem buffers mapped, " << FileIDs.size()
299 << " file ID's allocated.\n";
Chris Lattner30709b032006-06-21 03:01:55 +0000300 unsigned NumBuffers = 0, NumMacros = 0;
301 for (unsigned i = 0, e = FileIDs.size(); i != e; ++i) {
302 if (FileIDs[i].IDType == FileIDInfo::NormalBuffer)
303 ++NumBuffers;
304 else if (FileIDs[i].IDType == FileIDInfo::MacroExpansion)
305 ++NumMacros;
306 else
307 assert(0 && "Unknown FileID!");
308 }
309 std::cerr << " " << NumBuffers << " normal buffer FileID's, "
310 << NumMacros << " macro expansion FileID's.\n";
311
312
Chris Lattner22eb9722006-06-18 05:43:12 +0000313
314 unsigned NumLineNumsComputed = 0;
315 unsigned NumFileBytesMapped = 0;
316 for (std::map<const FileEntry *, FileInfo>::const_iterator I =
317 FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
318 NumLineNumsComputed += I->second.SourceLineCache != 0;
319 NumFileBytesMapped += I->second.Buffer->getBufferSize();
320 }
321 std::cerr << NumFileBytesMapped << " bytes of files mapped, "
322 << NumLineNumsComputed << " files with line #'s computed.\n";
323}