blob: c22f66de111939782463e79eb585201c9f5d4e3d [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 Lattner22eb9722006-06-18 05:43:12 +000096 return FileIDs.size();
97 }
98
99 // Create one FileID for each chunk of the file.
100 unsigned Result = FileIDs.size()+1;
101
102 unsigned ChunkNo = 0;
103 while (1) {
Chris Lattner5f4b1ff2006-06-20 05:02:40 +0000104 FileIDs.push_back(FileIDInfo::getNormalBuffer(IncludePos, ChunkNo++, File));
Chris Lattner22eb9722006-06-18 05:43:12 +0000105
106 if (FileSize+1 < (1 << SourceLocation::FilePosBits)) break;
107 FileSize -= (1 << SourceLocation::FilePosBits);
108 }
109
110 return Result;
111}
112
Chris Lattner7d6a4f62006-06-30 06:10:08 +0000113/// getInstantiationLoc - Return a new SourceLocation that encodes the fact
114/// that a token from physloc PhysLoc should actually be referenced from
115/// InstantiationLoc.
116SourceLocation SourceManager::getInstantiationLoc(SourceLocation PhysLoc,
117 SourceLocation InstantLoc) {
Chris Lattner4c37a8c2006-06-30 06:15:08 +0000118 // Resolve InstantLoc down to a real logical location.
119 InstantLoc = getLogicalLoc(InstantLoc);
120
121 // Add a FileID for this. FIXME: should cache these!
122 FileIDs.push_back(FileIDInfo::getMacroExpansion(InstantLoc,
123 PhysLoc.getFileID()));
124 unsigned InstantiationFileID = FileIDs.size();
125 return SourceLocation(InstantiationFileID, PhysLoc.getRawFilePos());
Chris Lattner7d6a4f62006-06-30 06:10:08 +0000126}
127
128
Chris Lattner30709b032006-06-21 03:01:55 +0000129
Chris Lattnerd01e2912006-06-18 16:22:51 +0000130/// getCharacterData - Return a pointer to the start of the specified location
131/// in the appropriate SourceBuffer. This returns null if it cannot be
132/// computed (e.g. invalid SourceLocation).
133const char *SourceManager::getCharacterData(SourceLocation SL) const {
134 if (unsigned FileID = SL.getFileID())
135 return getFileInfo(FileID)->Buffer->getBufferStart() + getFilePos(SL);
136 return 0;
137}
138
Chris Lattner685730f2006-06-26 01:36:22 +0000139/// getIncludeLoc - Return the location of the #include for the specified
140/// FileID.
141SourceLocation SourceManager::getIncludeLoc(unsigned FileID) const {
142 const SrcMgr::FileIDInfo *FIDInfo = getFIDInfo(FileID);
143
144 // For Macros, the physical loc is specified by the MacroTokenFileID.
Chris Lattner2dffd2b2006-06-29 16:44:08 +0000145 if (FIDInfo->IDType == SrcMgr::FileIDInfo::MacroExpansion)
Chris Lattner685730f2006-06-26 01:36:22 +0000146 FIDInfo = &FileIDs[FIDInfo->u.MacroTokenFileID-1];
147
148 return FIDInfo->IncludeLoc;
149}
150
Chris Lattnerd01e2912006-06-18 16:22:51 +0000151
Chris Lattner22eb9722006-06-18 05:43:12 +0000152/// getColumnNumber - Return the column # for the specified include position.
153/// this is significantly cheaper to compute than the line number. This returns
154/// zero if the column number isn't known.
Chris Lattner9a13bde2006-06-21 04:57:09 +0000155unsigned SourceManager::getColumnNumber(SourceLocation Loc) const {
Chris Lattner2dffd2b2006-06-29 16:44:08 +0000156 Loc = getLogicalLoc(Loc);
Chris Lattner9a13bde2006-06-21 04:57:09 +0000157 unsigned FileID = Loc.getFileID();
Chris Lattner22eb9722006-06-18 05:43:12 +0000158 if (FileID == 0) return 0;
Chris Lattner30709b032006-06-21 03:01:55 +0000159
Chris Lattner9a13bde2006-06-21 04:57:09 +0000160 unsigned FilePos = getFilePos(Loc);
Chris Lattner30709b032006-06-21 03:01:55 +0000161 const SourceBuffer *Buffer = getBuffer(FileID);
Chris Lattner22eb9722006-06-18 05:43:12 +0000162 const char *Buf = Buffer->getBufferStart();
163
164 unsigned LineStart = FilePos;
165 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
166 --LineStart;
167 return FilePos-LineStart+1;
168}
169
Chris Lattner9a13bde2006-06-21 04:57:09 +0000170/// getSourceName - This method returns the name of the file or buffer that
171/// the SourceLocation specifies. This can be modified with #line directives,
172/// etc.
173std::string SourceManager::getSourceName(SourceLocation Loc) {
Chris Lattner2dffd2b2006-06-29 16:44:08 +0000174 Loc = getLogicalLoc(Loc);
Chris Lattner9a13bde2006-06-21 04:57:09 +0000175 unsigned FileID = Loc.getFileID();
176 if (FileID == 0) return "";
Chris Lattner2dffd2b2006-06-29 16:44:08 +0000177 return getFileInfo(FileID)->Buffer->getBufferIdentifier();
Chris Lattner9a13bde2006-06-21 04:57:09 +0000178}
179
180
Chris Lattner22eb9722006-06-18 05:43:12 +0000181/// getLineNumber - Given a SourceLocation, return the physical line number
182/// for the position indicated. This requires building and caching a table of
183/// line offsets for the SourceBuffer, so this is not cheap: use only when
184/// about to emit a diagnostic.
Chris Lattner9a13bde2006-06-21 04:57:09 +0000185unsigned SourceManager::getLineNumber(SourceLocation Loc) {
Chris Lattner2dffd2b2006-06-29 16:44:08 +0000186 Loc = getLogicalLoc(Loc);
187 FileInfo *FileInfo = getFileInfo(Loc.getFileID());
Chris Lattner22eb9722006-06-18 05:43:12 +0000188
189 // If this is the first use of line information for this buffer, compute the
190 /// SourceLineCache for it on demand.
191 if (FileInfo->SourceLineCache == 0) {
192 const SourceBuffer *Buffer = FileInfo->Buffer;
193
194 // Find the file offsets of all of the *physical* source lines. This does
195 // not look at trigraphs, escaped newlines, or anything else tricky.
196 std::vector<unsigned> LineOffsets;
197
198 // Line #1 starts at char 0.
199 LineOffsets.push_back(0);
200
201 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
202 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
203 unsigned Offs = 0;
204 while (1) {
205 // Skip over the contents of the line.
206 // TODO: Vectorize this? This is very performance sensitive for programs
207 // with lots of diagnostics.
208 const unsigned char *NextBuf = (const unsigned char *)Buf;
209 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
210 ++NextBuf;
211 Offs += NextBuf-Buf;
212 Buf = NextBuf;
213
214 if (Buf[0] == '\n' || Buf[0] == '\r') {
215 // If this is \n\r or \r\n, skip both characters.
216 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
217 ++Offs, ++Buf;
218 ++Offs, ++Buf;
219 LineOffsets.push_back(Offs);
220 } else {
221 // Otherwise, this is a null. If end of file, exit.
222 if (Buf == End) break;
223 // Otherwise, skip the null.
224 ++Offs, ++Buf;
225 }
226 }
227 LineOffsets.push_back(Offs);
228
229 // Copy the offsets into the FileInfo structure.
230 FileInfo->NumLines = LineOffsets.size();
231 FileInfo->SourceLineCache = new unsigned[LineOffsets.size()];
232 std::copy(LineOffsets.begin(), LineOffsets.end(),
233 FileInfo->SourceLineCache);
234 }
235
236 // Okay, we know we have a line number table. Do a binary search to find the
237 // line number that this character position lands on.
238 unsigned NumLines = FileInfo->NumLines;
239 unsigned *SourceLineCache = FileInfo->SourceLineCache;
240
241 // TODO: If this is performance sensitive, we could try doing simple radix
242 // type approaches to make good (tight?) initial guesses based on the
243 // assumption that all lines are the same average size.
244 unsigned *Pos = std::lower_bound(SourceLineCache, SourceLineCache+NumLines,
Chris Lattner9a13bde2006-06-21 04:57:09 +0000245 getFilePos(Loc)+1);
Chris Lattner22eb9722006-06-18 05:43:12 +0000246 return Pos-SourceLineCache;
247}
248
Chris Lattnerf6fd68a2006-06-26 01:48:23 +0000249/// getSourceFilePos - This method returns the *logical* offset from the start
250/// of the file that the specified SourceLocation represents. This returns
251/// the location of the *logical* character data, not the physical file
252/// position. In the case of macros, for example, this returns where the
253/// macro was instantiated, not where the characters for the macro can be
254/// found.
255unsigned SourceManager::getSourceFilePos(SourceLocation Loc) const {
256
257 // If this is a macro, we need to get the instantiation location.
258 const SrcMgr::FileIDInfo *FIDInfo = getFIDInfo(Loc.getFileID());
Chris Lattnerdc9f9bf2006-06-29 06:33:42 +0000259 while (FIDInfo->IDType == SrcMgr::FileIDInfo::MacroExpansion) {
260 Loc = FIDInfo->IncludeLoc;
261 FIDInfo = getFIDInfo(Loc.getFileID());
262 }
Chris Lattnerf6fd68a2006-06-26 01:48:23 +0000263
264 return getFilePos(Loc);
265}
266
267
Chris Lattner22eb9722006-06-18 05:43:12 +0000268/// PrintStats - Print statistics to stderr.
269///
270void SourceManager::PrintStats() const {
271 std::cerr << "\n*** Source Manager Stats:\n";
272 std::cerr << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
273 << " mem buffers mapped, " << FileIDs.size()
274 << " file ID's allocated.\n";
Chris Lattner30709b032006-06-21 03:01:55 +0000275 unsigned NumBuffers = 0, NumMacros = 0;
276 for (unsigned i = 0, e = FileIDs.size(); i != e; ++i) {
277 if (FileIDs[i].IDType == FileIDInfo::NormalBuffer)
278 ++NumBuffers;
279 else if (FileIDs[i].IDType == FileIDInfo::MacroExpansion)
280 ++NumMacros;
281 else
282 assert(0 && "Unknown FileID!");
283 }
284 std::cerr << " " << NumBuffers << " normal buffer FileID's, "
285 << NumMacros << " macro expansion FileID's.\n";
286
287
Chris Lattner22eb9722006-06-18 05:43:12 +0000288
289 unsigned NumLineNumsComputed = 0;
290 unsigned NumFileBytesMapped = 0;
291 for (std::map<const FileEntry *, FileInfo>::const_iterator I =
292 FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
293 NumLineNumsComputed += I->second.SourceLineCache != 0;
294 NumFileBytesMapped += I->second.Buffer->getBufferSize();
295 }
296 std::cerr << NumFileBytesMapped << " bytes of files mapped, "
297 << NumLineNumsComputed << " files with line #'s computed.\n";
298}