blob: b69ba53f7b2abbfae7f86b6b91f2326adee8454e [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//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner22eb9722006-06-18 05:43:12 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the SourceManager interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Basic/SourceManager.h"
Douglas Gregora07ebc52009-04-13 15:31:25 +000015#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregor802b7762010-03-15 22:54:52 +000016#include "clang/Basic/Diagnostic.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000017#include "clang/Basic/FileManager.h"
Chris Lattner8996fff2007-07-24 05:57:19 +000018#include "llvm/Support/Compiler.h"
Chris Lattner739e7392007-04-29 07:12:06 +000019#include "llvm/Support/MemoryBuffer.h"
Chris Lattner3441b4f2009-08-23 22:45:33 +000020#include "llvm/Support/raw_ostream.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000021#include "llvm/System/Path.h"
22#include <algorithm>
Douglas Gregor802b7762010-03-15 22:54:52 +000023#include <string>
Douglas Gregor0adf3182010-03-15 23:33:37 +000024#include <cstdio>
Douglas Gregor802b7762010-03-15 22:54:52 +000025
Chris Lattner22eb9722006-06-18 05:43:12 +000026using namespace clang;
Chris Lattner5f4b1ff2006-06-20 05:02:40 +000027using namespace SrcMgr;
Chris Lattner23b7eb62007-06-15 23:05:46 +000028using llvm::MemoryBuffer;
Chris Lattner22eb9722006-06-18 05:43:12 +000029
Chris Lattner153a0f12009-02-04 00:40:31 +000030//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +000031// SourceManager Helper Classes
Chris Lattner153a0f12009-02-04 00:40:31 +000032//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +000033
Douglas Gregor802b7762010-03-15 22:54:52 +000034struct BufferResult::FailureData {
35 const llvm::MemoryBuffer *Buffer;
36 const char *FileName;
37 std::string ErrorStr;
38};
39
40BufferResult::BufferResult(const BufferResult &Other) {
41 if (const llvm::MemoryBuffer *Buffer
42 = Other.Data.dyn_cast<const llvm::MemoryBuffer *>()) {
43 Data = Buffer;
44 return;
45 }
46
47 Data = new FailureData(*Other.Data.get<FailureData *>());
48}
49
50BufferResult::BufferResult(const char *FileName, llvm::StringRef ErrorStr,
51 const llvm::MemoryBuffer *Buffer) {
52 FailureData *FD = new FailureData;
53 FD->FileName = FileName;
54 FD->ErrorStr = ErrorStr;
55 FD->Buffer = Buffer;
56 Data = FD;
57}
58
59BufferResult::~BufferResult() {
60 if (FailureData *FD = Data.dyn_cast<FailureData *>())
61 delete FD;
62}
63
64bool BufferResult::isInvalid() const {
65 return Data.is<FailureData *>();
66}
67
68const llvm::MemoryBuffer *BufferResult::getBuffer(Diagnostic &Diags) const {
69 llvm::StringRef FileName;
70 std::string ErrorMsg;
71 const llvm::MemoryBuffer *Result = getBuffer(FileName, ErrorMsg);
72 if (!ErrorMsg.empty()) {
73 Diags.Report(diag::err_cannot_open_file)
74 << FileName << ErrorMsg;
75 }
76 return Result;
77}
78
79const llvm::MemoryBuffer *BufferResult::getBuffer(llvm::StringRef &FileName,
80 std::string &Error) const {
81 if (const llvm::MemoryBuffer *Buffer
82 = Data.dyn_cast<const llvm::MemoryBuffer *>())
83 return Buffer;
84
85 FailureData *Fail = Data.get<FailureData *>();
86 FileName = Fail->FileName;
87 Error = Fail->ErrorStr;
88 return Fail->Buffer;
89}
90
91BufferResult::operator const llvm::MemoryBuffer *() const {
92 llvm::StringRef FileName;
93 std::string ErrorMsg;
94 const llvm::MemoryBuffer *Result = getBuffer(FileName, ErrorMsg);
95 if (!ErrorMsg.empty()) {
96 fprintf(stderr, "error: cannot open file '%s': %s\n",
97 FileName.str().c_str(), ErrorMsg.c_str());
98 }
99
100 return Result;
101}
102
Ted Kremenekc08bca62007-10-30 21:08:08 +0000103ContentCache::~ContentCache() {
104 delete Buffer;
Chris Lattner22eb9722006-06-18 05:43:12 +0000105}
106
Ted Kremenek12c2af42009-01-06 01:55:26 +0000107/// getSizeBytesMapped - Returns the number of bytes actually mapped for
108/// this ContentCache. This can be 0 if the MemBuffer was not actually
109/// instantiated.
110unsigned ContentCache::getSizeBytesMapped() const {
111 return Buffer ? Buffer->getBufferSize() : 0;
112}
113
114/// getSize - Returns the size of the content encapsulated by this ContentCache.
115/// This can be the size of the source file or the size of an arbitrary
116/// scratch buffer. If the ContentCache encapsulates a source file, that
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000117/// file is not lazily brought in from disk to satisfy this query.
Ted Kremenek12c2af42009-01-06 01:55:26 +0000118unsigned ContentCache::getSize() const {
Ted Kremenek4a265242010-03-10 18:22:38 +0000119 return Buffer ? (unsigned) Buffer->getBufferSize()
120 : (unsigned) Entry->getSize();
Ted Kremenek12c2af42009-01-06 01:55:26 +0000121}
122
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000123void ContentCache::replaceBuffer(const llvm::MemoryBuffer *B) {
Douglas Gregor5f498832009-12-03 17:05:59 +0000124 assert(B != Buffer);
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000125
126 delete Buffer;
127 Buffer = B;
128}
129
Douglas Gregor802b7762010-03-15 22:54:52 +0000130BufferResult ContentCache::getBuffer() const {
Ted Kremenek763ea552009-01-06 22:43:04 +0000131 // Lazily create the Buffer for ContentCaches that wrap files.
132 if (!Buffer && Entry) {
Douglas Gregor802b7762010-03-15 22:54:52 +0000133 std::string ErrorStr;
134 struct stat FileInfo;
135 Buffer = MemoryBuffer::getFile(Entry->getName(), &ErrorStr,
136 Entry->getSize(), &FileInfo);
Daniel Dunbar7cea5f12009-12-06 05:43:36 +0000137
138 // If we were unable to open the file, then we are in an inconsistent
139 // situation where the content cache referenced a file which no longer
140 // exists. Most likely, we were using a stat cache with an invalid entry but
141 // the file could also have been removed during processing. Since we can't
142 // really deal with this situation, just create an empty buffer.
143 //
144 // FIXME: This is definitely not ideal, but our immediate clients can't
145 // currently handle returning a null entry here. Ideally we should detect
146 // that we are in an inconsistent situation and error out as quickly as
147 // possible.
148 if (!Buffer) {
149 const llvm::StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
150 Buffer = MemoryBuffer::getNewMemBuffer(Entry->getSize(), "<invalid>");
151 char *Ptr = const_cast<char*>(Buffer->getBufferStart());
152 for (unsigned i = 0, e = Entry->getSize(); i != e; ++i)
153 Ptr[i] = FillStr[i % FillStr.size()];
Douglas Gregor802b7762010-03-15 22:54:52 +0000154 return BufferResult(Entry->getName(), ErrorStr, Buffer);
155 } else {
156 // Check that the file's size and modification time is the same as
157 // in the file entry (which may have come from a stat cache).
158 // FIXME: Make these strings localizable.
159 if (FileInfo.st_size != Entry->getSize()) {
160 ErrorStr = "file has changed size since it was originally read";
161 return BufferResult(Entry->getName(), ErrorStr, Buffer);
162 } else if (FileInfo.st_mtime != Entry->getModificationTime()) {
163 ErrorStr = "file has been modified since it was originally read";
164 return BufferResult(Entry->getName(), ErrorStr, Buffer);
165 }
Daniel Dunbar7cea5f12009-12-06 05:43:36 +0000166 }
Ted Kremenek763ea552009-01-06 22:43:04 +0000167 }
Douglas Gregor802b7762010-03-15 22:54:52 +0000168
Ted Kremenek12c2af42009-01-06 01:55:26 +0000169 return Buffer;
170}
171
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000172unsigned LineTableInfo::getLineTableFilenameID(const char *Ptr, unsigned Len) {
173 // Look up the filename in the string table, returning the pre-existing value
174 // if it exists.
Mike Stump11289f42009-09-09 15:08:12 +0000175 llvm::StringMapEntry<unsigned> &Entry =
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000176 FilenameIDs.GetOrCreateValue(Ptr, Ptr+Len, ~0U);
177 if (Entry.getValue() != ~0U)
178 return Entry.getValue();
Mike Stump11289f42009-09-09 15:08:12 +0000179
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000180 // Otherwise, assign this the next available ID.
181 Entry.setValue(FilenamesByID.size());
182 FilenamesByID.push_back(&Entry);
183 return FilenamesByID.size()-1;
184}
185
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000186/// AddLineNote - Add a line note to the line table that indicates that there
187/// is a #line at the specified FID/Offset location which changes the presumed
188/// location to LineNo/FilenameID.
Chris Lattner153a0f12009-02-04 00:40:31 +0000189void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000190 unsigned LineNo, int FilenameID) {
Chris Lattner153a0f12009-02-04 00:40:31 +0000191 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump11289f42009-09-09 15:08:12 +0000192
Chris Lattner153a0f12009-02-04 00:40:31 +0000193 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
194 "Adding line entries out of order!");
Mike Stump11289f42009-09-09 15:08:12 +0000195
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000196 SrcMgr::CharacteristicKind Kind = SrcMgr::C_User;
Chris Lattner1c967782009-02-04 06:25:26 +0000197 unsigned IncludeOffset = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000198
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000199 if (!Entries.empty()) {
200 // If this is a '#line 4' after '#line 42 "foo.h"', make sure to remember
201 // that we are still in "foo.h".
202 if (FilenameID == -1)
203 FilenameID = Entries.back().FilenameID;
Mike Stump11289f42009-09-09 15:08:12 +0000204
Chris Lattner1c967782009-02-04 06:25:26 +0000205 // If we are after a line marker that switched us to system header mode, or
206 // that set #include information, preserve it.
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000207 Kind = Entries.back().FileKind;
Chris Lattner1c967782009-02-04 06:25:26 +0000208 IncludeOffset = Entries.back().IncludeOffset;
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000209 }
Mike Stump11289f42009-09-09 15:08:12 +0000210
Chris Lattner1c967782009-02-04 06:25:26 +0000211 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, Kind,
212 IncludeOffset));
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000213}
214
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000215/// AddLineNote This is the same as the previous version of AddLineNote, but is
216/// used for GNU line markers. If EntryExit is 0, then this doesn't change the
217/// presumed #include stack. If it is 1, this is a file entry, if it is 2 then
218/// this is a file exit. FileKind specifies whether this is a system header or
219/// extern C system header.
220void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
221 unsigned LineNo, int FilenameID,
222 unsigned EntryExit,
223 SrcMgr::CharacteristicKind FileKind) {
224 assert(FilenameID != -1 && "Unspecified filename should use other accessor");
Mike Stump11289f42009-09-09 15:08:12 +0000225
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000226 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump11289f42009-09-09 15:08:12 +0000227
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000228 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
229 "Adding line entries out of order!");
230
Chris Lattner1c967782009-02-04 06:25:26 +0000231 unsigned IncludeOffset = 0;
232 if (EntryExit == 0) { // No #include stack change.
233 IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
234 } else if (EntryExit == 1) {
235 IncludeOffset = Offset-1;
236 } else if (EntryExit == 2) {
237 assert(!Entries.empty() && Entries.back().IncludeOffset &&
238 "PPDirectives should have caught case when popping empty include stack");
Mike Stump11289f42009-09-09 15:08:12 +0000239
Chris Lattner1c967782009-02-04 06:25:26 +0000240 // Get the include loc of the last entries' include loc as our include loc.
241 IncludeOffset = 0;
242 if (const LineEntry *PrevEntry =
243 FindNearestLineEntry(FID, Entries.back().IncludeOffset))
244 IncludeOffset = PrevEntry->IncludeOffset;
245 }
Mike Stump11289f42009-09-09 15:08:12 +0000246
Chris Lattner1c967782009-02-04 06:25:26 +0000247 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
248 IncludeOffset));
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000249}
250
251
Chris Lattnerd4293922009-02-04 01:55:42 +0000252/// FindNearestLineEntry - Find the line entry nearest to FID that is before
253/// it. If there is no line entry before Offset in FID, return null.
Mike Stump11289f42009-09-09 15:08:12 +0000254const LineEntry *LineTableInfo::FindNearestLineEntry(unsigned FID,
Chris Lattnerd4293922009-02-04 01:55:42 +0000255 unsigned Offset) {
256 const std::vector<LineEntry> &Entries = LineEntries[FID];
257 assert(!Entries.empty() && "No #line entries for this FID after all!");
258
Chris Lattner334a2ad2009-02-04 04:46:59 +0000259 // It is very common for the query to be after the last #line, check this
260 // first.
261 if (Entries.back().FileOffset <= Offset)
262 return &Entries.back();
Chris Lattnerd4293922009-02-04 01:55:42 +0000263
Chris Lattner334a2ad2009-02-04 04:46:59 +0000264 // Do a binary search to find the maximal element that is still before Offset.
265 std::vector<LineEntry>::const_iterator I =
266 std::upper_bound(Entries.begin(), Entries.end(), Offset);
267 if (I == Entries.begin()) return 0;
268 return &*--I;
Chris Lattnerd4293922009-02-04 01:55:42 +0000269}
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000270
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000271/// \brief Add a new line entry that has already been encoded into
272/// the internal representation of the line table.
Mike Stump11289f42009-09-09 15:08:12 +0000273void LineTableInfo::AddEntry(unsigned FID,
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000274 const std::vector<LineEntry> &Entries) {
275 LineEntries[FID] = Entries;
276}
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000277
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000278/// getLineTableFilenameID - Return the uniqued ID for the specified filename.
Mike Stump11289f42009-09-09 15:08:12 +0000279///
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000280unsigned SourceManager::getLineTableFilenameID(const char *Ptr, unsigned Len) {
281 if (LineTable == 0)
282 LineTable = new LineTableInfo();
283 return LineTable->getLineTableFilenameID(Ptr, Len);
284}
285
286
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000287/// AddLineNote - Add a line note to the line table for the FileID and offset
288/// specified by Loc. If FilenameID is -1, it is considered to be
289/// unspecified.
290void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
291 int FilenameID) {
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000292 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000293
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000294 const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile();
295
296 // Remember that this file has #line directives now if it doesn't already.
297 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump11289f42009-09-09 15:08:12 +0000298
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000299 if (LineTable == 0)
300 LineTable = new LineTableInfo();
Chris Lattner153a0f12009-02-04 00:40:31 +0000301 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID);
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000302}
303
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000304/// AddLineNote - Add a GNU line marker to the line table.
305void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
306 int FilenameID, bool IsFileEntry,
307 bool IsFileExit, bool IsSystemHeader,
308 bool IsExternCHeader) {
309 // If there is no filename and no flags, this is treated just like a #line,
310 // which does not change the flags of the previous line marker.
311 if (FilenameID == -1) {
312 assert(!IsFileEntry && !IsFileExit && !IsSystemHeader && !IsExternCHeader &&
313 "Can't set flags without setting the filename!");
314 return AddLineNote(Loc, LineNo, FilenameID);
315 }
Mike Stump11289f42009-09-09 15:08:12 +0000316
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000317 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
318 const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile();
Mike Stump11289f42009-09-09 15:08:12 +0000319
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000320 // Remember that this file has #line directives now if it doesn't already.
321 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump11289f42009-09-09 15:08:12 +0000322
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000323 if (LineTable == 0)
324 LineTable = new LineTableInfo();
Mike Stump11289f42009-09-09 15:08:12 +0000325
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000326 SrcMgr::CharacteristicKind FileKind;
327 if (IsExternCHeader)
328 FileKind = SrcMgr::C_ExternCSystem;
329 else if (IsSystemHeader)
330 FileKind = SrcMgr::C_System;
331 else
332 FileKind = SrcMgr::C_User;
Mike Stump11289f42009-09-09 15:08:12 +0000333
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000334 unsigned EntryExit = 0;
335 if (IsFileEntry)
336 EntryExit = 1;
337 else if (IsFileExit)
338 EntryExit = 2;
Mike Stump11289f42009-09-09 15:08:12 +0000339
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000340 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID,
341 EntryExit, FileKind);
342}
343
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000344LineTableInfo &SourceManager::getLineTable() {
345 if (LineTable == 0)
346 LineTable = new LineTableInfo();
347 return *LineTable;
348}
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000349
Chris Lattner153a0f12009-02-04 00:40:31 +0000350//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +0000351// Private 'Create' methods.
Chris Lattner153a0f12009-02-04 00:40:31 +0000352//===----------------------------------------------------------------------===//
Ted Kremenek12c2af42009-01-06 01:55:26 +0000353
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000354SourceManager::~SourceManager() {
355 delete LineTable;
Mike Stump11289f42009-09-09 15:08:12 +0000356
Chris Lattnerc8233df2009-02-03 07:30:45 +0000357 // Delete FileEntry objects corresponding to content caches. Since the actual
358 // content cache objects are bump pointer allocated, we just have to run the
359 // dtors, but we call the deallocate method for completeness.
360 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
361 MemBufferInfos[i]->~ContentCache();
362 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
363 }
364 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
365 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
366 I->second->~ContentCache();
367 ContentCacheAlloc.Deallocate(I->second);
368 }
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000369}
370
371void SourceManager::clearIDTables() {
372 MainFileID = FileID();
373 SLocEntryTable.clear();
374 LastLineNoFileIDQuery = FileID();
375 LastLineNoContentCache = 0;
376 LastFileIDLookup = FileID();
Mike Stump11289f42009-09-09 15:08:12 +0000377
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000378 if (LineTable)
379 LineTable->clear();
Mike Stump11289f42009-09-09 15:08:12 +0000380
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000381 // Use up FileID #0 as an invalid instantiation.
382 NextOffset = 0;
Chris Lattner9dc9c202009-02-15 20:52:18 +0000383 createInstantiationLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000384}
385
Chris Lattner4fa23622009-01-26 00:43:02 +0000386/// getOrCreateContentCache - Create or return a cached ContentCache for the
387/// specified file.
388const ContentCache *
389SourceManager::getOrCreateContentCache(const FileEntry *FileEnt) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000390 assert(FileEnt && "Didn't specify a file entry to use?");
Mike Stump11289f42009-09-09 15:08:12 +0000391
Chris Lattner22eb9722006-06-18 05:43:12 +0000392 // Do we already have information about this file?
Chris Lattnerc8233df2009-02-03 07:30:45 +0000393 ContentCache *&Entry = FileInfos[FileEnt];
394 if (Entry) return Entry;
Mike Stump11289f42009-09-09 15:08:12 +0000395
Chris Lattner9be4f6d2009-02-03 07:41:46 +0000396 // Nope, create a new Cache entry. Make sure it is at least 8-byte aligned
397 // so that FileInfo can use the low 3 bits of the pointer for its own
398 // nefarious purposes.
399 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
400 EntryAlign = std::max(8U, EntryAlign);
401 Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattnerc8233df2009-02-03 07:30:45 +0000402 new (Entry) ContentCache(FileEnt);
403 return Entry;
Chris Lattner22eb9722006-06-18 05:43:12 +0000404}
405
406
Ted Kremenek08bed092007-10-31 17:53:38 +0000407/// createMemBufferContentCache - Create a new ContentCache for the specified
408/// memory buffer. This does no caching.
Ted Kremenekc08bca62007-10-30 21:08:08 +0000409const ContentCache*
410SourceManager::createMemBufferContentCache(const MemoryBuffer *Buffer) {
Chris Lattner9be4f6d2009-02-03 07:41:46 +0000411 // Add a new ContentCache to the MemBufferInfos list and return it. Make sure
412 // it is at least 8-byte aligned so that FileInfo can use the low 3 bits of
413 // the pointer for its own nefarious purposes.
414 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
415 EntryAlign = std::max(8U, EntryAlign);
416 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattnerc8233df2009-02-03 07:30:45 +0000417 new (Entry) ContentCache();
418 MemBufferInfos.push_back(Entry);
419 Entry->setBuffer(Buffer);
420 return Entry;
Chris Lattner22eb9722006-06-18 05:43:12 +0000421}
422
Douglas Gregor258ae542009-04-27 06:38:32 +0000423void SourceManager::PreallocateSLocEntries(ExternalSLocEntrySource *Source,
424 unsigned NumSLocEntries,
425 unsigned NextOffset) {
426 ExternalSLocEntries = Source;
427 this->NextOffset = NextOffset;
428 SLocEntryLoaded.resize(NumSLocEntries + 1);
429 SLocEntryLoaded[0] = true;
430 SLocEntryTable.resize(SLocEntryTable.size() + NumSLocEntries);
431}
432
Douglas Gregor0bc12932009-04-27 21:28:04 +0000433void SourceManager::ClearPreallocatedSLocEntries() {
434 unsigned I = 0;
435 for (unsigned N = SLocEntryLoaded.size(); I != N; ++I)
436 if (!SLocEntryLoaded[I])
437 break;
438
439 // We've already loaded all preallocated source location entries.
440 if (I == SLocEntryLoaded.size())
441 return;
442
443 // Remove everything from location I onward.
444 SLocEntryTable.resize(I);
445 SLocEntryLoaded.clear();
446 ExternalSLocEntries = 0;
447}
448
Douglas Gregor258ae542009-04-27 06:38:32 +0000449
Chris Lattner4fa23622009-01-26 00:43:02 +0000450//===----------------------------------------------------------------------===//
451// Methods to create new FileID's and instantiations.
452//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000453
Nico Weber378c5532008-09-29 00:25:48 +0000454/// createFileID - Create a new fileID for the specified ContentCache and
Ted Kremeneke26f3c52007-10-30 22:57:35 +0000455/// include position. This works regardless of whether the ContentCache
456/// corresponds to a file or some other input source.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000457FileID SourceManager::createFileID(const ContentCache *File,
Chris Lattner4fa23622009-01-26 00:43:02 +0000458 SourceLocation IncludePos,
Douglas Gregor258ae542009-04-27 06:38:32 +0000459 SrcMgr::CharacteristicKind FileCharacter,
460 unsigned PreallocatedID,
461 unsigned Offset) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000462 if (PreallocatedID) {
463 // If we're filling in a preallocated ID, just load in the file
464 // entry and return.
Mike Stump11289f42009-09-09 15:08:12 +0000465 assert(PreallocatedID < SLocEntryLoaded.size() &&
Douglas Gregor258ae542009-04-27 06:38:32 +0000466 "Preallocate ID out-of-range");
Mike Stump11289f42009-09-09 15:08:12 +0000467 assert(!SLocEntryLoaded[PreallocatedID] &&
Douglas Gregor258ae542009-04-27 06:38:32 +0000468 "Source location entry already loaded");
469 assert(Offset && "Preallocate source location cannot have zero offset");
Mike Stump11289f42009-09-09 15:08:12 +0000470 SLocEntryTable[PreallocatedID]
Douglas Gregor258ae542009-04-27 06:38:32 +0000471 = SLocEntry::get(Offset, FileInfo::get(IncludePos, File, FileCharacter));
472 SLocEntryLoaded[PreallocatedID] = true;
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +0000473 FileID FID = FileID::get(PreallocatedID);
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +0000474 return LastFileIDLookup = FID;
Douglas Gregor258ae542009-04-27 06:38:32 +0000475 }
476
Mike Stump11289f42009-09-09 15:08:12 +0000477 SLocEntryTable.push_back(SLocEntry::get(NextOffset,
Chris Lattner4fa23622009-01-26 00:43:02 +0000478 FileInfo::get(IncludePos, File,
479 FileCharacter)));
Ted Kremenek12c2af42009-01-06 01:55:26 +0000480 unsigned FileSize = File->getSize();
Chris Lattner4fa23622009-01-26 00:43:02 +0000481 assert(NextOffset+FileSize+1 > NextOffset && "Ran out of source locations!");
482 NextOffset += FileSize+1;
Mike Stump11289f42009-09-09 15:08:12 +0000483
Chris Lattner4fa23622009-01-26 00:43:02 +0000484 // Set LastFileIDLookup to the newly created file. The next getFileID call is
485 // almost guaranteed to be from that file.
Argyrios Kyrtzidis0152c6c2009-06-23 00:42:06 +0000486 FileID FID = FileID::get(SLocEntryTable.size()-1);
Argyrios Kyrtzidis0152c6c2009-06-23 00:42:06 +0000487 return LastFileIDLookup = FID;
Chris Lattner22eb9722006-06-18 05:43:12 +0000488}
489
Chris Lattner4fa23622009-01-26 00:43:02 +0000490/// createInstantiationLoc - Return a new SourceLocation that encodes the fact
Chris Lattner53e384f2009-01-16 07:00:02 +0000491/// that a token from SpellingLoc should actually be referenced from
Chris Lattner7d6a4f62006-06-30 06:10:08 +0000492/// InstantiationLoc.
Chris Lattner4fa23622009-01-26 00:43:02 +0000493SourceLocation SourceManager::createInstantiationLoc(SourceLocation SpellingLoc,
Chris Lattner9dc9c202009-02-15 20:52:18 +0000494 SourceLocation ILocStart,
495 SourceLocation ILocEnd,
Douglas Gregor258ae542009-04-27 06:38:32 +0000496 unsigned TokLength,
497 unsigned PreallocatedID,
498 unsigned Offset) {
Chris Lattner9dc9c202009-02-15 20:52:18 +0000499 InstantiationInfo II = InstantiationInfo::get(ILocStart,ILocEnd, SpellingLoc);
Douglas Gregor258ae542009-04-27 06:38:32 +0000500 if (PreallocatedID) {
501 // If we're filling in a preallocated ID, just load in the
502 // instantiation entry and return.
Mike Stump11289f42009-09-09 15:08:12 +0000503 assert(PreallocatedID < SLocEntryLoaded.size() &&
Douglas Gregor258ae542009-04-27 06:38:32 +0000504 "Preallocate ID out-of-range");
Mike Stump11289f42009-09-09 15:08:12 +0000505 assert(!SLocEntryLoaded[PreallocatedID] &&
Douglas Gregor258ae542009-04-27 06:38:32 +0000506 "Source location entry already loaded");
507 assert(Offset && "Preallocate source location cannot have zero offset");
508 SLocEntryTable[PreallocatedID] = SLocEntry::get(Offset, II);
509 SLocEntryLoaded[PreallocatedID] = true;
510 return SourceLocation::getMacroLoc(Offset);
511 }
Chris Lattner9dc9c202009-02-15 20:52:18 +0000512 SLocEntryTable.push_back(SLocEntry::get(NextOffset, II));
Chris Lattner4fa23622009-01-26 00:43:02 +0000513 assert(NextOffset+TokLength+1 > NextOffset && "Ran out of source locations!");
514 NextOffset += TokLength+1;
515 return SourceLocation::getMacroLoc(NextOffset-(TokLength+1));
Chris Lattner7d6a4f62006-06-30 06:10:08 +0000516}
517
Douglas Gregor802b7762010-03-15 22:54:52 +0000518BufferResult SourceManager::getMemoryBufferForFile(const FileEntry *File) {
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000519 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
Douglas Gregor802b7762010-03-15 22:54:52 +0000520 assert(IR && "getOrCreateContentCache() cannot return NULL");
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000521 return IR->getBuffer();
522}
523
524bool SourceManager::overrideFileContents(const FileEntry *SourceFile,
525 const llvm::MemoryBuffer *Buffer) {
526 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
527 if (IR == 0)
528 return true;
529
530 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer);
531 return false;
532}
533
Chris Lattnerd32480d2009-01-17 06:22:33 +0000534std::pair<const char*, const char*>
Douglas Gregor802b7762010-03-15 22:54:52 +0000535SourceManager::getBufferData(FileID FID, llvm::StringRef &FileName,
536 std::string &Error) const {
537 const llvm::MemoryBuffer *Buf = getBuffer(FID).getBuffer(FileName, Error);
538 if (!Error.empty())
539 return std::make_pair((const char *)0, (const char *)0);
Chris Lattnerd32480d2009-01-17 06:22:33 +0000540 return std::make_pair(Buf->getBufferStart(), Buf->getBufferEnd());
541}
542
Douglas Gregor802b7762010-03-15 22:54:52 +0000543std::pair<const char*, const char*>
544SourceManager::getBufferData(FileID FID, Diagnostic &Diags) const {
545 const llvm::MemoryBuffer *Buf = getBuffer(FID).getBuffer(Diags);
546 if (!Buf)
547 return std::make_pair((const char *)0, (const char *)0);
548 return std::make_pair(Buf->getBufferStart(), Buf->getBufferEnd());
549}
Chris Lattnerd32480d2009-01-17 06:22:33 +0000550
Chris Lattner153a0f12009-02-04 00:40:31 +0000551//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +0000552// SourceLocation manipulation methods.
Chris Lattner153a0f12009-02-04 00:40:31 +0000553//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +0000554
555/// getFileIDSlow - Return the FileID for a SourceLocation. This is a very hot
556/// method that is used for all SourceManager queries that start with a
557/// SourceLocation object. It is responsible for finding the entry in
558/// SLocEntryTable which contains the specified location.
559///
560FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
561 assert(SLocOffset && "Invalid FileID");
Mike Stump11289f42009-09-09 15:08:12 +0000562
Chris Lattner4fa23622009-01-26 00:43:02 +0000563 // After the first and second level caches, I see two common sorts of
564 // behavior: 1) a lot of searched FileID's are "near" the cached file location
565 // or are "near" the cached instantiation location. 2) others are just
566 // completely random and may be a very long way away.
567 //
568 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
569 // then we fall back to a less cache efficient, but more scalable, binary
570 // search to find the location.
Mike Stump11289f42009-09-09 15:08:12 +0000571
Chris Lattner4fa23622009-01-26 00:43:02 +0000572 // See if this is near the file point - worst case we start scanning from the
573 // most newly created FileID.
574 std::vector<SrcMgr::SLocEntry>::const_iterator I;
Mike Stump11289f42009-09-09 15:08:12 +0000575
Chris Lattner4fa23622009-01-26 00:43:02 +0000576 if (SLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
577 // Neither loc prunes our search.
578 I = SLocEntryTable.end();
579 } else {
580 // Perhaps it is near the file point.
581 I = SLocEntryTable.begin()+LastFileIDLookup.ID;
582 }
583
584 // Find the FileID that contains this. "I" is an iterator that points to a
585 // FileID whose offset is known to be larger than SLocOffset.
586 unsigned NumProbes = 0;
587 while (1) {
588 --I;
Douglas Gregor258ae542009-04-27 06:38:32 +0000589 if (ExternalSLocEntries)
590 getSLocEntry(FileID::get(I - SLocEntryTable.begin()));
Chris Lattner4fa23622009-01-26 00:43:02 +0000591 if (I->getOffset() <= SLocOffset) {
592#if 0
593 printf("lin %d -> %d [%s] %d %d\n", SLocOffset,
594 I-SLocEntryTable.begin(),
595 I->isInstantiation() ? "inst" : "file",
596 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
597#endif
598 FileID Res = FileID::get(I-SLocEntryTable.begin());
Douglas Gregor258ae542009-04-27 06:38:32 +0000599
Chris Lattner4fa23622009-01-26 00:43:02 +0000600 // If this isn't an instantiation, remember it. We have good locality
601 // across FileID lookups.
602 if (!I->isInstantiation())
603 LastFileIDLookup = Res;
604 NumLinearScans += NumProbes+1;
605 return Res;
606 }
607 if (++NumProbes == 8)
608 break;
609 }
Mike Stump11289f42009-09-09 15:08:12 +0000610
Chris Lattner4fa23622009-01-26 00:43:02 +0000611 // Convert "I" back into an index. We know that it is an entry whose index is
612 // larger than the offset we are looking for.
613 unsigned GreaterIndex = I-SLocEntryTable.begin();
614 // LessIndex - This is the lower bound of the range that we're searching.
615 // We know that the offset corresponding to the FileID is is less than
616 // SLocOffset.
617 unsigned LessIndex = 0;
618 NumProbes = 0;
619 while (1) {
620 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
Douglas Gregor258ae542009-04-27 06:38:32 +0000621 unsigned MidOffset = getSLocEntry(FileID::get(MiddleIndex)).getOffset();
Mike Stump11289f42009-09-09 15:08:12 +0000622
Chris Lattner4fa23622009-01-26 00:43:02 +0000623 ++NumProbes;
Mike Stump11289f42009-09-09 15:08:12 +0000624
Chris Lattner4fa23622009-01-26 00:43:02 +0000625 // If the offset of the midpoint is too large, chop the high side of the
626 // range to the midpoint.
627 if (MidOffset > SLocOffset) {
628 GreaterIndex = MiddleIndex;
629 continue;
630 }
Mike Stump11289f42009-09-09 15:08:12 +0000631
Chris Lattner4fa23622009-01-26 00:43:02 +0000632 // If the middle index contains the value, succeed and return.
633 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
634#if 0
635 printf("bin %d -> %d [%s] %d %d\n", SLocOffset,
636 I-SLocEntryTable.begin(),
637 I->isInstantiation() ? "inst" : "file",
638 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
639#endif
640 FileID Res = FileID::get(MiddleIndex);
641
642 // If this isn't an instantiation, remember it. We have good locality
643 // across FileID lookups.
644 if (!I->isInstantiation())
645 LastFileIDLookup = Res;
646 NumBinaryProbes += NumProbes;
647 return Res;
648 }
Mike Stump11289f42009-09-09 15:08:12 +0000649
Chris Lattner4fa23622009-01-26 00:43:02 +0000650 // Otherwise, move the low-side up to the middle index.
651 LessIndex = MiddleIndex;
652 }
653}
654
Chris Lattner659ac5f2009-01-26 20:04:19 +0000655SourceLocation SourceManager::
656getInstantiationLocSlowCase(SourceLocation Loc) const {
657 do {
Chris Lattner5647d312010-02-12 19:31:35 +0000658 // Note: If Loc indicates an offset into a token that came from a macro
659 // expansion (e.g. the 5th character of the token) we do not want to add
660 // this offset when going to the instantiation location. The instatiation
661 // location is the macro invocation, which the offset has nothing to do
662 // with. This is unlike when we get the spelling loc, because the offset
663 // directly correspond to the token whose spelling we're inspecting.
664 Loc = getSLocEntry(getFileID(Loc)).getInstantiation()
Chris Lattner9dc9c202009-02-15 20:52:18 +0000665 .getInstantiationLocStart();
Chris Lattner659ac5f2009-01-26 20:04:19 +0000666 } while (!Loc.isFileID());
667
668 return Loc;
669}
670
671SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
672 do {
673 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
674 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
675 Loc = Loc.getFileLocWithOffset(LocInfo.second);
676 } while (!Loc.isFileID());
677 return Loc;
678}
679
680
Chris Lattner4fa23622009-01-26 00:43:02 +0000681std::pair<FileID, unsigned>
682SourceManager::getDecomposedInstantiationLocSlowCase(const SrcMgr::SLocEntry *E,
683 unsigned Offset) const {
684 // If this is an instantiation record, walk through all the instantiation
685 // points.
686 FileID FID;
687 SourceLocation Loc;
688 do {
Chris Lattner9dc9c202009-02-15 20:52:18 +0000689 Loc = E->getInstantiation().getInstantiationLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000690
Chris Lattner4fa23622009-01-26 00:43:02 +0000691 FID = getFileID(Loc);
692 E = &getSLocEntry(FID);
693 Offset += Loc.getOffset()-E->getOffset();
Chris Lattner31af4e02009-01-26 19:41:58 +0000694 } while (!Loc.isFileID());
Mike Stump11289f42009-09-09 15:08:12 +0000695
Chris Lattner4fa23622009-01-26 00:43:02 +0000696 return std::make_pair(FID, Offset);
697}
698
699std::pair<FileID, unsigned>
700SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
701 unsigned Offset) const {
Chris Lattner31af4e02009-01-26 19:41:58 +0000702 // If this is an instantiation record, walk through all the instantiation
703 // points.
704 FileID FID;
705 SourceLocation Loc;
706 do {
707 Loc = E->getInstantiation().getSpellingLoc();
Mike Stump11289f42009-09-09 15:08:12 +0000708
Chris Lattner31af4e02009-01-26 19:41:58 +0000709 FID = getFileID(Loc);
710 E = &getSLocEntry(FID);
711 Offset += Loc.getOffset()-E->getOffset();
712 } while (!Loc.isFileID());
Mike Stump11289f42009-09-09 15:08:12 +0000713
Chris Lattner4fa23622009-01-26 00:43:02 +0000714 return std::make_pair(FID, Offset);
715}
716
Chris Lattner8ad52d52009-02-17 08:04:48 +0000717/// getImmediateSpellingLoc - Given a SourceLocation object, return the
718/// spelling location referenced by the ID. This is the first level down
719/// towards the place where the characters that make up the lexed token can be
720/// found. This should not generally be used by clients.
721SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
722 if (Loc.isFileID()) return Loc;
723 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
724 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
725 return Loc.getFileLocWithOffset(LocInfo.second);
726}
727
728
Chris Lattner9dc9c202009-02-15 20:52:18 +0000729/// getImmediateInstantiationRange - Loc is required to be an instantiation
730/// location. Return the start/end of the instantiation information.
731std::pair<SourceLocation,SourceLocation>
732SourceManager::getImmediateInstantiationRange(SourceLocation Loc) const {
733 assert(Loc.isMacroID() && "Not an instantiation loc!");
734 const InstantiationInfo &II = getSLocEntry(getFileID(Loc)).getInstantiation();
735 return II.getInstantiationLocRange();
736}
737
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000738/// getInstantiationRange - Given a SourceLocation object, return the
739/// range of tokens covered by the instantiation in the ultimate file.
740std::pair<SourceLocation,SourceLocation>
741SourceManager::getInstantiationRange(SourceLocation Loc) const {
742 if (Loc.isFileID()) return std::make_pair(Loc, Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000743
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000744 std::pair<SourceLocation,SourceLocation> Res =
745 getImmediateInstantiationRange(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000746
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000747 // Fully resolve the start and end locations to their ultimate instantiation
748 // points.
749 while (!Res.first.isFileID())
750 Res.first = getImmediateInstantiationRange(Res.first).first;
751 while (!Res.second.isFileID())
752 Res.second = getImmediateInstantiationRange(Res.second).second;
753 return Res;
754}
755
Chris Lattner9dc9c202009-02-15 20:52:18 +0000756
Chris Lattner4fa23622009-01-26 00:43:02 +0000757
758//===----------------------------------------------------------------------===//
759// Queries about the code at a SourceLocation.
760//===----------------------------------------------------------------------===//
Chris Lattner30709b032006-06-21 03:01:55 +0000761
Chris Lattnerd01e2912006-06-18 16:22:51 +0000762/// getCharacterData - Return a pointer to the start of the specified location
Chris Lattner739e7392007-04-29 07:12:06 +0000763/// in the appropriate MemoryBuffer.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000764const char *SourceManager::getCharacterData(SourceLocation SL) const {
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000765 // Note that this is a hot function in the getSpelling() path, which is
766 // heavily used by -E mode.
Chris Lattner4fa23622009-01-26 00:43:02 +0000767 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
Mike Stump11289f42009-09-09 15:08:12 +0000768
Ted Kremenek12c2af42009-01-06 01:55:26 +0000769 // Note that calling 'getBuffer()' may lazily page in a source file.
Chris Lattner4fa23622009-01-26 00:43:02 +0000770 return getSLocEntry(LocInfo.first).getFile().getContentCache()
771 ->getBuffer()->getBufferStart() + LocInfo.second;
Chris Lattnerd01e2912006-06-18 16:22:51 +0000772}
773
Chris Lattner685730f2006-06-26 01:36:22 +0000774
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000775/// getColumnNumber - Return the column # for the specified file position.
Chris Lattnere4ad4172009-02-04 00:55:58 +0000776/// this is significantly cheaper to compute than the line number.
777unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos) const {
778 const char *Buf = getBuffer(FID)->getBufferStart();
Mike Stump11289f42009-09-09 15:08:12 +0000779
Chris Lattner22eb9722006-06-18 05:43:12 +0000780 unsigned LineStart = FilePos;
781 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
782 --LineStart;
783 return FilePos-LineStart+1;
784}
785
Chris Lattnere4ad4172009-02-04 00:55:58 +0000786unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc) const {
Chris Lattner88ea93e2009-02-04 01:06:56 +0000787 if (Loc.isInvalid()) return 0;
Chris Lattnere4ad4172009-02-04 00:55:58 +0000788 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
789 return getColumnNumber(LocInfo.first, LocInfo.second);
790}
791
792unsigned SourceManager::getInstantiationColumnNumber(SourceLocation Loc) const {
Chris Lattner88ea93e2009-02-04 01:06:56 +0000793 if (Loc.isInvalid()) return 0;
Chris Lattnere4ad4172009-02-04 00:55:58 +0000794 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
795 return getColumnNumber(LocInfo.first, LocInfo.second);
796}
797
798
799
Benjamin Kramer5e738282009-11-14 16:36:57 +0000800static DISABLE_INLINE void ComputeLineNumbers(ContentCache* FI,
801 llvm::BumpPtrAllocator &Alloc);
Mike Stump11289f42009-09-09 15:08:12 +0000802static void ComputeLineNumbers(ContentCache* FI, llvm::BumpPtrAllocator &Alloc){
Ted Kremenek12c2af42009-01-06 01:55:26 +0000803 // Note that calling 'getBuffer()' may lazily page in the file.
804 const MemoryBuffer *Buffer = FI->getBuffer();
Mike Stump11289f42009-09-09 15:08:12 +0000805
Chris Lattner8996fff2007-07-24 05:57:19 +0000806 // Find the file offsets of all of the *physical* source lines. This does
807 // not look at trigraphs, escaped newlines, or anything else tricky.
808 std::vector<unsigned> LineOffsets;
Mike Stump11289f42009-09-09 15:08:12 +0000809
Chris Lattner8996fff2007-07-24 05:57:19 +0000810 // Line #1 starts at char 0.
811 LineOffsets.push_back(0);
Mike Stump11289f42009-09-09 15:08:12 +0000812
Chris Lattner8996fff2007-07-24 05:57:19 +0000813 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
814 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
815 unsigned Offs = 0;
816 while (1) {
817 // Skip over the contents of the line.
818 // TODO: Vectorize this? This is very performance sensitive for programs
819 // with lots of diagnostics and in -E mode.
820 const unsigned char *NextBuf = (const unsigned char *)Buf;
821 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
822 ++NextBuf;
823 Offs += NextBuf-Buf;
824 Buf = NextBuf;
Mike Stump11289f42009-09-09 15:08:12 +0000825
Chris Lattner8996fff2007-07-24 05:57:19 +0000826 if (Buf[0] == '\n' || Buf[0] == '\r') {
827 // If this is \n\r or \r\n, skip both characters.
828 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
829 ++Offs, ++Buf;
830 ++Offs, ++Buf;
831 LineOffsets.push_back(Offs);
832 } else {
833 // Otherwise, this is a null. If end of file, exit.
834 if (Buf == End) break;
835 // Otherwise, skip the null.
836 ++Offs, ++Buf;
837 }
838 }
Mike Stump11289f42009-09-09 15:08:12 +0000839
Chris Lattner8996fff2007-07-24 05:57:19 +0000840 // Copy the offsets into the FileInfo structure.
841 FI->NumLines = LineOffsets.size();
Chris Lattnerc8233df2009-02-03 07:30:45 +0000842 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
Chris Lattner8996fff2007-07-24 05:57:19 +0000843 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
844}
Chris Lattner9a13bde2006-06-21 04:57:09 +0000845
Chris Lattner53e384f2009-01-16 07:00:02 +0000846/// getLineNumber - Given a SourceLocation, return the spelling line number
Chris Lattner22eb9722006-06-18 05:43:12 +0000847/// for the position indicated. This requires building and caching a table of
Chris Lattner739e7392007-04-29 07:12:06 +0000848/// line offsets for the MemoryBuffer, so this is not cheap: use only when
Chris Lattner22eb9722006-06-18 05:43:12 +0000849/// about to emit a diagnostic.
Chris Lattner88ea93e2009-02-04 01:06:56 +0000850unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos) const {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000851 ContentCache *Content;
Chris Lattner88ea93e2009-02-04 01:06:56 +0000852 if (LastLineNoFileIDQuery == FID)
Ted Kremenekc08bca62007-10-30 21:08:08 +0000853 Content = LastLineNoContentCache;
Chris Lattner8996fff2007-07-24 05:57:19 +0000854 else
Chris Lattner88ea93e2009-02-04 01:06:56 +0000855 Content = const_cast<ContentCache*>(getSLocEntry(FID)
Chris Lattner4fa23622009-01-26 00:43:02 +0000856 .getFile().getContentCache());
Mike Stump11289f42009-09-09 15:08:12 +0000857
Chris Lattner22eb9722006-06-18 05:43:12 +0000858 // If this is the first use of line information for this buffer, compute the
Chris Lattner8996fff2007-07-24 05:57:19 +0000859 /// SourceLineCache for it on demand.
Ted Kremenekc08bca62007-10-30 21:08:08 +0000860 if (Content->SourceLineCache == 0)
Chris Lattnerc8233df2009-02-03 07:30:45 +0000861 ComputeLineNumbers(Content, ContentCacheAlloc);
Chris Lattner22eb9722006-06-18 05:43:12 +0000862
863 // Okay, we know we have a line number table. Do a binary search to find the
864 // line number that this character position lands on.
Ted Kremenekc08bca62007-10-30 21:08:08 +0000865 unsigned *SourceLineCache = Content->SourceLineCache;
Chris Lattner8996fff2007-07-24 05:57:19 +0000866 unsigned *SourceLineCacheStart = SourceLineCache;
Ted Kremenekc08bca62007-10-30 21:08:08 +0000867 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
Mike Stump11289f42009-09-09 15:08:12 +0000868
Chris Lattner88ea93e2009-02-04 01:06:56 +0000869 unsigned QueriedFilePos = FilePos+1;
Chris Lattner8996fff2007-07-24 05:57:19 +0000870
Daniel Dunbar70f924df82009-05-18 17:30:52 +0000871 // FIXME: I would like to be convinced that this code is worth being as
Mike Stump11289f42009-09-09 15:08:12 +0000872 // complicated as it is, binary search isn't that slow.
Daniel Dunbar70f924df82009-05-18 17:30:52 +0000873 //
874 // If it is worth being optimized, then in my opinion it could be more
875 // performant, simpler, and more obviously correct by just "galloping" outward
876 // from the queried file position. In fact, this could be incorporated into a
877 // generic algorithm such as lower_bound_with_hint.
878 //
879 // If someone gives me a test case where this matters, and I will do it! - DWD
880
Chris Lattner8996fff2007-07-24 05:57:19 +0000881 // If the previous query was to the same file, we know both the file pos from
882 // that query and the line number returned. This allows us to narrow the
883 // search space from the entire file to something near the match.
Chris Lattner88ea93e2009-02-04 01:06:56 +0000884 if (LastLineNoFileIDQuery == FID) {
Chris Lattner8996fff2007-07-24 05:57:19 +0000885 if (QueriedFilePos >= LastLineNoFilePos) {
Daniel Dunbar70f924df82009-05-18 17:30:52 +0000886 // FIXME: Potential overflow?
Chris Lattner8996fff2007-07-24 05:57:19 +0000887 SourceLineCache = SourceLineCache+LastLineNoResult-1;
Mike Stump11289f42009-09-09 15:08:12 +0000888
Chris Lattner8996fff2007-07-24 05:57:19 +0000889 // The query is likely to be nearby the previous one. Here we check to
890 // see if it is within 5, 10 or 20 lines. It can be far away in cases
891 // where big comment blocks and vertical whitespace eat up lines but
892 // contribute no tokens.
893 if (SourceLineCache+5 < SourceLineCacheEnd) {
894 if (SourceLineCache[5] > QueriedFilePos)
895 SourceLineCacheEnd = SourceLineCache+5;
896 else if (SourceLineCache+10 < SourceLineCacheEnd) {
897 if (SourceLineCache[10] > QueriedFilePos)
898 SourceLineCacheEnd = SourceLineCache+10;
899 else if (SourceLineCache+20 < SourceLineCacheEnd) {
900 if (SourceLineCache[20] > QueriedFilePos)
901 SourceLineCacheEnd = SourceLineCache+20;
902 }
903 }
904 }
905 } else {
Daniel Dunbar70f924df82009-05-18 17:30:52 +0000906 if (LastLineNoResult < Content->NumLines)
907 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
Chris Lattner8996fff2007-07-24 05:57:19 +0000908 }
909 }
Mike Stump11289f42009-09-09 15:08:12 +0000910
Chris Lattner830a77f2007-07-24 06:43:46 +0000911 // If the spread is large, do a "radix" test as our initial guess, based on
912 // the assumption that lines average to approximately the same length.
913 // NOTE: This is currently disabled, as it does not appear to be profitable in
914 // initial measurements.
915 if (0 && SourceLineCacheEnd-SourceLineCache > 20) {
Ted Kremenekc08bca62007-10-30 21:08:08 +0000916 unsigned FileLen = Content->SourceLineCache[Content->NumLines-1];
Mike Stump11289f42009-09-09 15:08:12 +0000917
Chris Lattner830a77f2007-07-24 06:43:46 +0000918 // Take a stab at guessing where it is.
Ted Kremenekc08bca62007-10-30 21:08:08 +0000919 unsigned ApproxPos = Content->NumLines*QueriedFilePos / FileLen;
Mike Stump11289f42009-09-09 15:08:12 +0000920
Chris Lattner830a77f2007-07-24 06:43:46 +0000921 // Check for -10 and +10 lines.
922 unsigned LowerBound = std::max(int(ApproxPos-10), 0);
923 unsigned UpperBound = std::min(ApproxPos+10, FileLen);
924
925 // If the computed lower bound is less than the query location, move it in.
926 if (SourceLineCache < SourceLineCacheStart+LowerBound &&
927 SourceLineCacheStart[LowerBound] < QueriedFilePos)
928 SourceLineCache = SourceLineCacheStart+LowerBound;
Mike Stump11289f42009-09-09 15:08:12 +0000929
Chris Lattner830a77f2007-07-24 06:43:46 +0000930 // If the computed upper bound is greater than the query location, move it.
931 if (SourceLineCacheEnd > SourceLineCacheStart+UpperBound &&
932 SourceLineCacheStart[UpperBound] >= QueriedFilePos)
933 SourceLineCacheEnd = SourceLineCacheStart+UpperBound;
934 }
Mike Stump11289f42009-09-09 15:08:12 +0000935
Chris Lattner830a77f2007-07-24 06:43:46 +0000936 unsigned *Pos
937 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
Chris Lattner8996fff2007-07-24 05:57:19 +0000938 unsigned LineNo = Pos-SourceLineCacheStart;
Mike Stump11289f42009-09-09 15:08:12 +0000939
Chris Lattner88ea93e2009-02-04 01:06:56 +0000940 LastLineNoFileIDQuery = FID;
Ted Kremenekc08bca62007-10-30 21:08:08 +0000941 LastLineNoContentCache = Content;
Chris Lattner8996fff2007-07-24 05:57:19 +0000942 LastLineNoFilePos = QueriedFilePos;
943 LastLineNoResult = LineNo;
944 return LineNo;
Chris Lattner22eb9722006-06-18 05:43:12 +0000945}
946
Chris Lattner88ea93e2009-02-04 01:06:56 +0000947unsigned SourceManager::getInstantiationLineNumber(SourceLocation Loc) const {
948 if (Loc.isInvalid()) return 0;
949 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
950 return getLineNumber(LocInfo.first, LocInfo.second);
951}
952unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc) const {
953 if (Loc.isInvalid()) return 0;
954 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
955 return getLineNumber(LocInfo.first, LocInfo.second);
956}
957
Chris Lattner95d9c5e2009-02-04 05:33:01 +0000958/// getFileCharacteristic - return the file characteristic of the specified
Mike Stump11289f42009-09-09 15:08:12 +0000959/// source location, indicating whether this is a normal file, a system
Chris Lattner95d9c5e2009-02-04 05:33:01 +0000960/// header, or an "implicit extern C" system header.
961///
962/// This state can be modified with flags on GNU linemarker directives like:
963/// # 4 "foo.h" 3
964/// which changes all source locations in the current file after that to be
965/// considered to be from a system header.
Mike Stump11289f42009-09-09 15:08:12 +0000966SrcMgr::CharacteristicKind
Chris Lattner95d9c5e2009-02-04 05:33:01 +0000967SourceManager::getFileCharacteristic(SourceLocation Loc) const {
968 assert(!Loc.isInvalid() && "Can't get file characteristic of invalid loc!");
969 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
970 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile();
971
972 // If there are no #line directives in this file, just return the whole-file
973 // state.
974 if (!FI.hasLineDirectives())
975 return FI.getFileCharacteristic();
Mike Stump11289f42009-09-09 15:08:12 +0000976
Chris Lattner95d9c5e2009-02-04 05:33:01 +0000977 assert(LineTable && "Can't have linetable entries without a LineTable!");
978 // See if there is a #line directive before the location.
979 const LineEntry *Entry =
980 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second);
Mike Stump11289f42009-09-09 15:08:12 +0000981
Chris Lattner95d9c5e2009-02-04 05:33:01 +0000982 // If this is before the first line marker, use the file characteristic.
983 if (!Entry)
984 return FI.getFileCharacteristic();
985
986 return Entry->FileKind;
987}
988
Chris Lattnera6f037c2009-02-17 08:39:06 +0000989/// Return the filename or buffer identifier of the buffer the location is in.
990/// Note that this name does not respect #line directives. Use getPresumedLoc
991/// for normal clients.
992const char *SourceManager::getBufferName(SourceLocation Loc) const {
993 if (Loc.isInvalid()) return "<invalid loc>";
Mike Stump11289f42009-09-09 15:08:12 +0000994
Chris Lattnera6f037c2009-02-17 08:39:06 +0000995 return getBuffer(getFileID(Loc))->getBufferIdentifier();
996}
997
Chris Lattner88ea93e2009-02-04 01:06:56 +0000998
Chris Lattnerf1ca7d32009-01-27 07:57:44 +0000999/// getPresumedLoc - This method returns the "presumed" location of a
1000/// SourceLocation specifies. A "presumed location" can be modified by #line
1001/// or GNU line marker directives. This provides a view on the data that a
1002/// user should see in diagnostics, for example.
1003///
1004/// Note that a presumed location is always given as the instantiation point
1005/// of an instantiation location, not at the spelling location.
1006PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc) const {
1007 if (Loc.isInvalid()) return PresumedLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001008
Chris Lattnerf1ca7d32009-01-27 07:57:44 +00001009 // Presumed locations are always for instantiation points.
Chris Lattnere4ad4172009-02-04 00:55:58 +00001010 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +00001011
Chris Lattner88ea93e2009-02-04 01:06:56 +00001012 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile();
Chris Lattnerf1ca7d32009-01-27 07:57:44 +00001013 const SrcMgr::ContentCache *C = FI.getContentCache();
Mike Stump11289f42009-09-09 15:08:12 +00001014
Chris Lattnerd4293922009-02-04 01:55:42 +00001015 // To get the source name, first consult the FileEntry (if one exists)
1016 // before the MemBuffer as this will avoid unnecessarily paging in the
1017 // MemBuffer.
Mike Stump11289f42009-09-09 15:08:12 +00001018 const char *Filename =
Chris Lattnerf1ca7d32009-01-27 07:57:44 +00001019 C->Entry ? C->Entry->getName() : C->getBuffer()->getBufferIdentifier();
Chris Lattnerd4293922009-02-04 01:55:42 +00001020 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second);
1021 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second);
1022 SourceLocation IncludeLoc = FI.getIncludeLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001023
Chris Lattnerd4293922009-02-04 01:55:42 +00001024 // If we have #line directives in this file, update and overwrite the physical
1025 // location info if appropriate.
1026 if (FI.hasLineDirectives()) {
1027 assert(LineTable && "Can't have linetable entries without a LineTable!");
1028 // See if there is a #line directive before this. If so, get it.
1029 if (const LineEntry *Entry =
1030 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second)) {
Chris Lattnerc1219ff2009-02-04 02:00:59 +00001031 // If the LineEntry indicates a filename, use it.
Chris Lattnerd4293922009-02-04 01:55:42 +00001032 if (Entry->FilenameID != -1)
1033 Filename = LineTable->getFilename(Entry->FilenameID);
Chris Lattnerc1219ff2009-02-04 02:00:59 +00001034
1035 // Use the line number specified by the LineEntry. This line number may
1036 // be multiple lines down from the line entry. Add the difference in
1037 // physical line numbers from the query point and the line marker to the
1038 // total.
1039 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1040 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
Mike Stump11289f42009-09-09 15:08:12 +00001041
Chris Lattner20c50ba2009-02-04 02:15:40 +00001042 // Note that column numbers are not molested by line markers.
Mike Stump11289f42009-09-09 15:08:12 +00001043
Chris Lattner1c967782009-02-04 06:25:26 +00001044 // Handle virtual #include manipulation.
1045 if (Entry->IncludeOffset) {
1046 IncludeLoc = getLocForStartOfFile(LocInfo.first);
1047 IncludeLoc = IncludeLoc.getFileLocWithOffset(Entry->IncludeOffset);
1048 }
Chris Lattnerd4293922009-02-04 01:55:42 +00001049 }
1050 }
1051
1052 return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc);
Chris Lattner4fa23622009-01-26 00:43:02 +00001053}
1054
1055//===----------------------------------------------------------------------===//
1056// Other miscellaneous methods.
1057//===----------------------------------------------------------------------===//
1058
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001059/// \brief Get the source location for the given file:line:col triplet.
1060///
1061/// If the source file is included multiple times, the source location will
1062/// be based upon the first inclusion.
1063SourceLocation SourceManager::getLocation(const FileEntry *SourceFile,
1064 unsigned Line, unsigned Col) const {
1065 assert(SourceFile && "Null source file!");
1066 assert(Line && Col && "Line and column should start from 1!");
1067
1068 fileinfo_iterator FI = FileInfos.find(SourceFile);
1069 if (FI == FileInfos.end())
1070 return SourceLocation();
1071 ContentCache *Content = FI->second;
Mike Stump11289f42009-09-09 15:08:12 +00001072
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001073 // If this is the first use of line information for this buffer, compute the
1074 /// SourceLineCache for it on demand.
1075 if (Content->SourceLineCache == 0)
1076 ComputeLineNumbers(Content, ContentCacheAlloc);
1077
Douglas Gregor2a1b6912009-12-02 05:34:39 +00001078 // Find the first file ID that corresponds to the given file.
1079 FileID FirstFID;
1080
1081 // First, check the main file ID, since it is common to look for a
1082 // location in the main file.
1083 if (!MainFileID.isInvalid()) {
1084 const SLocEntry &MainSLoc = getSLocEntry(MainFileID);
1085 if (MainSLoc.isFile() && MainSLoc.getFile().getContentCache() == Content)
1086 FirstFID = MainFileID;
1087 }
1088
1089 if (FirstFID.isInvalid()) {
1090 // The location we're looking for isn't in the main file; look
1091 // through all of the source locations.
1092 for (unsigned I = 0, N = sloc_entry_size(); I != N; ++I) {
1093 const SLocEntry &SLoc = getSLocEntry(I);
1094 if (SLoc.isFile() && SLoc.getFile().getContentCache() == Content) {
1095 FirstFID = FileID::get(I);
1096 break;
1097 }
1098 }
1099 }
1100
1101 if (FirstFID.isInvalid())
1102 return SourceLocation();
1103
Douglas Gregorb8b9f282010-02-27 02:42:25 +00001104 if (Line > Content->NumLines) {
1105 unsigned Size = Content->getBuffer()->getBufferSize();
1106 if (Size > 0)
1107 --Size;
1108 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(Size);
1109 }
1110
1111 unsigned FilePos = Content->SourceLineCache[Line - 1];
1112 const char *Buf = Content->getBuffer()->getBufferStart() + FilePos;
1113 unsigned BufLength = Content->getBuffer()->getBufferEnd() - Buf;
1114 unsigned i = 0;
1115
1116 // Check that the given column is valid.
1117 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1118 ++i;
1119 if (i < Col-1)
1120 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + i);
1121
Douglas Gregor2a1b6912009-12-02 05:34:39 +00001122 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + Col - 1);
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001123}
1124
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001125/// \brief Determines the order of 2 source locations in the translation unit.
1126///
1127/// \returns true if LHS source location comes before RHS, false otherwise.
1128bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
1129 SourceLocation RHS) const {
1130 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
1131 if (LHS == RHS)
1132 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001133
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001134 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
1135 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00001136
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001137 // If the source locations are in the same file, just compare offsets.
1138 if (LOffs.first == ROffs.first)
1139 return LOffs.second < ROffs.second;
1140
1141 // If we are comparing a source location with multiple locations in the same
1142 // file, we get a big win by caching the result.
Mike Stump11289f42009-09-09 15:08:12 +00001143
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001144 if (LastLFIDForBeforeTUCheck == LOffs.first &&
1145 LastRFIDForBeforeTUCheck == ROffs.first)
1146 return LastResForBeforeTUCheck;
Mike Stump11289f42009-09-09 15:08:12 +00001147
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001148 LastLFIDForBeforeTUCheck = LOffs.first;
1149 LastRFIDForBeforeTUCheck = ROffs.first;
Mike Stump11289f42009-09-09 15:08:12 +00001150
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001151 // "Traverse" the include/instantiation stacks of both locations and try to
1152 // find a common "ancestor".
1153 //
1154 // First we traverse the stack of the right location and check each level
1155 // against the level of the left location, while collecting all levels in a
1156 // "stack map".
1157
1158 std::map<FileID, unsigned> ROffsMap;
1159 ROffsMap[ROffs.first] = ROffs.second;
1160
1161 while (1) {
1162 SourceLocation UpperLoc;
1163 const SrcMgr::SLocEntry &Entry = getSLocEntry(ROffs.first);
1164 if (Entry.isInstantiation())
1165 UpperLoc = Entry.getInstantiation().getInstantiationLocStart();
1166 else
1167 UpperLoc = Entry.getFile().getIncludeLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001168
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001169 if (UpperLoc.isInvalid())
1170 break; // We reached the top.
Mike Stump11289f42009-09-09 15:08:12 +00001171
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001172 ROffs = getDecomposedLoc(UpperLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001173
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001174 if (LOffs.first == ROffs.first)
1175 return LastResForBeforeTUCheck = LOffs.second < ROffs.second;
Mike Stump11289f42009-09-09 15:08:12 +00001176
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001177 ROffsMap[ROffs.first] = ROffs.second;
1178 }
1179
1180 // We didn't find a common ancestor. Now traverse the stack of the left
1181 // location, checking against the stack map of the right location.
1182
1183 while (1) {
1184 SourceLocation UpperLoc;
1185 const SrcMgr::SLocEntry &Entry = getSLocEntry(LOffs.first);
1186 if (Entry.isInstantiation())
1187 UpperLoc = Entry.getInstantiation().getInstantiationLocStart();
1188 else
1189 UpperLoc = Entry.getFile().getIncludeLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001190
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001191 if (UpperLoc.isInvalid())
1192 break; // We reached the top.
Mike Stump11289f42009-09-09 15:08:12 +00001193
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001194 LOffs = getDecomposedLoc(UpperLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001195
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001196 std::map<FileID, unsigned>::iterator I = ROffsMap.find(LOffs.first);
1197 if (I != ROffsMap.end())
1198 return LastResForBeforeTUCheck = LOffs.second < I->second;
1199 }
Mike Stump11289f42009-09-09 15:08:12 +00001200
Daniel Dunbar465f4c42009-12-01 23:07:57 +00001201 // There is no common ancestor, most probably because one location is in the
1202 // predefines buffer.
1203 //
1204 // FIXME: We should rearrange the external interface so this simply never
1205 // happens; it can't conceptually happen. Also see PR5662.
Mike Stump11289f42009-09-09 15:08:12 +00001206
Daniel Dunbar465f4c42009-12-01 23:07:57 +00001207 // If exactly one location is a memory buffer, assume it preceeds the other.
1208 bool LIsMB = !getSLocEntry(LOffs.first).getFile().getContentCache()->Entry;
1209 bool RIsMB = !getSLocEntry(ROffs.first).getFile().getContentCache()->Entry;
1210 if (LIsMB != RIsMB)
1211 return LastResForBeforeTUCheck = LIsMB;
Mike Stump11289f42009-09-09 15:08:12 +00001212
Daniel Dunbar465f4c42009-12-01 23:07:57 +00001213 // Otherwise, just assume FileIDs were created in order.
1214 return LastResForBeforeTUCheck = (LOffs.first < ROffs.first);
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001215}
Chris Lattner4fa23622009-01-26 00:43:02 +00001216
Chris Lattner22eb9722006-06-18 05:43:12 +00001217/// PrintStats - Print statistics to stderr.
1218///
1219void SourceManager::PrintStats() const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +00001220 llvm::errs() << "\n*** Source Manager Stats:\n";
1221 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
1222 << " mem buffers mapped.\n";
1223 llvm::errs() << SLocEntryTable.size() << " SLocEntry's allocated, "
1224 << NextOffset << "B of Sloc address space used.\n";
Mike Stump11289f42009-09-09 15:08:12 +00001225
Chris Lattner22eb9722006-06-18 05:43:12 +00001226 unsigned NumLineNumsComputed = 0;
1227 unsigned NumFileBytesMapped = 0;
Chris Lattnerc8233df2009-02-03 07:30:45 +00001228 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
1229 NumLineNumsComputed += I->second->SourceLineCache != 0;
1230 NumFileBytesMapped += I->second->getSizeBytesMapped();
Chris Lattner22eb9722006-06-18 05:43:12 +00001231 }
Mike Stump11289f42009-09-09 15:08:12 +00001232
Benjamin Kramer89b422c2009-08-23 12:08:50 +00001233 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
1234 << NumLineNumsComputed << " files with line #'s computed.\n";
1235 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
1236 << NumBinaryProbes << " binary.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +00001237}
Douglas Gregor258ae542009-04-27 06:38:32 +00001238
1239ExternalSLocEntrySource::~ExternalSLocEntrySource() { }