blob: 27a859c9d752068d39efc8f3ccb72da8cc477a17 [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);
Douglas Gregor9f692a02010-04-09 15:54:22 +0000101 } else if (FileInfo.st_size != Entry->getSize()
102#if !defined(LLVM_ON_WIN32)
103 // In our regression testing, the Windows file system
104 // seems to have inconsistent modification times that
105 // sometimes erroneously trigger this error-handling
106 // path.
107 || FileInfo.st_mtime != Entry->getModificationTime()
108#endif
109 ) {
110 // Check that the file's size and modification time are the same
111 // as in the file entry (which may have come from a stat cache).
Douglas Gregor93ea5cb2010-03-22 15:10:57 +0000112 if (Diag.isDiagnosticInFlight())
113 Diag.SetDelayedDiagnostic(diag::err_file_modified,
114 Entry->getName());
115 else
116 Diag.Report(diag::err_file_modified) << Entry->getName();
117
Douglas Gregore39b6002010-03-17 15:30:15 +0000118 Buffer.setInt(true);
Daniel Dunbar21a8bed2009-12-06 05:43:36 +0000119 }
Ted Kremenek5b034ad2009-01-06 22:43:04 +0000120 }
Douglas Gregoraea67db2010-03-15 22:54:52 +0000121
Douglas Gregorc8151082010-03-16 22:53:51 +0000122 if (Invalid)
123 *Invalid = Buffer.getInt();
124
125 return Buffer.getPointer();
Ted Kremenekc16c2082009-01-06 01:55:26 +0000126}
127
Chris Lattner5b9a5042009-01-26 07:57:50 +0000128unsigned LineTableInfo::getLineTableFilenameID(const char *Ptr, unsigned Len) {
129 // Look up the filename in the string table, returning the pre-existing value
130 // if it exists.
Mike Stump1eb44332009-09-09 15:08:12 +0000131 llvm::StringMapEntry<unsigned> &Entry =
Chris Lattner5b9a5042009-01-26 07:57:50 +0000132 FilenameIDs.GetOrCreateValue(Ptr, Ptr+Len, ~0U);
133 if (Entry.getValue() != ~0U)
134 return Entry.getValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000135
Chris Lattner5b9a5042009-01-26 07:57:50 +0000136 // Otherwise, assign this the next available ID.
137 Entry.setValue(FilenamesByID.size());
138 FilenamesByID.push_back(&Entry);
139 return FilenamesByID.size()-1;
140}
141
Chris Lattnerac50e342009-02-03 22:13:05 +0000142/// AddLineNote - Add a line note to the line table that indicates that there
143/// is a #line at the specified FID/Offset location which changes the presumed
144/// location to LineNo/FilenameID.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000145void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
Chris Lattnerac50e342009-02-03 22:13:05 +0000146 unsigned LineNo, int FilenameID) {
Chris Lattner23b5dc62009-02-04 00:40:31 +0000147 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump1eb44332009-09-09 15:08:12 +0000148
Chris Lattner23b5dc62009-02-04 00:40:31 +0000149 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
150 "Adding line entries out of order!");
Mike Stump1eb44332009-09-09 15:08:12 +0000151
Chris Lattner9d79eba2009-02-04 05:21:58 +0000152 SrcMgr::CharacteristicKind Kind = SrcMgr::C_User;
Chris Lattner137b6a62009-02-04 06:25:26 +0000153 unsigned IncludeOffset = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000154
Chris Lattner9d79eba2009-02-04 05:21:58 +0000155 if (!Entries.empty()) {
156 // If this is a '#line 4' after '#line 42 "foo.h"', make sure to remember
157 // that we are still in "foo.h".
158 if (FilenameID == -1)
159 FilenameID = Entries.back().FilenameID;
Mike Stump1eb44332009-09-09 15:08:12 +0000160
Chris Lattner137b6a62009-02-04 06:25:26 +0000161 // If we are after a line marker that switched us to system header mode, or
162 // that set #include information, preserve it.
Chris Lattner9d79eba2009-02-04 05:21:58 +0000163 Kind = Entries.back().FileKind;
Chris Lattner137b6a62009-02-04 06:25:26 +0000164 IncludeOffset = Entries.back().IncludeOffset;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000165 }
Mike Stump1eb44332009-09-09 15:08:12 +0000166
Chris Lattner137b6a62009-02-04 06:25:26 +0000167 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, Kind,
168 IncludeOffset));
Chris Lattnerac50e342009-02-03 22:13:05 +0000169}
170
Chris Lattner9d79eba2009-02-04 05:21:58 +0000171/// AddLineNote This is the same as the previous version of AddLineNote, but is
172/// used for GNU line markers. If EntryExit is 0, then this doesn't change the
173/// presumed #include stack. If it is 1, this is a file entry, if it is 2 then
174/// this is a file exit. FileKind specifies whether this is a system header or
175/// extern C system header.
176void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
177 unsigned LineNo, int FilenameID,
178 unsigned EntryExit,
179 SrcMgr::CharacteristicKind FileKind) {
180 assert(FilenameID != -1 && "Unspecified filename should use other accessor");
Mike Stump1eb44332009-09-09 15:08:12 +0000181
Chris Lattner9d79eba2009-02-04 05:21:58 +0000182 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump1eb44332009-09-09 15:08:12 +0000183
Chris Lattner9d79eba2009-02-04 05:21:58 +0000184 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
185 "Adding line entries out of order!");
186
Chris Lattner137b6a62009-02-04 06:25:26 +0000187 unsigned IncludeOffset = 0;
188 if (EntryExit == 0) { // No #include stack change.
189 IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
190 } else if (EntryExit == 1) {
191 IncludeOffset = Offset-1;
192 } else if (EntryExit == 2) {
193 assert(!Entries.empty() && Entries.back().IncludeOffset &&
194 "PPDirectives should have caught case when popping empty include stack");
Mike Stump1eb44332009-09-09 15:08:12 +0000195
Chris Lattner137b6a62009-02-04 06:25:26 +0000196 // Get the include loc of the last entries' include loc as our include loc.
197 IncludeOffset = 0;
198 if (const LineEntry *PrevEntry =
199 FindNearestLineEntry(FID, Entries.back().IncludeOffset))
200 IncludeOffset = PrevEntry->IncludeOffset;
201 }
Mike Stump1eb44332009-09-09 15:08:12 +0000202
Chris Lattner137b6a62009-02-04 06:25:26 +0000203 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
204 IncludeOffset));
Chris Lattner9d79eba2009-02-04 05:21:58 +0000205}
206
207
Chris Lattner3cd949c2009-02-04 01:55:42 +0000208/// FindNearestLineEntry - Find the line entry nearest to FID that is before
209/// it. If there is no line entry before Offset in FID, return null.
Mike Stump1eb44332009-09-09 15:08:12 +0000210const LineEntry *LineTableInfo::FindNearestLineEntry(unsigned FID,
Chris Lattner3cd949c2009-02-04 01:55:42 +0000211 unsigned Offset) {
212 const std::vector<LineEntry> &Entries = LineEntries[FID];
213 assert(!Entries.empty() && "No #line entries for this FID after all!");
214
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000215 // It is very common for the query to be after the last #line, check this
216 // first.
217 if (Entries.back().FileOffset <= Offset)
218 return &Entries.back();
Chris Lattner3cd949c2009-02-04 01:55:42 +0000219
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000220 // Do a binary search to find the maximal element that is still before Offset.
221 std::vector<LineEntry>::const_iterator I =
222 std::upper_bound(Entries.begin(), Entries.end(), Offset);
223 if (I == Entries.begin()) return 0;
224 return &*--I;
Chris Lattner3cd949c2009-02-04 01:55:42 +0000225}
Chris Lattnerac50e342009-02-03 22:13:05 +0000226
Douglas Gregorbd945002009-04-13 16:31:14 +0000227/// \brief Add a new line entry that has already been encoded into
228/// the internal representation of the line table.
Mike Stump1eb44332009-09-09 15:08:12 +0000229void LineTableInfo::AddEntry(unsigned FID,
Douglas Gregorbd945002009-04-13 16:31:14 +0000230 const std::vector<LineEntry> &Entries) {
231 LineEntries[FID] = Entries;
232}
Chris Lattnerac50e342009-02-03 22:13:05 +0000233
Chris Lattner5b9a5042009-01-26 07:57:50 +0000234/// getLineTableFilenameID - Return the uniqued ID for the specified filename.
Mike Stump1eb44332009-09-09 15:08:12 +0000235///
Chris Lattner5b9a5042009-01-26 07:57:50 +0000236unsigned SourceManager::getLineTableFilenameID(const char *Ptr, unsigned Len) {
237 if (LineTable == 0)
238 LineTable = new LineTableInfo();
239 return LineTable->getLineTableFilenameID(Ptr, Len);
240}
241
242
Chris Lattner4c4ea172009-02-03 21:52:55 +0000243/// AddLineNote - Add a line note to the line table for the FileID and offset
244/// specified by Loc. If FilenameID is -1, it is considered to be
245/// unspecified.
246void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
247 int FilenameID) {
Chris Lattnerac50e342009-02-03 22:13:05 +0000248 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000249
Chris Lattnerac50e342009-02-03 22:13:05 +0000250 const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile();
251
252 // Remember that this file has #line directives now if it doesn't already.
253 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump1eb44332009-09-09 15:08:12 +0000254
Chris Lattnerac50e342009-02-03 22:13:05 +0000255 if (LineTable == 0)
256 LineTable = new LineTableInfo();
Chris Lattner23b5dc62009-02-04 00:40:31 +0000257 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID);
Chris Lattner4c4ea172009-02-03 21:52:55 +0000258}
259
Chris Lattner9d79eba2009-02-04 05:21:58 +0000260/// AddLineNote - Add a GNU line marker to the line table.
261void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
262 int FilenameID, bool IsFileEntry,
263 bool IsFileExit, bool IsSystemHeader,
264 bool IsExternCHeader) {
265 // If there is no filename and no flags, this is treated just like a #line,
266 // which does not change the flags of the previous line marker.
267 if (FilenameID == -1) {
268 assert(!IsFileEntry && !IsFileExit && !IsSystemHeader && !IsExternCHeader &&
269 "Can't set flags without setting the filename!");
270 return AddLineNote(Loc, LineNo, FilenameID);
271 }
Mike Stump1eb44332009-09-09 15:08:12 +0000272
Chris Lattner9d79eba2009-02-04 05:21:58 +0000273 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
274 const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile();
Mike Stump1eb44332009-09-09 15:08:12 +0000275
Chris Lattner9d79eba2009-02-04 05:21:58 +0000276 // Remember that this file has #line directives now if it doesn't already.
277 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump1eb44332009-09-09 15:08:12 +0000278
Chris Lattner9d79eba2009-02-04 05:21:58 +0000279 if (LineTable == 0)
280 LineTable = new LineTableInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000281
Chris Lattner9d79eba2009-02-04 05:21:58 +0000282 SrcMgr::CharacteristicKind FileKind;
283 if (IsExternCHeader)
284 FileKind = SrcMgr::C_ExternCSystem;
285 else if (IsSystemHeader)
286 FileKind = SrcMgr::C_System;
287 else
288 FileKind = SrcMgr::C_User;
Mike Stump1eb44332009-09-09 15:08:12 +0000289
Chris Lattner9d79eba2009-02-04 05:21:58 +0000290 unsigned EntryExit = 0;
291 if (IsFileEntry)
292 EntryExit = 1;
293 else if (IsFileExit)
294 EntryExit = 2;
Mike Stump1eb44332009-09-09 15:08:12 +0000295
Chris Lattner9d79eba2009-02-04 05:21:58 +0000296 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID,
297 EntryExit, FileKind);
298}
299
Douglas Gregorbd945002009-04-13 16:31:14 +0000300LineTableInfo &SourceManager::getLineTable() {
301 if (LineTable == 0)
302 LineTable = new LineTableInfo();
303 return *LineTable;
304}
Chris Lattner4c4ea172009-02-03 21:52:55 +0000305
Chris Lattner23b5dc62009-02-04 00:40:31 +0000306//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000307// Private 'Create' methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000308//===----------------------------------------------------------------------===//
Ted Kremenekc16c2082009-01-06 01:55:26 +0000309
Chris Lattner5b9a5042009-01-26 07:57:50 +0000310SourceManager::~SourceManager() {
311 delete LineTable;
Mike Stump1eb44332009-09-09 15:08:12 +0000312
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000313 // Delete FileEntry objects corresponding to content caches. Since the actual
314 // content cache objects are bump pointer allocated, we just have to run the
315 // dtors, but we call the deallocate method for completeness.
316 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
317 MemBufferInfos[i]->~ContentCache();
318 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
319 }
320 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
321 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
322 I->second->~ContentCache();
323 ContentCacheAlloc.Deallocate(I->second);
324 }
Chris Lattner5b9a5042009-01-26 07:57:50 +0000325}
326
327void SourceManager::clearIDTables() {
328 MainFileID = FileID();
329 SLocEntryTable.clear();
330 LastLineNoFileIDQuery = FileID();
331 LastLineNoContentCache = 0;
332 LastFileIDLookup = FileID();
Mike Stump1eb44332009-09-09 15:08:12 +0000333
Chris Lattner5b9a5042009-01-26 07:57:50 +0000334 if (LineTable)
335 LineTable->clear();
Mike Stump1eb44332009-09-09 15:08:12 +0000336
Chris Lattner5b9a5042009-01-26 07:57:50 +0000337 // Use up FileID #0 as an invalid instantiation.
338 NextOffset = 0;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000339 createInstantiationLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000340}
341
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000342/// getOrCreateContentCache - Create or return a cached ContentCache for the
343/// specified file.
344const ContentCache *
345SourceManager::getOrCreateContentCache(const FileEntry *FileEnt) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000346 assert(FileEnt && "Didn't specify a file entry to use?");
Mike Stump1eb44332009-09-09 15:08:12 +0000347
Reid Spencer5f016e22007-07-11 17:01:13 +0000348 // Do we already have information about this file?
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000349 ContentCache *&Entry = FileInfos[FileEnt];
350 if (Entry) return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +0000351
Chris Lattner00282d62009-02-03 07:41:46 +0000352 // Nope, create a new Cache entry. Make sure it is at least 8-byte aligned
353 // so that FileInfo can use the low 3 bits of the pointer for its own
354 // nefarious purposes.
355 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
356 EntryAlign = std::max(8U, EntryAlign);
357 Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000358 new (Entry) ContentCache(FileEnt);
359 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000360}
361
362
Ted Kremenekd1c0eee2007-10-31 17:53:38 +0000363/// createMemBufferContentCache - Create a new ContentCache for the specified
364/// memory buffer. This does no caching.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000365const ContentCache*
366SourceManager::createMemBufferContentCache(const MemoryBuffer *Buffer) {
Chris Lattner00282d62009-02-03 07:41:46 +0000367 // Add a new ContentCache to the MemBufferInfos list and return it. Make sure
368 // it is at least 8-byte aligned so that FileInfo can use the low 3 bits of
369 // the pointer for its own nefarious purposes.
370 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
371 EntryAlign = std::max(8U, EntryAlign);
372 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000373 new (Entry) ContentCache();
374 MemBufferInfos.push_back(Entry);
375 Entry->setBuffer(Buffer);
376 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000377}
378
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000379void SourceManager::PreallocateSLocEntries(ExternalSLocEntrySource *Source,
380 unsigned NumSLocEntries,
381 unsigned NextOffset) {
382 ExternalSLocEntries = Source;
383 this->NextOffset = NextOffset;
384 SLocEntryLoaded.resize(NumSLocEntries + 1);
385 SLocEntryLoaded[0] = true;
386 SLocEntryTable.resize(SLocEntryTable.size() + NumSLocEntries);
387}
388
Douglas Gregor2bf1eb02009-04-27 21:28:04 +0000389void SourceManager::ClearPreallocatedSLocEntries() {
390 unsigned I = 0;
391 for (unsigned N = SLocEntryLoaded.size(); I != N; ++I)
392 if (!SLocEntryLoaded[I])
393 break;
394
395 // We've already loaded all preallocated source location entries.
396 if (I == SLocEntryLoaded.size())
397 return;
398
399 // Remove everything from location I onward.
400 SLocEntryTable.resize(I);
401 SLocEntryLoaded.clear();
402 ExternalSLocEntries = 0;
403}
404
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000405
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000406//===----------------------------------------------------------------------===//
407// Methods to create new FileID's and instantiations.
408//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000409
Nico Weber48002c82008-09-29 00:25:48 +0000410/// createFileID - Create a new fileID for the specified ContentCache and
Ted Kremenek0d892d82007-10-30 22:57:35 +0000411/// include position. This works regardless of whether the ContentCache
412/// corresponds to a file or some other input source.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000413FileID SourceManager::createFileID(const ContentCache *File,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000414 SourceLocation IncludePos,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000415 SrcMgr::CharacteristicKind FileCharacter,
416 unsigned PreallocatedID,
417 unsigned Offset) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000418 if (PreallocatedID) {
419 // If we're filling in a preallocated ID, just load in the file
420 // entry and return.
Mike Stump1eb44332009-09-09 15:08:12 +0000421 assert(PreallocatedID < SLocEntryLoaded.size() &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000422 "Preallocate ID out-of-range");
Mike Stump1eb44332009-09-09 15:08:12 +0000423 assert(!SLocEntryLoaded[PreallocatedID] &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000424 "Source location entry already loaded");
425 assert(Offset && "Preallocate source location cannot have zero offset");
Mike Stump1eb44332009-09-09 15:08:12 +0000426 SLocEntryTable[PreallocatedID]
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000427 = SLocEntry::get(Offset, FileInfo::get(IncludePos, File, FileCharacter));
428 SLocEntryLoaded[PreallocatedID] = true;
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +0000429 FileID FID = FileID::get(PreallocatedID);
Douglas Gregor5de65722010-03-19 06:12:06 +0000430 return FID;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000431 }
432
Mike Stump1eb44332009-09-09 15:08:12 +0000433 SLocEntryTable.push_back(SLocEntry::get(NextOffset,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000434 FileInfo::get(IncludePos, File,
435 FileCharacter)));
Ted Kremenekc16c2082009-01-06 01:55:26 +0000436 unsigned FileSize = File->getSize();
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000437 assert(NextOffset+FileSize+1 > NextOffset && "Ran out of source locations!");
438 NextOffset += FileSize+1;
Mike Stump1eb44332009-09-09 15:08:12 +0000439
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000440 // Set LastFileIDLookup to the newly created file. The next getFileID call is
441 // almost guaranteed to be from that file.
Argyrios Kyrtzidisea703f12009-06-23 00:42:06 +0000442 FileID FID = FileID::get(SLocEntryTable.size()-1);
Argyrios Kyrtzidisea703f12009-06-23 00:42:06 +0000443 return LastFileIDLookup = FID;
Reid Spencer5f016e22007-07-11 17:01:13 +0000444}
445
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000446/// createInstantiationLoc - Return a new SourceLocation that encodes the fact
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000447/// that a token from SpellingLoc should actually be referenced from
Reid Spencer5f016e22007-07-11 17:01:13 +0000448/// InstantiationLoc.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000449SourceLocation SourceManager::createInstantiationLoc(SourceLocation SpellingLoc,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000450 SourceLocation ILocStart,
451 SourceLocation ILocEnd,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000452 unsigned TokLength,
453 unsigned PreallocatedID,
454 unsigned Offset) {
Chris Lattnere7fb4842009-02-15 20:52:18 +0000455 InstantiationInfo II = InstantiationInfo::get(ILocStart,ILocEnd, SpellingLoc);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000456 if (PreallocatedID) {
457 // If we're filling in a preallocated ID, just load in the
458 // instantiation entry and return.
Mike Stump1eb44332009-09-09 15:08:12 +0000459 assert(PreallocatedID < SLocEntryLoaded.size() &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000460 "Preallocate ID out-of-range");
Mike Stump1eb44332009-09-09 15:08:12 +0000461 assert(!SLocEntryLoaded[PreallocatedID] &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000462 "Source location entry already loaded");
463 assert(Offset && "Preallocate source location cannot have zero offset");
464 SLocEntryTable[PreallocatedID] = SLocEntry::get(Offset, II);
465 SLocEntryLoaded[PreallocatedID] = true;
466 return SourceLocation::getMacroLoc(Offset);
467 }
Chris Lattnere7fb4842009-02-15 20:52:18 +0000468 SLocEntryTable.push_back(SLocEntry::get(NextOffset, II));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000469 assert(NextOffset+TokLength+1 > NextOffset && "Ran out of source locations!");
470 NextOffset += TokLength+1;
471 return SourceLocation::getMacroLoc(NextOffset-(TokLength+1));
Reid Spencer5f016e22007-07-11 17:01:13 +0000472}
473
Douglas Gregor36c35ba2010-03-16 00:35:39 +0000474const llvm::MemoryBuffer *
Douglas Gregor50f6af72010-03-16 05:20:39 +0000475SourceManager::getMemoryBufferForFile(const FileEntry *File,
476 bool *Invalid) {
Douglas Gregor29684422009-12-02 06:49:09 +0000477 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
Douglas Gregoraea67db2010-03-15 22:54:52 +0000478 assert(IR && "getOrCreateContentCache() cannot return NULL");
Douglas Gregor50f6af72010-03-16 05:20:39 +0000479 return IR->getBuffer(Diag, Invalid);
Douglas Gregor29684422009-12-02 06:49:09 +0000480}
481
482bool SourceManager::overrideFileContents(const FileEntry *SourceFile,
483 const llvm::MemoryBuffer *Buffer) {
484 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
485 if (IR == 0)
486 return true;
487
488 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer);
489 return false;
490}
491
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000492llvm::StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
Douglas Gregoraae58b02010-03-16 20:01:30 +0000493 bool MyInvalid = false;
494 const llvm::MemoryBuffer *Buf = getBuffer(FID, &MyInvalid);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000495 if (Invalid)
Douglas Gregoraae58b02010-03-16 20:01:30 +0000496 *Invalid = MyInvalid;
497
498 if (MyInvalid)
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000499 return "";
Douglas Gregoraae58b02010-03-16 20:01:30 +0000500
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000501 return Buf->getBuffer();
Douglas Gregoraea67db2010-03-15 22:54:52 +0000502}
Chris Lattner2b2453a2009-01-17 06:22:33 +0000503
Chris Lattner23b5dc62009-02-04 00:40:31 +0000504//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000505// SourceLocation manipulation methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000506//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000507
508/// getFileIDSlow - Return the FileID for a SourceLocation. This is a very hot
509/// method that is used for all SourceManager queries that start with a
510/// SourceLocation object. It is responsible for finding the entry in
511/// SLocEntryTable which contains the specified location.
512///
513FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
514 assert(SLocOffset && "Invalid FileID");
Mike Stump1eb44332009-09-09 15:08:12 +0000515
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000516 // After the first and second level caches, I see two common sorts of
517 // behavior: 1) a lot of searched FileID's are "near" the cached file location
518 // or are "near" the cached instantiation location. 2) others are just
519 // completely random and may be a very long way away.
520 //
521 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
522 // then we fall back to a less cache efficient, but more scalable, binary
523 // search to find the location.
Mike Stump1eb44332009-09-09 15:08:12 +0000524
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000525 // See if this is near the file point - worst case we start scanning from the
526 // most newly created FileID.
527 std::vector<SrcMgr::SLocEntry>::const_iterator I;
Mike Stump1eb44332009-09-09 15:08:12 +0000528
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000529 if (SLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
530 // Neither loc prunes our search.
531 I = SLocEntryTable.end();
532 } else {
533 // Perhaps it is near the file point.
534 I = SLocEntryTable.begin()+LastFileIDLookup.ID;
535 }
536
537 // Find the FileID that contains this. "I" is an iterator that points to a
538 // FileID whose offset is known to be larger than SLocOffset.
539 unsigned NumProbes = 0;
540 while (1) {
541 --I;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000542 if (ExternalSLocEntries)
543 getSLocEntry(FileID::get(I - SLocEntryTable.begin()));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000544 if (I->getOffset() <= SLocOffset) {
545#if 0
546 printf("lin %d -> %d [%s] %d %d\n", SLocOffset,
547 I-SLocEntryTable.begin(),
548 I->isInstantiation() ? "inst" : "file",
549 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
550#endif
551 FileID Res = FileID::get(I-SLocEntryTable.begin());
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000552
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000553 // If this isn't an instantiation, remember it. We have good locality
554 // across FileID lookups.
555 if (!I->isInstantiation())
556 LastFileIDLookup = Res;
557 NumLinearScans += NumProbes+1;
558 return Res;
559 }
560 if (++NumProbes == 8)
561 break;
562 }
Mike Stump1eb44332009-09-09 15:08:12 +0000563
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000564 // Convert "I" back into an index. We know that it is an entry whose index is
565 // larger than the offset we are looking for.
566 unsigned GreaterIndex = I-SLocEntryTable.begin();
567 // LessIndex - This is the lower bound of the range that we're searching.
568 // We know that the offset corresponding to the FileID is is less than
569 // SLocOffset.
570 unsigned LessIndex = 0;
571 NumProbes = 0;
572 while (1) {
573 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000574 unsigned MidOffset = getSLocEntry(FileID::get(MiddleIndex)).getOffset();
Mike Stump1eb44332009-09-09 15:08:12 +0000575
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000576 ++NumProbes;
Mike Stump1eb44332009-09-09 15:08:12 +0000577
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000578 // If the offset of the midpoint is too large, chop the high side of the
579 // range to the midpoint.
580 if (MidOffset > SLocOffset) {
581 GreaterIndex = MiddleIndex;
582 continue;
583 }
Mike Stump1eb44332009-09-09 15:08:12 +0000584
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000585 // If the middle index contains the value, succeed and return.
586 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
587#if 0
588 printf("bin %d -> %d [%s] %d %d\n", SLocOffset,
589 I-SLocEntryTable.begin(),
590 I->isInstantiation() ? "inst" : "file",
591 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
592#endif
593 FileID Res = FileID::get(MiddleIndex);
594
595 // If this isn't an instantiation, remember it. We have good locality
596 // across FileID lookups.
597 if (!I->isInstantiation())
598 LastFileIDLookup = Res;
599 NumBinaryProbes += NumProbes;
600 return Res;
601 }
Mike Stump1eb44332009-09-09 15:08:12 +0000602
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000603 // Otherwise, move the low-side up to the middle index.
604 LessIndex = MiddleIndex;
605 }
606}
607
Chris Lattneraddb7972009-01-26 20:04:19 +0000608SourceLocation SourceManager::
609getInstantiationLocSlowCase(SourceLocation Loc) const {
610 do {
Chris Lattnera5c6c582010-02-12 19:31:35 +0000611 // Note: If Loc indicates an offset into a token that came from a macro
612 // expansion (e.g. the 5th character of the token) we do not want to add
613 // this offset when going to the instantiation location. The instatiation
614 // location is the macro invocation, which the offset has nothing to do
615 // with. This is unlike when we get the spelling loc, because the offset
616 // directly correspond to the token whose spelling we're inspecting.
617 Loc = getSLocEntry(getFileID(Loc)).getInstantiation()
Chris Lattnere7fb4842009-02-15 20:52:18 +0000618 .getInstantiationLocStart();
Chris Lattneraddb7972009-01-26 20:04:19 +0000619 } while (!Loc.isFileID());
620
621 return Loc;
622}
623
624SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
625 do {
626 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
627 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
628 Loc = Loc.getFileLocWithOffset(LocInfo.second);
629 } while (!Loc.isFileID());
630 return Loc;
631}
632
633
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000634std::pair<FileID, unsigned>
635SourceManager::getDecomposedInstantiationLocSlowCase(const SrcMgr::SLocEntry *E,
636 unsigned Offset) const {
637 // If this is an instantiation record, walk through all the instantiation
638 // points.
639 FileID FID;
640 SourceLocation Loc;
641 do {
Chris Lattnere7fb4842009-02-15 20:52:18 +0000642 Loc = E->getInstantiation().getInstantiationLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000643
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000644 FID = getFileID(Loc);
645 E = &getSLocEntry(FID);
646 Offset += Loc.getOffset()-E->getOffset();
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000647 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000648
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000649 return std::make_pair(FID, Offset);
650}
651
652std::pair<FileID, unsigned>
653SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
654 unsigned Offset) const {
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000655 // If this is an instantiation record, walk through all the instantiation
656 // points.
657 FileID FID;
658 SourceLocation Loc;
659 do {
660 Loc = E->getInstantiation().getSpellingLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000661
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000662 FID = getFileID(Loc);
663 E = &getSLocEntry(FID);
664 Offset += Loc.getOffset()-E->getOffset();
665 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000666
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000667 return std::make_pair(FID, Offset);
668}
669
Chris Lattner387616e2009-02-17 08:04:48 +0000670/// getImmediateSpellingLoc - Given a SourceLocation object, return the
671/// spelling location referenced by the ID. This is the first level down
672/// towards the place where the characters that make up the lexed token can be
673/// found. This should not generally be used by clients.
674SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
675 if (Loc.isFileID()) return Loc;
676 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
677 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
678 return Loc.getFileLocWithOffset(LocInfo.second);
679}
680
681
Chris Lattnere7fb4842009-02-15 20:52:18 +0000682/// getImmediateInstantiationRange - Loc is required to be an instantiation
683/// location. Return the start/end of the instantiation information.
684std::pair<SourceLocation,SourceLocation>
685SourceManager::getImmediateInstantiationRange(SourceLocation Loc) const {
686 assert(Loc.isMacroID() && "Not an instantiation loc!");
687 const InstantiationInfo &II = getSLocEntry(getFileID(Loc)).getInstantiation();
688 return II.getInstantiationLocRange();
689}
690
Chris Lattner66781332009-02-15 21:26:50 +0000691/// getInstantiationRange - Given a SourceLocation object, return the
692/// range of tokens covered by the instantiation in the ultimate file.
693std::pair<SourceLocation,SourceLocation>
694SourceManager::getInstantiationRange(SourceLocation Loc) const {
695 if (Loc.isFileID()) return std::make_pair(Loc, Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000696
Chris Lattner66781332009-02-15 21:26:50 +0000697 std::pair<SourceLocation,SourceLocation> Res =
698 getImmediateInstantiationRange(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000699
Chris Lattner66781332009-02-15 21:26:50 +0000700 // Fully resolve the start and end locations to their ultimate instantiation
701 // points.
702 while (!Res.first.isFileID())
703 Res.first = getImmediateInstantiationRange(Res.first).first;
704 while (!Res.second.isFileID())
705 Res.second = getImmediateInstantiationRange(Res.second).second;
706 return Res;
707}
708
Chris Lattnere7fb4842009-02-15 20:52:18 +0000709
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000710
711//===----------------------------------------------------------------------===//
712// Queries about the code at a SourceLocation.
713//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000714
715/// getCharacterData - Return a pointer to the start of the specified location
716/// in the appropriate MemoryBuffer.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000717const char *SourceManager::getCharacterData(SourceLocation SL,
718 bool *Invalid) const {
Reid Spencer5f016e22007-07-11 17:01:13 +0000719 // Note that this is a hot function in the getSpelling() path, which is
720 // heavily used by -E mode.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000721 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
Mike Stump1eb44332009-09-09 15:08:12 +0000722
Ted Kremenekc16c2082009-01-06 01:55:26 +0000723 // Note that calling 'getBuffer()' may lazily page in a source file.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000724 bool CharDataInvalid = false;
725 const llvm::MemoryBuffer *Buffer
726 = getSLocEntry(LocInfo.first).getFile().getContentCache()->getBuffer(Diag,
727 &CharDataInvalid);
728 if (Invalid)
729 *Invalid = CharDataInvalid;
730 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
Reid Spencer5f016e22007-07-11 17:01:13 +0000731}
732
Reid Spencer5f016e22007-07-11 17:01:13 +0000733
Chris Lattner9dc1f532007-07-20 16:37:10 +0000734/// getColumnNumber - Return the column # for the specified file position.
Chris Lattner7da5aea2009-02-04 00:55:58 +0000735/// this is significantly cheaper to compute than the line number.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000736unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
737 bool *Invalid) const {
738 bool MyInvalid = false;
739 const char *Buf = getBuffer(FID, &MyInvalid)->getBufferStart();
740 if (Invalid)
741 *Invalid = MyInvalid;
742
743 if (MyInvalid)
744 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000745
Reid Spencer5f016e22007-07-11 17:01:13 +0000746 unsigned LineStart = FilePos;
747 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
748 --LineStart;
749 return FilePos-LineStart+1;
750}
751
Douglas Gregor50f6af72010-03-16 05:20:39 +0000752unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
753 bool *Invalid) const {
Chris Lattner30fc9332009-02-04 01:06:56 +0000754 if (Loc.isInvalid()) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +0000755 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000756 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +0000757}
758
Douglas Gregor50f6af72010-03-16 05:20:39 +0000759unsigned SourceManager::getInstantiationColumnNumber(SourceLocation Loc,
760 bool *Invalid) const {
Chris Lattner30fc9332009-02-04 01:06:56 +0000761 if (Loc.isInvalid()) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +0000762 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000763 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +0000764}
765
Douglas Gregor36c35ba2010-03-16 00:35:39 +0000766static DISABLE_INLINE void ComputeLineNumbers(Diagnostic &Diag,
767 ContentCache* FI,
Douglas Gregor50f6af72010-03-16 05:20:39 +0000768 llvm::BumpPtrAllocator &Alloc,
769 bool &Invalid);
Douglas Gregor36c35ba2010-03-16 00:35:39 +0000770static void ComputeLineNumbers(Diagnostic &Diag, ContentCache* FI,
Douglas Gregor50f6af72010-03-16 05:20:39 +0000771 llvm::BumpPtrAllocator &Alloc, bool &Invalid) {
Ted Kremenekc16c2082009-01-06 01:55:26 +0000772 // Note that calling 'getBuffer()' may lazily page in the file.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000773 const MemoryBuffer *Buffer = FI->getBuffer(Diag, &Invalid);
774 if (Invalid)
775 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000776
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000777 // Find the file offsets of all of the *physical* source lines. This does
778 // not look at trigraphs, escaped newlines, or anything else tricky.
779 std::vector<unsigned> LineOffsets;
Mike Stump1eb44332009-09-09 15:08:12 +0000780
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000781 // Line #1 starts at char 0.
782 LineOffsets.push_back(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000783
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000784 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
785 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
786 unsigned Offs = 0;
787 while (1) {
788 // Skip over the contents of the line.
789 // TODO: Vectorize this? This is very performance sensitive for programs
790 // with lots of diagnostics and in -E mode.
791 const unsigned char *NextBuf = (const unsigned char *)Buf;
792 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
793 ++NextBuf;
794 Offs += NextBuf-Buf;
795 Buf = NextBuf;
Mike Stump1eb44332009-09-09 15:08:12 +0000796
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000797 if (Buf[0] == '\n' || Buf[0] == '\r') {
798 // If this is \n\r or \r\n, skip both characters.
799 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
800 ++Offs, ++Buf;
801 ++Offs, ++Buf;
802 LineOffsets.push_back(Offs);
803 } else {
804 // Otherwise, this is a null. If end of file, exit.
805 if (Buf == End) break;
806 // Otherwise, skip the null.
807 ++Offs, ++Buf;
808 }
809 }
Mike Stump1eb44332009-09-09 15:08:12 +0000810
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000811 // Copy the offsets into the FileInfo structure.
812 FI->NumLines = LineOffsets.size();
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000813 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000814 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
815}
Reid Spencer5f016e22007-07-11 17:01:13 +0000816
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000817/// getLineNumber - Given a SourceLocation, return the spelling line number
Reid Spencer5f016e22007-07-11 17:01:13 +0000818/// for the position indicated. This requires building and caching a table of
819/// line offsets for the MemoryBuffer, so this is not cheap: use only when
820/// about to emit a diagnostic.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000821unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
822 bool *Invalid) const {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000823 ContentCache *Content;
Chris Lattner30fc9332009-02-04 01:06:56 +0000824 if (LastLineNoFileIDQuery == FID)
Ted Kremenek78d85f52007-10-30 21:08:08 +0000825 Content = LastLineNoContentCache;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000826 else
Chris Lattner30fc9332009-02-04 01:06:56 +0000827 Content = const_cast<ContentCache*>(getSLocEntry(FID)
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000828 .getFile().getContentCache());
Mike Stump1eb44332009-09-09 15:08:12 +0000829
Reid Spencer5f016e22007-07-11 17:01:13 +0000830 // If this is the first use of line information for this buffer, compute the
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000831 /// SourceLineCache for it on demand.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000832 if (Content->SourceLineCache == 0) {
833 bool MyInvalid = false;
834 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, MyInvalid);
835 if (Invalid)
836 *Invalid = MyInvalid;
837 if (MyInvalid)
838 return 1;
839 } else if (Invalid)
840 *Invalid = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000841
842 // Okay, we know we have a line number table. Do a binary search to find the
843 // line number that this character position lands on.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000844 unsigned *SourceLineCache = Content->SourceLineCache;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000845 unsigned *SourceLineCacheStart = SourceLineCache;
Ted Kremenek78d85f52007-10-30 21:08:08 +0000846 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
Mike Stump1eb44332009-09-09 15:08:12 +0000847
Chris Lattner30fc9332009-02-04 01:06:56 +0000848 unsigned QueriedFilePos = FilePos+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000849
Daniel Dunbar4106d692009-05-18 17:30:52 +0000850 // FIXME: I would like to be convinced that this code is worth being as
Mike Stump1eb44332009-09-09 15:08:12 +0000851 // complicated as it is, binary search isn't that slow.
Daniel Dunbar4106d692009-05-18 17:30:52 +0000852 //
853 // If it is worth being optimized, then in my opinion it could be more
854 // performant, simpler, and more obviously correct by just "galloping" outward
855 // from the queried file position. In fact, this could be incorporated into a
856 // generic algorithm such as lower_bound_with_hint.
857 //
858 // If someone gives me a test case where this matters, and I will do it! - DWD
859
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000860 // If the previous query was to the same file, we know both the file pos from
861 // that query and the line number returned. This allows us to narrow the
862 // search space from the entire file to something near the match.
Chris Lattner30fc9332009-02-04 01:06:56 +0000863 if (LastLineNoFileIDQuery == FID) {
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000864 if (QueriedFilePos >= LastLineNoFilePos) {
Daniel Dunbar4106d692009-05-18 17:30:52 +0000865 // FIXME: Potential overflow?
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000866 SourceLineCache = SourceLineCache+LastLineNoResult-1;
Mike Stump1eb44332009-09-09 15:08:12 +0000867
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000868 // The query is likely to be nearby the previous one. Here we check to
869 // see if it is within 5, 10 or 20 lines. It can be far away in cases
870 // where big comment blocks and vertical whitespace eat up lines but
871 // contribute no tokens.
872 if (SourceLineCache+5 < SourceLineCacheEnd) {
873 if (SourceLineCache[5] > QueriedFilePos)
874 SourceLineCacheEnd = SourceLineCache+5;
875 else if (SourceLineCache+10 < SourceLineCacheEnd) {
876 if (SourceLineCache[10] > QueriedFilePos)
877 SourceLineCacheEnd = SourceLineCache+10;
878 else if (SourceLineCache+20 < SourceLineCacheEnd) {
879 if (SourceLineCache[20] > QueriedFilePos)
880 SourceLineCacheEnd = SourceLineCache+20;
881 }
882 }
883 }
884 } else {
Daniel Dunbar4106d692009-05-18 17:30:52 +0000885 if (LastLineNoResult < Content->NumLines)
886 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000887 }
888 }
Mike Stump1eb44332009-09-09 15:08:12 +0000889
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000890 // If the spread is large, do a "radix" test as our initial guess, based on
891 // the assumption that lines average to approximately the same length.
892 // NOTE: This is currently disabled, as it does not appear to be profitable in
893 // initial measurements.
894 if (0 && SourceLineCacheEnd-SourceLineCache > 20) {
Ted Kremenek78d85f52007-10-30 21:08:08 +0000895 unsigned FileLen = Content->SourceLineCache[Content->NumLines-1];
Mike Stump1eb44332009-09-09 15:08:12 +0000896
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000897 // Take a stab at guessing where it is.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000898 unsigned ApproxPos = Content->NumLines*QueriedFilePos / FileLen;
Mike Stump1eb44332009-09-09 15:08:12 +0000899
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000900 // Check for -10 and +10 lines.
901 unsigned LowerBound = std::max(int(ApproxPos-10), 0);
902 unsigned UpperBound = std::min(ApproxPos+10, FileLen);
903
904 // If the computed lower bound is less than the query location, move it in.
905 if (SourceLineCache < SourceLineCacheStart+LowerBound &&
906 SourceLineCacheStart[LowerBound] < QueriedFilePos)
907 SourceLineCache = SourceLineCacheStart+LowerBound;
Mike Stump1eb44332009-09-09 15:08:12 +0000908
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000909 // If the computed upper bound is greater than the query location, move it.
910 if (SourceLineCacheEnd > SourceLineCacheStart+UpperBound &&
911 SourceLineCacheStart[UpperBound] >= QueriedFilePos)
912 SourceLineCacheEnd = SourceLineCacheStart+UpperBound;
913 }
Mike Stump1eb44332009-09-09 15:08:12 +0000914
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000915 unsigned *Pos
916 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000917 unsigned LineNo = Pos-SourceLineCacheStart;
Mike Stump1eb44332009-09-09 15:08:12 +0000918
Chris Lattner30fc9332009-02-04 01:06:56 +0000919 LastLineNoFileIDQuery = FID;
Ted Kremenek78d85f52007-10-30 21:08:08 +0000920 LastLineNoContentCache = Content;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000921 LastLineNoFilePos = QueriedFilePos;
922 LastLineNoResult = LineNo;
923 return LineNo;
Reid Spencer5f016e22007-07-11 17:01:13 +0000924}
925
Douglas Gregor50f6af72010-03-16 05:20:39 +0000926unsigned SourceManager::getInstantiationLineNumber(SourceLocation Loc,
927 bool *Invalid) const {
Chris Lattner30fc9332009-02-04 01:06:56 +0000928 if (Loc.isInvalid()) return 0;
929 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
930 return getLineNumber(LocInfo.first, LocInfo.second);
931}
Douglas Gregor50f6af72010-03-16 05:20:39 +0000932unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
933 bool *Invalid) const {
Chris Lattner30fc9332009-02-04 01:06:56 +0000934 if (Loc.isInvalid()) return 0;
935 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
936 return getLineNumber(LocInfo.first, LocInfo.second);
937}
938
Chris Lattner6b306672009-02-04 05:33:01 +0000939/// getFileCharacteristic - return the file characteristic of the specified
Mike Stump1eb44332009-09-09 15:08:12 +0000940/// source location, indicating whether this is a normal file, a system
Chris Lattner6b306672009-02-04 05:33:01 +0000941/// header, or an "implicit extern C" system header.
942///
943/// This state can be modified with flags on GNU linemarker directives like:
944/// # 4 "foo.h" 3
945/// which changes all source locations in the current file after that to be
946/// considered to be from a system header.
Mike Stump1eb44332009-09-09 15:08:12 +0000947SrcMgr::CharacteristicKind
Chris Lattner6b306672009-02-04 05:33:01 +0000948SourceManager::getFileCharacteristic(SourceLocation Loc) const {
949 assert(!Loc.isInvalid() && "Can't get file characteristic of invalid loc!");
950 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
951 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile();
952
953 // If there are no #line directives in this file, just return the whole-file
954 // state.
955 if (!FI.hasLineDirectives())
956 return FI.getFileCharacteristic();
Mike Stump1eb44332009-09-09 15:08:12 +0000957
Chris Lattner6b306672009-02-04 05:33:01 +0000958 assert(LineTable && "Can't have linetable entries without a LineTable!");
959 // See if there is a #line directive before the location.
960 const LineEntry *Entry =
961 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second);
Mike Stump1eb44332009-09-09 15:08:12 +0000962
Chris Lattner6b306672009-02-04 05:33:01 +0000963 // If this is before the first line marker, use the file characteristic.
964 if (!Entry)
965 return FI.getFileCharacteristic();
966
967 return Entry->FileKind;
968}
969
Chris Lattnerbff5c512009-02-17 08:39:06 +0000970/// Return the filename or buffer identifier of the buffer the location is in.
971/// Note that this name does not respect #line directives. Use getPresumedLoc
972/// for normal clients.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000973const char *SourceManager::getBufferName(SourceLocation Loc,
974 bool *Invalid) const {
Chris Lattnerbff5c512009-02-17 08:39:06 +0000975 if (Loc.isInvalid()) return "<invalid loc>";
Mike Stump1eb44332009-09-09 15:08:12 +0000976
Douglas Gregor50f6af72010-03-16 05:20:39 +0000977 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
Chris Lattnerbff5c512009-02-17 08:39:06 +0000978}
979
Chris Lattner30fc9332009-02-04 01:06:56 +0000980
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000981/// getPresumedLoc - This method returns the "presumed" location of a
982/// SourceLocation specifies. A "presumed location" can be modified by #line
983/// or GNU line marker directives. This provides a view on the data that a
984/// user should see in diagnostics, for example.
985///
986/// Note that a presumed location is always given as the instantiation point
987/// of an instantiation location, not at the spelling location.
988PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc) const {
989 if (Loc.isInvalid()) return PresumedLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000990
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000991 // Presumed locations are always for instantiation points.
Chris Lattner7da5aea2009-02-04 00:55:58 +0000992 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000993
Chris Lattner30fc9332009-02-04 01:06:56 +0000994 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile();
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000995 const SrcMgr::ContentCache *C = FI.getContentCache();
Mike Stump1eb44332009-09-09 15:08:12 +0000996
Chris Lattner3cd949c2009-02-04 01:55:42 +0000997 // To get the source name, first consult the FileEntry (if one exists)
998 // before the MemBuffer as this will avoid unnecessarily paging in the
999 // MemBuffer.
Mike Stump1eb44332009-09-09 15:08:12 +00001000 const char *Filename =
Douglas Gregor36c35ba2010-03-16 00:35:39 +00001001 C->Entry ? C->Entry->getName() : C->getBuffer(Diag)->getBufferIdentifier();
Chris Lattner3cd949c2009-02-04 01:55:42 +00001002 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second);
1003 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second);
1004 SourceLocation IncludeLoc = FI.getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001005
Chris Lattner3cd949c2009-02-04 01:55:42 +00001006 // If we have #line directives in this file, update and overwrite the physical
1007 // location info if appropriate.
1008 if (FI.hasLineDirectives()) {
1009 assert(LineTable && "Can't have linetable entries without a LineTable!");
1010 // See if there is a #line directive before this. If so, get it.
1011 if (const LineEntry *Entry =
1012 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second)) {
Chris Lattnerfc391332009-02-04 02:00:59 +00001013 // If the LineEntry indicates a filename, use it.
Chris Lattner3cd949c2009-02-04 01:55:42 +00001014 if (Entry->FilenameID != -1)
1015 Filename = LineTable->getFilename(Entry->FilenameID);
Chris Lattnerfc391332009-02-04 02:00:59 +00001016
1017 // Use the line number specified by the LineEntry. This line number may
1018 // be multiple lines down from the line entry. Add the difference in
1019 // physical line numbers from the query point and the line marker to the
1020 // total.
1021 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1022 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001023
Chris Lattner0e0e5da2009-02-04 02:15:40 +00001024 // Note that column numbers are not molested by line markers.
Mike Stump1eb44332009-09-09 15:08:12 +00001025
Chris Lattner137b6a62009-02-04 06:25:26 +00001026 // Handle virtual #include manipulation.
1027 if (Entry->IncludeOffset) {
1028 IncludeLoc = getLocForStartOfFile(LocInfo.first);
1029 IncludeLoc = IncludeLoc.getFileLocWithOffset(Entry->IncludeOffset);
1030 }
Chris Lattner3cd949c2009-02-04 01:55:42 +00001031 }
1032 }
1033
1034 return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc);
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001035}
1036
1037//===----------------------------------------------------------------------===//
1038// Other miscellaneous methods.
1039//===----------------------------------------------------------------------===//
1040
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001041/// \brief Get the source location for the given file:line:col triplet.
1042///
1043/// If the source file is included multiple times, the source location will
1044/// be based upon the first inclusion.
1045SourceLocation SourceManager::getLocation(const FileEntry *SourceFile,
1046 unsigned Line, unsigned Col) const {
1047 assert(SourceFile && "Null source file!");
1048 assert(Line && Col && "Line and column should start from 1!");
1049
1050 fileinfo_iterator FI = FileInfos.find(SourceFile);
1051 if (FI == FileInfos.end())
1052 return SourceLocation();
1053 ContentCache *Content = FI->second;
Mike Stump1eb44332009-09-09 15:08:12 +00001054
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001055 // If this is the first use of line information for this buffer, compute the
1056 /// SourceLineCache for it on demand.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001057 if (Content->SourceLineCache == 0) {
1058 bool MyInvalid = false;
1059 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, MyInvalid);
1060 if (MyInvalid)
1061 return SourceLocation();
1062 }
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001063
Douglas Gregor4a160e12009-12-02 05:34:39 +00001064 // Find the first file ID that corresponds to the given file.
1065 FileID FirstFID;
1066
1067 // First, check the main file ID, since it is common to look for a
1068 // location in the main file.
1069 if (!MainFileID.isInvalid()) {
1070 const SLocEntry &MainSLoc = getSLocEntry(MainFileID);
1071 if (MainSLoc.isFile() && MainSLoc.getFile().getContentCache() == Content)
1072 FirstFID = MainFileID;
1073 }
1074
1075 if (FirstFID.isInvalid()) {
1076 // The location we're looking for isn't in the main file; look
1077 // through all of the source locations.
1078 for (unsigned I = 0, N = sloc_entry_size(); I != N; ++I) {
1079 const SLocEntry &SLoc = getSLocEntry(I);
1080 if (SLoc.isFile() && SLoc.getFile().getContentCache() == Content) {
1081 FirstFID = FileID::get(I);
1082 break;
1083 }
1084 }
1085 }
1086
1087 if (FirstFID.isInvalid())
1088 return SourceLocation();
1089
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001090 if (Line > Content->NumLines) {
Douglas Gregor36c35ba2010-03-16 00:35:39 +00001091 unsigned Size = Content->getBuffer(Diag)->getBufferSize();
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001092 if (Size > 0)
1093 --Size;
1094 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(Size);
1095 }
1096
1097 unsigned FilePos = Content->SourceLineCache[Line - 1];
Douglas Gregor36c35ba2010-03-16 00:35:39 +00001098 const char *Buf = Content->getBuffer(Diag)->getBufferStart() + FilePos;
1099 unsigned BufLength = Content->getBuffer(Diag)->getBufferEnd() - Buf;
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001100 unsigned i = 0;
1101
1102 // Check that the given column is valid.
1103 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1104 ++i;
1105 if (i < Col-1)
1106 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + i);
1107
Douglas Gregor4a160e12009-12-02 05:34:39 +00001108 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + Col - 1);
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001109}
1110
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001111/// \brief Determines the order of 2 source locations in the translation unit.
1112///
1113/// \returns true if LHS source location comes before RHS, false otherwise.
1114bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
1115 SourceLocation RHS) const {
1116 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
1117 if (LHS == RHS)
1118 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001119
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001120 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
1121 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00001122
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001123 // If the source locations are in the same file, just compare offsets.
1124 if (LOffs.first == ROffs.first)
1125 return LOffs.second < ROffs.second;
1126
1127 // If we are comparing a source location with multiple locations in the same
1128 // file, we get a big win by caching the result.
Mike Stump1eb44332009-09-09 15:08:12 +00001129
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001130 if (LastLFIDForBeforeTUCheck == LOffs.first &&
1131 LastRFIDForBeforeTUCheck == ROffs.first)
1132 return LastResForBeforeTUCheck;
Mike Stump1eb44332009-09-09 15:08:12 +00001133
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001134 LastLFIDForBeforeTUCheck = LOffs.first;
1135 LastRFIDForBeforeTUCheck = ROffs.first;
Mike Stump1eb44332009-09-09 15:08:12 +00001136
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001137 // "Traverse" the include/instantiation stacks of both locations and try to
1138 // find a common "ancestor".
1139 //
1140 // First we traverse the stack of the right location and check each level
1141 // against the level of the left location, while collecting all levels in a
1142 // "stack map".
1143
1144 std::map<FileID, unsigned> ROffsMap;
1145 ROffsMap[ROffs.first] = ROffs.second;
1146
1147 while (1) {
1148 SourceLocation UpperLoc;
1149 const SrcMgr::SLocEntry &Entry = getSLocEntry(ROffs.first);
1150 if (Entry.isInstantiation())
1151 UpperLoc = Entry.getInstantiation().getInstantiationLocStart();
1152 else
1153 UpperLoc = Entry.getFile().getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001154
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001155 if (UpperLoc.isInvalid())
1156 break; // We reached the top.
Mike Stump1eb44332009-09-09 15:08:12 +00001157
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001158 ROffs = getDecomposedLoc(UpperLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001159
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001160 if (LOffs.first == ROffs.first)
1161 return LastResForBeforeTUCheck = LOffs.second < ROffs.second;
Mike Stump1eb44332009-09-09 15:08:12 +00001162
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001163 ROffsMap[ROffs.first] = ROffs.second;
1164 }
1165
1166 // We didn't find a common ancestor. Now traverse the stack of the left
1167 // location, checking against the stack map of the right location.
1168
1169 while (1) {
1170 SourceLocation UpperLoc;
1171 const SrcMgr::SLocEntry &Entry = getSLocEntry(LOffs.first);
1172 if (Entry.isInstantiation())
1173 UpperLoc = Entry.getInstantiation().getInstantiationLocStart();
1174 else
1175 UpperLoc = Entry.getFile().getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001176
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001177 if (UpperLoc.isInvalid())
1178 break; // We reached the top.
Mike Stump1eb44332009-09-09 15:08:12 +00001179
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001180 LOffs = getDecomposedLoc(UpperLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001181
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001182 std::map<FileID, unsigned>::iterator I = ROffsMap.find(LOffs.first);
1183 if (I != ROffsMap.end())
1184 return LastResForBeforeTUCheck = LOffs.second < I->second;
1185 }
Mike Stump1eb44332009-09-09 15:08:12 +00001186
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001187 // There is no common ancestor, most probably because one location is in the
1188 // predefines buffer.
1189 //
1190 // FIXME: We should rearrange the external interface so this simply never
1191 // happens; it can't conceptually happen. Also see PR5662.
Mike Stump1eb44332009-09-09 15:08:12 +00001192
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001193 // If exactly one location is a memory buffer, assume it preceeds the other.
1194 bool LIsMB = !getSLocEntry(LOffs.first).getFile().getContentCache()->Entry;
1195 bool RIsMB = !getSLocEntry(ROffs.first).getFile().getContentCache()->Entry;
1196 if (LIsMB != RIsMB)
1197 return LastResForBeforeTUCheck = LIsMB;
Mike Stump1eb44332009-09-09 15:08:12 +00001198
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001199 // Otherwise, just assume FileIDs were created in order.
1200 return LastResForBeforeTUCheck = (LOffs.first < ROffs.first);
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001201}
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001202
Reid Spencer5f016e22007-07-11 17:01:13 +00001203/// PrintStats - Print statistics to stderr.
1204///
1205void SourceManager::PrintStats() const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001206 llvm::errs() << "\n*** Source Manager Stats:\n";
1207 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
1208 << " mem buffers mapped.\n";
1209 llvm::errs() << SLocEntryTable.size() << " SLocEntry's allocated, "
1210 << NextOffset << "B of Sloc address space used.\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001211
Reid Spencer5f016e22007-07-11 17:01:13 +00001212 unsigned NumLineNumsComputed = 0;
1213 unsigned NumFileBytesMapped = 0;
Chris Lattner0d0bf8c2009-02-03 07:30:45 +00001214 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
1215 NumLineNumsComputed += I->second->SourceLineCache != 0;
1216 NumFileBytesMapped += I->second->getSizeBytesMapped();
Reid Spencer5f016e22007-07-11 17:01:13 +00001217 }
Mike Stump1eb44332009-09-09 15:08:12 +00001218
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001219 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
1220 << NumLineNumsComputed << " files with line #'s computed.\n";
1221 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
1222 << NumBinaryProbes << " binary.\n";
Reid Spencer5f016e22007-07-11 17:01:13 +00001223}
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001224
1225ExternalSLocEntrySource::~ExternalSLocEntrySource() { }