blob: be7c256b5b1b750c656981d23d6186049ca85e3d [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SourceManager.cpp - Track and cache source files -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the SourceManager interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Basic/SourceManager.h"
Douglas Gregord4f77aa2009-04-13 15:31:25 +000015#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregoraea67db2010-03-15 22:54:52 +000016#include "clang/Basic/Diagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/Basic/FileManager.h"
Chris Lattner5e36a7a2007-07-24 05:57:19 +000018#include "llvm/Support/Compiler.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000019#include "llvm/Support/MemoryBuffer.h"
Chris Lattnerd57a7ef2009-08-23 22:45:33 +000020#include "llvm/Support/raw_ostream.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000021#include "llvm/System/Path.h"
22#include <algorithm>
Douglas Gregoraea67db2010-03-15 22:54:52 +000023#include <string>
Douglas Gregorf715ca12010-03-16 00:06:06 +000024#include <cstring>
Douglas Gregoraea67db2010-03-15 22:54:52 +000025
Reid Spencer5f016e22007-07-11 17:01:13 +000026using namespace clang;
27using namespace SrcMgr;
28using llvm::MemoryBuffer;
29
Chris Lattner23b5dc62009-02-04 00:40:31 +000030//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +000031// SourceManager Helper Classes
Chris Lattner23b5dc62009-02-04 00:40:31 +000032//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +000033
Ted Kremenek78d85f52007-10-30 21:08:08 +000034ContentCache::~ContentCache() {
Douglas Gregorc8151082010-03-16 22:53:51 +000035 delete Buffer.getPointer();
Reid Spencer5f016e22007-07-11 17:01:13 +000036}
37
Ted Kremenekc16c2082009-01-06 01:55:26 +000038/// getSizeBytesMapped - Returns the number of bytes actually mapped for
39/// this ContentCache. This can be 0 if the MemBuffer was not actually
40/// instantiated.
41unsigned ContentCache::getSizeBytesMapped() const {
Douglas Gregorc8151082010-03-16 22:53:51 +000042 return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 0;
Ted Kremenekc16c2082009-01-06 01:55:26 +000043}
44
45/// getSize - Returns the size of the content encapsulated by this ContentCache.
46/// This can be the size of the source file or the size of an arbitrary
47/// scratch buffer. If the ContentCache encapsulates a source file, that
Douglas Gregor29684422009-12-02 06:49:09 +000048/// file is not lazily brought in from disk to satisfy this query.
Ted Kremenekc16c2082009-01-06 01:55:26 +000049unsigned ContentCache::getSize() const {
Douglas Gregorc8151082010-03-16 22:53:51 +000050 return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize()
51 : (unsigned) Entry->getSize();
Ted Kremenekc16c2082009-01-06 01:55:26 +000052}
53
Douglas Gregor29684422009-12-02 06:49:09 +000054void ContentCache::replaceBuffer(const llvm::MemoryBuffer *B) {
Douglas Gregorc8151082010-03-16 22:53:51 +000055 assert(B != Buffer.getPointer());
Douglas Gregor29684422009-12-02 06:49:09 +000056
Douglas Gregorc8151082010-03-16 22:53:51 +000057 delete Buffer.getPointer();
58 Buffer.setPointer(B);
59 Buffer.setInt(false);
Douglas Gregor29684422009-12-02 06:49:09 +000060}
61
Douglas Gregor36c35ba2010-03-16 00:35:39 +000062const llvm::MemoryBuffer *ContentCache::getBuffer(Diagnostic &Diag,
63 bool *Invalid) const {
64 if (Invalid)
65 *Invalid = false;
66
Ted Kremenek5b034ad2009-01-06 22:43:04 +000067 // Lazily create the Buffer for ContentCaches that wrap files.
Douglas Gregorc8151082010-03-16 22:53:51 +000068 if (!Buffer.getPointer() && Entry) {
Douglas Gregoraea67db2010-03-15 22:54:52 +000069 std::string ErrorStr;
70 struct stat FileInfo;
Douglas Gregorc8151082010-03-16 22:53:51 +000071 Buffer.setPointer(MemoryBuffer::getFile(Entry->getName(), &ErrorStr,
72 Entry->getSize(), &FileInfo));
73 Buffer.setInt(false);
74
Daniel Dunbar21a8bed2009-12-06 05:43:36 +000075 // If we were unable to open the file, then we are in an inconsistent
76 // situation where the content cache referenced a file which no longer
77 // exists. Most likely, we were using a stat cache with an invalid entry but
78 // the file could also have been removed during processing. Since we can't
79 // really deal with this situation, just create an empty buffer.
80 //
81 // FIXME: This is definitely not ideal, but our immediate clients can't
82 // currently handle returning a null entry here. Ideally we should detect
83 // that we are in an inconsistent situation and error out as quickly as
84 // possible.
Douglas Gregorc8151082010-03-16 22:53:51 +000085 if (!Buffer.getPointer()) {
Daniel Dunbar21a8bed2009-12-06 05:43:36 +000086 const llvm::StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
Douglas Gregorc8151082010-03-16 22:53:51 +000087 Buffer.setPointer(MemoryBuffer::getNewMemBuffer(Entry->getSize(),
88 "<invalid>"));
89 char *Ptr = const_cast<char*>(Buffer.getPointer()->getBufferStart());
Daniel Dunbar21a8bed2009-12-06 05:43:36 +000090 for (unsigned i = 0, e = Entry->getSize(); i != e; ++i)
91 Ptr[i] = FillStr[i % FillStr.size()];
Douglas Gregor36c35ba2010-03-16 00:35:39 +000092 Diag.Report(diag::err_cannot_open_file)
93 << Entry->getName() << ErrorStr;
Douglas Gregorc8151082010-03-16 22:53:51 +000094 Buffer.setInt(true);
Douglas Gregoraea67db2010-03-15 22:54:52 +000095 } else {
96 // Check that the file's size and modification time is the same as
97 // in the file entry (which may have come from a stat cache).
Douglas Gregoraea67db2010-03-15 22:54:52 +000098 if (FileInfo.st_size != Entry->getSize()) {
Douglas Gregor36c35ba2010-03-16 00:35:39 +000099 Diag.Report(diag::err_file_size_changed)
100 << Entry->getName() << (unsigned)Entry->getSize()
101 << (unsigned)FileInfo.st_size;
Douglas Gregorc8151082010-03-16 22:53:51 +0000102 Buffer.setInt(true);
Douglas Gregoraea67db2010-03-15 22:54:52 +0000103 } else if (FileInfo.st_mtime != Entry->getModificationTime()) {
Douglas Gregor36c35ba2010-03-16 00:35:39 +0000104 Diag.Report(diag::err_file_modified) << Entry->getName();
Douglas Gregorc8151082010-03-16 22:53:51 +0000105 Buffer.setInt(true);
Douglas Gregoraea67db2010-03-15 22:54:52 +0000106 }
Daniel Dunbar21a8bed2009-12-06 05:43:36 +0000107 }
Ted Kremenek5b034ad2009-01-06 22:43:04 +0000108 }
Douglas Gregoraea67db2010-03-15 22:54:52 +0000109
Douglas Gregorc8151082010-03-16 22:53:51 +0000110 if (Invalid)
111 *Invalid = Buffer.getInt();
112
113 return Buffer.getPointer();
Ted Kremenekc16c2082009-01-06 01:55:26 +0000114}
115
Chris Lattner5b9a5042009-01-26 07:57:50 +0000116unsigned LineTableInfo::getLineTableFilenameID(const char *Ptr, unsigned Len) {
117 // Look up the filename in the string table, returning the pre-existing value
118 // if it exists.
Mike Stump1eb44332009-09-09 15:08:12 +0000119 llvm::StringMapEntry<unsigned> &Entry =
Chris Lattner5b9a5042009-01-26 07:57:50 +0000120 FilenameIDs.GetOrCreateValue(Ptr, Ptr+Len, ~0U);
121 if (Entry.getValue() != ~0U)
122 return Entry.getValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000123
Chris Lattner5b9a5042009-01-26 07:57:50 +0000124 // Otherwise, assign this the next available ID.
125 Entry.setValue(FilenamesByID.size());
126 FilenamesByID.push_back(&Entry);
127 return FilenamesByID.size()-1;
128}
129
Chris Lattnerac50e342009-02-03 22:13:05 +0000130/// AddLineNote - Add a line note to the line table that indicates that there
131/// is a #line at the specified FID/Offset location which changes the presumed
132/// location to LineNo/FilenameID.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000133void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
Chris Lattnerac50e342009-02-03 22:13:05 +0000134 unsigned LineNo, int FilenameID) {
Chris Lattner23b5dc62009-02-04 00:40:31 +0000135 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump1eb44332009-09-09 15:08:12 +0000136
Chris Lattner23b5dc62009-02-04 00:40:31 +0000137 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
138 "Adding line entries out of order!");
Mike Stump1eb44332009-09-09 15:08:12 +0000139
Chris Lattner9d79eba2009-02-04 05:21:58 +0000140 SrcMgr::CharacteristicKind Kind = SrcMgr::C_User;
Chris Lattner137b6a62009-02-04 06:25:26 +0000141 unsigned IncludeOffset = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000142
Chris Lattner9d79eba2009-02-04 05:21:58 +0000143 if (!Entries.empty()) {
144 // If this is a '#line 4' after '#line 42 "foo.h"', make sure to remember
145 // that we are still in "foo.h".
146 if (FilenameID == -1)
147 FilenameID = Entries.back().FilenameID;
Mike Stump1eb44332009-09-09 15:08:12 +0000148
Chris Lattner137b6a62009-02-04 06:25:26 +0000149 // If we are after a line marker that switched us to system header mode, or
150 // that set #include information, preserve it.
Chris Lattner9d79eba2009-02-04 05:21:58 +0000151 Kind = Entries.back().FileKind;
Chris Lattner137b6a62009-02-04 06:25:26 +0000152 IncludeOffset = Entries.back().IncludeOffset;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000153 }
Mike Stump1eb44332009-09-09 15:08:12 +0000154
Chris Lattner137b6a62009-02-04 06:25:26 +0000155 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, Kind,
156 IncludeOffset));
Chris Lattnerac50e342009-02-03 22:13:05 +0000157}
158
Chris Lattner9d79eba2009-02-04 05:21:58 +0000159/// AddLineNote This is the same as the previous version of AddLineNote, but is
160/// used for GNU line markers. If EntryExit is 0, then this doesn't change the
161/// presumed #include stack. If it is 1, this is a file entry, if it is 2 then
162/// this is a file exit. FileKind specifies whether this is a system header or
163/// extern C system header.
164void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
165 unsigned LineNo, int FilenameID,
166 unsigned EntryExit,
167 SrcMgr::CharacteristicKind FileKind) {
168 assert(FilenameID != -1 && "Unspecified filename should use other accessor");
Mike Stump1eb44332009-09-09 15:08:12 +0000169
Chris Lattner9d79eba2009-02-04 05:21:58 +0000170 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump1eb44332009-09-09 15:08:12 +0000171
Chris Lattner9d79eba2009-02-04 05:21:58 +0000172 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
173 "Adding line entries out of order!");
174
Chris Lattner137b6a62009-02-04 06:25:26 +0000175 unsigned IncludeOffset = 0;
176 if (EntryExit == 0) { // No #include stack change.
177 IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
178 } else if (EntryExit == 1) {
179 IncludeOffset = Offset-1;
180 } else if (EntryExit == 2) {
181 assert(!Entries.empty() && Entries.back().IncludeOffset &&
182 "PPDirectives should have caught case when popping empty include stack");
Mike Stump1eb44332009-09-09 15:08:12 +0000183
Chris Lattner137b6a62009-02-04 06:25:26 +0000184 // Get the include loc of the last entries' include loc as our include loc.
185 IncludeOffset = 0;
186 if (const LineEntry *PrevEntry =
187 FindNearestLineEntry(FID, Entries.back().IncludeOffset))
188 IncludeOffset = PrevEntry->IncludeOffset;
189 }
Mike Stump1eb44332009-09-09 15:08:12 +0000190
Chris Lattner137b6a62009-02-04 06:25:26 +0000191 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
192 IncludeOffset));
Chris Lattner9d79eba2009-02-04 05:21:58 +0000193}
194
195
Chris Lattner3cd949c2009-02-04 01:55:42 +0000196/// FindNearestLineEntry - Find the line entry nearest to FID that is before
197/// it. If there is no line entry before Offset in FID, return null.
Mike Stump1eb44332009-09-09 15:08:12 +0000198const LineEntry *LineTableInfo::FindNearestLineEntry(unsigned FID,
Chris Lattner3cd949c2009-02-04 01:55:42 +0000199 unsigned Offset) {
200 const std::vector<LineEntry> &Entries = LineEntries[FID];
201 assert(!Entries.empty() && "No #line entries for this FID after all!");
202
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000203 // It is very common for the query to be after the last #line, check this
204 // first.
205 if (Entries.back().FileOffset <= Offset)
206 return &Entries.back();
Chris Lattner3cd949c2009-02-04 01:55:42 +0000207
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000208 // Do a binary search to find the maximal element that is still before Offset.
209 std::vector<LineEntry>::const_iterator I =
210 std::upper_bound(Entries.begin(), Entries.end(), Offset);
211 if (I == Entries.begin()) return 0;
212 return &*--I;
Chris Lattner3cd949c2009-02-04 01:55:42 +0000213}
Chris Lattnerac50e342009-02-03 22:13:05 +0000214
Douglas Gregorbd945002009-04-13 16:31:14 +0000215/// \brief Add a new line entry that has already been encoded into
216/// the internal representation of the line table.
Mike Stump1eb44332009-09-09 15:08:12 +0000217void LineTableInfo::AddEntry(unsigned FID,
Douglas Gregorbd945002009-04-13 16:31:14 +0000218 const std::vector<LineEntry> &Entries) {
219 LineEntries[FID] = Entries;
220}
Chris Lattnerac50e342009-02-03 22:13:05 +0000221
Chris Lattner5b9a5042009-01-26 07:57:50 +0000222/// getLineTableFilenameID - Return the uniqued ID for the specified filename.
Mike Stump1eb44332009-09-09 15:08:12 +0000223///
Chris Lattner5b9a5042009-01-26 07:57:50 +0000224unsigned SourceManager::getLineTableFilenameID(const char *Ptr, unsigned Len) {
225 if (LineTable == 0)
226 LineTable = new LineTableInfo();
227 return LineTable->getLineTableFilenameID(Ptr, Len);
228}
229
230
Chris Lattner4c4ea172009-02-03 21:52:55 +0000231/// AddLineNote - Add a line note to the line table for the FileID and offset
232/// specified by Loc. If FilenameID is -1, it is considered to be
233/// unspecified.
234void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
235 int FilenameID) {
Chris Lattnerac50e342009-02-03 22:13:05 +0000236 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000237
Chris Lattnerac50e342009-02-03 22:13:05 +0000238 const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile();
239
240 // Remember that this file has #line directives now if it doesn't already.
241 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump1eb44332009-09-09 15:08:12 +0000242
Chris Lattnerac50e342009-02-03 22:13:05 +0000243 if (LineTable == 0)
244 LineTable = new LineTableInfo();
Chris Lattner23b5dc62009-02-04 00:40:31 +0000245 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID);
Chris Lattner4c4ea172009-02-03 21:52:55 +0000246}
247
Chris Lattner9d79eba2009-02-04 05:21:58 +0000248/// AddLineNote - Add a GNU line marker to the line table.
249void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
250 int FilenameID, bool IsFileEntry,
251 bool IsFileExit, bool IsSystemHeader,
252 bool IsExternCHeader) {
253 // If there is no filename and no flags, this is treated just like a #line,
254 // which does not change the flags of the previous line marker.
255 if (FilenameID == -1) {
256 assert(!IsFileEntry && !IsFileExit && !IsSystemHeader && !IsExternCHeader &&
257 "Can't set flags without setting the filename!");
258 return AddLineNote(Loc, LineNo, FilenameID);
259 }
Mike Stump1eb44332009-09-09 15:08:12 +0000260
Chris Lattner9d79eba2009-02-04 05:21:58 +0000261 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
262 const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile();
Mike Stump1eb44332009-09-09 15:08:12 +0000263
Chris Lattner9d79eba2009-02-04 05:21:58 +0000264 // Remember that this file has #line directives now if it doesn't already.
265 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump1eb44332009-09-09 15:08:12 +0000266
Chris Lattner9d79eba2009-02-04 05:21:58 +0000267 if (LineTable == 0)
268 LineTable = new LineTableInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000269
Chris Lattner9d79eba2009-02-04 05:21:58 +0000270 SrcMgr::CharacteristicKind FileKind;
271 if (IsExternCHeader)
272 FileKind = SrcMgr::C_ExternCSystem;
273 else if (IsSystemHeader)
274 FileKind = SrcMgr::C_System;
275 else
276 FileKind = SrcMgr::C_User;
Mike Stump1eb44332009-09-09 15:08:12 +0000277
Chris Lattner9d79eba2009-02-04 05:21:58 +0000278 unsigned EntryExit = 0;
279 if (IsFileEntry)
280 EntryExit = 1;
281 else if (IsFileExit)
282 EntryExit = 2;
Mike Stump1eb44332009-09-09 15:08:12 +0000283
Chris Lattner9d79eba2009-02-04 05:21:58 +0000284 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID,
285 EntryExit, FileKind);
286}
287
Douglas Gregorbd945002009-04-13 16:31:14 +0000288LineTableInfo &SourceManager::getLineTable() {
289 if (LineTable == 0)
290 LineTable = new LineTableInfo();
291 return *LineTable;
292}
Chris Lattner4c4ea172009-02-03 21:52:55 +0000293
Chris Lattner23b5dc62009-02-04 00:40:31 +0000294//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000295// Private 'Create' methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000296//===----------------------------------------------------------------------===//
Ted Kremenekc16c2082009-01-06 01:55:26 +0000297
Chris Lattner5b9a5042009-01-26 07:57:50 +0000298SourceManager::~SourceManager() {
299 delete LineTable;
Mike Stump1eb44332009-09-09 15:08:12 +0000300
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000301 // Delete FileEntry objects corresponding to content caches. Since the actual
302 // content cache objects are bump pointer allocated, we just have to run the
303 // dtors, but we call the deallocate method for completeness.
304 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
305 MemBufferInfos[i]->~ContentCache();
306 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
307 }
308 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
309 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
310 I->second->~ContentCache();
311 ContentCacheAlloc.Deallocate(I->second);
312 }
Chris Lattner5b9a5042009-01-26 07:57:50 +0000313}
314
315void SourceManager::clearIDTables() {
316 MainFileID = FileID();
317 SLocEntryTable.clear();
318 LastLineNoFileIDQuery = FileID();
319 LastLineNoContentCache = 0;
320 LastFileIDLookup = FileID();
Mike Stump1eb44332009-09-09 15:08:12 +0000321
Chris Lattner5b9a5042009-01-26 07:57:50 +0000322 if (LineTable)
323 LineTable->clear();
Mike Stump1eb44332009-09-09 15:08:12 +0000324
Chris Lattner5b9a5042009-01-26 07:57:50 +0000325 // Use up FileID #0 as an invalid instantiation.
326 NextOffset = 0;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000327 createInstantiationLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000328}
329
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000330/// getOrCreateContentCache - Create or return a cached ContentCache for the
331/// specified file.
332const ContentCache *
333SourceManager::getOrCreateContentCache(const FileEntry *FileEnt) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000334 assert(FileEnt && "Didn't specify a file entry to use?");
Mike Stump1eb44332009-09-09 15:08:12 +0000335
Reid Spencer5f016e22007-07-11 17:01:13 +0000336 // Do we already have information about this file?
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000337 ContentCache *&Entry = FileInfos[FileEnt];
338 if (Entry) return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +0000339
Chris Lattner00282d62009-02-03 07:41:46 +0000340 // Nope, create a new Cache entry. Make sure it is at least 8-byte aligned
341 // so that FileInfo can use the low 3 bits of the pointer for its own
342 // nefarious purposes.
343 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
344 EntryAlign = std::max(8U, EntryAlign);
345 Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000346 new (Entry) ContentCache(FileEnt);
347 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000348}
349
350
Ted Kremenekd1c0eee2007-10-31 17:53:38 +0000351/// createMemBufferContentCache - Create a new ContentCache for the specified
352/// memory buffer. This does no caching.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000353const ContentCache*
354SourceManager::createMemBufferContentCache(const MemoryBuffer *Buffer) {
Chris Lattner00282d62009-02-03 07:41:46 +0000355 // Add a new ContentCache to the MemBufferInfos list and return it. Make sure
356 // it is at least 8-byte aligned so that FileInfo can use the low 3 bits of
357 // the pointer for its own nefarious purposes.
358 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
359 EntryAlign = std::max(8U, EntryAlign);
360 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000361 new (Entry) ContentCache();
362 MemBufferInfos.push_back(Entry);
363 Entry->setBuffer(Buffer);
364 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000365}
366
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000367void SourceManager::PreallocateSLocEntries(ExternalSLocEntrySource *Source,
368 unsigned NumSLocEntries,
369 unsigned NextOffset) {
370 ExternalSLocEntries = Source;
371 this->NextOffset = NextOffset;
372 SLocEntryLoaded.resize(NumSLocEntries + 1);
373 SLocEntryLoaded[0] = true;
374 SLocEntryTable.resize(SLocEntryTable.size() + NumSLocEntries);
375}
376
Douglas Gregor2bf1eb02009-04-27 21:28:04 +0000377void SourceManager::ClearPreallocatedSLocEntries() {
378 unsigned I = 0;
379 for (unsigned N = SLocEntryLoaded.size(); I != N; ++I)
380 if (!SLocEntryLoaded[I])
381 break;
382
383 // We've already loaded all preallocated source location entries.
384 if (I == SLocEntryLoaded.size())
385 return;
386
387 // Remove everything from location I onward.
388 SLocEntryTable.resize(I);
389 SLocEntryLoaded.clear();
390 ExternalSLocEntries = 0;
391}
392
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000393
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000394//===----------------------------------------------------------------------===//
395// Methods to create new FileID's and instantiations.
396//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000397
Nico Weber48002c82008-09-29 00:25:48 +0000398/// createFileID - Create a new fileID for the specified ContentCache and
Ted Kremenek0d892d82007-10-30 22:57:35 +0000399/// include position. This works regardless of whether the ContentCache
400/// corresponds to a file or some other input source.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000401FileID SourceManager::createFileID(const ContentCache *File,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000402 SourceLocation IncludePos,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000403 SrcMgr::CharacteristicKind FileCharacter,
404 unsigned PreallocatedID,
405 unsigned Offset) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000406 if (PreallocatedID) {
407 // If we're filling in a preallocated ID, just load in the file
408 // entry and return.
Mike Stump1eb44332009-09-09 15:08:12 +0000409 assert(PreallocatedID < SLocEntryLoaded.size() &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000410 "Preallocate ID out-of-range");
Mike Stump1eb44332009-09-09 15:08:12 +0000411 assert(!SLocEntryLoaded[PreallocatedID] &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000412 "Source location entry already loaded");
413 assert(Offset && "Preallocate source location cannot have zero offset");
Mike Stump1eb44332009-09-09 15:08:12 +0000414 SLocEntryTable[PreallocatedID]
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000415 = SLocEntry::get(Offset, FileInfo::get(IncludePos, File, FileCharacter));
416 SLocEntryLoaded[PreallocatedID] = true;
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +0000417 FileID FID = FileID::get(PreallocatedID);
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +0000418 return LastFileIDLookup = FID;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000419 }
420
Mike Stump1eb44332009-09-09 15:08:12 +0000421 SLocEntryTable.push_back(SLocEntry::get(NextOffset,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000422 FileInfo::get(IncludePos, File,
423 FileCharacter)));
Ted Kremenekc16c2082009-01-06 01:55:26 +0000424 unsigned FileSize = File->getSize();
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000425 assert(NextOffset+FileSize+1 > NextOffset && "Ran out of source locations!");
426 NextOffset += FileSize+1;
Mike Stump1eb44332009-09-09 15:08:12 +0000427
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000428 // Set LastFileIDLookup to the newly created file. The next getFileID call is
429 // almost guaranteed to be from that file.
Argyrios Kyrtzidisea703f12009-06-23 00:42:06 +0000430 FileID FID = FileID::get(SLocEntryTable.size()-1);
Argyrios Kyrtzidisea703f12009-06-23 00:42:06 +0000431 return LastFileIDLookup = FID;
Reid Spencer5f016e22007-07-11 17:01:13 +0000432}
433
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000434/// createInstantiationLoc - Return a new SourceLocation that encodes the fact
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000435/// that a token from SpellingLoc should actually be referenced from
Reid Spencer5f016e22007-07-11 17:01:13 +0000436/// InstantiationLoc.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000437SourceLocation SourceManager::createInstantiationLoc(SourceLocation SpellingLoc,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000438 SourceLocation ILocStart,
439 SourceLocation ILocEnd,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000440 unsigned TokLength,
441 unsigned PreallocatedID,
442 unsigned Offset) {
Chris Lattnere7fb4842009-02-15 20:52:18 +0000443 InstantiationInfo II = InstantiationInfo::get(ILocStart,ILocEnd, SpellingLoc);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000444 if (PreallocatedID) {
445 // If we're filling in a preallocated ID, just load in the
446 // instantiation entry and return.
Mike Stump1eb44332009-09-09 15:08:12 +0000447 assert(PreallocatedID < SLocEntryLoaded.size() &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000448 "Preallocate ID out-of-range");
Mike Stump1eb44332009-09-09 15:08:12 +0000449 assert(!SLocEntryLoaded[PreallocatedID] &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000450 "Source location entry already loaded");
451 assert(Offset && "Preallocate source location cannot have zero offset");
452 SLocEntryTable[PreallocatedID] = SLocEntry::get(Offset, II);
453 SLocEntryLoaded[PreallocatedID] = true;
454 return SourceLocation::getMacroLoc(Offset);
455 }
Chris Lattnere7fb4842009-02-15 20:52:18 +0000456 SLocEntryTable.push_back(SLocEntry::get(NextOffset, II));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000457 assert(NextOffset+TokLength+1 > NextOffset && "Ran out of source locations!");
458 NextOffset += TokLength+1;
459 return SourceLocation::getMacroLoc(NextOffset-(TokLength+1));
Reid Spencer5f016e22007-07-11 17:01:13 +0000460}
461
Douglas Gregor36c35ba2010-03-16 00:35:39 +0000462const llvm::MemoryBuffer *
Douglas Gregor50f6af72010-03-16 05:20:39 +0000463SourceManager::getMemoryBufferForFile(const FileEntry *File,
464 bool *Invalid) {
Douglas Gregor29684422009-12-02 06:49:09 +0000465 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
Douglas Gregoraea67db2010-03-15 22:54:52 +0000466 assert(IR && "getOrCreateContentCache() cannot return NULL");
Douglas Gregor50f6af72010-03-16 05:20:39 +0000467 return IR->getBuffer(Diag, Invalid);
Douglas Gregor29684422009-12-02 06:49:09 +0000468}
469
470bool SourceManager::overrideFileContents(const FileEntry *SourceFile,
471 const llvm::MemoryBuffer *Buffer) {
472 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
473 if (IR == 0)
474 return true;
475
476 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer);
477 return false;
478}
479
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000480llvm::StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
Douglas Gregoraae58b02010-03-16 20:01:30 +0000481 bool MyInvalid = false;
482 const llvm::MemoryBuffer *Buf = getBuffer(FID, &MyInvalid);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000483 if (Invalid)
Douglas Gregoraae58b02010-03-16 20:01:30 +0000484 *Invalid = MyInvalid;
485
486 if (MyInvalid)
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000487 return "";
Douglas Gregoraae58b02010-03-16 20:01:30 +0000488
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000489 return Buf->getBuffer();
Douglas Gregoraea67db2010-03-15 22:54:52 +0000490}
Chris Lattner2b2453a2009-01-17 06:22:33 +0000491
Chris Lattner23b5dc62009-02-04 00:40:31 +0000492//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000493// SourceLocation manipulation methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000494//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000495
496/// getFileIDSlow - Return the FileID for a SourceLocation. This is a very hot
497/// method that is used for all SourceManager queries that start with a
498/// SourceLocation object. It is responsible for finding the entry in
499/// SLocEntryTable which contains the specified location.
500///
501FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
502 assert(SLocOffset && "Invalid FileID");
Mike Stump1eb44332009-09-09 15:08:12 +0000503
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000504 // After the first and second level caches, I see two common sorts of
505 // behavior: 1) a lot of searched FileID's are "near" the cached file location
506 // or are "near" the cached instantiation location. 2) others are just
507 // completely random and may be a very long way away.
508 //
509 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
510 // then we fall back to a less cache efficient, but more scalable, binary
511 // search to find the location.
Mike Stump1eb44332009-09-09 15:08:12 +0000512
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000513 // See if this is near the file point - worst case we start scanning from the
514 // most newly created FileID.
515 std::vector<SrcMgr::SLocEntry>::const_iterator I;
Mike Stump1eb44332009-09-09 15:08:12 +0000516
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000517 if (SLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
518 // Neither loc prunes our search.
519 I = SLocEntryTable.end();
520 } else {
521 // Perhaps it is near the file point.
522 I = SLocEntryTable.begin()+LastFileIDLookup.ID;
523 }
524
525 // Find the FileID that contains this. "I" is an iterator that points to a
526 // FileID whose offset is known to be larger than SLocOffset.
527 unsigned NumProbes = 0;
528 while (1) {
529 --I;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000530 if (ExternalSLocEntries)
531 getSLocEntry(FileID::get(I - SLocEntryTable.begin()));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000532 if (I->getOffset() <= SLocOffset) {
533#if 0
534 printf("lin %d -> %d [%s] %d %d\n", SLocOffset,
535 I-SLocEntryTable.begin(),
536 I->isInstantiation() ? "inst" : "file",
537 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
538#endif
539 FileID Res = FileID::get(I-SLocEntryTable.begin());
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000540
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000541 // If this isn't an instantiation, remember it. We have good locality
542 // across FileID lookups.
543 if (!I->isInstantiation())
544 LastFileIDLookup = Res;
545 NumLinearScans += NumProbes+1;
546 return Res;
547 }
548 if (++NumProbes == 8)
549 break;
550 }
Mike Stump1eb44332009-09-09 15:08:12 +0000551
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000552 // Convert "I" back into an index. We know that it is an entry whose index is
553 // larger than the offset we are looking for.
554 unsigned GreaterIndex = I-SLocEntryTable.begin();
555 // LessIndex - This is the lower bound of the range that we're searching.
556 // We know that the offset corresponding to the FileID is is less than
557 // SLocOffset.
558 unsigned LessIndex = 0;
559 NumProbes = 0;
560 while (1) {
561 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000562 unsigned MidOffset = getSLocEntry(FileID::get(MiddleIndex)).getOffset();
Mike Stump1eb44332009-09-09 15:08:12 +0000563
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000564 ++NumProbes;
Mike Stump1eb44332009-09-09 15:08:12 +0000565
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000566 // If the offset of the midpoint is too large, chop the high side of the
567 // range to the midpoint.
568 if (MidOffset > SLocOffset) {
569 GreaterIndex = MiddleIndex;
570 continue;
571 }
Mike Stump1eb44332009-09-09 15:08:12 +0000572
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000573 // If the middle index contains the value, succeed and return.
574 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
575#if 0
576 printf("bin %d -> %d [%s] %d %d\n", SLocOffset,
577 I-SLocEntryTable.begin(),
578 I->isInstantiation() ? "inst" : "file",
579 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
580#endif
581 FileID Res = FileID::get(MiddleIndex);
582
583 // If this isn't an instantiation, remember it. We have good locality
584 // across FileID lookups.
585 if (!I->isInstantiation())
586 LastFileIDLookup = Res;
587 NumBinaryProbes += NumProbes;
588 return Res;
589 }
Mike Stump1eb44332009-09-09 15:08:12 +0000590
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000591 // Otherwise, move the low-side up to the middle index.
592 LessIndex = MiddleIndex;
593 }
594}
595
Chris Lattneraddb7972009-01-26 20:04:19 +0000596SourceLocation SourceManager::
597getInstantiationLocSlowCase(SourceLocation Loc) const {
598 do {
Chris Lattnera5c6c582010-02-12 19:31:35 +0000599 // Note: If Loc indicates an offset into a token that came from a macro
600 // expansion (e.g. the 5th character of the token) we do not want to add
601 // this offset when going to the instantiation location. The instatiation
602 // location is the macro invocation, which the offset has nothing to do
603 // with. This is unlike when we get the spelling loc, because the offset
604 // directly correspond to the token whose spelling we're inspecting.
605 Loc = getSLocEntry(getFileID(Loc)).getInstantiation()
Chris Lattnere7fb4842009-02-15 20:52:18 +0000606 .getInstantiationLocStart();
Chris Lattneraddb7972009-01-26 20:04:19 +0000607 } while (!Loc.isFileID());
608
609 return Loc;
610}
611
612SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
613 do {
614 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
615 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
616 Loc = Loc.getFileLocWithOffset(LocInfo.second);
617 } while (!Loc.isFileID());
618 return Loc;
619}
620
621
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000622std::pair<FileID, unsigned>
623SourceManager::getDecomposedInstantiationLocSlowCase(const SrcMgr::SLocEntry *E,
624 unsigned Offset) const {
625 // If this is an instantiation record, walk through all the instantiation
626 // points.
627 FileID FID;
628 SourceLocation Loc;
629 do {
Chris Lattnere7fb4842009-02-15 20:52:18 +0000630 Loc = E->getInstantiation().getInstantiationLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000631
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000632 FID = getFileID(Loc);
633 E = &getSLocEntry(FID);
634 Offset += Loc.getOffset()-E->getOffset();
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000635 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000636
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000637 return std::make_pair(FID, Offset);
638}
639
640std::pair<FileID, unsigned>
641SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
642 unsigned Offset) const {
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000643 // If this is an instantiation record, walk through all the instantiation
644 // points.
645 FileID FID;
646 SourceLocation Loc;
647 do {
648 Loc = E->getInstantiation().getSpellingLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000649
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000650 FID = getFileID(Loc);
651 E = &getSLocEntry(FID);
652 Offset += Loc.getOffset()-E->getOffset();
653 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000654
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000655 return std::make_pair(FID, Offset);
656}
657
Chris Lattner387616e2009-02-17 08:04:48 +0000658/// getImmediateSpellingLoc - Given a SourceLocation object, return the
659/// spelling location referenced by the ID. This is the first level down
660/// towards the place where the characters that make up the lexed token can be
661/// found. This should not generally be used by clients.
662SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
663 if (Loc.isFileID()) return Loc;
664 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
665 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
666 return Loc.getFileLocWithOffset(LocInfo.second);
667}
668
669
Chris Lattnere7fb4842009-02-15 20:52:18 +0000670/// getImmediateInstantiationRange - Loc is required to be an instantiation
671/// location. Return the start/end of the instantiation information.
672std::pair<SourceLocation,SourceLocation>
673SourceManager::getImmediateInstantiationRange(SourceLocation Loc) const {
674 assert(Loc.isMacroID() && "Not an instantiation loc!");
675 const InstantiationInfo &II = getSLocEntry(getFileID(Loc)).getInstantiation();
676 return II.getInstantiationLocRange();
677}
678
Chris Lattner66781332009-02-15 21:26:50 +0000679/// getInstantiationRange - Given a SourceLocation object, return the
680/// range of tokens covered by the instantiation in the ultimate file.
681std::pair<SourceLocation,SourceLocation>
682SourceManager::getInstantiationRange(SourceLocation Loc) const {
683 if (Loc.isFileID()) return std::make_pair(Loc, Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000684
Chris Lattner66781332009-02-15 21:26:50 +0000685 std::pair<SourceLocation,SourceLocation> Res =
686 getImmediateInstantiationRange(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000687
Chris Lattner66781332009-02-15 21:26:50 +0000688 // Fully resolve the start and end locations to their ultimate instantiation
689 // points.
690 while (!Res.first.isFileID())
691 Res.first = getImmediateInstantiationRange(Res.first).first;
692 while (!Res.second.isFileID())
693 Res.second = getImmediateInstantiationRange(Res.second).second;
694 return Res;
695}
696
Chris Lattnere7fb4842009-02-15 20:52:18 +0000697
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000698
699//===----------------------------------------------------------------------===//
700// Queries about the code at a SourceLocation.
701//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000702
703/// getCharacterData - Return a pointer to the start of the specified location
704/// in the appropriate MemoryBuffer.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000705const char *SourceManager::getCharacterData(SourceLocation SL,
706 bool *Invalid) const {
Reid Spencer5f016e22007-07-11 17:01:13 +0000707 // Note that this is a hot function in the getSpelling() path, which is
708 // heavily used by -E mode.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000709 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
Mike Stump1eb44332009-09-09 15:08:12 +0000710
Ted Kremenekc16c2082009-01-06 01:55:26 +0000711 // Note that calling 'getBuffer()' may lazily page in a source file.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000712 bool CharDataInvalid = false;
713 const llvm::MemoryBuffer *Buffer
714 = getSLocEntry(LocInfo.first).getFile().getContentCache()->getBuffer(Diag,
715 &CharDataInvalid);
716 if (Invalid)
717 *Invalid = CharDataInvalid;
718 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
Reid Spencer5f016e22007-07-11 17:01:13 +0000719}
720
Reid Spencer5f016e22007-07-11 17:01:13 +0000721
Chris Lattner9dc1f532007-07-20 16:37:10 +0000722/// getColumnNumber - Return the column # for the specified file position.
Chris Lattner7da5aea2009-02-04 00:55:58 +0000723/// this is significantly cheaper to compute than the line number.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000724unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
725 bool *Invalid) const {
726 bool MyInvalid = false;
727 const char *Buf = getBuffer(FID, &MyInvalid)->getBufferStart();
728 if (Invalid)
729 *Invalid = MyInvalid;
730
731 if (MyInvalid)
732 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000733
Reid Spencer5f016e22007-07-11 17:01:13 +0000734 unsigned LineStart = FilePos;
735 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
736 --LineStart;
737 return FilePos-LineStart+1;
738}
739
Douglas Gregor50f6af72010-03-16 05:20:39 +0000740unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
741 bool *Invalid) const {
Chris Lattner30fc9332009-02-04 01:06:56 +0000742 if (Loc.isInvalid()) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +0000743 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000744 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +0000745}
746
Douglas Gregor50f6af72010-03-16 05:20:39 +0000747unsigned SourceManager::getInstantiationColumnNumber(SourceLocation Loc,
748 bool *Invalid) const {
Chris Lattner30fc9332009-02-04 01:06:56 +0000749 if (Loc.isInvalid()) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +0000750 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000751 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +0000752}
753
Douglas Gregor36c35ba2010-03-16 00:35:39 +0000754static DISABLE_INLINE void ComputeLineNumbers(Diagnostic &Diag,
755 ContentCache* FI,
Douglas Gregor50f6af72010-03-16 05:20:39 +0000756 llvm::BumpPtrAllocator &Alloc,
757 bool &Invalid);
Douglas Gregor36c35ba2010-03-16 00:35:39 +0000758static void ComputeLineNumbers(Diagnostic &Diag, ContentCache* FI,
Douglas Gregor50f6af72010-03-16 05:20:39 +0000759 llvm::BumpPtrAllocator &Alloc, bool &Invalid) {
Ted Kremenekc16c2082009-01-06 01:55:26 +0000760 // Note that calling 'getBuffer()' may lazily page in the file.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000761 const MemoryBuffer *Buffer = FI->getBuffer(Diag, &Invalid);
762 if (Invalid)
763 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000764
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000765 // Find the file offsets of all of the *physical* source lines. This does
766 // not look at trigraphs, escaped newlines, or anything else tricky.
767 std::vector<unsigned> LineOffsets;
Mike Stump1eb44332009-09-09 15:08:12 +0000768
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000769 // Line #1 starts at char 0.
770 LineOffsets.push_back(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000771
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000772 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
773 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
774 unsigned Offs = 0;
775 while (1) {
776 // Skip over the contents of the line.
777 // TODO: Vectorize this? This is very performance sensitive for programs
778 // with lots of diagnostics and in -E mode.
779 const unsigned char *NextBuf = (const unsigned char *)Buf;
780 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
781 ++NextBuf;
782 Offs += NextBuf-Buf;
783 Buf = NextBuf;
Mike Stump1eb44332009-09-09 15:08:12 +0000784
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000785 if (Buf[0] == '\n' || Buf[0] == '\r') {
786 // If this is \n\r or \r\n, skip both characters.
787 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
788 ++Offs, ++Buf;
789 ++Offs, ++Buf;
790 LineOffsets.push_back(Offs);
791 } else {
792 // Otherwise, this is a null. If end of file, exit.
793 if (Buf == End) break;
794 // Otherwise, skip the null.
795 ++Offs, ++Buf;
796 }
797 }
Mike Stump1eb44332009-09-09 15:08:12 +0000798
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000799 // Copy the offsets into the FileInfo structure.
800 FI->NumLines = LineOffsets.size();
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000801 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000802 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
803}
Reid Spencer5f016e22007-07-11 17:01:13 +0000804
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000805/// getLineNumber - Given a SourceLocation, return the spelling line number
Reid Spencer5f016e22007-07-11 17:01:13 +0000806/// for the position indicated. This requires building and caching a table of
807/// line offsets for the MemoryBuffer, so this is not cheap: use only when
808/// about to emit a diagnostic.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000809unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
810 bool *Invalid) const {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000811 ContentCache *Content;
Chris Lattner30fc9332009-02-04 01:06:56 +0000812 if (LastLineNoFileIDQuery == FID)
Ted Kremenek78d85f52007-10-30 21:08:08 +0000813 Content = LastLineNoContentCache;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000814 else
Chris Lattner30fc9332009-02-04 01:06:56 +0000815 Content = const_cast<ContentCache*>(getSLocEntry(FID)
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000816 .getFile().getContentCache());
Mike Stump1eb44332009-09-09 15:08:12 +0000817
Reid Spencer5f016e22007-07-11 17:01:13 +0000818 // If this is the first use of line information for this buffer, compute the
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000819 /// SourceLineCache for it on demand.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000820 if (Content->SourceLineCache == 0) {
821 bool MyInvalid = false;
822 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, MyInvalid);
823 if (Invalid)
824 *Invalid = MyInvalid;
825 if (MyInvalid)
826 return 1;
827 } else if (Invalid)
828 *Invalid = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000829
830 // Okay, we know we have a line number table. Do a binary search to find the
831 // line number that this character position lands on.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000832 unsigned *SourceLineCache = Content->SourceLineCache;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000833 unsigned *SourceLineCacheStart = SourceLineCache;
Ted Kremenek78d85f52007-10-30 21:08:08 +0000834 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
Mike Stump1eb44332009-09-09 15:08:12 +0000835
Chris Lattner30fc9332009-02-04 01:06:56 +0000836 unsigned QueriedFilePos = FilePos+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000837
Daniel Dunbar4106d692009-05-18 17:30:52 +0000838 // FIXME: I would like to be convinced that this code is worth being as
Mike Stump1eb44332009-09-09 15:08:12 +0000839 // complicated as it is, binary search isn't that slow.
Daniel Dunbar4106d692009-05-18 17:30:52 +0000840 //
841 // If it is worth being optimized, then in my opinion it could be more
842 // performant, simpler, and more obviously correct by just "galloping" outward
843 // from the queried file position. In fact, this could be incorporated into a
844 // generic algorithm such as lower_bound_with_hint.
845 //
846 // If someone gives me a test case where this matters, and I will do it! - DWD
847
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000848 // If the previous query was to the same file, we know both the file pos from
849 // that query and the line number returned. This allows us to narrow the
850 // search space from the entire file to something near the match.
Chris Lattner30fc9332009-02-04 01:06:56 +0000851 if (LastLineNoFileIDQuery == FID) {
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000852 if (QueriedFilePos >= LastLineNoFilePos) {
Daniel Dunbar4106d692009-05-18 17:30:52 +0000853 // FIXME: Potential overflow?
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000854 SourceLineCache = SourceLineCache+LastLineNoResult-1;
Mike Stump1eb44332009-09-09 15:08:12 +0000855
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000856 // The query is likely to be nearby the previous one. Here we check to
857 // see if it is within 5, 10 or 20 lines. It can be far away in cases
858 // where big comment blocks and vertical whitespace eat up lines but
859 // contribute no tokens.
860 if (SourceLineCache+5 < SourceLineCacheEnd) {
861 if (SourceLineCache[5] > QueriedFilePos)
862 SourceLineCacheEnd = SourceLineCache+5;
863 else if (SourceLineCache+10 < SourceLineCacheEnd) {
864 if (SourceLineCache[10] > QueriedFilePos)
865 SourceLineCacheEnd = SourceLineCache+10;
866 else if (SourceLineCache+20 < SourceLineCacheEnd) {
867 if (SourceLineCache[20] > QueriedFilePos)
868 SourceLineCacheEnd = SourceLineCache+20;
869 }
870 }
871 }
872 } else {
Daniel Dunbar4106d692009-05-18 17:30:52 +0000873 if (LastLineNoResult < Content->NumLines)
874 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000875 }
876 }
Mike Stump1eb44332009-09-09 15:08:12 +0000877
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000878 // If the spread is large, do a "radix" test as our initial guess, based on
879 // the assumption that lines average to approximately the same length.
880 // NOTE: This is currently disabled, as it does not appear to be profitable in
881 // initial measurements.
882 if (0 && SourceLineCacheEnd-SourceLineCache > 20) {
Ted Kremenek78d85f52007-10-30 21:08:08 +0000883 unsigned FileLen = Content->SourceLineCache[Content->NumLines-1];
Mike Stump1eb44332009-09-09 15:08:12 +0000884
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000885 // Take a stab at guessing where it is.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000886 unsigned ApproxPos = Content->NumLines*QueriedFilePos / FileLen;
Mike Stump1eb44332009-09-09 15:08:12 +0000887
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000888 // Check for -10 and +10 lines.
889 unsigned LowerBound = std::max(int(ApproxPos-10), 0);
890 unsigned UpperBound = std::min(ApproxPos+10, FileLen);
891
892 // If the computed lower bound is less than the query location, move it in.
893 if (SourceLineCache < SourceLineCacheStart+LowerBound &&
894 SourceLineCacheStart[LowerBound] < QueriedFilePos)
895 SourceLineCache = SourceLineCacheStart+LowerBound;
Mike Stump1eb44332009-09-09 15:08:12 +0000896
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000897 // If the computed upper bound is greater than the query location, move it.
898 if (SourceLineCacheEnd > SourceLineCacheStart+UpperBound &&
899 SourceLineCacheStart[UpperBound] >= QueriedFilePos)
900 SourceLineCacheEnd = SourceLineCacheStart+UpperBound;
901 }
Mike Stump1eb44332009-09-09 15:08:12 +0000902
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000903 unsigned *Pos
904 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000905 unsigned LineNo = Pos-SourceLineCacheStart;
Mike Stump1eb44332009-09-09 15:08:12 +0000906
Chris Lattner30fc9332009-02-04 01:06:56 +0000907 LastLineNoFileIDQuery = FID;
Ted Kremenek78d85f52007-10-30 21:08:08 +0000908 LastLineNoContentCache = Content;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000909 LastLineNoFilePos = QueriedFilePos;
910 LastLineNoResult = LineNo;
911 return LineNo;
Reid Spencer5f016e22007-07-11 17:01:13 +0000912}
913
Douglas Gregor50f6af72010-03-16 05:20:39 +0000914unsigned SourceManager::getInstantiationLineNumber(SourceLocation Loc,
915 bool *Invalid) const {
Chris Lattner30fc9332009-02-04 01:06:56 +0000916 if (Loc.isInvalid()) return 0;
917 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
918 return getLineNumber(LocInfo.first, LocInfo.second);
919}
Douglas Gregor50f6af72010-03-16 05:20:39 +0000920unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
921 bool *Invalid) const {
Chris Lattner30fc9332009-02-04 01:06:56 +0000922 if (Loc.isInvalid()) return 0;
923 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
924 return getLineNumber(LocInfo.first, LocInfo.second);
925}
926
Chris Lattner6b306672009-02-04 05:33:01 +0000927/// getFileCharacteristic - return the file characteristic of the specified
Mike Stump1eb44332009-09-09 15:08:12 +0000928/// source location, indicating whether this is a normal file, a system
Chris Lattner6b306672009-02-04 05:33:01 +0000929/// header, or an "implicit extern C" system header.
930///
931/// This state can be modified with flags on GNU linemarker directives like:
932/// # 4 "foo.h" 3
933/// which changes all source locations in the current file after that to be
934/// considered to be from a system header.
Mike Stump1eb44332009-09-09 15:08:12 +0000935SrcMgr::CharacteristicKind
Chris Lattner6b306672009-02-04 05:33:01 +0000936SourceManager::getFileCharacteristic(SourceLocation Loc) const {
937 assert(!Loc.isInvalid() && "Can't get file characteristic of invalid loc!");
938 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
939 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile();
940
941 // If there are no #line directives in this file, just return the whole-file
942 // state.
943 if (!FI.hasLineDirectives())
944 return FI.getFileCharacteristic();
Mike Stump1eb44332009-09-09 15:08:12 +0000945
Chris Lattner6b306672009-02-04 05:33:01 +0000946 assert(LineTable && "Can't have linetable entries without a LineTable!");
947 // See if there is a #line directive before the location.
948 const LineEntry *Entry =
949 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second);
Mike Stump1eb44332009-09-09 15:08:12 +0000950
Chris Lattner6b306672009-02-04 05:33:01 +0000951 // If this is before the first line marker, use the file characteristic.
952 if (!Entry)
953 return FI.getFileCharacteristic();
954
955 return Entry->FileKind;
956}
957
Chris Lattnerbff5c512009-02-17 08:39:06 +0000958/// Return the filename or buffer identifier of the buffer the location is in.
959/// Note that this name does not respect #line directives. Use getPresumedLoc
960/// for normal clients.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000961const char *SourceManager::getBufferName(SourceLocation Loc,
962 bool *Invalid) const {
Chris Lattnerbff5c512009-02-17 08:39:06 +0000963 if (Loc.isInvalid()) return "<invalid loc>";
Mike Stump1eb44332009-09-09 15:08:12 +0000964
Douglas Gregor50f6af72010-03-16 05:20:39 +0000965 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
Chris Lattnerbff5c512009-02-17 08:39:06 +0000966}
967
Chris Lattner30fc9332009-02-04 01:06:56 +0000968
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000969/// getPresumedLoc - This method returns the "presumed" location of a
970/// SourceLocation specifies. A "presumed location" can be modified by #line
971/// or GNU line marker directives. This provides a view on the data that a
972/// user should see in diagnostics, for example.
973///
974/// Note that a presumed location is always given as the instantiation point
975/// of an instantiation location, not at the spelling location.
976PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc) const {
977 if (Loc.isInvalid()) return PresumedLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000978
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000979 // Presumed locations are always for instantiation points.
Chris Lattner7da5aea2009-02-04 00:55:58 +0000980 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000981
Chris Lattner30fc9332009-02-04 01:06:56 +0000982 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile();
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000983 const SrcMgr::ContentCache *C = FI.getContentCache();
Mike Stump1eb44332009-09-09 15:08:12 +0000984
Chris Lattner3cd949c2009-02-04 01:55:42 +0000985 // To get the source name, first consult the FileEntry (if one exists)
986 // before the MemBuffer as this will avoid unnecessarily paging in the
987 // MemBuffer.
Mike Stump1eb44332009-09-09 15:08:12 +0000988 const char *Filename =
Douglas Gregor36c35ba2010-03-16 00:35:39 +0000989 C->Entry ? C->Entry->getName() : C->getBuffer(Diag)->getBufferIdentifier();
Chris Lattner3cd949c2009-02-04 01:55:42 +0000990 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second);
991 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second);
992 SourceLocation IncludeLoc = FI.getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000993
Chris Lattner3cd949c2009-02-04 01:55:42 +0000994 // If we have #line directives in this file, update and overwrite the physical
995 // location info if appropriate.
996 if (FI.hasLineDirectives()) {
997 assert(LineTable && "Can't have linetable entries without a LineTable!");
998 // See if there is a #line directive before this. If so, get it.
999 if (const LineEntry *Entry =
1000 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second)) {
Chris Lattnerfc391332009-02-04 02:00:59 +00001001 // If the LineEntry indicates a filename, use it.
Chris Lattner3cd949c2009-02-04 01:55:42 +00001002 if (Entry->FilenameID != -1)
1003 Filename = LineTable->getFilename(Entry->FilenameID);
Chris Lattnerfc391332009-02-04 02:00:59 +00001004
1005 // Use the line number specified by the LineEntry. This line number may
1006 // be multiple lines down from the line entry. Add the difference in
1007 // physical line numbers from the query point and the line marker to the
1008 // total.
1009 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1010 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001011
Chris Lattner0e0e5da2009-02-04 02:15:40 +00001012 // Note that column numbers are not molested by line markers.
Mike Stump1eb44332009-09-09 15:08:12 +00001013
Chris Lattner137b6a62009-02-04 06:25:26 +00001014 // Handle virtual #include manipulation.
1015 if (Entry->IncludeOffset) {
1016 IncludeLoc = getLocForStartOfFile(LocInfo.first);
1017 IncludeLoc = IncludeLoc.getFileLocWithOffset(Entry->IncludeOffset);
1018 }
Chris Lattner3cd949c2009-02-04 01:55:42 +00001019 }
1020 }
1021
1022 return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc);
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001023}
1024
1025//===----------------------------------------------------------------------===//
1026// Other miscellaneous methods.
1027//===----------------------------------------------------------------------===//
1028
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001029/// \brief Get the source location for the given file:line:col triplet.
1030///
1031/// If the source file is included multiple times, the source location will
1032/// be based upon the first inclusion.
1033SourceLocation SourceManager::getLocation(const FileEntry *SourceFile,
1034 unsigned Line, unsigned Col) const {
1035 assert(SourceFile && "Null source file!");
1036 assert(Line && Col && "Line and column should start from 1!");
1037
1038 fileinfo_iterator FI = FileInfos.find(SourceFile);
1039 if (FI == FileInfos.end())
1040 return SourceLocation();
1041 ContentCache *Content = FI->second;
Mike Stump1eb44332009-09-09 15:08:12 +00001042
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001043 // If this is the first use of line information for this buffer, compute the
1044 /// SourceLineCache for it on demand.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001045 if (Content->SourceLineCache == 0) {
1046 bool MyInvalid = false;
1047 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, MyInvalid);
1048 if (MyInvalid)
1049 return SourceLocation();
1050 }
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001051
Douglas Gregor4a160e12009-12-02 05:34:39 +00001052 // Find the first file ID that corresponds to the given file.
1053 FileID FirstFID;
1054
1055 // First, check the main file ID, since it is common to look for a
1056 // location in the main file.
1057 if (!MainFileID.isInvalid()) {
1058 const SLocEntry &MainSLoc = getSLocEntry(MainFileID);
1059 if (MainSLoc.isFile() && MainSLoc.getFile().getContentCache() == Content)
1060 FirstFID = MainFileID;
1061 }
1062
1063 if (FirstFID.isInvalid()) {
1064 // The location we're looking for isn't in the main file; look
1065 // through all of the source locations.
1066 for (unsigned I = 0, N = sloc_entry_size(); I != N; ++I) {
1067 const SLocEntry &SLoc = getSLocEntry(I);
1068 if (SLoc.isFile() && SLoc.getFile().getContentCache() == Content) {
1069 FirstFID = FileID::get(I);
1070 break;
1071 }
1072 }
1073 }
1074
1075 if (FirstFID.isInvalid())
1076 return SourceLocation();
1077
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001078 if (Line > Content->NumLines) {
Douglas Gregor36c35ba2010-03-16 00:35:39 +00001079 unsigned Size = Content->getBuffer(Diag)->getBufferSize();
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001080 if (Size > 0)
1081 --Size;
1082 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(Size);
1083 }
1084
1085 unsigned FilePos = Content->SourceLineCache[Line - 1];
Douglas Gregor36c35ba2010-03-16 00:35:39 +00001086 const char *Buf = Content->getBuffer(Diag)->getBufferStart() + FilePos;
1087 unsigned BufLength = Content->getBuffer(Diag)->getBufferEnd() - Buf;
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001088 unsigned i = 0;
1089
1090 // Check that the given column is valid.
1091 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1092 ++i;
1093 if (i < Col-1)
1094 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + i);
1095
Douglas Gregor4a160e12009-12-02 05:34:39 +00001096 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + Col - 1);
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001097}
1098
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001099/// \brief Determines the order of 2 source locations in the translation unit.
1100///
1101/// \returns true if LHS source location comes before RHS, false otherwise.
1102bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
1103 SourceLocation RHS) const {
1104 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
1105 if (LHS == RHS)
1106 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001107
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001108 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
1109 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00001110
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001111 // If the source locations are in the same file, just compare offsets.
1112 if (LOffs.first == ROffs.first)
1113 return LOffs.second < ROffs.second;
1114
1115 // If we are comparing a source location with multiple locations in the same
1116 // file, we get a big win by caching the result.
Mike Stump1eb44332009-09-09 15:08:12 +00001117
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001118 if (LastLFIDForBeforeTUCheck == LOffs.first &&
1119 LastRFIDForBeforeTUCheck == ROffs.first)
1120 return LastResForBeforeTUCheck;
Mike Stump1eb44332009-09-09 15:08:12 +00001121
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001122 LastLFIDForBeforeTUCheck = LOffs.first;
1123 LastRFIDForBeforeTUCheck = ROffs.first;
Mike Stump1eb44332009-09-09 15:08:12 +00001124
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001125 // "Traverse" the include/instantiation stacks of both locations and try to
1126 // find a common "ancestor".
1127 //
1128 // First we traverse the stack of the right location and check each level
1129 // against the level of the left location, while collecting all levels in a
1130 // "stack map".
1131
1132 std::map<FileID, unsigned> ROffsMap;
1133 ROffsMap[ROffs.first] = ROffs.second;
1134
1135 while (1) {
1136 SourceLocation UpperLoc;
1137 const SrcMgr::SLocEntry &Entry = getSLocEntry(ROffs.first);
1138 if (Entry.isInstantiation())
1139 UpperLoc = Entry.getInstantiation().getInstantiationLocStart();
1140 else
1141 UpperLoc = Entry.getFile().getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001142
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001143 if (UpperLoc.isInvalid())
1144 break; // We reached the top.
Mike Stump1eb44332009-09-09 15:08:12 +00001145
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001146 ROffs = getDecomposedLoc(UpperLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001147
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001148 if (LOffs.first == ROffs.first)
1149 return LastResForBeforeTUCheck = LOffs.second < ROffs.second;
Mike Stump1eb44332009-09-09 15:08:12 +00001150
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001151 ROffsMap[ROffs.first] = ROffs.second;
1152 }
1153
1154 // We didn't find a common ancestor. Now traverse the stack of the left
1155 // location, checking against the stack map of the right location.
1156
1157 while (1) {
1158 SourceLocation UpperLoc;
1159 const SrcMgr::SLocEntry &Entry = getSLocEntry(LOffs.first);
1160 if (Entry.isInstantiation())
1161 UpperLoc = Entry.getInstantiation().getInstantiationLocStart();
1162 else
1163 UpperLoc = Entry.getFile().getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001164
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001165 if (UpperLoc.isInvalid())
1166 break; // We reached the top.
Mike Stump1eb44332009-09-09 15:08:12 +00001167
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001168 LOffs = getDecomposedLoc(UpperLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001169
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001170 std::map<FileID, unsigned>::iterator I = ROffsMap.find(LOffs.first);
1171 if (I != ROffsMap.end())
1172 return LastResForBeforeTUCheck = LOffs.second < I->second;
1173 }
Mike Stump1eb44332009-09-09 15:08:12 +00001174
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001175 // There is no common ancestor, most probably because one location is in the
1176 // predefines buffer.
1177 //
1178 // FIXME: We should rearrange the external interface so this simply never
1179 // happens; it can't conceptually happen. Also see PR5662.
Mike Stump1eb44332009-09-09 15:08:12 +00001180
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001181 // If exactly one location is a memory buffer, assume it preceeds the other.
1182 bool LIsMB = !getSLocEntry(LOffs.first).getFile().getContentCache()->Entry;
1183 bool RIsMB = !getSLocEntry(ROffs.first).getFile().getContentCache()->Entry;
1184 if (LIsMB != RIsMB)
1185 return LastResForBeforeTUCheck = LIsMB;
Mike Stump1eb44332009-09-09 15:08:12 +00001186
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001187 // Otherwise, just assume FileIDs were created in order.
1188 return LastResForBeforeTUCheck = (LOffs.first < ROffs.first);
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001189}
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001190
Reid Spencer5f016e22007-07-11 17:01:13 +00001191/// PrintStats - Print statistics to stderr.
1192///
1193void SourceManager::PrintStats() const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001194 llvm::errs() << "\n*** Source Manager Stats:\n";
1195 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
1196 << " mem buffers mapped.\n";
1197 llvm::errs() << SLocEntryTable.size() << " SLocEntry's allocated, "
1198 << NextOffset << "B of Sloc address space used.\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001199
Reid Spencer5f016e22007-07-11 17:01:13 +00001200 unsigned NumLineNumsComputed = 0;
1201 unsigned NumFileBytesMapped = 0;
Chris Lattner0d0bf8c2009-02-03 07:30:45 +00001202 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
1203 NumLineNumsComputed += I->second->SourceLineCache != 0;
1204 NumFileBytesMapped += I->second->getSizeBytesMapped();
Reid Spencer5f016e22007-07-11 17:01:13 +00001205 }
Mike Stump1eb44332009-09-09 15:08:12 +00001206
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001207 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
1208 << NumLineNumsComputed << " files with line #'s computed.\n";
1209 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
1210 << NumBinaryProbes << " binary.\n";
Reid Spencer5f016e22007-07-11 17:01:13 +00001211}
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001212
1213ExternalSLocEntrySource::~ExternalSLocEntrySource() { }