blob: 053cfe333d0b5308b477a22c6d896f4a9bfccc55 [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 Gregor93ea5cb2010-03-22 15:10:57 +000092
93 if (Diag.isDiagnosticInFlight())
94 Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
95 Entry->getName(), ErrorStr);
96 else
97 Diag.Report(diag::err_cannot_open_file)
98 << Entry->getName() << ErrorStr;
99
Douglas Gregorc8151082010-03-16 22:53:51 +0000100 Buffer.setInt(true);
Daniel Dunbar0b3c7732010-04-10 01:17:16 +0000101
102 // FIXME: This conditionalization is horrible, but we see spurious failures
103 // in the test suite due to this warning and no one has had time to hunt it
104 // down. So for now, we just don't emit this diagnostic on Win32, and hope
105 // nothing bad happens.
106 //
107 // PR6812.
Douglas Gregor9f692a02010-04-09 15:54:22 +0000108#if !defined(LLVM_ON_WIN32)
Daniel Dunbar0b3c7732010-04-10 01:17:16 +0000109 } else if (FileInfo.st_size != Entry->getSize() ||
110 FileInfo.st_mtime != Entry->getModificationTime()) {
Douglas Gregor9f692a02010-04-09 15:54:22 +0000111 // Check that the file's size and modification time are the same
112 // as in the file entry (which may have come from a stat cache).
Douglas Gregor93ea5cb2010-03-22 15:10:57 +0000113 if (Diag.isDiagnosticInFlight())
Daniel Dunbar0b3c7732010-04-10 01:17:16 +0000114 Diag.SetDelayedDiagnostic(diag::err_file_modified,
Douglas Gregor93ea5cb2010-03-22 15:10:57 +0000115 Entry->getName());
Daniel Dunbar0b3c7732010-04-10 01:17:16 +0000116 else
Douglas Gregor93ea5cb2010-03-22 15:10:57 +0000117 Diag.Report(diag::err_file_modified) << Entry->getName();
118
Douglas Gregore39b6002010-03-17 15:30:15 +0000119 Buffer.setInt(true);
Daniel Dunbar0b3c7732010-04-10 01:17:16 +0000120#endif
Daniel Dunbar21a8bed2009-12-06 05:43:36 +0000121 }
Ted Kremenek5b034ad2009-01-06 22:43:04 +0000122 }
Douglas Gregoraea67db2010-03-15 22:54:52 +0000123
Douglas Gregorc8151082010-03-16 22:53:51 +0000124 if (Invalid)
125 *Invalid = Buffer.getInt();
126
127 return Buffer.getPointer();
Ted Kremenekc16c2082009-01-06 01:55:26 +0000128}
129
Chris Lattner5b9a5042009-01-26 07:57:50 +0000130unsigned LineTableInfo::getLineTableFilenameID(const char *Ptr, unsigned Len) {
131 // Look up the filename in the string table, returning the pre-existing value
132 // if it exists.
Mike Stump1eb44332009-09-09 15:08:12 +0000133 llvm::StringMapEntry<unsigned> &Entry =
Chris Lattner5b9a5042009-01-26 07:57:50 +0000134 FilenameIDs.GetOrCreateValue(Ptr, Ptr+Len, ~0U);
135 if (Entry.getValue() != ~0U)
136 return Entry.getValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000137
Chris Lattner5b9a5042009-01-26 07:57:50 +0000138 // Otherwise, assign this the next available ID.
139 Entry.setValue(FilenamesByID.size());
140 FilenamesByID.push_back(&Entry);
141 return FilenamesByID.size()-1;
142}
143
Chris Lattnerac50e342009-02-03 22:13:05 +0000144/// AddLineNote - Add a line note to the line table that indicates that there
145/// is a #line at the specified FID/Offset location which changes the presumed
146/// location to LineNo/FilenameID.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000147void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
Chris Lattnerac50e342009-02-03 22:13:05 +0000148 unsigned LineNo, int FilenameID) {
Chris Lattner23b5dc62009-02-04 00:40:31 +0000149 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump1eb44332009-09-09 15:08:12 +0000150
Chris Lattner23b5dc62009-02-04 00:40:31 +0000151 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
152 "Adding line entries out of order!");
Mike Stump1eb44332009-09-09 15:08:12 +0000153
Chris Lattner9d79eba2009-02-04 05:21:58 +0000154 SrcMgr::CharacteristicKind Kind = SrcMgr::C_User;
Chris Lattner137b6a62009-02-04 06:25:26 +0000155 unsigned IncludeOffset = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000156
Chris Lattner9d79eba2009-02-04 05:21:58 +0000157 if (!Entries.empty()) {
158 // If this is a '#line 4' after '#line 42 "foo.h"', make sure to remember
159 // that we are still in "foo.h".
160 if (FilenameID == -1)
161 FilenameID = Entries.back().FilenameID;
Mike Stump1eb44332009-09-09 15:08:12 +0000162
Chris Lattner137b6a62009-02-04 06:25:26 +0000163 // If we are after a line marker that switched us to system header mode, or
164 // that set #include information, preserve it.
Chris Lattner9d79eba2009-02-04 05:21:58 +0000165 Kind = Entries.back().FileKind;
Chris Lattner137b6a62009-02-04 06:25:26 +0000166 IncludeOffset = Entries.back().IncludeOffset;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000167 }
Mike Stump1eb44332009-09-09 15:08:12 +0000168
Chris Lattner137b6a62009-02-04 06:25:26 +0000169 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, Kind,
170 IncludeOffset));
Chris Lattnerac50e342009-02-03 22:13:05 +0000171}
172
Chris Lattner9d79eba2009-02-04 05:21:58 +0000173/// AddLineNote This is the same as the previous version of AddLineNote, but is
174/// used for GNU line markers. If EntryExit is 0, then this doesn't change the
175/// presumed #include stack. If it is 1, this is a file entry, if it is 2 then
176/// this is a file exit. FileKind specifies whether this is a system header or
177/// extern C system header.
178void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
179 unsigned LineNo, int FilenameID,
180 unsigned EntryExit,
181 SrcMgr::CharacteristicKind FileKind) {
182 assert(FilenameID != -1 && "Unspecified filename should use other accessor");
Mike Stump1eb44332009-09-09 15:08:12 +0000183
Chris Lattner9d79eba2009-02-04 05:21:58 +0000184 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump1eb44332009-09-09 15:08:12 +0000185
Chris Lattner9d79eba2009-02-04 05:21:58 +0000186 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
187 "Adding line entries out of order!");
188
Chris Lattner137b6a62009-02-04 06:25:26 +0000189 unsigned IncludeOffset = 0;
190 if (EntryExit == 0) { // No #include stack change.
191 IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
192 } else if (EntryExit == 1) {
193 IncludeOffset = Offset-1;
194 } else if (EntryExit == 2) {
195 assert(!Entries.empty() && Entries.back().IncludeOffset &&
196 "PPDirectives should have caught case when popping empty include stack");
Mike Stump1eb44332009-09-09 15:08:12 +0000197
Chris Lattner137b6a62009-02-04 06:25:26 +0000198 // Get the include loc of the last entries' include loc as our include loc.
199 IncludeOffset = 0;
200 if (const LineEntry *PrevEntry =
201 FindNearestLineEntry(FID, Entries.back().IncludeOffset))
202 IncludeOffset = PrevEntry->IncludeOffset;
203 }
Mike Stump1eb44332009-09-09 15:08:12 +0000204
Chris Lattner137b6a62009-02-04 06:25:26 +0000205 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
206 IncludeOffset));
Chris Lattner9d79eba2009-02-04 05:21:58 +0000207}
208
209
Chris Lattner3cd949c2009-02-04 01:55:42 +0000210/// FindNearestLineEntry - Find the line entry nearest to FID that is before
211/// it. If there is no line entry before Offset in FID, return null.
Mike Stump1eb44332009-09-09 15:08:12 +0000212const LineEntry *LineTableInfo::FindNearestLineEntry(unsigned FID,
Chris Lattner3cd949c2009-02-04 01:55:42 +0000213 unsigned Offset) {
214 const std::vector<LineEntry> &Entries = LineEntries[FID];
215 assert(!Entries.empty() && "No #line entries for this FID after all!");
216
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000217 // It is very common for the query to be after the last #line, check this
218 // first.
219 if (Entries.back().FileOffset <= Offset)
220 return &Entries.back();
Chris Lattner3cd949c2009-02-04 01:55:42 +0000221
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000222 // Do a binary search to find the maximal element that is still before Offset.
223 std::vector<LineEntry>::const_iterator I =
224 std::upper_bound(Entries.begin(), Entries.end(), Offset);
225 if (I == Entries.begin()) return 0;
226 return &*--I;
Chris Lattner3cd949c2009-02-04 01:55:42 +0000227}
Chris Lattnerac50e342009-02-03 22:13:05 +0000228
Douglas Gregorbd945002009-04-13 16:31:14 +0000229/// \brief Add a new line entry that has already been encoded into
230/// the internal representation of the line table.
Mike Stump1eb44332009-09-09 15:08:12 +0000231void LineTableInfo::AddEntry(unsigned FID,
Douglas Gregorbd945002009-04-13 16:31:14 +0000232 const std::vector<LineEntry> &Entries) {
233 LineEntries[FID] = Entries;
234}
Chris Lattnerac50e342009-02-03 22:13:05 +0000235
Chris Lattner5b9a5042009-01-26 07:57:50 +0000236/// getLineTableFilenameID - Return the uniqued ID for the specified filename.
Mike Stump1eb44332009-09-09 15:08:12 +0000237///
Chris Lattner5b9a5042009-01-26 07:57:50 +0000238unsigned SourceManager::getLineTableFilenameID(const char *Ptr, unsigned Len) {
239 if (LineTable == 0)
240 LineTable = new LineTableInfo();
241 return LineTable->getLineTableFilenameID(Ptr, Len);
242}
243
244
Chris Lattner4c4ea172009-02-03 21:52:55 +0000245/// AddLineNote - Add a line note to the line table for the FileID and offset
246/// specified by Loc. If FilenameID is -1, it is considered to be
247/// unspecified.
248void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
249 int FilenameID) {
Chris Lattnerac50e342009-02-03 22:13:05 +0000250 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000251
Chris Lattnerac50e342009-02-03 22:13:05 +0000252 const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile();
253
254 // Remember that this file has #line directives now if it doesn't already.
255 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump1eb44332009-09-09 15:08:12 +0000256
Chris Lattnerac50e342009-02-03 22:13:05 +0000257 if (LineTable == 0)
258 LineTable = new LineTableInfo();
Chris Lattner23b5dc62009-02-04 00:40:31 +0000259 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID);
Chris Lattner4c4ea172009-02-03 21:52:55 +0000260}
261
Chris Lattner9d79eba2009-02-04 05:21:58 +0000262/// AddLineNote - Add a GNU line marker to the line table.
263void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
264 int FilenameID, bool IsFileEntry,
265 bool IsFileExit, bool IsSystemHeader,
266 bool IsExternCHeader) {
267 // If there is no filename and no flags, this is treated just like a #line,
268 // which does not change the flags of the previous line marker.
269 if (FilenameID == -1) {
270 assert(!IsFileEntry && !IsFileExit && !IsSystemHeader && !IsExternCHeader &&
271 "Can't set flags without setting the filename!");
272 return AddLineNote(Loc, LineNo, FilenameID);
273 }
Mike Stump1eb44332009-09-09 15:08:12 +0000274
Chris Lattner9d79eba2009-02-04 05:21:58 +0000275 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
276 const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile();
Mike Stump1eb44332009-09-09 15:08:12 +0000277
Chris Lattner9d79eba2009-02-04 05:21:58 +0000278 // Remember that this file has #line directives now if it doesn't already.
279 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump1eb44332009-09-09 15:08:12 +0000280
Chris Lattner9d79eba2009-02-04 05:21:58 +0000281 if (LineTable == 0)
282 LineTable = new LineTableInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000283
Chris Lattner9d79eba2009-02-04 05:21:58 +0000284 SrcMgr::CharacteristicKind FileKind;
285 if (IsExternCHeader)
286 FileKind = SrcMgr::C_ExternCSystem;
287 else if (IsSystemHeader)
288 FileKind = SrcMgr::C_System;
289 else
290 FileKind = SrcMgr::C_User;
Mike Stump1eb44332009-09-09 15:08:12 +0000291
Chris Lattner9d79eba2009-02-04 05:21:58 +0000292 unsigned EntryExit = 0;
293 if (IsFileEntry)
294 EntryExit = 1;
295 else if (IsFileExit)
296 EntryExit = 2;
Mike Stump1eb44332009-09-09 15:08:12 +0000297
Chris Lattner9d79eba2009-02-04 05:21:58 +0000298 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID,
299 EntryExit, FileKind);
300}
301
Douglas Gregorbd945002009-04-13 16:31:14 +0000302LineTableInfo &SourceManager::getLineTable() {
303 if (LineTable == 0)
304 LineTable = new LineTableInfo();
305 return *LineTable;
306}
Chris Lattner4c4ea172009-02-03 21:52:55 +0000307
Chris Lattner23b5dc62009-02-04 00:40:31 +0000308//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000309// Private 'Create' methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000310//===----------------------------------------------------------------------===//
Ted Kremenekc16c2082009-01-06 01:55:26 +0000311
Chris Lattner5b9a5042009-01-26 07:57:50 +0000312SourceManager::~SourceManager() {
313 delete LineTable;
Mike Stump1eb44332009-09-09 15:08:12 +0000314
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000315 // Delete FileEntry objects corresponding to content caches. Since the actual
316 // content cache objects are bump pointer allocated, we just have to run the
317 // dtors, but we call the deallocate method for completeness.
318 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
319 MemBufferInfos[i]->~ContentCache();
320 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
321 }
322 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
323 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
324 I->second->~ContentCache();
325 ContentCacheAlloc.Deallocate(I->second);
326 }
Chris Lattner5b9a5042009-01-26 07:57:50 +0000327}
328
329void SourceManager::clearIDTables() {
330 MainFileID = FileID();
331 SLocEntryTable.clear();
332 LastLineNoFileIDQuery = FileID();
333 LastLineNoContentCache = 0;
334 LastFileIDLookup = FileID();
Mike Stump1eb44332009-09-09 15:08:12 +0000335
Chris Lattner5b9a5042009-01-26 07:57:50 +0000336 if (LineTable)
337 LineTable->clear();
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Chris Lattner5b9a5042009-01-26 07:57:50 +0000339 // Use up FileID #0 as an invalid instantiation.
340 NextOffset = 0;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000341 createInstantiationLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000342}
343
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000344/// getOrCreateContentCache - Create or return a cached ContentCache for the
345/// specified file.
346const ContentCache *
347SourceManager::getOrCreateContentCache(const FileEntry *FileEnt) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000348 assert(FileEnt && "Didn't specify a file entry to use?");
Mike Stump1eb44332009-09-09 15:08:12 +0000349
Reid Spencer5f016e22007-07-11 17:01:13 +0000350 // Do we already have information about this file?
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000351 ContentCache *&Entry = FileInfos[FileEnt];
352 if (Entry) return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +0000353
Chris Lattner00282d62009-02-03 07:41:46 +0000354 // Nope, create a new Cache entry. Make sure it is at least 8-byte aligned
355 // so that FileInfo can use the low 3 bits of the pointer for its own
356 // nefarious purposes.
357 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
358 EntryAlign = std::max(8U, EntryAlign);
359 Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000360 new (Entry) ContentCache(FileEnt);
361 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000362}
363
364
Ted Kremenekd1c0eee2007-10-31 17:53:38 +0000365/// createMemBufferContentCache - Create a new ContentCache for the specified
366/// memory buffer. This does no caching.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000367const ContentCache*
368SourceManager::createMemBufferContentCache(const MemoryBuffer *Buffer) {
Chris Lattner00282d62009-02-03 07:41:46 +0000369 // Add a new ContentCache to the MemBufferInfos list and return it. Make sure
370 // it is at least 8-byte aligned so that FileInfo can use the low 3 bits of
371 // the pointer for its own nefarious purposes.
372 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
373 EntryAlign = std::max(8U, EntryAlign);
374 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000375 new (Entry) ContentCache();
376 MemBufferInfos.push_back(Entry);
377 Entry->setBuffer(Buffer);
378 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000379}
380
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000381void SourceManager::PreallocateSLocEntries(ExternalSLocEntrySource *Source,
382 unsigned NumSLocEntries,
383 unsigned NextOffset) {
384 ExternalSLocEntries = Source;
385 this->NextOffset = NextOffset;
386 SLocEntryLoaded.resize(NumSLocEntries + 1);
387 SLocEntryLoaded[0] = true;
388 SLocEntryTable.resize(SLocEntryTable.size() + NumSLocEntries);
389}
390
Douglas Gregor2bf1eb02009-04-27 21:28:04 +0000391void SourceManager::ClearPreallocatedSLocEntries() {
392 unsigned I = 0;
393 for (unsigned N = SLocEntryLoaded.size(); I != N; ++I)
394 if (!SLocEntryLoaded[I])
395 break;
396
397 // We've already loaded all preallocated source location entries.
398 if (I == SLocEntryLoaded.size())
399 return;
400
401 // Remove everything from location I onward.
402 SLocEntryTable.resize(I);
403 SLocEntryLoaded.clear();
404 ExternalSLocEntries = 0;
405}
406
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000407
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000408//===----------------------------------------------------------------------===//
409// Methods to create new FileID's and instantiations.
410//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000411
Nico Weber48002c82008-09-29 00:25:48 +0000412/// createFileID - Create a new fileID for the specified ContentCache and
Ted Kremenek0d892d82007-10-30 22:57:35 +0000413/// include position. This works regardless of whether the ContentCache
414/// corresponds to a file or some other input source.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000415FileID SourceManager::createFileID(const ContentCache *File,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000416 SourceLocation IncludePos,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000417 SrcMgr::CharacteristicKind FileCharacter,
418 unsigned PreallocatedID,
419 unsigned Offset) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000420 if (PreallocatedID) {
421 // If we're filling in a preallocated ID, just load in the file
422 // entry and return.
Mike Stump1eb44332009-09-09 15:08:12 +0000423 assert(PreallocatedID < SLocEntryLoaded.size() &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000424 "Preallocate ID out-of-range");
Mike Stump1eb44332009-09-09 15:08:12 +0000425 assert(!SLocEntryLoaded[PreallocatedID] &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000426 "Source location entry already loaded");
427 assert(Offset && "Preallocate source location cannot have zero offset");
Mike Stump1eb44332009-09-09 15:08:12 +0000428 SLocEntryTable[PreallocatedID]
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000429 = SLocEntry::get(Offset, FileInfo::get(IncludePos, File, FileCharacter));
430 SLocEntryLoaded[PreallocatedID] = true;
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +0000431 FileID FID = FileID::get(PreallocatedID);
Douglas Gregor5de65722010-03-19 06:12:06 +0000432 return FID;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000433 }
434
Mike Stump1eb44332009-09-09 15:08:12 +0000435 SLocEntryTable.push_back(SLocEntry::get(NextOffset,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000436 FileInfo::get(IncludePos, File,
437 FileCharacter)));
Ted Kremenekc16c2082009-01-06 01:55:26 +0000438 unsigned FileSize = File->getSize();
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000439 assert(NextOffset+FileSize+1 > NextOffset && "Ran out of source locations!");
440 NextOffset += FileSize+1;
Mike Stump1eb44332009-09-09 15:08:12 +0000441
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000442 // Set LastFileIDLookup to the newly created file. The next getFileID call is
443 // almost guaranteed to be from that file.
Argyrios Kyrtzidisea703f12009-06-23 00:42:06 +0000444 FileID FID = FileID::get(SLocEntryTable.size()-1);
Argyrios Kyrtzidisea703f12009-06-23 00:42:06 +0000445 return LastFileIDLookup = FID;
Reid Spencer5f016e22007-07-11 17:01:13 +0000446}
447
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000448/// createInstantiationLoc - Return a new SourceLocation that encodes the fact
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000449/// that a token from SpellingLoc should actually be referenced from
Reid Spencer5f016e22007-07-11 17:01:13 +0000450/// InstantiationLoc.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000451SourceLocation SourceManager::createInstantiationLoc(SourceLocation SpellingLoc,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000452 SourceLocation ILocStart,
453 SourceLocation ILocEnd,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000454 unsigned TokLength,
455 unsigned PreallocatedID,
456 unsigned Offset) {
Chris Lattnere7fb4842009-02-15 20:52:18 +0000457 InstantiationInfo II = InstantiationInfo::get(ILocStart,ILocEnd, SpellingLoc);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000458 if (PreallocatedID) {
459 // If we're filling in a preallocated ID, just load in the
460 // instantiation entry and return.
Mike Stump1eb44332009-09-09 15:08:12 +0000461 assert(PreallocatedID < SLocEntryLoaded.size() &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000462 "Preallocate ID out-of-range");
Mike Stump1eb44332009-09-09 15:08:12 +0000463 assert(!SLocEntryLoaded[PreallocatedID] &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000464 "Source location entry already loaded");
465 assert(Offset && "Preallocate source location cannot have zero offset");
466 SLocEntryTable[PreallocatedID] = SLocEntry::get(Offset, II);
467 SLocEntryLoaded[PreallocatedID] = true;
468 return SourceLocation::getMacroLoc(Offset);
469 }
Chris Lattnere7fb4842009-02-15 20:52:18 +0000470 SLocEntryTable.push_back(SLocEntry::get(NextOffset, II));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000471 assert(NextOffset+TokLength+1 > NextOffset && "Ran out of source locations!");
472 NextOffset += TokLength+1;
473 return SourceLocation::getMacroLoc(NextOffset-(TokLength+1));
Reid Spencer5f016e22007-07-11 17:01:13 +0000474}
475
Douglas Gregor36c35ba2010-03-16 00:35:39 +0000476const llvm::MemoryBuffer *
Douglas Gregor50f6af72010-03-16 05:20:39 +0000477SourceManager::getMemoryBufferForFile(const FileEntry *File,
478 bool *Invalid) {
Douglas Gregor29684422009-12-02 06:49:09 +0000479 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
Douglas Gregoraea67db2010-03-15 22:54:52 +0000480 assert(IR && "getOrCreateContentCache() cannot return NULL");
Douglas Gregor50f6af72010-03-16 05:20:39 +0000481 return IR->getBuffer(Diag, Invalid);
Douglas Gregor29684422009-12-02 06:49:09 +0000482}
483
484bool SourceManager::overrideFileContents(const FileEntry *SourceFile,
485 const llvm::MemoryBuffer *Buffer) {
486 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
487 if (IR == 0)
488 return true;
489
490 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer);
491 return false;
492}
493
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000494llvm::StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
Douglas Gregoraae58b02010-03-16 20:01:30 +0000495 bool MyInvalid = false;
496 const llvm::MemoryBuffer *Buf = getBuffer(FID, &MyInvalid);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000497 if (Invalid)
Douglas Gregoraae58b02010-03-16 20:01:30 +0000498 *Invalid = MyInvalid;
499
500 if (MyInvalid)
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000501 return "";
Douglas Gregoraae58b02010-03-16 20:01:30 +0000502
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000503 return Buf->getBuffer();
Douglas Gregoraea67db2010-03-15 22:54:52 +0000504}
Chris Lattner2b2453a2009-01-17 06:22:33 +0000505
Chris Lattner23b5dc62009-02-04 00:40:31 +0000506//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000507// SourceLocation manipulation methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000508//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000509
510/// getFileIDSlow - Return the FileID for a SourceLocation. This is a very hot
511/// method that is used for all SourceManager queries that start with a
512/// SourceLocation object. It is responsible for finding the entry in
513/// SLocEntryTable which contains the specified location.
514///
515FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
516 assert(SLocOffset && "Invalid FileID");
Mike Stump1eb44332009-09-09 15:08:12 +0000517
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000518 // After the first and second level caches, I see two common sorts of
519 // behavior: 1) a lot of searched FileID's are "near" the cached file location
520 // or are "near" the cached instantiation location. 2) others are just
521 // completely random and may be a very long way away.
522 //
523 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
524 // then we fall back to a less cache efficient, but more scalable, binary
525 // search to find the location.
Mike Stump1eb44332009-09-09 15:08:12 +0000526
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000527 // See if this is near the file point - worst case we start scanning from the
528 // most newly created FileID.
529 std::vector<SrcMgr::SLocEntry>::const_iterator I;
Mike Stump1eb44332009-09-09 15:08:12 +0000530
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000531 if (SLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
532 // Neither loc prunes our search.
533 I = SLocEntryTable.end();
534 } else {
535 // Perhaps it is near the file point.
536 I = SLocEntryTable.begin()+LastFileIDLookup.ID;
537 }
538
539 // Find the FileID that contains this. "I" is an iterator that points to a
540 // FileID whose offset is known to be larger than SLocOffset.
541 unsigned NumProbes = 0;
542 while (1) {
543 --I;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000544 if (ExternalSLocEntries)
545 getSLocEntry(FileID::get(I - SLocEntryTable.begin()));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000546 if (I->getOffset() <= SLocOffset) {
547#if 0
548 printf("lin %d -> %d [%s] %d %d\n", SLocOffset,
549 I-SLocEntryTable.begin(),
550 I->isInstantiation() ? "inst" : "file",
551 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
552#endif
553 FileID Res = FileID::get(I-SLocEntryTable.begin());
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000554
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000555 // If this isn't an instantiation, remember it. We have good locality
556 // across FileID lookups.
557 if (!I->isInstantiation())
558 LastFileIDLookup = Res;
559 NumLinearScans += NumProbes+1;
560 return Res;
561 }
562 if (++NumProbes == 8)
563 break;
564 }
Mike Stump1eb44332009-09-09 15:08:12 +0000565
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000566 // Convert "I" back into an index. We know that it is an entry whose index is
567 // larger than the offset we are looking for.
568 unsigned GreaterIndex = I-SLocEntryTable.begin();
569 // LessIndex - This is the lower bound of the range that we're searching.
570 // We know that the offset corresponding to the FileID is is less than
571 // SLocOffset.
572 unsigned LessIndex = 0;
573 NumProbes = 0;
574 while (1) {
575 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000576 unsigned MidOffset = getSLocEntry(FileID::get(MiddleIndex)).getOffset();
Mike Stump1eb44332009-09-09 15:08:12 +0000577
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000578 ++NumProbes;
Mike Stump1eb44332009-09-09 15:08:12 +0000579
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000580 // If the offset of the midpoint is too large, chop the high side of the
581 // range to the midpoint.
582 if (MidOffset > SLocOffset) {
583 GreaterIndex = MiddleIndex;
584 continue;
585 }
Mike Stump1eb44332009-09-09 15:08:12 +0000586
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000587 // If the middle index contains the value, succeed and return.
588 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
589#if 0
590 printf("bin %d -> %d [%s] %d %d\n", SLocOffset,
591 I-SLocEntryTable.begin(),
592 I->isInstantiation() ? "inst" : "file",
593 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
594#endif
595 FileID Res = FileID::get(MiddleIndex);
596
597 // If this isn't an instantiation, remember it. We have good locality
598 // across FileID lookups.
599 if (!I->isInstantiation())
600 LastFileIDLookup = Res;
601 NumBinaryProbes += NumProbes;
602 return Res;
603 }
Mike Stump1eb44332009-09-09 15:08:12 +0000604
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000605 // Otherwise, move the low-side up to the middle index.
606 LessIndex = MiddleIndex;
607 }
608}
609
Chris Lattneraddb7972009-01-26 20:04:19 +0000610SourceLocation SourceManager::
611getInstantiationLocSlowCase(SourceLocation Loc) const {
612 do {
Chris Lattnera5c6c582010-02-12 19:31:35 +0000613 // Note: If Loc indicates an offset into a token that came from a macro
614 // expansion (e.g. the 5th character of the token) we do not want to add
615 // this offset when going to the instantiation location. The instatiation
616 // location is the macro invocation, which the offset has nothing to do
617 // with. This is unlike when we get the spelling loc, because the offset
618 // directly correspond to the token whose spelling we're inspecting.
619 Loc = getSLocEntry(getFileID(Loc)).getInstantiation()
Chris Lattnere7fb4842009-02-15 20:52:18 +0000620 .getInstantiationLocStart();
Chris Lattneraddb7972009-01-26 20:04:19 +0000621 } while (!Loc.isFileID());
622
623 return Loc;
624}
625
626SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
627 do {
628 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
629 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
630 Loc = Loc.getFileLocWithOffset(LocInfo.second);
631 } while (!Loc.isFileID());
632 return Loc;
633}
634
635
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000636std::pair<FileID, unsigned>
637SourceManager::getDecomposedInstantiationLocSlowCase(const SrcMgr::SLocEntry *E,
638 unsigned Offset) const {
639 // If this is an instantiation record, walk through all the instantiation
640 // points.
641 FileID FID;
642 SourceLocation Loc;
643 do {
Chris Lattnere7fb4842009-02-15 20:52:18 +0000644 Loc = E->getInstantiation().getInstantiationLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000645
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000646 FID = getFileID(Loc);
647 E = &getSLocEntry(FID);
648 Offset += Loc.getOffset()-E->getOffset();
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000649 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000650
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000651 return std::make_pair(FID, Offset);
652}
653
654std::pair<FileID, unsigned>
655SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
656 unsigned Offset) const {
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000657 // If this is an instantiation record, walk through all the instantiation
658 // points.
659 FileID FID;
660 SourceLocation Loc;
661 do {
662 Loc = E->getInstantiation().getSpellingLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000663
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000664 FID = getFileID(Loc);
665 E = &getSLocEntry(FID);
666 Offset += Loc.getOffset()-E->getOffset();
667 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000668
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000669 return std::make_pair(FID, Offset);
670}
671
Chris Lattner387616e2009-02-17 08:04:48 +0000672/// getImmediateSpellingLoc - Given a SourceLocation object, return the
673/// spelling location referenced by the ID. This is the first level down
674/// towards the place where the characters that make up the lexed token can be
675/// found. This should not generally be used by clients.
676SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
677 if (Loc.isFileID()) return Loc;
678 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
679 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
680 return Loc.getFileLocWithOffset(LocInfo.second);
681}
682
683
Chris Lattnere7fb4842009-02-15 20:52:18 +0000684/// getImmediateInstantiationRange - Loc is required to be an instantiation
685/// location. Return the start/end of the instantiation information.
686std::pair<SourceLocation,SourceLocation>
687SourceManager::getImmediateInstantiationRange(SourceLocation Loc) const {
688 assert(Loc.isMacroID() && "Not an instantiation loc!");
689 const InstantiationInfo &II = getSLocEntry(getFileID(Loc)).getInstantiation();
690 return II.getInstantiationLocRange();
691}
692
Chris Lattner66781332009-02-15 21:26:50 +0000693/// getInstantiationRange - Given a SourceLocation object, return the
694/// range of tokens covered by the instantiation in the ultimate file.
695std::pair<SourceLocation,SourceLocation>
696SourceManager::getInstantiationRange(SourceLocation Loc) const {
697 if (Loc.isFileID()) return std::make_pair(Loc, Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000698
Chris Lattner66781332009-02-15 21:26:50 +0000699 std::pair<SourceLocation,SourceLocation> Res =
700 getImmediateInstantiationRange(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000701
Chris Lattner66781332009-02-15 21:26:50 +0000702 // Fully resolve the start and end locations to their ultimate instantiation
703 // points.
704 while (!Res.first.isFileID())
705 Res.first = getImmediateInstantiationRange(Res.first).first;
706 while (!Res.second.isFileID())
707 Res.second = getImmediateInstantiationRange(Res.second).second;
708 return Res;
709}
710
Chris Lattnere7fb4842009-02-15 20:52:18 +0000711
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000712
713//===----------------------------------------------------------------------===//
714// Queries about the code at a SourceLocation.
715//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000716
717/// getCharacterData - Return a pointer to the start of the specified location
718/// in the appropriate MemoryBuffer.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000719const char *SourceManager::getCharacterData(SourceLocation SL,
720 bool *Invalid) const {
Reid Spencer5f016e22007-07-11 17:01:13 +0000721 // Note that this is a hot function in the getSpelling() path, which is
722 // heavily used by -E mode.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000723 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
Mike Stump1eb44332009-09-09 15:08:12 +0000724
Ted Kremenekc16c2082009-01-06 01:55:26 +0000725 // Note that calling 'getBuffer()' may lazily page in a source file.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000726 bool CharDataInvalid = false;
727 const llvm::MemoryBuffer *Buffer
728 = getSLocEntry(LocInfo.first).getFile().getContentCache()->getBuffer(Diag,
729 &CharDataInvalid);
730 if (Invalid)
731 *Invalid = CharDataInvalid;
732 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
Reid Spencer5f016e22007-07-11 17:01:13 +0000733}
734
Reid Spencer5f016e22007-07-11 17:01:13 +0000735
Chris Lattner9dc1f532007-07-20 16:37:10 +0000736/// getColumnNumber - Return the column # for the specified file position.
Chris Lattner7da5aea2009-02-04 00:55:58 +0000737/// this is significantly cheaper to compute than the line number.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000738unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
739 bool *Invalid) const {
740 bool MyInvalid = false;
741 const char *Buf = getBuffer(FID, &MyInvalid)->getBufferStart();
742 if (Invalid)
743 *Invalid = MyInvalid;
744
745 if (MyInvalid)
746 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000747
Reid Spencer5f016e22007-07-11 17:01:13 +0000748 unsigned LineStart = FilePos;
749 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
750 --LineStart;
751 return FilePos-LineStart+1;
752}
753
Douglas Gregor50f6af72010-03-16 05:20:39 +0000754unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
755 bool *Invalid) const {
Chris Lattner30fc9332009-02-04 01:06:56 +0000756 if (Loc.isInvalid()) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +0000757 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000758 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +0000759}
760
Douglas Gregor50f6af72010-03-16 05:20:39 +0000761unsigned SourceManager::getInstantiationColumnNumber(SourceLocation Loc,
762 bool *Invalid) const {
Chris Lattner30fc9332009-02-04 01:06:56 +0000763 if (Loc.isInvalid()) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +0000764 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000765 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +0000766}
767
Douglas Gregor36c35ba2010-03-16 00:35:39 +0000768static DISABLE_INLINE void ComputeLineNumbers(Diagnostic &Diag,
769 ContentCache* FI,
Douglas Gregor50f6af72010-03-16 05:20:39 +0000770 llvm::BumpPtrAllocator &Alloc,
771 bool &Invalid);
Douglas Gregor36c35ba2010-03-16 00:35:39 +0000772static void ComputeLineNumbers(Diagnostic &Diag, ContentCache* FI,
Douglas Gregor50f6af72010-03-16 05:20:39 +0000773 llvm::BumpPtrAllocator &Alloc, bool &Invalid) {
Ted Kremenekc16c2082009-01-06 01:55:26 +0000774 // Note that calling 'getBuffer()' may lazily page in the file.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000775 const MemoryBuffer *Buffer = FI->getBuffer(Diag, &Invalid);
776 if (Invalid)
777 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000778
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000779 // Find the file offsets of all of the *physical* source lines. This does
780 // not look at trigraphs, escaped newlines, or anything else tricky.
781 std::vector<unsigned> LineOffsets;
Mike Stump1eb44332009-09-09 15:08:12 +0000782
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000783 // Line #1 starts at char 0.
784 LineOffsets.push_back(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000785
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000786 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
787 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
788 unsigned Offs = 0;
789 while (1) {
790 // Skip over the contents of the line.
791 // TODO: Vectorize this? This is very performance sensitive for programs
792 // with lots of diagnostics and in -E mode.
793 const unsigned char *NextBuf = (const unsigned char *)Buf;
794 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
795 ++NextBuf;
796 Offs += NextBuf-Buf;
797 Buf = NextBuf;
Mike Stump1eb44332009-09-09 15:08:12 +0000798
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000799 if (Buf[0] == '\n' || Buf[0] == '\r') {
800 // If this is \n\r or \r\n, skip both characters.
801 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
802 ++Offs, ++Buf;
803 ++Offs, ++Buf;
804 LineOffsets.push_back(Offs);
805 } else {
806 // Otherwise, this is a null. If end of file, exit.
807 if (Buf == End) break;
808 // Otherwise, skip the null.
809 ++Offs, ++Buf;
810 }
811 }
Mike Stump1eb44332009-09-09 15:08:12 +0000812
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000813 // Copy the offsets into the FileInfo structure.
814 FI->NumLines = LineOffsets.size();
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000815 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000816 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
817}
Reid Spencer5f016e22007-07-11 17:01:13 +0000818
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000819/// getLineNumber - Given a SourceLocation, return the spelling line number
Reid Spencer5f016e22007-07-11 17:01:13 +0000820/// for the position indicated. This requires building and caching a table of
821/// line offsets for the MemoryBuffer, so this is not cheap: use only when
822/// about to emit a diagnostic.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000823unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
824 bool *Invalid) const {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000825 ContentCache *Content;
Chris Lattner30fc9332009-02-04 01:06:56 +0000826 if (LastLineNoFileIDQuery == FID)
Ted Kremenek78d85f52007-10-30 21:08:08 +0000827 Content = LastLineNoContentCache;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000828 else
Chris Lattner30fc9332009-02-04 01:06:56 +0000829 Content = const_cast<ContentCache*>(getSLocEntry(FID)
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000830 .getFile().getContentCache());
Mike Stump1eb44332009-09-09 15:08:12 +0000831
Reid Spencer5f016e22007-07-11 17:01:13 +0000832 // If this is the first use of line information for this buffer, compute the
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000833 /// SourceLineCache for it on demand.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000834 if (Content->SourceLineCache == 0) {
835 bool MyInvalid = false;
836 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, MyInvalid);
837 if (Invalid)
838 *Invalid = MyInvalid;
839 if (MyInvalid)
840 return 1;
841 } else if (Invalid)
842 *Invalid = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000843
844 // Okay, we know we have a line number table. Do a binary search to find the
845 // line number that this character position lands on.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000846 unsigned *SourceLineCache = Content->SourceLineCache;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000847 unsigned *SourceLineCacheStart = SourceLineCache;
Ted Kremenek78d85f52007-10-30 21:08:08 +0000848 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
Mike Stump1eb44332009-09-09 15:08:12 +0000849
Chris Lattner30fc9332009-02-04 01:06:56 +0000850 unsigned QueriedFilePos = FilePos+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000851
Daniel Dunbar4106d692009-05-18 17:30:52 +0000852 // FIXME: I would like to be convinced that this code is worth being as
Mike Stump1eb44332009-09-09 15:08:12 +0000853 // complicated as it is, binary search isn't that slow.
Daniel Dunbar4106d692009-05-18 17:30:52 +0000854 //
855 // If it is worth being optimized, then in my opinion it could be more
856 // performant, simpler, and more obviously correct by just "galloping" outward
857 // from the queried file position. In fact, this could be incorporated into a
858 // generic algorithm such as lower_bound_with_hint.
859 //
860 // If someone gives me a test case where this matters, and I will do it! - DWD
861
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000862 // If the previous query was to the same file, we know both the file pos from
863 // that query and the line number returned. This allows us to narrow the
864 // search space from the entire file to something near the match.
Chris Lattner30fc9332009-02-04 01:06:56 +0000865 if (LastLineNoFileIDQuery == FID) {
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000866 if (QueriedFilePos >= LastLineNoFilePos) {
Daniel Dunbar4106d692009-05-18 17:30:52 +0000867 // FIXME: Potential overflow?
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000868 SourceLineCache = SourceLineCache+LastLineNoResult-1;
Mike Stump1eb44332009-09-09 15:08:12 +0000869
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000870 // The query is likely to be nearby the previous one. Here we check to
871 // see if it is within 5, 10 or 20 lines. It can be far away in cases
872 // where big comment blocks and vertical whitespace eat up lines but
873 // contribute no tokens.
874 if (SourceLineCache+5 < SourceLineCacheEnd) {
875 if (SourceLineCache[5] > QueriedFilePos)
876 SourceLineCacheEnd = SourceLineCache+5;
877 else if (SourceLineCache+10 < SourceLineCacheEnd) {
878 if (SourceLineCache[10] > QueriedFilePos)
879 SourceLineCacheEnd = SourceLineCache+10;
880 else if (SourceLineCache+20 < SourceLineCacheEnd) {
881 if (SourceLineCache[20] > QueriedFilePos)
882 SourceLineCacheEnd = SourceLineCache+20;
883 }
884 }
885 }
886 } else {
Daniel Dunbar4106d692009-05-18 17:30:52 +0000887 if (LastLineNoResult < Content->NumLines)
888 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000889 }
890 }
Mike Stump1eb44332009-09-09 15:08:12 +0000891
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000892 // If the spread is large, do a "radix" test as our initial guess, based on
893 // the assumption that lines average to approximately the same length.
894 // NOTE: This is currently disabled, as it does not appear to be profitable in
895 // initial measurements.
896 if (0 && SourceLineCacheEnd-SourceLineCache > 20) {
Ted Kremenek78d85f52007-10-30 21:08:08 +0000897 unsigned FileLen = Content->SourceLineCache[Content->NumLines-1];
Mike Stump1eb44332009-09-09 15:08:12 +0000898
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000899 // Take a stab at guessing where it is.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000900 unsigned ApproxPos = Content->NumLines*QueriedFilePos / FileLen;
Mike Stump1eb44332009-09-09 15:08:12 +0000901
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000902 // Check for -10 and +10 lines.
903 unsigned LowerBound = std::max(int(ApproxPos-10), 0);
904 unsigned UpperBound = std::min(ApproxPos+10, FileLen);
905
906 // If the computed lower bound is less than the query location, move it in.
907 if (SourceLineCache < SourceLineCacheStart+LowerBound &&
908 SourceLineCacheStart[LowerBound] < QueriedFilePos)
909 SourceLineCache = SourceLineCacheStart+LowerBound;
Mike Stump1eb44332009-09-09 15:08:12 +0000910
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000911 // If the computed upper bound is greater than the query location, move it.
912 if (SourceLineCacheEnd > SourceLineCacheStart+UpperBound &&
913 SourceLineCacheStart[UpperBound] >= QueriedFilePos)
914 SourceLineCacheEnd = SourceLineCacheStart+UpperBound;
915 }
Mike Stump1eb44332009-09-09 15:08:12 +0000916
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000917 unsigned *Pos
918 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000919 unsigned LineNo = Pos-SourceLineCacheStart;
Mike Stump1eb44332009-09-09 15:08:12 +0000920
Chris Lattner30fc9332009-02-04 01:06:56 +0000921 LastLineNoFileIDQuery = FID;
Ted Kremenek78d85f52007-10-30 21:08:08 +0000922 LastLineNoContentCache = Content;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000923 LastLineNoFilePos = QueriedFilePos;
924 LastLineNoResult = LineNo;
925 return LineNo;
Reid Spencer5f016e22007-07-11 17:01:13 +0000926}
927
Douglas Gregor50f6af72010-03-16 05:20:39 +0000928unsigned SourceManager::getInstantiationLineNumber(SourceLocation Loc,
929 bool *Invalid) const {
Chris Lattner30fc9332009-02-04 01:06:56 +0000930 if (Loc.isInvalid()) return 0;
931 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
932 return getLineNumber(LocInfo.first, LocInfo.second);
933}
Douglas Gregor50f6af72010-03-16 05:20:39 +0000934unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
935 bool *Invalid) const {
Chris Lattner30fc9332009-02-04 01:06:56 +0000936 if (Loc.isInvalid()) return 0;
937 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
938 return getLineNumber(LocInfo.first, LocInfo.second);
939}
940
Chris Lattner6b306672009-02-04 05:33:01 +0000941/// getFileCharacteristic - return the file characteristic of the specified
Mike Stump1eb44332009-09-09 15:08:12 +0000942/// source location, indicating whether this is a normal file, a system
Chris Lattner6b306672009-02-04 05:33:01 +0000943/// header, or an "implicit extern C" system header.
944///
945/// This state can be modified with flags on GNU linemarker directives like:
946/// # 4 "foo.h" 3
947/// which changes all source locations in the current file after that to be
948/// considered to be from a system header.
Mike Stump1eb44332009-09-09 15:08:12 +0000949SrcMgr::CharacteristicKind
Chris Lattner6b306672009-02-04 05:33:01 +0000950SourceManager::getFileCharacteristic(SourceLocation Loc) const {
951 assert(!Loc.isInvalid() && "Can't get file characteristic of invalid loc!");
952 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
953 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile();
954
955 // If there are no #line directives in this file, just return the whole-file
956 // state.
957 if (!FI.hasLineDirectives())
958 return FI.getFileCharacteristic();
Mike Stump1eb44332009-09-09 15:08:12 +0000959
Chris Lattner6b306672009-02-04 05:33:01 +0000960 assert(LineTable && "Can't have linetable entries without a LineTable!");
961 // See if there is a #line directive before the location.
962 const LineEntry *Entry =
963 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second);
Mike Stump1eb44332009-09-09 15:08:12 +0000964
Chris Lattner6b306672009-02-04 05:33:01 +0000965 // If this is before the first line marker, use the file characteristic.
966 if (!Entry)
967 return FI.getFileCharacteristic();
968
969 return Entry->FileKind;
970}
971
Chris Lattnerbff5c512009-02-17 08:39:06 +0000972/// Return the filename or buffer identifier of the buffer the location is in.
973/// Note that this name does not respect #line directives. Use getPresumedLoc
974/// for normal clients.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000975const char *SourceManager::getBufferName(SourceLocation Loc,
976 bool *Invalid) const {
Chris Lattnerbff5c512009-02-17 08:39:06 +0000977 if (Loc.isInvalid()) return "<invalid loc>";
Mike Stump1eb44332009-09-09 15:08:12 +0000978
Douglas Gregor50f6af72010-03-16 05:20:39 +0000979 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
Chris Lattnerbff5c512009-02-17 08:39:06 +0000980}
981
Chris Lattner30fc9332009-02-04 01:06:56 +0000982
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000983/// getPresumedLoc - This method returns the "presumed" location of a
984/// SourceLocation specifies. A "presumed location" can be modified by #line
985/// or GNU line marker directives. This provides a view on the data that a
986/// user should see in diagnostics, for example.
987///
988/// Note that a presumed location is always given as the instantiation point
989/// of an instantiation location, not at the spelling location.
990PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc) const {
991 if (Loc.isInvalid()) return PresumedLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000992
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000993 // Presumed locations are always for instantiation points.
Chris Lattner7da5aea2009-02-04 00:55:58 +0000994 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000995
Chris Lattner30fc9332009-02-04 01:06:56 +0000996 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile();
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000997 const SrcMgr::ContentCache *C = FI.getContentCache();
Mike Stump1eb44332009-09-09 15:08:12 +0000998
Chris Lattner3cd949c2009-02-04 01:55:42 +0000999 // To get the source name, first consult the FileEntry (if one exists)
1000 // before the MemBuffer as this will avoid unnecessarily paging in the
1001 // MemBuffer.
Mike Stump1eb44332009-09-09 15:08:12 +00001002 const char *Filename =
Douglas Gregor36c35ba2010-03-16 00:35:39 +00001003 C->Entry ? C->Entry->getName() : C->getBuffer(Diag)->getBufferIdentifier();
Chris Lattner3cd949c2009-02-04 01:55:42 +00001004 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second);
1005 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second);
1006 SourceLocation IncludeLoc = FI.getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001007
Chris Lattner3cd949c2009-02-04 01:55:42 +00001008 // If we have #line directives in this file, update and overwrite the physical
1009 // location info if appropriate.
1010 if (FI.hasLineDirectives()) {
1011 assert(LineTable && "Can't have linetable entries without a LineTable!");
1012 // See if there is a #line directive before this. If so, get it.
1013 if (const LineEntry *Entry =
1014 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second)) {
Chris Lattnerfc391332009-02-04 02:00:59 +00001015 // If the LineEntry indicates a filename, use it.
Chris Lattner3cd949c2009-02-04 01:55:42 +00001016 if (Entry->FilenameID != -1)
1017 Filename = LineTable->getFilename(Entry->FilenameID);
Chris Lattnerfc391332009-02-04 02:00:59 +00001018
1019 // Use the line number specified by the LineEntry. This line number may
1020 // be multiple lines down from the line entry. Add the difference in
1021 // physical line numbers from the query point and the line marker to the
1022 // total.
1023 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1024 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001025
Chris Lattner0e0e5da2009-02-04 02:15:40 +00001026 // Note that column numbers are not molested by line markers.
Mike Stump1eb44332009-09-09 15:08:12 +00001027
Chris Lattner137b6a62009-02-04 06:25:26 +00001028 // Handle virtual #include manipulation.
1029 if (Entry->IncludeOffset) {
1030 IncludeLoc = getLocForStartOfFile(LocInfo.first);
1031 IncludeLoc = IncludeLoc.getFileLocWithOffset(Entry->IncludeOffset);
1032 }
Chris Lattner3cd949c2009-02-04 01:55:42 +00001033 }
1034 }
1035
1036 return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc);
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001037}
1038
1039//===----------------------------------------------------------------------===//
1040// Other miscellaneous methods.
1041//===----------------------------------------------------------------------===//
1042
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001043/// \brief Get the source location for the given file:line:col triplet.
1044///
1045/// If the source file is included multiple times, the source location will
1046/// be based upon the first inclusion.
1047SourceLocation SourceManager::getLocation(const FileEntry *SourceFile,
1048 unsigned Line, unsigned Col) const {
1049 assert(SourceFile && "Null source file!");
1050 assert(Line && Col && "Line and column should start from 1!");
1051
1052 fileinfo_iterator FI = FileInfos.find(SourceFile);
1053 if (FI == FileInfos.end())
1054 return SourceLocation();
1055 ContentCache *Content = FI->second;
Mike Stump1eb44332009-09-09 15:08:12 +00001056
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001057 // If this is the first use of line information for this buffer, compute the
1058 /// SourceLineCache for it on demand.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001059 if (Content->SourceLineCache == 0) {
1060 bool MyInvalid = false;
1061 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, MyInvalid);
1062 if (MyInvalid)
1063 return SourceLocation();
1064 }
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001065
Douglas Gregor4a160e12009-12-02 05:34:39 +00001066 // Find the first file ID that corresponds to the given file.
1067 FileID FirstFID;
1068
1069 // First, check the main file ID, since it is common to look for a
1070 // location in the main file.
1071 if (!MainFileID.isInvalid()) {
1072 const SLocEntry &MainSLoc = getSLocEntry(MainFileID);
1073 if (MainSLoc.isFile() && MainSLoc.getFile().getContentCache() == Content)
1074 FirstFID = MainFileID;
1075 }
1076
1077 if (FirstFID.isInvalid()) {
1078 // The location we're looking for isn't in the main file; look
1079 // through all of the source locations.
1080 for (unsigned I = 0, N = sloc_entry_size(); I != N; ++I) {
1081 const SLocEntry &SLoc = getSLocEntry(I);
1082 if (SLoc.isFile() && SLoc.getFile().getContentCache() == Content) {
1083 FirstFID = FileID::get(I);
1084 break;
1085 }
1086 }
1087 }
1088
1089 if (FirstFID.isInvalid())
1090 return SourceLocation();
1091
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001092 if (Line > Content->NumLines) {
Douglas Gregor36c35ba2010-03-16 00:35:39 +00001093 unsigned Size = Content->getBuffer(Diag)->getBufferSize();
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001094 if (Size > 0)
1095 --Size;
1096 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(Size);
1097 }
1098
1099 unsigned FilePos = Content->SourceLineCache[Line - 1];
Douglas Gregor36c35ba2010-03-16 00:35:39 +00001100 const char *Buf = Content->getBuffer(Diag)->getBufferStart() + FilePos;
1101 unsigned BufLength = Content->getBuffer(Diag)->getBufferEnd() - Buf;
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001102 unsigned i = 0;
1103
1104 // Check that the given column is valid.
1105 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1106 ++i;
1107 if (i < Col-1)
1108 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + i);
1109
Douglas Gregor4a160e12009-12-02 05:34:39 +00001110 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + Col - 1);
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001111}
1112
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001113/// \brief Determines the order of 2 source locations in the translation unit.
1114///
1115/// \returns true if LHS source location comes before RHS, false otherwise.
1116bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
1117 SourceLocation RHS) const {
1118 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
1119 if (LHS == RHS)
1120 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001121
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001122 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
1123 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00001124
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001125 // If the source locations are in the same file, just compare offsets.
1126 if (LOffs.first == ROffs.first)
1127 return LOffs.second < ROffs.second;
1128
1129 // If we are comparing a source location with multiple locations in the same
1130 // file, we get a big win by caching the result.
Mike Stump1eb44332009-09-09 15:08:12 +00001131
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001132 if (LastLFIDForBeforeTUCheck == LOffs.first &&
1133 LastRFIDForBeforeTUCheck == ROffs.first)
1134 return LastResForBeforeTUCheck;
Mike Stump1eb44332009-09-09 15:08:12 +00001135
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001136 LastLFIDForBeforeTUCheck = LOffs.first;
1137 LastRFIDForBeforeTUCheck = ROffs.first;
Mike Stump1eb44332009-09-09 15:08:12 +00001138
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001139 // "Traverse" the include/instantiation stacks of both locations and try to
1140 // find a common "ancestor".
1141 //
1142 // First we traverse the stack of the right location and check each level
1143 // against the level of the left location, while collecting all levels in a
1144 // "stack map".
1145
1146 std::map<FileID, unsigned> ROffsMap;
1147 ROffsMap[ROffs.first] = ROffs.second;
1148
1149 while (1) {
1150 SourceLocation UpperLoc;
1151 const SrcMgr::SLocEntry &Entry = getSLocEntry(ROffs.first);
1152 if (Entry.isInstantiation())
1153 UpperLoc = Entry.getInstantiation().getInstantiationLocStart();
1154 else
1155 UpperLoc = Entry.getFile().getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001156
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001157 if (UpperLoc.isInvalid())
1158 break; // We reached the top.
Mike Stump1eb44332009-09-09 15:08:12 +00001159
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001160 ROffs = getDecomposedLoc(UpperLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001161
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001162 if (LOffs.first == ROffs.first)
1163 return LastResForBeforeTUCheck = LOffs.second < ROffs.second;
Mike Stump1eb44332009-09-09 15:08:12 +00001164
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001165 ROffsMap[ROffs.first] = ROffs.second;
1166 }
1167
1168 // We didn't find a common ancestor. Now traverse the stack of the left
1169 // location, checking against the stack map of the right location.
1170
1171 while (1) {
1172 SourceLocation UpperLoc;
1173 const SrcMgr::SLocEntry &Entry = getSLocEntry(LOffs.first);
1174 if (Entry.isInstantiation())
1175 UpperLoc = Entry.getInstantiation().getInstantiationLocStart();
1176 else
1177 UpperLoc = Entry.getFile().getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001178
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001179 if (UpperLoc.isInvalid())
1180 break; // We reached the top.
Mike Stump1eb44332009-09-09 15:08:12 +00001181
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001182 LOffs = getDecomposedLoc(UpperLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001183
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001184 std::map<FileID, unsigned>::iterator I = ROffsMap.find(LOffs.first);
1185 if (I != ROffsMap.end())
1186 return LastResForBeforeTUCheck = LOffs.second < I->second;
1187 }
Mike Stump1eb44332009-09-09 15:08:12 +00001188
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001189 // There is no common ancestor, most probably because one location is in the
1190 // predefines buffer.
1191 //
1192 // FIXME: We should rearrange the external interface so this simply never
1193 // happens; it can't conceptually happen. Also see PR5662.
Mike Stump1eb44332009-09-09 15:08:12 +00001194
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001195 // If exactly one location is a memory buffer, assume it preceeds the other.
1196 bool LIsMB = !getSLocEntry(LOffs.first).getFile().getContentCache()->Entry;
1197 bool RIsMB = !getSLocEntry(ROffs.first).getFile().getContentCache()->Entry;
1198 if (LIsMB != RIsMB)
1199 return LastResForBeforeTUCheck = LIsMB;
Mike Stump1eb44332009-09-09 15:08:12 +00001200
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001201 // Otherwise, just assume FileIDs were created in order.
1202 return LastResForBeforeTUCheck = (LOffs.first < ROffs.first);
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001203}
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001204
Reid Spencer5f016e22007-07-11 17:01:13 +00001205/// PrintStats - Print statistics to stderr.
1206///
1207void SourceManager::PrintStats() const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001208 llvm::errs() << "\n*** Source Manager Stats:\n";
1209 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
1210 << " mem buffers mapped.\n";
1211 llvm::errs() << SLocEntryTable.size() << " SLocEntry's allocated, "
1212 << NextOffset << "B of Sloc address space used.\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001213
Reid Spencer5f016e22007-07-11 17:01:13 +00001214 unsigned NumLineNumsComputed = 0;
1215 unsigned NumFileBytesMapped = 0;
Chris Lattner0d0bf8c2009-02-03 07:30:45 +00001216 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
1217 NumLineNumsComputed += I->second->SourceLineCache != 0;
1218 NumFileBytesMapped += I->second->getSizeBytesMapped();
Reid Spencer5f016e22007-07-11 17:01:13 +00001219 }
Mike Stump1eb44332009-09-09 15:08:12 +00001220
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001221 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
1222 << NumLineNumsComputed << " files with line #'s computed.\n";
1223 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
1224 << NumBinaryProbes << " binary.\n";
Reid Spencer5f016e22007-07-11 17:01:13 +00001225}
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001226
1227ExternalSLocEntrySource::~ExternalSLocEntrySource() { }