blob: 07565a34383c068b978a46424694a0383ab9c890 [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 Lattner30709b032006-06-21 03:01:55 +0000113/// createFileIDForMacroExp - Return a new FileID for a macro expansion at
114/// SourcePos, where the macro token character came from PhysicalFileID.
115///
116unsigned SourceManager::createFileIDForMacroExp(SourceLocation SourcePos,
117 unsigned PhysicalFileID) {
118 FileIDs.push_back(FileIDInfo::getMacroExpansion(SourcePos, PhysicalFileID));
119 return FileIDs.size();
120}
121
122
Chris Lattnerd01e2912006-06-18 16:22:51 +0000123/// getCharacterData - Return a pointer to the start of the specified location
124/// in the appropriate SourceBuffer. This returns null if it cannot be
125/// computed (e.g. invalid SourceLocation).
126const char *SourceManager::getCharacterData(SourceLocation SL) const {
127 if (unsigned FileID = SL.getFileID())
128 return getFileInfo(FileID)->Buffer->getBufferStart() + getFilePos(SL);
129 return 0;
130}
131
132
Chris Lattner22eb9722006-06-18 05:43:12 +0000133/// getColumnNumber - Return the column # for the specified include position.
134/// this is significantly cheaper to compute than the line number. This returns
135/// zero if the column number isn't known.
136unsigned SourceManager::getColumnNumber(SourceLocation IncludePos) const {
137 unsigned FileID = IncludePos.getFileID();
138 if (FileID == 0) return 0;
Chris Lattner30709b032006-06-21 03:01:55 +0000139
140 // If this is a macro, we need to get the instantiation location.
141 const SrcMgr::FileIDInfo *FIDInfo = getFIDInfo(FileID);
142 if (FIDInfo->IDType == SrcMgr::FileIDInfo::MacroExpansion) {
143 IncludePos = FIDInfo->IncludeLoc;
144 FileID = IncludePos.getFileID();
145 }
146
Chris Lattner22eb9722006-06-18 05:43:12 +0000147 unsigned FilePos = getFilePos(IncludePos);
Chris Lattner30709b032006-06-21 03:01:55 +0000148 const SourceBuffer *Buffer = getBuffer(FileID);
Chris Lattner22eb9722006-06-18 05:43:12 +0000149 const char *Buf = Buffer->getBufferStart();
150
151 unsigned LineStart = FilePos;
152 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
153 --LineStart;
154 return FilePos-LineStart+1;
155}
156
157/// getLineNumber - Given a SourceLocation, return the physical line number
158/// for the position indicated. This requires building and caching a table of
159/// line offsets for the SourceBuffer, so this is not cheap: use only when
160/// about to emit a diagnostic.
161unsigned SourceManager::getLineNumber(SourceLocation IncludePos) {
Chris Lattnerbb893c32006-06-21 03:27:29 +0000162 unsigned FileID = IncludePos.getFileID();
163 // If this is a macro, we need to get the instantiation location.
164 const SrcMgr::FileIDInfo *FIDInfo = getFIDInfo(FileID);
165 if (FIDInfo->IDType == SrcMgr::FileIDInfo::MacroExpansion) {
166 IncludePos = FIDInfo->IncludeLoc;
167 FileID = IncludePos.getFileID();
168 FIDInfo = getFIDInfo(FileID);
169 }
170
171 FileInfo *FileInfo = getFileInfo(FileID);
Chris Lattner22eb9722006-06-18 05:43:12 +0000172
173 // If this is the first use of line information for this buffer, compute the
174 /// SourceLineCache for it on demand.
175 if (FileInfo->SourceLineCache == 0) {
176 const SourceBuffer *Buffer = FileInfo->Buffer;
177
178 // Find the file offsets of all of the *physical* source lines. This does
179 // not look at trigraphs, escaped newlines, or anything else tricky.
180 std::vector<unsigned> LineOffsets;
181
182 // Line #1 starts at char 0.
183 LineOffsets.push_back(0);
184
185 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
186 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
187 unsigned Offs = 0;
188 while (1) {
189 // Skip over the contents of the line.
190 // TODO: Vectorize this? This is very performance sensitive for programs
191 // with lots of diagnostics.
192 const unsigned char *NextBuf = (const unsigned char *)Buf;
193 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
194 ++NextBuf;
195 Offs += NextBuf-Buf;
196 Buf = NextBuf;
197
198 if (Buf[0] == '\n' || Buf[0] == '\r') {
199 // If this is \n\r or \r\n, skip both characters.
200 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
201 ++Offs, ++Buf;
202 ++Offs, ++Buf;
203 LineOffsets.push_back(Offs);
204 } else {
205 // Otherwise, this is a null. If end of file, exit.
206 if (Buf == End) break;
207 // Otherwise, skip the null.
208 ++Offs, ++Buf;
209 }
210 }
211 LineOffsets.push_back(Offs);
212
213 // Copy the offsets into the FileInfo structure.
214 FileInfo->NumLines = LineOffsets.size();
215 FileInfo->SourceLineCache = new unsigned[LineOffsets.size()];
216 std::copy(LineOffsets.begin(), LineOffsets.end(),
217 FileInfo->SourceLineCache);
218 }
219
220 // Okay, we know we have a line number table. Do a binary search to find the
221 // line number that this character position lands on.
222 unsigned NumLines = FileInfo->NumLines;
223 unsigned *SourceLineCache = FileInfo->SourceLineCache;
224
225 // TODO: If this is performance sensitive, we could try doing simple radix
226 // type approaches to make good (tight?) initial guesses based on the
227 // assumption that all lines are the same average size.
228 unsigned *Pos = std::lower_bound(SourceLineCache, SourceLineCache+NumLines,
229 getFilePos(IncludePos)+1);
230 return Pos-SourceLineCache;
231}
232
233/// PrintStats - Print statistics to stderr.
234///
235void SourceManager::PrintStats() const {
236 std::cerr << "\n*** Source Manager Stats:\n";
237 std::cerr << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
238 << " mem buffers mapped, " << FileIDs.size()
239 << " file ID's allocated.\n";
Chris Lattner30709b032006-06-21 03:01:55 +0000240 unsigned NumBuffers = 0, NumMacros = 0;
241 for (unsigned i = 0, e = FileIDs.size(); i != e; ++i) {
242 if (FileIDs[i].IDType == FileIDInfo::NormalBuffer)
243 ++NumBuffers;
244 else if (FileIDs[i].IDType == FileIDInfo::MacroExpansion)
245 ++NumMacros;
246 else
247 assert(0 && "Unknown FileID!");
248 }
249 std::cerr << " " << NumBuffers << " normal buffer FileID's, "
250 << NumMacros << " macro expansion FileID's.\n";
251
252
Chris Lattner22eb9722006-06-18 05:43:12 +0000253
254 unsigned NumLineNumsComputed = 0;
255 unsigned NumFileBytesMapped = 0;
256 for (std::map<const FileEntry *, FileInfo>::const_iterator I =
257 FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
258 NumLineNumsComputed += I->second.SourceLineCache != 0;
259 NumFileBytesMapped += I->second.Buffer->getBufferSize();
260 }
261 std::cerr << NumFileBytesMapped << " bytes of files mapped, "
262 << NumLineNumsComputed << " files with line #'s computed.\n";
263}