blob: dcbd4f166bfa8f6bc4f0f9337387c29e4c1a2df6 [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>
24
Reid Spencer5f016e22007-07-11 17:01:13 +000025using namespace clang;
26using namespace SrcMgr;
27using llvm::MemoryBuffer;
28
Chris Lattner23b5dc62009-02-04 00:40:31 +000029//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +000030// SourceManager Helper Classes
Chris Lattner23b5dc62009-02-04 00:40:31 +000031//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +000032
Douglas Gregoraea67db2010-03-15 22:54:52 +000033struct BufferResult::FailureData {
34 const llvm::MemoryBuffer *Buffer;
35 const char *FileName;
36 std::string ErrorStr;
37};
38
39BufferResult::BufferResult(const BufferResult &Other) {
40 if (const llvm::MemoryBuffer *Buffer
41 = Other.Data.dyn_cast<const llvm::MemoryBuffer *>()) {
42 Data = Buffer;
43 return;
44 }
45
46 Data = new FailureData(*Other.Data.get<FailureData *>());
47}
48
49BufferResult::BufferResult(const char *FileName, llvm::StringRef ErrorStr,
50 const llvm::MemoryBuffer *Buffer) {
51 FailureData *FD = new FailureData;
52 FD->FileName = FileName;
53 FD->ErrorStr = ErrorStr;
54 FD->Buffer = Buffer;
55 Data = FD;
56}
57
58BufferResult::~BufferResult() {
59 if (FailureData *FD = Data.dyn_cast<FailureData *>())
60 delete FD;
61}
62
63bool BufferResult::isInvalid() const {
64 return Data.is<FailureData *>();
65}
66
67const llvm::MemoryBuffer *BufferResult::getBuffer(Diagnostic &Diags) const {
68 llvm::StringRef FileName;
69 std::string ErrorMsg;
70 const llvm::MemoryBuffer *Result = getBuffer(FileName, ErrorMsg);
71 if (!ErrorMsg.empty()) {
72 Diags.Report(diag::err_cannot_open_file)
73 << FileName << ErrorMsg;
74 }
75 return Result;
76}
77
78const llvm::MemoryBuffer *BufferResult::getBuffer(llvm::StringRef &FileName,
79 std::string &Error) const {
80 if (const llvm::MemoryBuffer *Buffer
81 = Data.dyn_cast<const llvm::MemoryBuffer *>())
82 return Buffer;
83
84 FailureData *Fail = Data.get<FailureData *>();
85 FileName = Fail->FileName;
86 Error = Fail->ErrorStr;
87 return Fail->Buffer;
88}
89
90BufferResult::operator const llvm::MemoryBuffer *() const {
91 llvm::StringRef FileName;
92 std::string ErrorMsg;
93 const llvm::MemoryBuffer *Result = getBuffer(FileName, ErrorMsg);
94 if (!ErrorMsg.empty()) {
95 fprintf(stderr, "error: cannot open file '%s': %s\n",
96 FileName.str().c_str(), ErrorMsg.c_str());
97 }
98
99 return Result;
100}
101
Ted Kremenek78d85f52007-10-30 21:08:08 +0000102ContentCache::~ContentCache() {
103 delete Buffer;
Reid Spencer5f016e22007-07-11 17:01:13 +0000104}
105
Ted Kremenekc16c2082009-01-06 01:55:26 +0000106/// getSizeBytesMapped - Returns the number of bytes actually mapped for
107/// this ContentCache. This can be 0 if the MemBuffer was not actually
108/// instantiated.
109unsigned ContentCache::getSizeBytesMapped() const {
110 return Buffer ? Buffer->getBufferSize() : 0;
111}
112
113/// getSize - Returns the size of the content encapsulated by this ContentCache.
114/// This can be the size of the source file or the size of an arbitrary
115/// scratch buffer. If the ContentCache encapsulates a source file, that
Douglas Gregor29684422009-12-02 06:49:09 +0000116/// file is not lazily brought in from disk to satisfy this query.
Ted Kremenekc16c2082009-01-06 01:55:26 +0000117unsigned ContentCache::getSize() const {
Ted Kremenek8515fbf2010-03-10 18:22:38 +0000118 return Buffer ? (unsigned) Buffer->getBufferSize()
119 : (unsigned) Entry->getSize();
Ted Kremenekc16c2082009-01-06 01:55:26 +0000120}
121
Douglas Gregor29684422009-12-02 06:49:09 +0000122void ContentCache::replaceBuffer(const llvm::MemoryBuffer *B) {
Douglas Gregor109ae732009-12-03 17:05:59 +0000123 assert(B != Buffer);
Douglas Gregor29684422009-12-02 06:49:09 +0000124
125 delete Buffer;
126 Buffer = B;
127}
128
Douglas Gregoraea67db2010-03-15 22:54:52 +0000129BufferResult ContentCache::getBuffer() const {
Ted Kremenek5b034ad2009-01-06 22:43:04 +0000130 // Lazily create the Buffer for ContentCaches that wrap files.
131 if (!Buffer && Entry) {
Douglas Gregoraea67db2010-03-15 22:54:52 +0000132 std::string ErrorStr;
133 struct stat FileInfo;
134 Buffer = MemoryBuffer::getFile(Entry->getName(), &ErrorStr,
135 Entry->getSize(), &FileInfo);
Daniel Dunbar21a8bed2009-12-06 05:43:36 +0000136
137 // If we were unable to open the file, then we are in an inconsistent
138 // situation where the content cache referenced a file which no longer
139 // exists. Most likely, we were using a stat cache with an invalid entry but
140 // the file could also have been removed during processing. Since we can't
141 // really deal with this situation, just create an empty buffer.
142 //
143 // FIXME: This is definitely not ideal, but our immediate clients can't
144 // currently handle returning a null entry here. Ideally we should detect
145 // that we are in an inconsistent situation and error out as quickly as
146 // possible.
147 if (!Buffer) {
148 const llvm::StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
149 Buffer = MemoryBuffer::getNewMemBuffer(Entry->getSize(), "<invalid>");
150 char *Ptr = const_cast<char*>(Buffer->getBufferStart());
151 for (unsigned i = 0, e = Entry->getSize(); i != e; ++i)
152 Ptr[i] = FillStr[i % FillStr.size()];
Douglas Gregoraea67db2010-03-15 22:54:52 +0000153 return BufferResult(Entry->getName(), ErrorStr, Buffer);
154 } else {
155 // Check that the file's size and modification time is the same as
156 // in the file entry (which may have come from a stat cache).
157 // FIXME: Make these strings localizable.
158 if (FileInfo.st_size != Entry->getSize()) {
159 ErrorStr = "file has changed size since it was originally read";
160 return BufferResult(Entry->getName(), ErrorStr, Buffer);
161 } else if (FileInfo.st_mtime != Entry->getModificationTime()) {
162 ErrorStr = "file has been modified since it was originally read";
163 return BufferResult(Entry->getName(), ErrorStr, Buffer);
164 }
Daniel Dunbar21a8bed2009-12-06 05:43:36 +0000165 }
Ted Kremenek5b034ad2009-01-06 22:43:04 +0000166 }
Douglas Gregoraea67db2010-03-15 22:54:52 +0000167
Ted Kremenekc16c2082009-01-06 01:55:26 +0000168 return Buffer;
169}
170
Chris Lattner5b9a5042009-01-26 07:57:50 +0000171unsigned LineTableInfo::getLineTableFilenameID(const char *Ptr, unsigned Len) {
172 // Look up the filename in the string table, returning the pre-existing value
173 // if it exists.
Mike Stump1eb44332009-09-09 15:08:12 +0000174 llvm::StringMapEntry<unsigned> &Entry =
Chris Lattner5b9a5042009-01-26 07:57:50 +0000175 FilenameIDs.GetOrCreateValue(Ptr, Ptr+Len, ~0U);
176 if (Entry.getValue() != ~0U)
177 return Entry.getValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000178
Chris Lattner5b9a5042009-01-26 07:57:50 +0000179 // Otherwise, assign this the next available ID.
180 Entry.setValue(FilenamesByID.size());
181 FilenamesByID.push_back(&Entry);
182 return FilenamesByID.size()-1;
183}
184
Chris Lattnerac50e342009-02-03 22:13:05 +0000185/// AddLineNote - Add a line note to the line table that indicates that there
186/// is a #line at the specified FID/Offset location which changes the presumed
187/// location to LineNo/FilenameID.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000188void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
Chris Lattnerac50e342009-02-03 22:13:05 +0000189 unsigned LineNo, int FilenameID) {
Chris Lattner23b5dc62009-02-04 00:40:31 +0000190 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump1eb44332009-09-09 15:08:12 +0000191
Chris Lattner23b5dc62009-02-04 00:40:31 +0000192 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
193 "Adding line entries out of order!");
Mike Stump1eb44332009-09-09 15:08:12 +0000194
Chris Lattner9d79eba2009-02-04 05:21:58 +0000195 SrcMgr::CharacteristicKind Kind = SrcMgr::C_User;
Chris Lattner137b6a62009-02-04 06:25:26 +0000196 unsigned IncludeOffset = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000197
Chris Lattner9d79eba2009-02-04 05:21:58 +0000198 if (!Entries.empty()) {
199 // If this is a '#line 4' after '#line 42 "foo.h"', make sure to remember
200 // that we are still in "foo.h".
201 if (FilenameID == -1)
202 FilenameID = Entries.back().FilenameID;
Mike Stump1eb44332009-09-09 15:08:12 +0000203
Chris Lattner137b6a62009-02-04 06:25:26 +0000204 // If we are after a line marker that switched us to system header mode, or
205 // that set #include information, preserve it.
Chris Lattner9d79eba2009-02-04 05:21:58 +0000206 Kind = Entries.back().FileKind;
Chris Lattner137b6a62009-02-04 06:25:26 +0000207 IncludeOffset = Entries.back().IncludeOffset;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000208 }
Mike Stump1eb44332009-09-09 15:08:12 +0000209
Chris Lattner137b6a62009-02-04 06:25:26 +0000210 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, Kind,
211 IncludeOffset));
Chris Lattnerac50e342009-02-03 22:13:05 +0000212}
213
Chris Lattner9d79eba2009-02-04 05:21:58 +0000214/// AddLineNote This is the same as the previous version of AddLineNote, but is
215/// used for GNU line markers. If EntryExit is 0, then this doesn't change the
216/// presumed #include stack. If it is 1, this is a file entry, if it is 2 then
217/// this is a file exit. FileKind specifies whether this is a system header or
218/// extern C system header.
219void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
220 unsigned LineNo, int FilenameID,
221 unsigned EntryExit,
222 SrcMgr::CharacteristicKind FileKind) {
223 assert(FilenameID != -1 && "Unspecified filename should use other accessor");
Mike Stump1eb44332009-09-09 15:08:12 +0000224
Chris Lattner9d79eba2009-02-04 05:21:58 +0000225 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump1eb44332009-09-09 15:08:12 +0000226
Chris Lattner9d79eba2009-02-04 05:21:58 +0000227 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
228 "Adding line entries out of order!");
229
Chris Lattner137b6a62009-02-04 06:25:26 +0000230 unsigned IncludeOffset = 0;
231 if (EntryExit == 0) { // No #include stack change.
232 IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
233 } else if (EntryExit == 1) {
234 IncludeOffset = Offset-1;
235 } else if (EntryExit == 2) {
236 assert(!Entries.empty() && Entries.back().IncludeOffset &&
237 "PPDirectives should have caught case when popping empty include stack");
Mike Stump1eb44332009-09-09 15:08:12 +0000238
Chris Lattner137b6a62009-02-04 06:25:26 +0000239 // Get the include loc of the last entries' include loc as our include loc.
240 IncludeOffset = 0;
241 if (const LineEntry *PrevEntry =
242 FindNearestLineEntry(FID, Entries.back().IncludeOffset))
243 IncludeOffset = PrevEntry->IncludeOffset;
244 }
Mike Stump1eb44332009-09-09 15:08:12 +0000245
Chris Lattner137b6a62009-02-04 06:25:26 +0000246 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
247 IncludeOffset));
Chris Lattner9d79eba2009-02-04 05:21:58 +0000248}
249
250
Chris Lattner3cd949c2009-02-04 01:55:42 +0000251/// FindNearestLineEntry - Find the line entry nearest to FID that is before
252/// it. If there is no line entry before Offset in FID, return null.
Mike Stump1eb44332009-09-09 15:08:12 +0000253const LineEntry *LineTableInfo::FindNearestLineEntry(unsigned FID,
Chris Lattner3cd949c2009-02-04 01:55:42 +0000254 unsigned Offset) {
255 const std::vector<LineEntry> &Entries = LineEntries[FID];
256 assert(!Entries.empty() && "No #line entries for this FID after all!");
257
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000258 // It is very common for the query to be after the last #line, check this
259 // first.
260 if (Entries.back().FileOffset <= Offset)
261 return &Entries.back();
Chris Lattner3cd949c2009-02-04 01:55:42 +0000262
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000263 // Do a binary search to find the maximal element that is still before Offset.
264 std::vector<LineEntry>::const_iterator I =
265 std::upper_bound(Entries.begin(), Entries.end(), Offset);
266 if (I == Entries.begin()) return 0;
267 return &*--I;
Chris Lattner3cd949c2009-02-04 01:55:42 +0000268}
Chris Lattnerac50e342009-02-03 22:13:05 +0000269
Douglas Gregorbd945002009-04-13 16:31:14 +0000270/// \brief Add a new line entry that has already been encoded into
271/// the internal representation of the line table.
Mike Stump1eb44332009-09-09 15:08:12 +0000272void LineTableInfo::AddEntry(unsigned FID,
Douglas Gregorbd945002009-04-13 16:31:14 +0000273 const std::vector<LineEntry> &Entries) {
274 LineEntries[FID] = Entries;
275}
Chris Lattnerac50e342009-02-03 22:13:05 +0000276
Chris Lattner5b9a5042009-01-26 07:57:50 +0000277/// getLineTableFilenameID - Return the uniqued ID for the specified filename.
Mike Stump1eb44332009-09-09 15:08:12 +0000278///
Chris Lattner5b9a5042009-01-26 07:57:50 +0000279unsigned SourceManager::getLineTableFilenameID(const char *Ptr, unsigned Len) {
280 if (LineTable == 0)
281 LineTable = new LineTableInfo();
282 return LineTable->getLineTableFilenameID(Ptr, Len);
283}
284
285
Chris Lattner4c4ea172009-02-03 21:52:55 +0000286/// AddLineNote - Add a line note to the line table for the FileID and offset
287/// specified by Loc. If FilenameID is -1, it is considered to be
288/// unspecified.
289void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
290 int FilenameID) {
Chris Lattnerac50e342009-02-03 22:13:05 +0000291 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000292
Chris Lattnerac50e342009-02-03 22:13:05 +0000293 const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile();
294
295 // Remember that this file has #line directives now if it doesn't already.
296 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump1eb44332009-09-09 15:08:12 +0000297
Chris Lattnerac50e342009-02-03 22:13:05 +0000298 if (LineTable == 0)
299 LineTable = new LineTableInfo();
Chris Lattner23b5dc62009-02-04 00:40:31 +0000300 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID);
Chris Lattner4c4ea172009-02-03 21:52:55 +0000301}
302
Chris Lattner9d79eba2009-02-04 05:21:58 +0000303/// AddLineNote - Add a GNU line marker to the line table.
304void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
305 int FilenameID, bool IsFileEntry,
306 bool IsFileExit, bool IsSystemHeader,
307 bool IsExternCHeader) {
308 // If there is no filename and no flags, this is treated just like a #line,
309 // which does not change the flags of the previous line marker.
310 if (FilenameID == -1) {
311 assert(!IsFileEntry && !IsFileExit && !IsSystemHeader && !IsExternCHeader &&
312 "Can't set flags without setting the filename!");
313 return AddLineNote(Loc, LineNo, FilenameID);
314 }
Mike Stump1eb44332009-09-09 15:08:12 +0000315
Chris Lattner9d79eba2009-02-04 05:21:58 +0000316 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
317 const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile();
Mike Stump1eb44332009-09-09 15:08:12 +0000318
Chris Lattner9d79eba2009-02-04 05:21:58 +0000319 // Remember that this file has #line directives now if it doesn't already.
320 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump1eb44332009-09-09 15:08:12 +0000321
Chris Lattner9d79eba2009-02-04 05:21:58 +0000322 if (LineTable == 0)
323 LineTable = new LineTableInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000324
Chris Lattner9d79eba2009-02-04 05:21:58 +0000325 SrcMgr::CharacteristicKind FileKind;
326 if (IsExternCHeader)
327 FileKind = SrcMgr::C_ExternCSystem;
328 else if (IsSystemHeader)
329 FileKind = SrcMgr::C_System;
330 else
331 FileKind = SrcMgr::C_User;
Mike Stump1eb44332009-09-09 15:08:12 +0000332
Chris Lattner9d79eba2009-02-04 05:21:58 +0000333 unsigned EntryExit = 0;
334 if (IsFileEntry)
335 EntryExit = 1;
336 else if (IsFileExit)
337 EntryExit = 2;
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Chris Lattner9d79eba2009-02-04 05:21:58 +0000339 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID,
340 EntryExit, FileKind);
341}
342
Douglas Gregorbd945002009-04-13 16:31:14 +0000343LineTableInfo &SourceManager::getLineTable() {
344 if (LineTable == 0)
345 LineTable = new LineTableInfo();
346 return *LineTable;
347}
Chris Lattner4c4ea172009-02-03 21:52:55 +0000348
Chris Lattner23b5dc62009-02-04 00:40:31 +0000349//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000350// Private 'Create' methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000351//===----------------------------------------------------------------------===//
Ted Kremenekc16c2082009-01-06 01:55:26 +0000352
Chris Lattner5b9a5042009-01-26 07:57:50 +0000353SourceManager::~SourceManager() {
354 delete LineTable;
Mike Stump1eb44332009-09-09 15:08:12 +0000355
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000356 // Delete FileEntry objects corresponding to content caches. Since the actual
357 // content cache objects are bump pointer allocated, we just have to run the
358 // dtors, but we call the deallocate method for completeness.
359 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
360 MemBufferInfos[i]->~ContentCache();
361 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
362 }
363 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
364 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
365 I->second->~ContentCache();
366 ContentCacheAlloc.Deallocate(I->second);
367 }
Chris Lattner5b9a5042009-01-26 07:57:50 +0000368}
369
370void SourceManager::clearIDTables() {
371 MainFileID = FileID();
372 SLocEntryTable.clear();
373 LastLineNoFileIDQuery = FileID();
374 LastLineNoContentCache = 0;
375 LastFileIDLookup = FileID();
Mike Stump1eb44332009-09-09 15:08:12 +0000376
Chris Lattner5b9a5042009-01-26 07:57:50 +0000377 if (LineTable)
378 LineTable->clear();
Mike Stump1eb44332009-09-09 15:08:12 +0000379
Chris Lattner5b9a5042009-01-26 07:57:50 +0000380 // Use up FileID #0 as an invalid instantiation.
381 NextOffset = 0;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000382 createInstantiationLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000383}
384
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000385/// getOrCreateContentCache - Create or return a cached ContentCache for the
386/// specified file.
387const ContentCache *
388SourceManager::getOrCreateContentCache(const FileEntry *FileEnt) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000389 assert(FileEnt && "Didn't specify a file entry to use?");
Mike Stump1eb44332009-09-09 15:08:12 +0000390
Reid Spencer5f016e22007-07-11 17:01:13 +0000391 // Do we already have information about this file?
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000392 ContentCache *&Entry = FileInfos[FileEnt];
393 if (Entry) return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +0000394
Chris Lattner00282d62009-02-03 07:41:46 +0000395 // Nope, create a new Cache entry. Make sure it is at least 8-byte aligned
396 // so that FileInfo can use the low 3 bits of the pointer for its own
397 // nefarious purposes.
398 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
399 EntryAlign = std::max(8U, EntryAlign);
400 Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000401 new (Entry) ContentCache(FileEnt);
402 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000403}
404
405
Ted Kremenekd1c0eee2007-10-31 17:53:38 +0000406/// createMemBufferContentCache - Create a new ContentCache for the specified
407/// memory buffer. This does no caching.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000408const ContentCache*
409SourceManager::createMemBufferContentCache(const MemoryBuffer *Buffer) {
Chris Lattner00282d62009-02-03 07:41:46 +0000410 // Add a new ContentCache to the MemBufferInfos list and return it. Make sure
411 // it is at least 8-byte aligned so that FileInfo can use the low 3 bits of
412 // the pointer for its own nefarious purposes.
413 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
414 EntryAlign = std::max(8U, EntryAlign);
415 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000416 new (Entry) ContentCache();
417 MemBufferInfos.push_back(Entry);
418 Entry->setBuffer(Buffer);
419 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000420}
421
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000422void SourceManager::PreallocateSLocEntries(ExternalSLocEntrySource *Source,
423 unsigned NumSLocEntries,
424 unsigned NextOffset) {
425 ExternalSLocEntries = Source;
426 this->NextOffset = NextOffset;
427 SLocEntryLoaded.resize(NumSLocEntries + 1);
428 SLocEntryLoaded[0] = true;
429 SLocEntryTable.resize(SLocEntryTable.size() + NumSLocEntries);
430}
431
Douglas Gregor2bf1eb02009-04-27 21:28:04 +0000432void SourceManager::ClearPreallocatedSLocEntries() {
433 unsigned I = 0;
434 for (unsigned N = SLocEntryLoaded.size(); I != N; ++I)
435 if (!SLocEntryLoaded[I])
436 break;
437
438 // We've already loaded all preallocated source location entries.
439 if (I == SLocEntryLoaded.size())
440 return;
441
442 // Remove everything from location I onward.
443 SLocEntryTable.resize(I);
444 SLocEntryLoaded.clear();
445 ExternalSLocEntries = 0;
446}
447
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000448
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000449//===----------------------------------------------------------------------===//
450// Methods to create new FileID's and instantiations.
451//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000452
Nico Weber48002c82008-09-29 00:25:48 +0000453/// createFileID - Create a new fileID for the specified ContentCache and
Ted Kremenek0d892d82007-10-30 22:57:35 +0000454/// include position. This works regardless of whether the ContentCache
455/// corresponds to a file or some other input source.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000456FileID SourceManager::createFileID(const ContentCache *File,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000457 SourceLocation IncludePos,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000458 SrcMgr::CharacteristicKind FileCharacter,
459 unsigned PreallocatedID,
460 unsigned Offset) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000461 if (PreallocatedID) {
462 // If we're filling in a preallocated ID, just load in the file
463 // entry and return.
Mike Stump1eb44332009-09-09 15:08:12 +0000464 assert(PreallocatedID < SLocEntryLoaded.size() &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000465 "Preallocate ID out-of-range");
Mike Stump1eb44332009-09-09 15:08:12 +0000466 assert(!SLocEntryLoaded[PreallocatedID] &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000467 "Source location entry already loaded");
468 assert(Offset && "Preallocate source location cannot have zero offset");
Mike Stump1eb44332009-09-09 15:08:12 +0000469 SLocEntryTable[PreallocatedID]
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000470 = SLocEntry::get(Offset, FileInfo::get(IncludePos, File, FileCharacter));
471 SLocEntryLoaded[PreallocatedID] = true;
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +0000472 FileID FID = FileID::get(PreallocatedID);
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +0000473 return LastFileIDLookup = FID;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000474 }
475
Mike Stump1eb44332009-09-09 15:08:12 +0000476 SLocEntryTable.push_back(SLocEntry::get(NextOffset,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000477 FileInfo::get(IncludePos, File,
478 FileCharacter)));
Ted Kremenekc16c2082009-01-06 01:55:26 +0000479 unsigned FileSize = File->getSize();
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000480 assert(NextOffset+FileSize+1 > NextOffset && "Ran out of source locations!");
481 NextOffset += FileSize+1;
Mike Stump1eb44332009-09-09 15:08:12 +0000482
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000483 // Set LastFileIDLookup to the newly created file. The next getFileID call is
484 // almost guaranteed to be from that file.
Argyrios Kyrtzidisea703f12009-06-23 00:42:06 +0000485 FileID FID = FileID::get(SLocEntryTable.size()-1);
Argyrios Kyrtzidisea703f12009-06-23 00:42:06 +0000486 return LastFileIDLookup = FID;
Reid Spencer5f016e22007-07-11 17:01:13 +0000487}
488
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000489/// createInstantiationLoc - Return a new SourceLocation that encodes the fact
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000490/// that a token from SpellingLoc should actually be referenced from
Reid Spencer5f016e22007-07-11 17:01:13 +0000491/// InstantiationLoc.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000492SourceLocation SourceManager::createInstantiationLoc(SourceLocation SpellingLoc,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000493 SourceLocation ILocStart,
494 SourceLocation ILocEnd,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000495 unsigned TokLength,
496 unsigned PreallocatedID,
497 unsigned Offset) {
Chris Lattnere7fb4842009-02-15 20:52:18 +0000498 InstantiationInfo II = InstantiationInfo::get(ILocStart,ILocEnd, SpellingLoc);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000499 if (PreallocatedID) {
500 // If we're filling in a preallocated ID, just load in the
501 // instantiation entry and return.
Mike Stump1eb44332009-09-09 15:08:12 +0000502 assert(PreallocatedID < SLocEntryLoaded.size() &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000503 "Preallocate ID out-of-range");
Mike Stump1eb44332009-09-09 15:08:12 +0000504 assert(!SLocEntryLoaded[PreallocatedID] &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000505 "Source location entry already loaded");
506 assert(Offset && "Preallocate source location cannot have zero offset");
507 SLocEntryTable[PreallocatedID] = SLocEntry::get(Offset, II);
508 SLocEntryLoaded[PreallocatedID] = true;
509 return SourceLocation::getMacroLoc(Offset);
510 }
Chris Lattnere7fb4842009-02-15 20:52:18 +0000511 SLocEntryTable.push_back(SLocEntry::get(NextOffset, II));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000512 assert(NextOffset+TokLength+1 > NextOffset && "Ran out of source locations!");
513 NextOffset += TokLength+1;
514 return SourceLocation::getMacroLoc(NextOffset-(TokLength+1));
Reid Spencer5f016e22007-07-11 17:01:13 +0000515}
516
Douglas Gregoraea67db2010-03-15 22:54:52 +0000517BufferResult SourceManager::getMemoryBufferForFile(const FileEntry *File) {
Douglas Gregor29684422009-12-02 06:49:09 +0000518 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
Douglas Gregoraea67db2010-03-15 22:54:52 +0000519 assert(IR && "getOrCreateContentCache() cannot return NULL");
Douglas Gregor29684422009-12-02 06:49:09 +0000520 return IR->getBuffer();
521}
522
523bool SourceManager::overrideFileContents(const FileEntry *SourceFile,
524 const llvm::MemoryBuffer *Buffer) {
525 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
526 if (IR == 0)
527 return true;
528
529 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer);
530 return false;
531}
532
Chris Lattner2b2453a2009-01-17 06:22:33 +0000533std::pair<const char*, const char*>
Douglas Gregoraea67db2010-03-15 22:54:52 +0000534SourceManager::getBufferData(FileID FID, llvm::StringRef &FileName,
535 std::string &Error) const {
536 const llvm::MemoryBuffer *Buf = getBuffer(FID).getBuffer(FileName, Error);
537 if (!Error.empty())
538 return std::make_pair((const char *)0, (const char *)0);
Chris Lattner2b2453a2009-01-17 06:22:33 +0000539 return std::make_pair(Buf->getBufferStart(), Buf->getBufferEnd());
540}
541
Douglas Gregoraea67db2010-03-15 22:54:52 +0000542std::pair<const char*, const char*>
543SourceManager::getBufferData(FileID FID, Diagnostic &Diags) const {
544 const llvm::MemoryBuffer *Buf = getBuffer(FID).getBuffer(Diags);
545 if (!Buf)
546 return std::make_pair((const char *)0, (const char *)0);
547 return std::make_pair(Buf->getBufferStart(), Buf->getBufferEnd());
548}
Chris Lattner2b2453a2009-01-17 06:22:33 +0000549
Chris Lattner23b5dc62009-02-04 00:40:31 +0000550//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000551// SourceLocation manipulation methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000552//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000553
554/// getFileIDSlow - Return the FileID for a SourceLocation. This is a very hot
555/// method that is used for all SourceManager queries that start with a
556/// SourceLocation object. It is responsible for finding the entry in
557/// SLocEntryTable which contains the specified location.
558///
559FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
560 assert(SLocOffset && "Invalid FileID");
Mike Stump1eb44332009-09-09 15:08:12 +0000561
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000562 // After the first and second level caches, I see two common sorts of
563 // behavior: 1) a lot of searched FileID's are "near" the cached file location
564 // or are "near" the cached instantiation location. 2) others are just
565 // completely random and may be a very long way away.
566 //
567 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
568 // then we fall back to a less cache efficient, but more scalable, binary
569 // search to find the location.
Mike Stump1eb44332009-09-09 15:08:12 +0000570
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000571 // See if this is near the file point - worst case we start scanning from the
572 // most newly created FileID.
573 std::vector<SrcMgr::SLocEntry>::const_iterator I;
Mike Stump1eb44332009-09-09 15:08:12 +0000574
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000575 if (SLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
576 // Neither loc prunes our search.
577 I = SLocEntryTable.end();
578 } else {
579 // Perhaps it is near the file point.
580 I = SLocEntryTable.begin()+LastFileIDLookup.ID;
581 }
582
583 // Find the FileID that contains this. "I" is an iterator that points to a
584 // FileID whose offset is known to be larger than SLocOffset.
585 unsigned NumProbes = 0;
586 while (1) {
587 --I;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000588 if (ExternalSLocEntries)
589 getSLocEntry(FileID::get(I - SLocEntryTable.begin()));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000590 if (I->getOffset() <= SLocOffset) {
591#if 0
592 printf("lin %d -> %d [%s] %d %d\n", SLocOffset,
593 I-SLocEntryTable.begin(),
594 I->isInstantiation() ? "inst" : "file",
595 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
596#endif
597 FileID Res = FileID::get(I-SLocEntryTable.begin());
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000598
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000599 // If this isn't an instantiation, remember it. We have good locality
600 // across FileID lookups.
601 if (!I->isInstantiation())
602 LastFileIDLookup = Res;
603 NumLinearScans += NumProbes+1;
604 return Res;
605 }
606 if (++NumProbes == 8)
607 break;
608 }
Mike Stump1eb44332009-09-09 15:08:12 +0000609
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000610 // Convert "I" back into an index. We know that it is an entry whose index is
611 // larger than the offset we are looking for.
612 unsigned GreaterIndex = I-SLocEntryTable.begin();
613 // LessIndex - This is the lower bound of the range that we're searching.
614 // We know that the offset corresponding to the FileID is is less than
615 // SLocOffset.
616 unsigned LessIndex = 0;
617 NumProbes = 0;
618 while (1) {
619 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000620 unsigned MidOffset = getSLocEntry(FileID::get(MiddleIndex)).getOffset();
Mike Stump1eb44332009-09-09 15:08:12 +0000621
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000622 ++NumProbes;
Mike Stump1eb44332009-09-09 15:08:12 +0000623
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000624 // If the offset of the midpoint is too large, chop the high side of the
625 // range to the midpoint.
626 if (MidOffset > SLocOffset) {
627 GreaterIndex = MiddleIndex;
628 continue;
629 }
Mike Stump1eb44332009-09-09 15:08:12 +0000630
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000631 // If the middle index contains the value, succeed and return.
632 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
633#if 0
634 printf("bin %d -> %d [%s] %d %d\n", SLocOffset,
635 I-SLocEntryTable.begin(),
636 I->isInstantiation() ? "inst" : "file",
637 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
638#endif
639 FileID Res = FileID::get(MiddleIndex);
640
641 // If this isn't an instantiation, remember it. We have good locality
642 // across FileID lookups.
643 if (!I->isInstantiation())
644 LastFileIDLookup = Res;
645 NumBinaryProbes += NumProbes;
646 return Res;
647 }
Mike Stump1eb44332009-09-09 15:08:12 +0000648
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000649 // Otherwise, move the low-side up to the middle index.
650 LessIndex = MiddleIndex;
651 }
652}
653
Chris Lattneraddb7972009-01-26 20:04:19 +0000654SourceLocation SourceManager::
655getInstantiationLocSlowCase(SourceLocation Loc) const {
656 do {
Chris Lattnera5c6c582010-02-12 19:31:35 +0000657 // Note: If Loc indicates an offset into a token that came from a macro
658 // expansion (e.g. the 5th character of the token) we do not want to add
659 // this offset when going to the instantiation location. The instatiation
660 // location is the macro invocation, which the offset has nothing to do
661 // with. This is unlike when we get the spelling loc, because the offset
662 // directly correspond to the token whose spelling we're inspecting.
663 Loc = getSLocEntry(getFileID(Loc)).getInstantiation()
Chris Lattnere7fb4842009-02-15 20:52:18 +0000664 .getInstantiationLocStart();
Chris Lattneraddb7972009-01-26 20:04:19 +0000665 } while (!Loc.isFileID());
666
667 return Loc;
668}
669
670SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
671 do {
672 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
673 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
674 Loc = Loc.getFileLocWithOffset(LocInfo.second);
675 } while (!Loc.isFileID());
676 return Loc;
677}
678
679
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000680std::pair<FileID, unsigned>
681SourceManager::getDecomposedInstantiationLocSlowCase(const SrcMgr::SLocEntry *E,
682 unsigned Offset) const {
683 // If this is an instantiation record, walk through all the instantiation
684 // points.
685 FileID FID;
686 SourceLocation Loc;
687 do {
Chris Lattnere7fb4842009-02-15 20:52:18 +0000688 Loc = E->getInstantiation().getInstantiationLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000689
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000690 FID = getFileID(Loc);
691 E = &getSLocEntry(FID);
692 Offset += Loc.getOffset()-E->getOffset();
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000693 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000694
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000695 return std::make_pair(FID, Offset);
696}
697
698std::pair<FileID, unsigned>
699SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
700 unsigned Offset) const {
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000701 // If this is an instantiation record, walk through all the instantiation
702 // points.
703 FileID FID;
704 SourceLocation Loc;
705 do {
706 Loc = E->getInstantiation().getSpellingLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000707
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000708 FID = getFileID(Loc);
709 E = &getSLocEntry(FID);
710 Offset += Loc.getOffset()-E->getOffset();
711 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000712
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000713 return std::make_pair(FID, Offset);
714}
715
Chris Lattner387616e2009-02-17 08:04:48 +0000716/// getImmediateSpellingLoc - Given a SourceLocation object, return the
717/// spelling location referenced by the ID. This is the first level down
718/// towards the place where the characters that make up the lexed token can be
719/// found. This should not generally be used by clients.
720SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
721 if (Loc.isFileID()) return Loc;
722 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
723 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
724 return Loc.getFileLocWithOffset(LocInfo.second);
725}
726
727
Chris Lattnere7fb4842009-02-15 20:52:18 +0000728/// getImmediateInstantiationRange - Loc is required to be an instantiation
729/// location. Return the start/end of the instantiation information.
730std::pair<SourceLocation,SourceLocation>
731SourceManager::getImmediateInstantiationRange(SourceLocation Loc) const {
732 assert(Loc.isMacroID() && "Not an instantiation loc!");
733 const InstantiationInfo &II = getSLocEntry(getFileID(Loc)).getInstantiation();
734 return II.getInstantiationLocRange();
735}
736
Chris Lattner66781332009-02-15 21:26:50 +0000737/// getInstantiationRange - Given a SourceLocation object, return the
738/// range of tokens covered by the instantiation in the ultimate file.
739std::pair<SourceLocation,SourceLocation>
740SourceManager::getInstantiationRange(SourceLocation Loc) const {
741 if (Loc.isFileID()) return std::make_pair(Loc, Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000742
Chris Lattner66781332009-02-15 21:26:50 +0000743 std::pair<SourceLocation,SourceLocation> Res =
744 getImmediateInstantiationRange(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000745
Chris Lattner66781332009-02-15 21:26:50 +0000746 // Fully resolve the start and end locations to their ultimate instantiation
747 // points.
748 while (!Res.first.isFileID())
749 Res.first = getImmediateInstantiationRange(Res.first).first;
750 while (!Res.second.isFileID())
751 Res.second = getImmediateInstantiationRange(Res.second).second;
752 return Res;
753}
754
Chris Lattnere7fb4842009-02-15 20:52:18 +0000755
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000756
757//===----------------------------------------------------------------------===//
758// Queries about the code at a SourceLocation.
759//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000760
761/// getCharacterData - Return a pointer to the start of the specified location
762/// in the appropriate MemoryBuffer.
763const char *SourceManager::getCharacterData(SourceLocation SL) const {
764 // Note that this is a hot function in the getSpelling() path, which is
765 // heavily used by -E mode.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000766 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
Mike Stump1eb44332009-09-09 15:08:12 +0000767
Ted Kremenekc16c2082009-01-06 01:55:26 +0000768 // Note that calling 'getBuffer()' may lazily page in a source file.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000769 return getSLocEntry(LocInfo.first).getFile().getContentCache()
770 ->getBuffer()->getBufferStart() + LocInfo.second;
Reid Spencer5f016e22007-07-11 17:01:13 +0000771}
772
Reid Spencer5f016e22007-07-11 17:01:13 +0000773
Chris Lattner9dc1f532007-07-20 16:37:10 +0000774/// getColumnNumber - Return the column # for the specified file position.
Chris Lattner7da5aea2009-02-04 00:55:58 +0000775/// this is significantly cheaper to compute than the line number.
776unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos) const {
777 const char *Buf = getBuffer(FID)->getBufferStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000778
Reid Spencer5f016e22007-07-11 17:01:13 +0000779 unsigned LineStart = FilePos;
780 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
781 --LineStart;
782 return FilePos-LineStart+1;
783}
784
Chris Lattner7da5aea2009-02-04 00:55:58 +0000785unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc) const {
Chris Lattner30fc9332009-02-04 01:06:56 +0000786 if (Loc.isInvalid()) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +0000787 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
788 return getColumnNumber(LocInfo.first, LocInfo.second);
789}
790
791unsigned SourceManager::getInstantiationColumnNumber(SourceLocation Loc) const {
Chris Lattner30fc9332009-02-04 01:06:56 +0000792 if (Loc.isInvalid()) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +0000793 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
794 return getColumnNumber(LocInfo.first, LocInfo.second);
795}
796
797
798
Benjamin Kramerc997eb42009-11-14 16:36:57 +0000799static DISABLE_INLINE void ComputeLineNumbers(ContentCache* FI,
800 llvm::BumpPtrAllocator &Alloc);
Mike Stump1eb44332009-09-09 15:08:12 +0000801static void ComputeLineNumbers(ContentCache* FI, llvm::BumpPtrAllocator &Alloc){
Ted Kremenekc16c2082009-01-06 01:55:26 +0000802 // Note that calling 'getBuffer()' may lazily page in the file.
803 const MemoryBuffer *Buffer = FI->getBuffer();
Mike Stump1eb44332009-09-09 15:08:12 +0000804
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000805 // Find the file offsets of all of the *physical* source lines. This does
806 // not look at trigraphs, escaped newlines, or anything else tricky.
807 std::vector<unsigned> LineOffsets;
Mike Stump1eb44332009-09-09 15:08:12 +0000808
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000809 // Line #1 starts at char 0.
810 LineOffsets.push_back(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000811
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000812 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
813 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
814 unsigned Offs = 0;
815 while (1) {
816 // Skip over the contents of the line.
817 // TODO: Vectorize this? This is very performance sensitive for programs
818 // with lots of diagnostics and in -E mode.
819 const unsigned char *NextBuf = (const unsigned char *)Buf;
820 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
821 ++NextBuf;
822 Offs += NextBuf-Buf;
823 Buf = NextBuf;
Mike Stump1eb44332009-09-09 15:08:12 +0000824
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000825 if (Buf[0] == '\n' || Buf[0] == '\r') {
826 // If this is \n\r or \r\n, skip both characters.
827 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
828 ++Offs, ++Buf;
829 ++Offs, ++Buf;
830 LineOffsets.push_back(Offs);
831 } else {
832 // Otherwise, this is a null. If end of file, exit.
833 if (Buf == End) break;
834 // Otherwise, skip the null.
835 ++Offs, ++Buf;
836 }
837 }
Mike Stump1eb44332009-09-09 15:08:12 +0000838
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000839 // Copy the offsets into the FileInfo structure.
840 FI->NumLines = LineOffsets.size();
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000841 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000842 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
843}
Reid Spencer5f016e22007-07-11 17:01:13 +0000844
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000845/// getLineNumber - Given a SourceLocation, return the spelling line number
Reid Spencer5f016e22007-07-11 17:01:13 +0000846/// for the position indicated. This requires building and caching a table of
847/// line offsets for the MemoryBuffer, so this is not cheap: use only when
848/// about to emit a diagnostic.
Chris Lattner30fc9332009-02-04 01:06:56 +0000849unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos) const {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000850 ContentCache *Content;
Chris Lattner30fc9332009-02-04 01:06:56 +0000851 if (LastLineNoFileIDQuery == FID)
Ted Kremenek78d85f52007-10-30 21:08:08 +0000852 Content = LastLineNoContentCache;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000853 else
Chris Lattner30fc9332009-02-04 01:06:56 +0000854 Content = const_cast<ContentCache*>(getSLocEntry(FID)
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000855 .getFile().getContentCache());
Mike Stump1eb44332009-09-09 15:08:12 +0000856
Reid Spencer5f016e22007-07-11 17:01:13 +0000857 // If this is the first use of line information for this buffer, compute the
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000858 /// SourceLineCache for it on demand.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000859 if (Content->SourceLineCache == 0)
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000860 ComputeLineNumbers(Content, ContentCacheAlloc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000861
862 // Okay, we know we have a line number table. Do a binary search to find the
863 // line number that this character position lands on.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000864 unsigned *SourceLineCache = Content->SourceLineCache;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000865 unsigned *SourceLineCacheStart = SourceLineCache;
Ted Kremenek78d85f52007-10-30 21:08:08 +0000866 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
Mike Stump1eb44332009-09-09 15:08:12 +0000867
Chris Lattner30fc9332009-02-04 01:06:56 +0000868 unsigned QueriedFilePos = FilePos+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000869
Daniel Dunbar4106d692009-05-18 17:30:52 +0000870 // FIXME: I would like to be convinced that this code is worth being as
Mike Stump1eb44332009-09-09 15:08:12 +0000871 // complicated as it is, binary search isn't that slow.
Daniel Dunbar4106d692009-05-18 17:30:52 +0000872 //
873 // If it is worth being optimized, then in my opinion it could be more
874 // performant, simpler, and more obviously correct by just "galloping" outward
875 // from the queried file position. In fact, this could be incorporated into a
876 // generic algorithm such as lower_bound_with_hint.
877 //
878 // If someone gives me a test case where this matters, and I will do it! - DWD
879
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000880 // If the previous query was to the same file, we know both the file pos from
881 // that query and the line number returned. This allows us to narrow the
882 // search space from the entire file to something near the match.
Chris Lattner30fc9332009-02-04 01:06:56 +0000883 if (LastLineNoFileIDQuery == FID) {
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000884 if (QueriedFilePos >= LastLineNoFilePos) {
Daniel Dunbar4106d692009-05-18 17:30:52 +0000885 // FIXME: Potential overflow?
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000886 SourceLineCache = SourceLineCache+LastLineNoResult-1;
Mike Stump1eb44332009-09-09 15:08:12 +0000887
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000888 // The query is likely to be nearby the previous one. Here we check to
889 // see if it is within 5, 10 or 20 lines. It can be far away in cases
890 // where big comment blocks and vertical whitespace eat up lines but
891 // contribute no tokens.
892 if (SourceLineCache+5 < SourceLineCacheEnd) {
893 if (SourceLineCache[5] > QueriedFilePos)
894 SourceLineCacheEnd = SourceLineCache+5;
895 else if (SourceLineCache+10 < SourceLineCacheEnd) {
896 if (SourceLineCache[10] > QueriedFilePos)
897 SourceLineCacheEnd = SourceLineCache+10;
898 else if (SourceLineCache+20 < SourceLineCacheEnd) {
899 if (SourceLineCache[20] > QueriedFilePos)
900 SourceLineCacheEnd = SourceLineCache+20;
901 }
902 }
903 }
904 } else {
Daniel Dunbar4106d692009-05-18 17:30:52 +0000905 if (LastLineNoResult < Content->NumLines)
906 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000907 }
908 }
Mike Stump1eb44332009-09-09 15:08:12 +0000909
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000910 // If the spread is large, do a "radix" test as our initial guess, based on
911 // the assumption that lines average to approximately the same length.
912 // NOTE: This is currently disabled, as it does not appear to be profitable in
913 // initial measurements.
914 if (0 && SourceLineCacheEnd-SourceLineCache > 20) {
Ted Kremenek78d85f52007-10-30 21:08:08 +0000915 unsigned FileLen = Content->SourceLineCache[Content->NumLines-1];
Mike Stump1eb44332009-09-09 15:08:12 +0000916
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000917 // Take a stab at guessing where it is.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000918 unsigned ApproxPos = Content->NumLines*QueriedFilePos / FileLen;
Mike Stump1eb44332009-09-09 15:08:12 +0000919
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000920 // Check for -10 and +10 lines.
921 unsigned LowerBound = std::max(int(ApproxPos-10), 0);
922 unsigned UpperBound = std::min(ApproxPos+10, FileLen);
923
924 // If the computed lower bound is less than the query location, move it in.
925 if (SourceLineCache < SourceLineCacheStart+LowerBound &&
926 SourceLineCacheStart[LowerBound] < QueriedFilePos)
927 SourceLineCache = SourceLineCacheStart+LowerBound;
Mike Stump1eb44332009-09-09 15:08:12 +0000928
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000929 // If the computed upper bound is greater than the query location, move it.
930 if (SourceLineCacheEnd > SourceLineCacheStart+UpperBound &&
931 SourceLineCacheStart[UpperBound] >= QueriedFilePos)
932 SourceLineCacheEnd = SourceLineCacheStart+UpperBound;
933 }
Mike Stump1eb44332009-09-09 15:08:12 +0000934
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000935 unsigned *Pos
936 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000937 unsigned LineNo = Pos-SourceLineCacheStart;
Mike Stump1eb44332009-09-09 15:08:12 +0000938
Chris Lattner30fc9332009-02-04 01:06:56 +0000939 LastLineNoFileIDQuery = FID;
Ted Kremenek78d85f52007-10-30 21:08:08 +0000940 LastLineNoContentCache = Content;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000941 LastLineNoFilePos = QueriedFilePos;
942 LastLineNoResult = LineNo;
943 return LineNo;
Reid Spencer5f016e22007-07-11 17:01:13 +0000944}
945
Chris Lattner30fc9332009-02-04 01:06:56 +0000946unsigned SourceManager::getInstantiationLineNumber(SourceLocation Loc) const {
947 if (Loc.isInvalid()) return 0;
948 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
949 return getLineNumber(LocInfo.first, LocInfo.second);
950}
951unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc) const {
952 if (Loc.isInvalid()) return 0;
953 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
954 return getLineNumber(LocInfo.first, LocInfo.second);
955}
956
Chris Lattner6b306672009-02-04 05:33:01 +0000957/// getFileCharacteristic - return the file characteristic of the specified
Mike Stump1eb44332009-09-09 15:08:12 +0000958/// source location, indicating whether this is a normal file, a system
Chris Lattner6b306672009-02-04 05:33:01 +0000959/// header, or an "implicit extern C" system header.
960///
961/// This state can be modified with flags on GNU linemarker directives like:
962/// # 4 "foo.h" 3
963/// which changes all source locations in the current file after that to be
964/// considered to be from a system header.
Mike Stump1eb44332009-09-09 15:08:12 +0000965SrcMgr::CharacteristicKind
Chris Lattner6b306672009-02-04 05:33:01 +0000966SourceManager::getFileCharacteristic(SourceLocation Loc) const {
967 assert(!Loc.isInvalid() && "Can't get file characteristic of invalid loc!");
968 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
969 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile();
970
971 // If there are no #line directives in this file, just return the whole-file
972 // state.
973 if (!FI.hasLineDirectives())
974 return FI.getFileCharacteristic();
Mike Stump1eb44332009-09-09 15:08:12 +0000975
Chris Lattner6b306672009-02-04 05:33:01 +0000976 assert(LineTable && "Can't have linetable entries without a LineTable!");
977 // See if there is a #line directive before the location.
978 const LineEntry *Entry =
979 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second);
Mike Stump1eb44332009-09-09 15:08:12 +0000980
Chris Lattner6b306672009-02-04 05:33:01 +0000981 // If this is before the first line marker, use the file characteristic.
982 if (!Entry)
983 return FI.getFileCharacteristic();
984
985 return Entry->FileKind;
986}
987
Chris Lattnerbff5c512009-02-17 08:39:06 +0000988/// Return the filename or buffer identifier of the buffer the location is in.
989/// Note that this name does not respect #line directives. Use getPresumedLoc
990/// for normal clients.
991const char *SourceManager::getBufferName(SourceLocation Loc) const {
992 if (Loc.isInvalid()) return "<invalid loc>";
Mike Stump1eb44332009-09-09 15:08:12 +0000993
Chris Lattnerbff5c512009-02-17 08:39:06 +0000994 return getBuffer(getFileID(Loc))->getBufferIdentifier();
995}
996
Chris Lattner30fc9332009-02-04 01:06:56 +0000997
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000998/// getPresumedLoc - This method returns the "presumed" location of a
999/// SourceLocation specifies. A "presumed location" can be modified by #line
1000/// or GNU line marker directives. This provides a view on the data that a
1001/// user should see in diagnostics, for example.
1002///
1003/// Note that a presumed location is always given as the instantiation point
1004/// of an instantiation location, not at the spelling location.
1005PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc) const {
1006 if (Loc.isInvalid()) return PresumedLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001007
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001008 // Presumed locations are always for instantiation points.
Chris Lattner7da5aea2009-02-04 00:55:58 +00001009 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +00001010
Chris Lattner30fc9332009-02-04 01:06:56 +00001011 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile();
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001012 const SrcMgr::ContentCache *C = FI.getContentCache();
Mike Stump1eb44332009-09-09 15:08:12 +00001013
Chris Lattner3cd949c2009-02-04 01:55:42 +00001014 // To get the source name, first consult the FileEntry (if one exists)
1015 // before the MemBuffer as this will avoid unnecessarily paging in the
1016 // MemBuffer.
Mike Stump1eb44332009-09-09 15:08:12 +00001017 const char *Filename =
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001018 C->Entry ? C->Entry->getName() : C->getBuffer()->getBufferIdentifier();
Chris Lattner3cd949c2009-02-04 01:55:42 +00001019 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second);
1020 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second);
1021 SourceLocation IncludeLoc = FI.getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001022
Chris Lattner3cd949c2009-02-04 01:55:42 +00001023 // If we have #line directives in this file, update and overwrite the physical
1024 // location info if appropriate.
1025 if (FI.hasLineDirectives()) {
1026 assert(LineTable && "Can't have linetable entries without a LineTable!");
1027 // See if there is a #line directive before this. If so, get it.
1028 if (const LineEntry *Entry =
1029 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second)) {
Chris Lattnerfc391332009-02-04 02:00:59 +00001030 // If the LineEntry indicates a filename, use it.
Chris Lattner3cd949c2009-02-04 01:55:42 +00001031 if (Entry->FilenameID != -1)
1032 Filename = LineTable->getFilename(Entry->FilenameID);
Chris Lattnerfc391332009-02-04 02:00:59 +00001033
1034 // Use the line number specified by the LineEntry. This line number may
1035 // be multiple lines down from the line entry. Add the difference in
1036 // physical line numbers from the query point and the line marker to the
1037 // total.
1038 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1039 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001040
Chris Lattner0e0e5da2009-02-04 02:15:40 +00001041 // Note that column numbers are not molested by line markers.
Mike Stump1eb44332009-09-09 15:08:12 +00001042
Chris Lattner137b6a62009-02-04 06:25:26 +00001043 // Handle virtual #include manipulation.
1044 if (Entry->IncludeOffset) {
1045 IncludeLoc = getLocForStartOfFile(LocInfo.first);
1046 IncludeLoc = IncludeLoc.getFileLocWithOffset(Entry->IncludeOffset);
1047 }
Chris Lattner3cd949c2009-02-04 01:55:42 +00001048 }
1049 }
1050
1051 return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc);
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001052}
1053
1054//===----------------------------------------------------------------------===//
1055// Other miscellaneous methods.
1056//===----------------------------------------------------------------------===//
1057
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001058/// \brief Get the source location for the given file:line:col triplet.
1059///
1060/// If the source file is included multiple times, the source location will
1061/// be based upon the first inclusion.
1062SourceLocation SourceManager::getLocation(const FileEntry *SourceFile,
1063 unsigned Line, unsigned Col) const {
1064 assert(SourceFile && "Null source file!");
1065 assert(Line && Col && "Line and column should start from 1!");
1066
1067 fileinfo_iterator FI = FileInfos.find(SourceFile);
1068 if (FI == FileInfos.end())
1069 return SourceLocation();
1070 ContentCache *Content = FI->second;
Mike Stump1eb44332009-09-09 15:08:12 +00001071
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001072 // If this is the first use of line information for this buffer, compute the
1073 /// SourceLineCache for it on demand.
1074 if (Content->SourceLineCache == 0)
1075 ComputeLineNumbers(Content, ContentCacheAlloc);
1076
Douglas Gregor4a160e12009-12-02 05:34:39 +00001077 // Find the first file ID that corresponds to the given file.
1078 FileID FirstFID;
1079
1080 // First, check the main file ID, since it is common to look for a
1081 // location in the main file.
1082 if (!MainFileID.isInvalid()) {
1083 const SLocEntry &MainSLoc = getSLocEntry(MainFileID);
1084 if (MainSLoc.isFile() && MainSLoc.getFile().getContentCache() == Content)
1085 FirstFID = MainFileID;
1086 }
1087
1088 if (FirstFID.isInvalid()) {
1089 // The location we're looking for isn't in the main file; look
1090 // through all of the source locations.
1091 for (unsigned I = 0, N = sloc_entry_size(); I != N; ++I) {
1092 const SLocEntry &SLoc = getSLocEntry(I);
1093 if (SLoc.isFile() && SLoc.getFile().getContentCache() == Content) {
1094 FirstFID = FileID::get(I);
1095 break;
1096 }
1097 }
1098 }
1099
1100 if (FirstFID.isInvalid())
1101 return SourceLocation();
1102
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001103 if (Line > Content->NumLines) {
1104 unsigned Size = Content->getBuffer()->getBufferSize();
1105 if (Size > 0)
1106 --Size;
1107 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(Size);
1108 }
1109
1110 unsigned FilePos = Content->SourceLineCache[Line - 1];
1111 const char *Buf = Content->getBuffer()->getBufferStart() + FilePos;
1112 unsigned BufLength = Content->getBuffer()->getBufferEnd() - Buf;
1113 unsigned i = 0;
1114
1115 // Check that the given column is valid.
1116 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1117 ++i;
1118 if (i < Col-1)
1119 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + i);
1120
Douglas Gregor4a160e12009-12-02 05:34:39 +00001121 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + Col - 1);
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001122}
1123
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001124/// \brief Determines the order of 2 source locations in the translation unit.
1125///
1126/// \returns true if LHS source location comes before RHS, false otherwise.
1127bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
1128 SourceLocation RHS) const {
1129 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
1130 if (LHS == RHS)
1131 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001132
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001133 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
1134 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00001135
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001136 // If the source locations are in the same file, just compare offsets.
1137 if (LOffs.first == ROffs.first)
1138 return LOffs.second < ROffs.second;
1139
1140 // If we are comparing a source location with multiple locations in the same
1141 // file, we get a big win by caching the result.
Mike Stump1eb44332009-09-09 15:08:12 +00001142
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001143 if (LastLFIDForBeforeTUCheck == LOffs.first &&
1144 LastRFIDForBeforeTUCheck == ROffs.first)
1145 return LastResForBeforeTUCheck;
Mike Stump1eb44332009-09-09 15:08:12 +00001146
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001147 LastLFIDForBeforeTUCheck = LOffs.first;
1148 LastRFIDForBeforeTUCheck = ROffs.first;
Mike Stump1eb44332009-09-09 15:08:12 +00001149
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001150 // "Traverse" the include/instantiation stacks of both locations and try to
1151 // find a common "ancestor".
1152 //
1153 // First we traverse the stack of the right location and check each level
1154 // against the level of the left location, while collecting all levels in a
1155 // "stack map".
1156
1157 std::map<FileID, unsigned> ROffsMap;
1158 ROffsMap[ROffs.first] = ROffs.second;
1159
1160 while (1) {
1161 SourceLocation UpperLoc;
1162 const SrcMgr::SLocEntry &Entry = getSLocEntry(ROffs.first);
1163 if (Entry.isInstantiation())
1164 UpperLoc = Entry.getInstantiation().getInstantiationLocStart();
1165 else
1166 UpperLoc = Entry.getFile().getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001167
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001168 if (UpperLoc.isInvalid())
1169 break; // We reached the top.
Mike Stump1eb44332009-09-09 15:08:12 +00001170
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001171 ROffs = getDecomposedLoc(UpperLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001172
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001173 if (LOffs.first == ROffs.first)
1174 return LastResForBeforeTUCheck = LOffs.second < ROffs.second;
Mike Stump1eb44332009-09-09 15:08:12 +00001175
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001176 ROffsMap[ROffs.first] = ROffs.second;
1177 }
1178
1179 // We didn't find a common ancestor. Now traverse the stack of the left
1180 // location, checking against the stack map of the right location.
1181
1182 while (1) {
1183 SourceLocation UpperLoc;
1184 const SrcMgr::SLocEntry &Entry = getSLocEntry(LOffs.first);
1185 if (Entry.isInstantiation())
1186 UpperLoc = Entry.getInstantiation().getInstantiationLocStart();
1187 else
1188 UpperLoc = Entry.getFile().getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001189
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001190 if (UpperLoc.isInvalid())
1191 break; // We reached the top.
Mike Stump1eb44332009-09-09 15:08:12 +00001192
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001193 LOffs = getDecomposedLoc(UpperLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001194
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001195 std::map<FileID, unsigned>::iterator I = ROffsMap.find(LOffs.first);
1196 if (I != ROffsMap.end())
1197 return LastResForBeforeTUCheck = LOffs.second < I->second;
1198 }
Mike Stump1eb44332009-09-09 15:08:12 +00001199
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001200 // There is no common ancestor, most probably because one location is in the
1201 // predefines buffer.
1202 //
1203 // FIXME: We should rearrange the external interface so this simply never
1204 // happens; it can't conceptually happen. Also see PR5662.
Mike Stump1eb44332009-09-09 15:08:12 +00001205
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001206 // If exactly one location is a memory buffer, assume it preceeds the other.
1207 bool LIsMB = !getSLocEntry(LOffs.first).getFile().getContentCache()->Entry;
1208 bool RIsMB = !getSLocEntry(ROffs.first).getFile().getContentCache()->Entry;
1209 if (LIsMB != RIsMB)
1210 return LastResForBeforeTUCheck = LIsMB;
Mike Stump1eb44332009-09-09 15:08:12 +00001211
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001212 // Otherwise, just assume FileIDs were created in order.
1213 return LastResForBeforeTUCheck = (LOffs.first < ROffs.first);
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001214}
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001215
Reid Spencer5f016e22007-07-11 17:01:13 +00001216/// PrintStats - Print statistics to stderr.
1217///
1218void SourceManager::PrintStats() const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001219 llvm::errs() << "\n*** Source Manager Stats:\n";
1220 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
1221 << " mem buffers mapped.\n";
1222 llvm::errs() << SLocEntryTable.size() << " SLocEntry's allocated, "
1223 << NextOffset << "B of Sloc address space used.\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001224
Reid Spencer5f016e22007-07-11 17:01:13 +00001225 unsigned NumLineNumsComputed = 0;
1226 unsigned NumFileBytesMapped = 0;
Chris Lattner0d0bf8c2009-02-03 07:30:45 +00001227 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
1228 NumLineNumsComputed += I->second->SourceLineCache != 0;
1229 NumFileBytesMapped += I->second->getSizeBytesMapped();
Reid Spencer5f016e22007-07-11 17:01:13 +00001230 }
Mike Stump1eb44332009-09-09 15:08:12 +00001231
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001232 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
1233 << NumLineNumsComputed << " files with line #'s computed.\n";
1234 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
1235 << NumBinaryProbes << " binary.\n";
Reid Spencer5f016e22007-07-11 17:01:13 +00001236}
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001237
1238ExternalSLocEntrySource::~ExternalSLocEntrySource() { }