blob: f2903e985d8f771bafd7ffc6b4d3c3e896233373 [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"
Benjamin Kramer5807d9c2010-11-18 12:46:39 +000018#include "llvm/ADT/StringSwitch.h"
Douglas Gregor86a4d0d2011-02-03 17:17:35 +000019#include "llvm/ADT/Optional.h"
Chris Lattner5e36a7a2007-07-24 05:57:19 +000020#include "llvm/Support/Compiler.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000021#include "llvm/Support/MemoryBuffer.h"
Chris Lattnerd57a7ef2009-08-23 22:45:33 +000022#include "llvm/Support/raw_ostream.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000023#include "llvm/Support/Path.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024#include <algorithm>
Douglas Gregoraea67db2010-03-15 22:54:52 +000025#include <string>
Douglas Gregorf715ca12010-03-16 00:06:06 +000026#include <cstring>
Douglas Gregor86a4d0d2011-02-03 17:17:35 +000027#include <sys/stat.h>
Douglas Gregoraea67db2010-03-15 22:54:52 +000028
Reid Spencer5f016e22007-07-11 17:01:13 +000029using namespace clang;
30using namespace SrcMgr;
31using llvm::MemoryBuffer;
32
Chris Lattner23b5dc62009-02-04 00:40:31 +000033//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +000034// SourceManager Helper Classes
Chris Lattner23b5dc62009-02-04 00:40:31 +000035//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +000036
Ted Kremenek78d85f52007-10-30 21:08:08 +000037ContentCache::~ContentCache() {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000038 if (shouldFreeBuffer())
39 delete Buffer.getPointer();
Reid Spencer5f016e22007-07-11 17:01:13 +000040}
41
Chandler Carruth3201f382011-07-26 05:17:23 +000042/// getSizeBytesMapped - Returns the number of bytes actually mapped for this
43/// ContentCache. This can be 0 if the MemBuffer was not actually expanded.
Ted Kremenekc16c2082009-01-06 01:55:26 +000044unsigned ContentCache::getSizeBytesMapped() const {
Douglas Gregorc8151082010-03-16 22:53:51 +000045 return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 0;
Ted Kremenekc16c2082009-01-06 01:55:26 +000046}
47
Ted Kremenekf61b8312011-04-28 20:36:42 +000048/// Returns the kind of memory used to back the memory buffer for
49/// this content cache. This is used for performance analysis.
50llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const {
51 assert(Buffer.getPointer());
52
53 // Should be unreachable, but keep for sanity.
54 if (!Buffer.getPointer())
55 return llvm::MemoryBuffer::MemoryBuffer_Malloc;
56
57 const llvm::MemoryBuffer *buf = Buffer.getPointer();
58 return buf->getBufferKind();
59}
60
Ted Kremenekc16c2082009-01-06 01:55:26 +000061/// getSize - Returns the size of the content encapsulated by this ContentCache.
62/// This can be the size of the source file or the size of an arbitrary
63/// scratch buffer. If the ContentCache encapsulates a source file, that
Douglas Gregor29684422009-12-02 06:49:09 +000064/// file is not lazily brought in from disk to satisfy this query.
Ted Kremenekc16c2082009-01-06 01:55:26 +000065unsigned ContentCache::getSize() const {
Douglas Gregorc8151082010-03-16 22:53:51 +000066 return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize()
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +000067 : (unsigned) ContentsEntry->getSize();
Ted Kremenekc16c2082009-01-06 01:55:26 +000068}
69
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000070void ContentCache::replaceBuffer(const llvm::MemoryBuffer *B,
71 bool DoNotFree) {
Douglas Gregorc8151082010-03-16 22:53:51 +000072 assert(B != Buffer.getPointer());
Douglas Gregor29684422009-12-02 06:49:09 +000073
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000074 if (shouldFreeBuffer())
75 delete Buffer.getPointer();
Douglas Gregorc8151082010-03-16 22:53:51 +000076 Buffer.setPointer(B);
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000077 Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
Douglas Gregor29684422009-12-02 06:49:09 +000078}
79
Douglas Gregor36c35ba2010-03-16 00:35:39 +000080const llvm::MemoryBuffer *ContentCache::getBuffer(Diagnostic &Diag,
Chris Lattner5c5db4e2010-04-20 20:49:23 +000081 const SourceManager &SM,
Chris Lattnere127a0d2010-04-20 20:35:58 +000082 SourceLocation Loc,
Douglas Gregor36c35ba2010-03-16 00:35:39 +000083 bool *Invalid) const {
Chris Lattnerb088cd32010-11-23 08:50:03 +000084 // Lazily create the Buffer for ContentCaches that wrap files. If we already
Chris Lattnerfc8f0e12011-04-15 05:22:18 +000085 // computed it, just return what we have.
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +000086 if (Buffer.getPointer() || ContentsEntry == 0) {
Chris Lattnerb088cd32010-11-23 08:50:03 +000087 if (Invalid)
88 *Invalid = isBufferInvalid();
Chris Lattner38caec42010-04-20 18:14:03 +000089
Chris Lattnerb088cd32010-11-23 08:50:03 +000090 return Buffer.getPointer();
91 }
Benjamin Kramer5807d9c2010-11-18 12:46:39 +000092
Chris Lattnerb088cd32010-11-23 08:50:03 +000093 std::string ErrorStr;
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +000094 Buffer.setPointer(SM.getFileManager().getBufferForFile(ContentsEntry, &ErrorStr));
Chris Lattnerb088cd32010-11-23 08:50:03 +000095
96 // If we were unable to open the file, then we are in an inconsistent
97 // situation where the content cache referenced a file which no longer
98 // exists. Most likely, we were using a stat cache with an invalid entry but
99 // the file could also have been removed during processing. Since we can't
100 // really deal with this situation, just create an empty buffer.
101 //
102 // FIXME: This is definitely not ideal, but our immediate clients can't
103 // currently handle returning a null entry here. Ideally we should detect
104 // that we are in an inconsistent situation and error out as quickly as
105 // possible.
106 if (!Buffer.getPointer()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000107 const StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000108 Buffer.setPointer(MemoryBuffer::getNewMemBuffer(ContentsEntry->getSize(),
Chris Lattnerb088cd32010-11-23 08:50:03 +0000109 "<invalid>"));
110 char *Ptr = const_cast<char*>(Buffer.getPointer()->getBufferStart());
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000111 for (unsigned i = 0, e = ContentsEntry->getSize(); i != e; ++i)
Chris Lattnerb088cd32010-11-23 08:50:03 +0000112 Ptr[i] = FillStr[i % FillStr.size()];
113
114 if (Diag.isDiagnosticInFlight())
115 Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000116 ContentsEntry->getName(), ErrorStr);
Chris Lattnerb088cd32010-11-23 08:50:03 +0000117 else
118 Diag.Report(Loc, diag::err_cannot_open_file)
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000119 << ContentsEntry->getName() << ErrorStr;
Chris Lattnerb088cd32010-11-23 08:50:03 +0000120
121 Buffer.setInt(Buffer.getInt() | InvalidFlag);
122
123 if (Invalid) *Invalid = true;
124 return Buffer.getPointer();
125 }
126
127 // Check that the file's size is the same as in the file entry (which may
128 // have come from a stat cache).
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000129 if (getRawBuffer()->getBufferSize() != (size_t)ContentsEntry->getSize()) {
Chris Lattnerb088cd32010-11-23 08:50:03 +0000130 if (Diag.isDiagnosticInFlight())
131 Diag.SetDelayedDiagnostic(diag::err_file_modified,
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000132 ContentsEntry->getName());
Chris Lattnerb088cd32010-11-23 08:50:03 +0000133 else
134 Diag.Report(Loc, diag::err_file_modified)
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000135 << ContentsEntry->getName();
Chris Lattnerb088cd32010-11-23 08:50:03 +0000136
137 Buffer.setInt(Buffer.getInt() | InvalidFlag);
138 if (Invalid) *Invalid = true;
139 return Buffer.getPointer();
140 }
Eric Christopher156119d2011-04-09 00:01:04 +0000141
Chris Lattnerb088cd32010-11-23 08:50:03 +0000142 // If the buffer is valid, check to see if it has a UTF Byte Order Mark
Eric Christopher156119d2011-04-09 00:01:04 +0000143 // (BOM). We only support UTF-8 with and without a BOM right now. See
Chris Lattnerb088cd32010-11-23 08:50:03 +0000144 // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000145 StringRef BufStr = Buffer.getPointer()->getBuffer();
Eric Christopher156119d2011-04-09 00:01:04 +0000146 const char *InvalidBOM = llvm::StringSwitch<const char *>(BufStr)
Chris Lattnerb088cd32010-11-23 08:50:03 +0000147 .StartsWith("\xFE\xFF", "UTF-16 (BE)")
148 .StartsWith("\xFF\xFE", "UTF-16 (LE)")
149 .StartsWith("\x00\x00\xFE\xFF", "UTF-32 (BE)")
150 .StartsWith("\xFF\xFE\x00\x00", "UTF-32 (LE)")
151 .StartsWith("\x2B\x2F\x76", "UTF-7")
152 .StartsWith("\xF7\x64\x4C", "UTF-1")
153 .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
154 .StartsWith("\x0E\xFE\xFF", "SDSU")
155 .StartsWith("\xFB\xEE\x28", "BOCU-1")
156 .StartsWith("\x84\x31\x95\x33", "GB-18030")
157 .Default(0);
158
Eric Christopher156119d2011-04-09 00:01:04 +0000159 if (InvalidBOM) {
Chris Lattnerb088cd32010-11-23 08:50:03 +0000160 Diag.Report(Loc, diag::err_unsupported_bom)
Eric Christopher156119d2011-04-09 00:01:04 +0000161 << InvalidBOM << ContentsEntry->getName();
Chris Lattnerb088cd32010-11-23 08:50:03 +0000162 Buffer.setInt(Buffer.getInt() | InvalidFlag);
Ted Kremenek5b034ad2009-01-06 22:43:04 +0000163 }
Douglas Gregoraea67db2010-03-15 22:54:52 +0000164
Douglas Gregorc8151082010-03-16 22:53:51 +0000165 if (Invalid)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000166 *Invalid = isBufferInvalid();
Douglas Gregorc8151082010-03-16 22:53:51 +0000167
168 return Buffer.getPointer();
Ted Kremenekc16c2082009-01-06 01:55:26 +0000169}
170
Chris Lattner5f9e2722011-07-23 10:55:15 +0000171unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000172 // 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 =
Jay Foad65aa6882011-06-21 15:13:30 +0000175 FilenameIDs.GetOrCreateValue(Name, ~0U);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000176 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.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000188void LineTableInfo::AddLineNote(int 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.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000219void LineTableInfo::AddLineNote(int FID, unsigned Offset,
Chris Lattner9d79eba2009-02-04 05:21:58 +0000220 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.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000253const LineEntry *LineTableInfo::FindNearestLineEntry(int 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.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000272void LineTableInfo::AddEntry(int 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 Lattner5f9e2722011-07-23 10:55:15 +0000279unsigned SourceManager::getLineTableFilenameID(StringRef Name) {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000280 if (LineTable == 0)
281 LineTable = new LineTableInfo();
Jay Foad65aa6882011-06-21 15:13:30 +0000282 return LineTable->getLineTableFilenameID(Name);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000283}
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) {
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000291 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000292
Douglas Gregore23ac652011-04-20 00:21:03 +0000293 bool Invalid = false;
294 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
295 if (!Entry.isFile() || Invalid)
296 return;
297
298 const SrcMgr::FileInfo &FileInfo = Entry.getFile();
Chris Lattnerac50e342009-02-03 22:13:05 +0000299
300 // Remember that this file has #line directives now if it doesn't already.
301 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump1eb44332009-09-09 15:08:12 +0000302
Chris Lattnerac50e342009-02-03 22:13:05 +0000303 if (LineTable == 0)
304 LineTable = new LineTableInfo();
Chris Lattner23b5dc62009-02-04 00:40:31 +0000305 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID);
Chris Lattner4c4ea172009-02-03 21:52:55 +0000306}
307
Chris Lattner9d79eba2009-02-04 05:21:58 +0000308/// AddLineNote - Add a GNU line marker to the line table.
309void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
310 int FilenameID, bool IsFileEntry,
311 bool IsFileExit, bool IsSystemHeader,
312 bool IsExternCHeader) {
313 // If there is no filename and no flags, this is treated just like a #line,
314 // which does not change the flags of the previous line marker.
315 if (FilenameID == -1) {
316 assert(!IsFileEntry && !IsFileExit && !IsSystemHeader && !IsExternCHeader &&
317 "Can't set flags without setting the filename!");
318 return AddLineNote(Loc, LineNo, FilenameID);
319 }
Mike Stump1eb44332009-09-09 15:08:12 +0000320
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000321 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Douglas Gregore23ac652011-04-20 00:21:03 +0000322
323 bool Invalid = false;
324 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
325 if (!Entry.isFile() || Invalid)
326 return;
327
328 const SrcMgr::FileInfo &FileInfo = Entry.getFile();
Mike Stump1eb44332009-09-09 15:08:12 +0000329
Chris Lattner9d79eba2009-02-04 05:21:58 +0000330 // Remember that this file has #line directives now if it doesn't already.
331 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump1eb44332009-09-09 15:08:12 +0000332
Chris Lattner9d79eba2009-02-04 05:21:58 +0000333 if (LineTable == 0)
334 LineTable = new LineTableInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000335
Chris Lattner9d79eba2009-02-04 05:21:58 +0000336 SrcMgr::CharacteristicKind FileKind;
337 if (IsExternCHeader)
338 FileKind = SrcMgr::C_ExternCSystem;
339 else if (IsSystemHeader)
340 FileKind = SrcMgr::C_System;
341 else
342 FileKind = SrcMgr::C_User;
Mike Stump1eb44332009-09-09 15:08:12 +0000343
Chris Lattner9d79eba2009-02-04 05:21:58 +0000344 unsigned EntryExit = 0;
345 if (IsFileEntry)
346 EntryExit = 1;
347 else if (IsFileExit)
348 EntryExit = 2;
Mike Stump1eb44332009-09-09 15:08:12 +0000349
Chris Lattner9d79eba2009-02-04 05:21:58 +0000350 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID,
351 EntryExit, FileKind);
352}
353
Douglas Gregorbd945002009-04-13 16:31:14 +0000354LineTableInfo &SourceManager::getLineTable() {
355 if (LineTable == 0)
356 LineTable = new LineTableInfo();
357 return *LineTable;
358}
Chris Lattner4c4ea172009-02-03 21:52:55 +0000359
Chris Lattner23b5dc62009-02-04 00:40:31 +0000360//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000361// Private 'Create' methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000362//===----------------------------------------------------------------------===//
Ted Kremenekc16c2082009-01-06 01:55:26 +0000363
Chris Lattner39b49bc2010-11-23 08:35:12 +0000364SourceManager::SourceManager(Diagnostic &Diag, FileManager &FileMgr)
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +0000365 : Diag(Diag), FileMgr(FileMgr), OverridenFilesKeepOriginalName(true),
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000366 ExternalSLocEntries(0), LineTable(0), NumLinearScans(0),
Douglas Gregore23ac652011-04-20 00:21:03 +0000367 NumBinaryProbes(0), FakeBufferForRecovery(0) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000368 clearIDTables();
369 Diag.setSourceManager(this);
370}
371
Chris Lattner5b9a5042009-01-26 07:57:50 +0000372SourceManager::~SourceManager() {
373 delete LineTable;
Mike Stump1eb44332009-09-09 15:08:12 +0000374
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000375 // Delete FileEntry objects corresponding to content caches. Since the actual
376 // content cache objects are bump pointer allocated, we just have to run the
377 // dtors, but we call the deallocate method for completeness.
378 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
379 MemBufferInfos[i]->~ContentCache();
380 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
381 }
382 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
383 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
384 I->second->~ContentCache();
385 ContentCacheAlloc.Deallocate(I->second);
386 }
Douglas Gregore23ac652011-04-20 00:21:03 +0000387
388 delete FakeBufferForRecovery;
Chris Lattner5b9a5042009-01-26 07:57:50 +0000389}
390
391void SourceManager::clearIDTables() {
392 MainFileID = FileID();
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000393 LocalSLocEntryTable.clear();
394 LoadedSLocEntryTable.clear();
395 SLocEntryLoaded.clear();
Chris Lattner5b9a5042009-01-26 07:57:50 +0000396 LastLineNoFileIDQuery = FileID();
397 LastLineNoContentCache = 0;
398 LastFileIDLookup = FileID();
Mike Stump1eb44332009-09-09 15:08:12 +0000399
Chris Lattner5b9a5042009-01-26 07:57:50 +0000400 if (LineTable)
401 LineTable->clear();
Mike Stump1eb44332009-09-09 15:08:12 +0000402
Chandler Carruth3201f382011-07-26 05:17:23 +0000403 // Use up FileID #0 as an invalid expansion.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000404 NextLocalOffset = 0;
405 // The highest possible offset is 2^31-1, so CurrentLoadedOffset starts at
406 // 2^31.
407 CurrentLoadedOffset = 1U << 31U;
Chandler Carruthbf340e42011-07-26 03:03:05 +0000408 createExpansionLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000409}
410
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000411/// getOrCreateContentCache - Create or return a cached ContentCache for the
412/// specified file.
413const ContentCache *
414SourceManager::getOrCreateContentCache(const FileEntry *FileEnt) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000415 assert(FileEnt && "Didn't specify a file entry to use?");
Mike Stump1eb44332009-09-09 15:08:12 +0000416
Reid Spencer5f016e22007-07-11 17:01:13 +0000417 // Do we already have information about this file?
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000418 ContentCache *&Entry = FileInfos[FileEnt];
419 if (Entry) return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +0000420
Chris Lattner00282d62009-02-03 07:41:46 +0000421 // Nope, create a new Cache entry. Make sure it is at least 8-byte aligned
422 // so that FileInfo can use the low 3 bits of the pointer for its own
423 // nefarious purposes.
424 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
425 EntryAlign = std::max(8U, EntryAlign);
426 Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000427
428 // If the file contents are overridden with contents from another file,
429 // pass that file to ContentCache.
430 llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
431 overI = OverriddenFiles.find(FileEnt);
432 if (overI == OverriddenFiles.end())
433 new (Entry) ContentCache(FileEnt);
434 else
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +0000435 new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt
436 : overI->second,
437 overI->second);
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000438
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000439 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000440}
441
442
Ted Kremenekd1c0eee2007-10-31 17:53:38 +0000443/// createMemBufferContentCache - Create a new ContentCache for the specified
444/// memory buffer. This does no caching.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000445const ContentCache*
446SourceManager::createMemBufferContentCache(const MemoryBuffer *Buffer) {
Chris Lattner00282d62009-02-03 07:41:46 +0000447 // Add a new ContentCache to the MemBufferInfos list and return it. Make sure
448 // it is at least 8-byte aligned so that FileInfo can use the low 3 bits of
449 // the pointer for its own nefarious purposes.
450 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
451 EntryAlign = std::max(8U, EntryAlign);
452 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000453 new (Entry) ContentCache();
454 MemBufferInfos.push_back(Entry);
455 Entry->setBuffer(Buffer);
456 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000457}
458
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000459std::pair<int, unsigned>
460SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries,
461 unsigned TotalSize) {
462 assert(ExternalSLocEntries && "Don't have an external sloc source");
463 LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries);
464 SLocEntryLoaded.resize(LoadedSLocEntryTable.size());
465 CurrentLoadedOffset -= TotalSize;
466 assert(CurrentLoadedOffset >= NextLocalOffset && "Out of source locations");
467 int ID = LoadedSLocEntryTable.size();
468 return std::make_pair(-ID - 1, CurrentLoadedOffset);
Douglas Gregor2bf1eb02009-04-27 21:28:04 +0000469}
470
Douglas Gregore23ac652011-04-20 00:21:03 +0000471/// \brief As part of recovering from missing or changed content, produce a
472/// fake, non-empty buffer.
473const llvm::MemoryBuffer *SourceManager::getFakeBufferForRecovery() const {
474 if (!FakeBufferForRecovery)
475 FakeBufferForRecovery
476 = llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");
477
478 return FakeBufferForRecovery;
479}
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000480
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000481//===----------------------------------------------------------------------===//
Chandler Carruth3201f382011-07-26 05:17:23 +0000482// Methods to create new FileID's and macro expansions.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000483//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000484
Dan Gohman3f86b782010-08-26 21:27:06 +0000485/// createFileID - Create a new FileID for the specified ContentCache and
Ted Kremenek0d892d82007-10-30 22:57:35 +0000486/// include position. This works regardless of whether the ContentCache
487/// corresponds to a file or some other input source.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000488FileID SourceManager::createFileID(const ContentCache *File,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000489 SourceLocation IncludePos,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000490 SrcMgr::CharacteristicKind FileCharacter,
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000491 int LoadedID, unsigned LoadedOffset) {
492 if (LoadedID < 0) {
493 assert(LoadedID != -1 && "Loading sentinel FileID");
494 unsigned Index = unsigned(-LoadedID) - 2;
495 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
496 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
497 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset,
498 FileInfo::get(IncludePos, File, FileCharacter));
499 SLocEntryLoaded[Index] = true;
500 return FileID::get(LoadedID);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000501 }
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000502 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset,
503 FileInfo::get(IncludePos, File,
504 FileCharacter)));
Ted Kremenekc16c2082009-01-06 01:55:26 +0000505 unsigned FileSize = File->getSize();
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000506 assert(NextLocalOffset + FileSize + 1 > NextLocalOffset &&
507 NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset &&
508 "Ran out of source locations!");
509 // We do a +1 here because we want a SourceLocation that means "the end of the
510 // file", e.g. for the "no newline at the end of the file" diagnostic.
511 NextLocalOffset += FileSize + 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000512
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000513 // Set LastFileIDLookup to the newly created file. The next getFileID call is
514 // almost guaranteed to be from that file.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000515 FileID FID = FileID::get(LocalSLocEntryTable.size()-1);
Argyrios Kyrtzidisea703f12009-06-23 00:42:06 +0000516 return LastFileIDLookup = FID;
Reid Spencer5f016e22007-07-11 17:01:13 +0000517}
518
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000519SourceLocation
Chandler Carruthbf340e42011-07-26 03:03:05 +0000520SourceManager::createMacroArgExpansionLoc(SourceLocation SpellingLoc,
521 SourceLocation ExpansionLoc,
522 unsigned TokLength) {
Chandler Carruth78df8362011-07-26 04:41:47 +0000523 ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc,
524 ExpansionLoc);
525 return createExpansionLocImpl(Info, TokLength);
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000526}
527
528SourceLocation
Chandler Carruthbf340e42011-07-26 03:03:05 +0000529SourceManager::createExpansionLoc(SourceLocation SpellingLoc,
530 SourceLocation ExpansionLocStart,
531 SourceLocation ExpansionLocEnd,
532 unsigned TokLength,
533 int LoadedID,
534 unsigned LoadedOffset) {
Chandler Carruth78df8362011-07-26 04:41:47 +0000535 ExpansionInfo Info = ExpansionInfo::create(SpellingLoc, ExpansionLocStart,
536 ExpansionLocEnd);
537 return createExpansionLocImpl(Info, TokLength, LoadedID, LoadedOffset);
Chandler Carruthbf340e42011-07-26 03:03:05 +0000538}
539
540SourceLocation
Chandler Carruth78df8362011-07-26 04:41:47 +0000541SourceManager::createExpansionLocImpl(const ExpansionInfo &Info,
Chandler Carruthbf340e42011-07-26 03:03:05 +0000542 unsigned TokLength,
543 int LoadedID,
544 unsigned LoadedOffset) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000545 if (LoadedID < 0) {
546 assert(LoadedID != -1 && "Loading sentinel FileID");
547 unsigned Index = unsigned(-LoadedID) - 2;
548 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
549 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
Chandler Carruth78df8362011-07-26 04:41:47 +0000550 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info);
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000551 SLocEntryLoaded[Index] = true;
552 return SourceLocation::getMacroLoc(LoadedOffset);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000553 }
Chandler Carruth78df8362011-07-26 04:41:47 +0000554 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000555 assert(NextLocalOffset + TokLength + 1 > NextLocalOffset &&
556 NextLocalOffset + TokLength + 1 <= CurrentLoadedOffset &&
557 "Ran out of source locations!");
558 // See createFileID for that +1.
559 NextLocalOffset += TokLength + 1;
560 return SourceLocation::getMacroLoc(NextLocalOffset - (TokLength + 1));
Reid Spencer5f016e22007-07-11 17:01:13 +0000561}
562
Douglas Gregor36c35ba2010-03-16 00:35:39 +0000563const llvm::MemoryBuffer *
Douglas Gregor50f6af72010-03-16 05:20:39 +0000564SourceManager::getMemoryBufferForFile(const FileEntry *File,
565 bool *Invalid) {
Douglas Gregor29684422009-12-02 06:49:09 +0000566 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
Douglas Gregoraea67db2010-03-15 22:54:52 +0000567 assert(IR && "getOrCreateContentCache() cannot return NULL");
Chris Lattnere127a0d2010-04-20 20:35:58 +0000568 return IR->getBuffer(Diag, *this, SourceLocation(), Invalid);
Douglas Gregor29684422009-12-02 06:49:09 +0000569}
570
Dan Gohman0d06e992010-10-26 20:47:28 +0000571void SourceManager::overrideFileContents(const FileEntry *SourceFile,
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000572 const llvm::MemoryBuffer *Buffer,
573 bool DoNotFree) {
Douglas Gregor29684422009-12-02 06:49:09 +0000574 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
Dan Gohman0d06e992010-10-26 20:47:28 +0000575 assert(IR && "getOrCreateContentCache() cannot return NULL");
Douglas Gregor29684422009-12-02 06:49:09 +0000576
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000577 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree);
Douglas Gregor29684422009-12-02 06:49:09 +0000578}
579
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000580void SourceManager::overrideFileContents(const FileEntry *SourceFile,
581 const FileEntry *NewFile) {
582 assert(SourceFile->getSize() == NewFile->getSize() &&
583 "Different sizes, use the FileManager to create a virtual file with "
584 "the correct size");
585 assert(FileInfos.count(SourceFile) == 0 &&
586 "This function should be called at the initialization stage, before "
587 "any parsing occurs.");
588 OverriddenFiles[SourceFile] = NewFile;
589}
590
Chris Lattner5f9e2722011-07-23 10:55:15 +0000591StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
Douglas Gregoraae58b02010-03-16 20:01:30 +0000592 bool MyInvalid = false;
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000593 const SLocEntry &SLoc = getSLocEntry(FID, &MyInvalid);
Douglas Gregore23ac652011-04-20 00:21:03 +0000594 if (!SLoc.isFile() || MyInvalid) {
Douglas Gregor3de84242011-01-31 22:42:36 +0000595 if (Invalid)
596 *Invalid = true;
597 return "<<<<<INVALID SOURCE LOCATION>>>>>";
598 }
599
600 const llvm::MemoryBuffer *Buf
601 = SLoc.getFile().getContentCache()->getBuffer(Diag, *this, SourceLocation(),
602 &MyInvalid);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000603 if (Invalid)
Douglas Gregoraae58b02010-03-16 20:01:30 +0000604 *Invalid = MyInvalid;
605
606 if (MyInvalid)
Douglas Gregor3de84242011-01-31 22:42:36 +0000607 return "<<<<<INVALID SOURCE LOCATION>>>>>";
Douglas Gregoraae58b02010-03-16 20:01:30 +0000608
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000609 return Buf->getBuffer();
Douglas Gregoraea67db2010-03-15 22:54:52 +0000610}
Chris Lattner2b2453a2009-01-17 06:22:33 +0000611
Chris Lattner23b5dc62009-02-04 00:40:31 +0000612//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000613// SourceLocation manipulation methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000614//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000615
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000616/// \brief Return the FileID for a SourceLocation.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000617///
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000618/// This is the cache-miss path of getFileID. Not as hot as that function, but
619/// still very important. It is responsible for finding the entry in the
620/// SLocEntry tables that contains the specified location.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000621FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
Douglas Gregore23ac652011-04-20 00:21:03 +0000622 if (!SLocOffset)
623 return FileID::get(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000624
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000625 // Now it is time to search for the correct file. See where the SLocOffset
626 // sits in the global view and consult local or loaded buffers for it.
627 if (SLocOffset < NextLocalOffset)
628 return getFileIDLocal(SLocOffset);
629 return getFileIDLoaded(SLocOffset);
630}
631
632/// \brief Return the FileID for a SourceLocation with a low offset.
633///
634/// This function knows that the SourceLocation is in a local buffer, not a
635/// loaded one.
636FileID SourceManager::getFileIDLocal(unsigned SLocOffset) const {
637 assert(SLocOffset < NextLocalOffset && "Bad function choice");
638
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000639 // After the first and second level caches, I see two common sorts of
Chandler Carruth3201f382011-07-26 05:17:23 +0000640 // behavior: 1) a lot of searched FileID's are "near" the cached file
641 // location or are "near" the cached expansion location. 2) others are just
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000642 // completely random and may be a very long way away.
643 //
644 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
645 // then we fall back to a less cache efficient, but more scalable, binary
646 // search to find the location.
Mike Stump1eb44332009-09-09 15:08:12 +0000647
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000648 // See if this is near the file point - worst case we start scanning from the
649 // most newly created FileID.
650 std::vector<SrcMgr::SLocEntry>::const_iterator I;
Mike Stump1eb44332009-09-09 15:08:12 +0000651
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000652 if (LastFileIDLookup.ID < 0 ||
653 LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000654 // Neither loc prunes our search.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000655 I = LocalSLocEntryTable.end();
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000656 } else {
657 // Perhaps it is near the file point.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000658 I = LocalSLocEntryTable.begin()+LastFileIDLookup.ID;
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000659 }
660
661 // Find the FileID that contains this. "I" is an iterator that points to a
662 // FileID whose offset is known to be larger than SLocOffset.
663 unsigned NumProbes = 0;
664 while (1) {
665 --I;
666 if (I->getOffset() <= SLocOffset) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000667 FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin()));
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000668
Chandler Carruth3201f382011-07-26 05:17:23 +0000669 // If this isn't an expansion, remember it. We have good locality across
670 // FileID lookups.
Chandler Carruth17287622011-07-26 04:56:51 +0000671 if (!I->isExpansion())
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000672 LastFileIDLookup = Res;
673 NumLinearScans += NumProbes+1;
674 return Res;
675 }
676 if (++NumProbes == 8)
677 break;
678 }
Mike Stump1eb44332009-09-09 15:08:12 +0000679
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000680 // Convert "I" back into an index. We know that it is an entry whose index is
681 // larger than the offset we are looking for.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000682 unsigned GreaterIndex = I - LocalSLocEntryTable.begin();
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000683 // LessIndex - This is the lower bound of the range that we're searching.
684 // We know that the offset corresponding to the FileID is is less than
685 // SLocOffset.
686 unsigned LessIndex = 0;
687 NumProbes = 0;
688 while (1) {
Douglas Gregore23ac652011-04-20 00:21:03 +0000689 bool Invalid = false;
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000690 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000691 unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset();
Douglas Gregore23ac652011-04-20 00:21:03 +0000692 if (Invalid)
693 return FileID::get(0);
694
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000695 ++NumProbes;
Mike Stump1eb44332009-09-09 15:08:12 +0000696
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000697 // If the offset of the midpoint is too large, chop the high side of the
698 // range to the midpoint.
699 if (MidOffset > SLocOffset) {
700 GreaterIndex = MiddleIndex;
701 continue;
702 }
Mike Stump1eb44332009-09-09 15:08:12 +0000703
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000704 // If the middle index contains the value, succeed and return.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000705 // FIXME: This could be made faster by using a function that's aware of
706 // being in the local area.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000707 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000708 FileID Res = FileID::get(MiddleIndex);
709
Chandler Carruth17287622011-07-26 04:56:51 +0000710 // If this isn't a macro expansion, remember it. We have good locality
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000711 // across FileID lookups.
Chandler Carruth17287622011-07-26 04:56:51 +0000712 if (!LocalSLocEntryTable[MiddleIndex].isExpansion())
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000713 LastFileIDLookup = Res;
714 NumBinaryProbes += NumProbes;
715 return Res;
716 }
Mike Stump1eb44332009-09-09 15:08:12 +0000717
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000718 // Otherwise, move the low-side up to the middle index.
719 LessIndex = MiddleIndex;
720 }
721}
722
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000723/// \brief Return the FileID for a SourceLocation with a high offset.
724///
725/// This function knows that the SourceLocation is in a loaded buffer, not a
726/// local one.
727FileID SourceManager::getFileIDLoaded(unsigned SLocOffset) const {
728 assert(SLocOffset >= CurrentLoadedOffset && "Bad function choice");
729
730 // Essentially the same as the local case, but the loaded array is sorted
731 // in the other direction.
732
733 // First do a linear scan from the last lookup position, if possible.
734 unsigned I;
735 int LastID = LastFileIDLookup.ID;
736 if (LastID >= 0 || getLoadedSLocEntryByID(LastID).getOffset() < SLocOffset)
737 I = 0;
738 else
739 I = (-LastID - 2) + 1;
740
741 unsigned NumProbes;
742 for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++I) {
743 // Make sure the entry is loaded!
744 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(I);
745 if (E.getOffset() <= SLocOffset) {
746 FileID Res = FileID::get(-int(I) - 2);
747
Chandler Carruth17287622011-07-26 04:56:51 +0000748 if (!E.isExpansion())
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000749 LastFileIDLookup = Res;
750 NumLinearScans += NumProbes + 1;
751 return Res;
752 }
753 }
754
755 // Linear scan failed. Do the binary search. Note the reverse sorting of the
756 // table: GreaterIndex is the one where the offset is greater, which is
757 // actually a lower index!
758 unsigned GreaterIndex = I;
759 unsigned LessIndex = LoadedSLocEntryTable.size();
760 NumProbes = 0;
761 while (1) {
762 ++NumProbes;
763 unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex;
764 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(MiddleIndex);
765
766 ++NumProbes;
767
768 if (E.getOffset() > SLocOffset) {
769 GreaterIndex = MiddleIndex;
770 continue;
771 }
772
773 if (isOffsetInFileID(FileID::get(-int(MiddleIndex) - 2), SLocOffset)) {
774 FileID Res = FileID::get(-int(MiddleIndex) - 2);
Chandler Carruth17287622011-07-26 04:56:51 +0000775 if (!E.isExpansion())
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000776 LastFileIDLookup = Res;
777 NumBinaryProbes += NumProbes;
778 return Res;
779 }
780
781 LessIndex = MiddleIndex;
782 }
783}
784
Chris Lattneraddb7972009-01-26 20:04:19 +0000785SourceLocation SourceManager::
Chandler Carruthf84ef952011-07-25 20:52:26 +0000786getExpansionLocSlowCase(SourceLocation Loc) const {
Chris Lattneraddb7972009-01-26 20:04:19 +0000787 do {
Chris Lattnera5c6c582010-02-12 19:31:35 +0000788 // Note: If Loc indicates an offset into a token that came from a macro
789 // expansion (e.g. the 5th character of the token) we do not want to add
Chandler Carruth17287622011-07-26 04:56:51 +0000790 // this offset when going to the expansion location. The expansion
Chris Lattnera5c6c582010-02-12 19:31:35 +0000791 // location is the macro invocation, which the offset has nothing to do
792 // with. This is unlike when we get the spelling loc, because the offset
793 // directly correspond to the token whose spelling we're inspecting.
Chandler Carruth17287622011-07-26 04:56:51 +0000794 Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart();
Chris Lattneraddb7972009-01-26 20:04:19 +0000795 } while (!Loc.isFileID());
796
797 return Loc;
798}
799
800SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
801 do {
802 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
Chandler Carruth17287622011-07-26 04:56:51 +0000803 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
Chris Lattneraddb7972009-01-26 20:04:19 +0000804 Loc = Loc.getFileLocWithOffset(LocInfo.second);
805 } while (!Loc.isFileID());
806 return Loc;
807}
808
809
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000810std::pair<FileID, unsigned>
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000811SourceManager::getDecomposedExpansionLocSlowCase(
Argyrios Kyrtzidis8b86ef02011-07-07 03:40:27 +0000812 const SrcMgr::SLocEntry *E) const {
Chandler Carruth3201f382011-07-26 05:17:23 +0000813 // If this is an expansion record, walk through all the expansion points.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000814 FileID FID;
815 SourceLocation Loc;
Argyrios Kyrtzidis8b86ef02011-07-07 03:40:27 +0000816 unsigned Offset;
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000817 do {
Chandler Carruth17287622011-07-26 04:56:51 +0000818 Loc = E->getExpansion().getExpansionLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000819
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000820 FID = getFileID(Loc);
821 E = &getSLocEntry(FID);
Argyrios Kyrtzidis8b86ef02011-07-07 03:40:27 +0000822 Offset = Loc.getOffset()-E->getOffset();
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000823 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000824
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000825 return std::make_pair(FID, Offset);
826}
827
828std::pair<FileID, unsigned>
829SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
830 unsigned Offset) const {
Chandler Carruth3201f382011-07-26 05:17:23 +0000831 // If this is an expansion record, walk through all the expansion points.
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000832 FileID FID;
833 SourceLocation Loc;
834 do {
Chandler Carruth17287622011-07-26 04:56:51 +0000835 Loc = E->getExpansion().getSpellingLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000836
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000837 FID = getFileID(Loc);
838 E = &getSLocEntry(FID);
839 Offset += Loc.getOffset()-E->getOffset();
840 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000841
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000842 return std::make_pair(FID, Offset);
843}
844
Chris Lattner387616e2009-02-17 08:04:48 +0000845/// getImmediateSpellingLoc - Given a SourceLocation object, return the
846/// spelling location referenced by the ID. This is the first level down
847/// towards the place where the characters that make up the lexed token can be
848/// found. This should not generally be used by clients.
849SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
850 if (Loc.isFileID()) return Loc;
851 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
Chandler Carruth17287622011-07-26 04:56:51 +0000852 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
Chris Lattner387616e2009-02-17 08:04:48 +0000853 return Loc.getFileLocWithOffset(LocInfo.second);
854}
855
856
Chandler Carruth3201f382011-07-26 05:17:23 +0000857/// getImmediateExpansionRange - Loc is required to be an expansion location.
858/// Return the start/end of the expansion information.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000859std::pair<SourceLocation,SourceLocation>
Chandler Carruth999f7392011-07-25 20:52:21 +0000860SourceManager::getImmediateExpansionRange(SourceLocation Loc) const {
Chandler Carruth3201f382011-07-26 05:17:23 +0000861 assert(Loc.isMacroID() && "Not a macro expansion loc!");
Chandler Carruth17287622011-07-26 04:56:51 +0000862 const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion();
Chandler Carruth78df8362011-07-26 04:41:47 +0000863 return Expansion.getExpansionLocRange();
Chris Lattnere7fb4842009-02-15 20:52:18 +0000864}
865
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000866/// getExpansionRange - Given a SourceLocation object, return the range of
867/// tokens covered by the expansion in the ultimate file.
Chris Lattner66781332009-02-15 21:26:50 +0000868std::pair<SourceLocation,SourceLocation>
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000869SourceManager::getExpansionRange(SourceLocation Loc) const {
Chris Lattner66781332009-02-15 21:26:50 +0000870 if (Loc.isFileID()) return std::make_pair(Loc, Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000871
Chris Lattner66781332009-02-15 21:26:50 +0000872 std::pair<SourceLocation,SourceLocation> Res =
Chandler Carruth999f7392011-07-25 20:52:21 +0000873 getImmediateExpansionRange(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000874
Chandler Carruth3201f382011-07-26 05:17:23 +0000875 // Fully resolve the start and end locations to their ultimate expansion
Chris Lattner66781332009-02-15 21:26:50 +0000876 // points.
877 while (!Res.first.isFileID())
Chandler Carruth999f7392011-07-25 20:52:21 +0000878 Res.first = getImmediateExpansionRange(Res.first).first;
Chris Lattner66781332009-02-15 21:26:50 +0000879 while (!Res.second.isFileID())
Chandler Carruth999f7392011-07-25 20:52:21 +0000880 Res.second = getImmediateExpansionRange(Res.second).second;
Chris Lattner66781332009-02-15 21:26:50 +0000881 return Res;
882}
883
Chandler Carruth96d35892011-07-26 03:03:00 +0000884bool SourceManager::isMacroArgExpansion(SourceLocation Loc) const {
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000885 if (!Loc.isMacroID()) return false;
886
887 FileID FID = getFileID(Loc);
888 const SrcMgr::SLocEntry *E = &getSLocEntry(FID);
Chandler Carruth17287622011-07-26 04:56:51 +0000889 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
Chandler Carruth78df8362011-07-26 04:41:47 +0000890 return Expansion.isMacroArgExpansion();
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000891}
Chris Lattnere7fb4842009-02-15 20:52:18 +0000892
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000893
894//===----------------------------------------------------------------------===//
895// Queries about the code at a SourceLocation.
896//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000897
898/// getCharacterData - Return a pointer to the start of the specified location
899/// in the appropriate MemoryBuffer.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000900const char *SourceManager::getCharacterData(SourceLocation SL,
901 bool *Invalid) const {
Reid Spencer5f016e22007-07-11 17:01:13 +0000902 // Note that this is a hot function in the getSpelling() path, which is
903 // heavily used by -E mode.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000904 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
Mike Stump1eb44332009-09-09 15:08:12 +0000905
Ted Kremenekc16c2082009-01-06 01:55:26 +0000906 // Note that calling 'getBuffer()' may lazily page in a source file.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000907 bool CharDataInvalid = false;
Douglas Gregore23ac652011-04-20 00:21:03 +0000908 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
909 if (CharDataInvalid || !Entry.isFile()) {
910 if (Invalid)
911 *Invalid = true;
912
913 return "<<<<INVALID BUFFER>>>>";
914 }
Douglas Gregor50f6af72010-03-16 05:20:39 +0000915 const llvm::MemoryBuffer *Buffer
Douglas Gregore23ac652011-04-20 00:21:03 +0000916 = Entry.getFile().getContentCache()
917 ->getBuffer(Diag, *this, SourceLocation(), &CharDataInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000918 if (Invalid)
919 *Invalid = CharDataInvalid;
920 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
Reid Spencer5f016e22007-07-11 17:01:13 +0000921}
922
Reid Spencer5f016e22007-07-11 17:01:13 +0000923
Chris Lattner9dc1f532007-07-20 16:37:10 +0000924/// getColumnNumber - Return the column # for the specified file position.
Chris Lattner7da5aea2009-02-04 00:55:58 +0000925/// this is significantly cheaper to compute than the line number.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000926unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
927 bool *Invalid) const {
928 bool MyInvalid = false;
929 const char *Buf = getBuffer(FID, &MyInvalid)->getBufferStart();
930 if (Invalid)
931 *Invalid = MyInvalid;
932
933 if (MyInvalid)
934 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000935
Reid Spencer5f016e22007-07-11 17:01:13 +0000936 unsigned LineStart = FilePos;
937 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
938 --LineStart;
939 return FilePos-LineStart+1;
940}
941
Zhanyong Wan1f24e112010-10-05 17:56:33 +0000942// isInvalid - Return the result of calling loc.isInvalid(), and
943// if Invalid is not null, set its value to same.
944static bool isInvalid(SourceLocation Loc, bool *Invalid) {
945 bool MyInvalid = Loc.isInvalid();
946 if (Invalid)
947 *Invalid = MyInvalid;
948 return MyInvalid;
949}
950
Douglas Gregor50f6af72010-03-16 05:20:39 +0000951unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
952 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +0000953 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +0000954 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000955 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +0000956}
957
Chandler Carrutha77c0312011-07-25 20:57:57 +0000958unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc,
959 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +0000960 if (isInvalid(Loc, Invalid)) return 0;
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000961 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000962 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +0000963}
964
Chandler Carruth5ef04ee2011-02-23 00:47:48 +0000965unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
966 bool *Invalid) const {
967 if (isInvalid(Loc, Invalid)) return 0;
968 return getPresumedLoc(Loc).getColumn();
969}
970
Chandler Carruth14bd9652010-10-23 08:44:57 +0000971static LLVM_ATTRIBUTE_NOINLINE void
Chris Lattnere127a0d2010-04-20 20:35:58 +0000972ComputeLineNumbers(Diagnostic &Diag, ContentCache *FI,
973 llvm::BumpPtrAllocator &Alloc,
974 const SourceManager &SM, bool &Invalid);
975static void ComputeLineNumbers(Diagnostic &Diag, ContentCache *FI,
976 llvm::BumpPtrAllocator &Alloc,
977 const SourceManager &SM, bool &Invalid) {
Ted Kremenekc16c2082009-01-06 01:55:26 +0000978 // Note that calling 'getBuffer()' may lazily page in the file.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000979 const MemoryBuffer *Buffer = FI->getBuffer(Diag, SM, SourceLocation(),
980 &Invalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000981 if (Invalid)
982 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000983
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000984 // Find the file offsets of all of the *physical* source lines. This does
985 // not look at trigraphs, escaped newlines, or anything else tricky.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000986 SmallVector<unsigned, 256> LineOffsets;
Mike Stump1eb44332009-09-09 15:08:12 +0000987
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000988 // Line #1 starts at char 0.
989 LineOffsets.push_back(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000990
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000991 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
992 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
993 unsigned Offs = 0;
994 while (1) {
995 // Skip over the contents of the line.
996 // TODO: Vectorize this? This is very performance sensitive for programs
997 // with lots of diagnostics and in -E mode.
998 const unsigned char *NextBuf = (const unsigned char *)Buf;
999 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
1000 ++NextBuf;
1001 Offs += NextBuf-Buf;
1002 Buf = NextBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00001003
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001004 if (Buf[0] == '\n' || Buf[0] == '\r') {
1005 // If this is \n\r or \r\n, skip both characters.
1006 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
1007 ++Offs, ++Buf;
1008 ++Offs, ++Buf;
1009 LineOffsets.push_back(Offs);
1010 } else {
1011 // Otherwise, this is a null. If end of file, exit.
1012 if (Buf == End) break;
1013 // Otherwise, skip the null.
1014 ++Offs, ++Buf;
1015 }
1016 }
Mike Stump1eb44332009-09-09 15:08:12 +00001017
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001018 // Copy the offsets into the FileInfo structure.
1019 FI->NumLines = LineOffsets.size();
Chris Lattner0d0bf8c2009-02-03 07:30:45 +00001020 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001021 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
1022}
Reid Spencer5f016e22007-07-11 17:01:13 +00001023
Chris Lattnerdf7c17a2009-01-16 07:00:02 +00001024/// getLineNumber - Given a SourceLocation, return the spelling line number
Reid Spencer5f016e22007-07-11 17:01:13 +00001025/// for the position indicated. This requires building and caching a table of
1026/// line offsets for the MemoryBuffer, so this is not cheap: use only when
1027/// about to emit a diagnostic.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001028unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
1029 bool *Invalid) const {
Argyrios Kyrtzidis5adc0512011-05-17 22:09:53 +00001030 if (FID.isInvalid()) {
1031 if (Invalid)
1032 *Invalid = true;
1033 return 1;
1034 }
1035
Chris Lattner2b2453a2009-01-17 06:22:33 +00001036 ContentCache *Content;
Chris Lattner30fc9332009-02-04 01:06:56 +00001037 if (LastLineNoFileIDQuery == FID)
Ted Kremenek78d85f52007-10-30 21:08:08 +00001038 Content = LastLineNoContentCache;
Douglas Gregore23ac652011-04-20 00:21:03 +00001039 else {
1040 bool MyInvalid = false;
1041 const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
1042 if (MyInvalid || !Entry.isFile()) {
1043 if (Invalid)
1044 *Invalid = true;
1045 return 1;
1046 }
1047
1048 Content = const_cast<ContentCache*>(Entry.getFile().getContentCache());
1049 }
1050
Reid Spencer5f016e22007-07-11 17:01:13 +00001051 // If this is the first use of line information for this buffer, compute the
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001052 /// SourceLineCache for it on demand.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001053 if (Content->SourceLineCache == 0) {
1054 bool MyInvalid = false;
Chris Lattnere127a0d2010-04-20 20:35:58 +00001055 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001056 if (Invalid)
1057 *Invalid = MyInvalid;
1058 if (MyInvalid)
1059 return 1;
1060 } else if (Invalid)
1061 *Invalid = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001062
1063 // Okay, we know we have a line number table. Do a binary search to find the
1064 // line number that this character position lands on.
Ted Kremenek78d85f52007-10-30 21:08:08 +00001065 unsigned *SourceLineCache = Content->SourceLineCache;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001066 unsigned *SourceLineCacheStart = SourceLineCache;
Ted Kremenek78d85f52007-10-30 21:08:08 +00001067 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
Mike Stump1eb44332009-09-09 15:08:12 +00001068
Chris Lattner30fc9332009-02-04 01:06:56 +00001069 unsigned QueriedFilePos = FilePos+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001070
Daniel Dunbar4106d692009-05-18 17:30:52 +00001071 // FIXME: I would like to be convinced that this code is worth being as
Mike Stump1eb44332009-09-09 15:08:12 +00001072 // complicated as it is, binary search isn't that slow.
Daniel Dunbar4106d692009-05-18 17:30:52 +00001073 //
1074 // If it is worth being optimized, then in my opinion it could be more
1075 // performant, simpler, and more obviously correct by just "galloping" outward
1076 // from the queried file position. In fact, this could be incorporated into a
1077 // generic algorithm such as lower_bound_with_hint.
1078 //
1079 // If someone gives me a test case where this matters, and I will do it! - DWD
1080
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001081 // If the previous query was to the same file, we know both the file pos from
1082 // that query and the line number returned. This allows us to narrow the
1083 // search space from the entire file to something near the match.
Chris Lattner30fc9332009-02-04 01:06:56 +00001084 if (LastLineNoFileIDQuery == FID) {
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001085 if (QueriedFilePos >= LastLineNoFilePos) {
Daniel Dunbar4106d692009-05-18 17:30:52 +00001086 // FIXME: Potential overflow?
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001087 SourceLineCache = SourceLineCache+LastLineNoResult-1;
Mike Stump1eb44332009-09-09 15:08:12 +00001088
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001089 // The query is likely to be nearby the previous one. Here we check to
1090 // see if it is within 5, 10 or 20 lines. It can be far away in cases
1091 // where big comment blocks and vertical whitespace eat up lines but
1092 // contribute no tokens.
1093 if (SourceLineCache+5 < SourceLineCacheEnd) {
1094 if (SourceLineCache[5] > QueriedFilePos)
1095 SourceLineCacheEnd = SourceLineCache+5;
1096 else if (SourceLineCache+10 < SourceLineCacheEnd) {
1097 if (SourceLineCache[10] > QueriedFilePos)
1098 SourceLineCacheEnd = SourceLineCache+10;
1099 else if (SourceLineCache+20 < SourceLineCacheEnd) {
1100 if (SourceLineCache[20] > QueriedFilePos)
1101 SourceLineCacheEnd = SourceLineCache+20;
1102 }
1103 }
1104 }
1105 } else {
Daniel Dunbar4106d692009-05-18 17:30:52 +00001106 if (LastLineNoResult < Content->NumLines)
1107 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001108 }
1109 }
Mike Stump1eb44332009-09-09 15:08:12 +00001110
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001111 // If the spread is large, do a "radix" test as our initial guess, based on
1112 // the assumption that lines average to approximately the same length.
1113 // NOTE: This is currently disabled, as it does not appear to be profitable in
1114 // initial measurements.
1115 if (0 && SourceLineCacheEnd-SourceLineCache > 20) {
Ted Kremenek78d85f52007-10-30 21:08:08 +00001116 unsigned FileLen = Content->SourceLineCache[Content->NumLines-1];
Mike Stump1eb44332009-09-09 15:08:12 +00001117
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001118 // Take a stab at guessing where it is.
Ted Kremenek78d85f52007-10-30 21:08:08 +00001119 unsigned ApproxPos = Content->NumLines*QueriedFilePos / FileLen;
Mike Stump1eb44332009-09-09 15:08:12 +00001120
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001121 // Check for -10 and +10 lines.
1122 unsigned LowerBound = std::max(int(ApproxPos-10), 0);
1123 unsigned UpperBound = std::min(ApproxPos+10, FileLen);
1124
1125 // If the computed lower bound is less than the query location, move it in.
1126 if (SourceLineCache < SourceLineCacheStart+LowerBound &&
1127 SourceLineCacheStart[LowerBound] < QueriedFilePos)
1128 SourceLineCache = SourceLineCacheStart+LowerBound;
Mike Stump1eb44332009-09-09 15:08:12 +00001129
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001130 // If the computed upper bound is greater than the query location, move it.
1131 if (SourceLineCacheEnd > SourceLineCacheStart+UpperBound &&
1132 SourceLineCacheStart[UpperBound] >= QueriedFilePos)
1133 SourceLineCacheEnd = SourceLineCacheStart+UpperBound;
1134 }
Mike Stump1eb44332009-09-09 15:08:12 +00001135
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001136 unsigned *Pos
1137 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001138 unsigned LineNo = Pos-SourceLineCacheStart;
Mike Stump1eb44332009-09-09 15:08:12 +00001139
Chris Lattner30fc9332009-02-04 01:06:56 +00001140 LastLineNoFileIDQuery = FID;
Ted Kremenek78d85f52007-10-30 21:08:08 +00001141 LastLineNoContentCache = Content;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001142 LastLineNoFilePos = QueriedFilePos;
1143 LastLineNoResult = LineNo;
1144 return LineNo;
Reid Spencer5f016e22007-07-11 17:01:13 +00001145}
1146
Chandler Carruth5ef04ee2011-02-23 00:47:48 +00001147unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
1148 bool *Invalid) const {
1149 if (isInvalid(Loc, Invalid)) return 0;
1150 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1151 return getLineNumber(LocInfo.first, LocInfo.second);
1152}
Chandler Carruth64211622011-07-25 21:09:52 +00001153unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc,
1154 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001155 if (isInvalid(Loc, Invalid)) return 0;
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +00001156 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Chris Lattner30fc9332009-02-04 01:06:56 +00001157 return getLineNumber(LocInfo.first, LocInfo.second);
1158}
Chandler Carruth5ef04ee2011-02-23 00:47:48 +00001159unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
Douglas Gregor50f6af72010-03-16 05:20:39 +00001160 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001161 if (isInvalid(Loc, Invalid)) return 0;
Chandler Carruth5ef04ee2011-02-23 00:47:48 +00001162 return getPresumedLoc(Loc).getLine();
Chris Lattner30fc9332009-02-04 01:06:56 +00001163}
1164
Chris Lattner6b306672009-02-04 05:33:01 +00001165/// getFileCharacteristic - return the file characteristic of the specified
Mike Stump1eb44332009-09-09 15:08:12 +00001166/// source location, indicating whether this is a normal file, a system
Chris Lattner6b306672009-02-04 05:33:01 +00001167/// header, or an "implicit extern C" system header.
1168///
1169/// This state can be modified with flags on GNU linemarker directives like:
1170/// # 4 "foo.h" 3
1171/// which changes all source locations in the current file after that to be
1172/// considered to be from a system header.
Mike Stump1eb44332009-09-09 15:08:12 +00001173SrcMgr::CharacteristicKind
Chris Lattner6b306672009-02-04 05:33:01 +00001174SourceManager::getFileCharacteristic(SourceLocation Loc) const {
1175 assert(!Loc.isInvalid() && "Can't get file characteristic of invalid loc!");
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +00001176 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Douglas Gregore23ac652011-04-20 00:21:03 +00001177 bool Invalid = false;
1178 const SLocEntry &SEntry = getSLocEntry(LocInfo.first, &Invalid);
1179 if (Invalid || !SEntry.isFile())
1180 return C_User;
1181
1182 const SrcMgr::FileInfo &FI = SEntry.getFile();
Chris Lattner6b306672009-02-04 05:33:01 +00001183
1184 // If there are no #line directives in this file, just return the whole-file
1185 // state.
1186 if (!FI.hasLineDirectives())
1187 return FI.getFileCharacteristic();
Mike Stump1eb44332009-09-09 15:08:12 +00001188
Chris Lattner6b306672009-02-04 05:33:01 +00001189 assert(LineTable && "Can't have linetable entries without a LineTable!");
1190 // See if there is a #line directive before the location.
1191 const LineEntry *Entry =
1192 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001193
Chris Lattner6b306672009-02-04 05:33:01 +00001194 // If this is before the first line marker, use the file characteristic.
1195 if (!Entry)
1196 return FI.getFileCharacteristic();
1197
1198 return Entry->FileKind;
1199}
1200
Chris Lattnerbff5c512009-02-17 08:39:06 +00001201/// Return the filename or buffer identifier of the buffer the location is in.
1202/// Note that this name does not respect #line directives. Use getPresumedLoc
1203/// for normal clients.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001204const char *SourceManager::getBufferName(SourceLocation Loc,
1205 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001206 if (isInvalid(Loc, Invalid)) return "<invalid loc>";
Mike Stump1eb44332009-09-09 15:08:12 +00001207
Douglas Gregor50f6af72010-03-16 05:20:39 +00001208 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
Chris Lattnerbff5c512009-02-17 08:39:06 +00001209}
1210
Chris Lattner30fc9332009-02-04 01:06:56 +00001211
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001212/// getPresumedLoc - This method returns the "presumed" location of a
1213/// SourceLocation specifies. A "presumed location" can be modified by #line
1214/// or GNU line marker directives. This provides a view on the data that a
1215/// user should see in diagnostics, for example.
1216///
Chandler Carruth3201f382011-07-26 05:17:23 +00001217/// Note that a presumed location is always given as the expansion point of an
1218/// expansion location, not at the spelling location.
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001219PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc) const {
1220 if (Loc.isInvalid()) return PresumedLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001221
Chandler Carruth3201f382011-07-26 05:17:23 +00001222 // Presumed locations are always for expansion points.
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +00001223 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +00001224
Douglas Gregore23ac652011-04-20 00:21:03 +00001225 bool Invalid = false;
1226 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1227 if (Invalid || !Entry.isFile())
1228 return PresumedLoc();
1229
1230 const SrcMgr::FileInfo &FI = Entry.getFile();
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001231 const SrcMgr::ContentCache *C = FI.getContentCache();
Mike Stump1eb44332009-09-09 15:08:12 +00001232
Chris Lattner3cd949c2009-02-04 01:55:42 +00001233 // To get the source name, first consult the FileEntry (if one exists)
1234 // before the MemBuffer as this will avoid unnecessarily paging in the
1235 // MemBuffer.
Chris Lattnere127a0d2010-04-20 20:35:58 +00001236 const char *Filename;
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001237 if (C->OrigEntry)
1238 Filename = C->OrigEntry->getName();
Chris Lattnere127a0d2010-04-20 20:35:58 +00001239 else
1240 Filename = C->getBuffer(Diag, *this)->getBufferIdentifier();
Douglas Gregore23ac652011-04-20 00:21:03 +00001241
Douglas Gregorc417fa02010-11-02 00:39:22 +00001242 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1243 if (Invalid)
1244 return PresumedLoc();
1245 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1246 if (Invalid)
1247 return PresumedLoc();
1248
Chris Lattner3cd949c2009-02-04 01:55:42 +00001249 SourceLocation IncludeLoc = FI.getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001250
Chris Lattner3cd949c2009-02-04 01:55:42 +00001251 // If we have #line directives in this file, update and overwrite the physical
1252 // location info if appropriate.
1253 if (FI.hasLineDirectives()) {
1254 assert(LineTable && "Can't have linetable entries without a LineTable!");
1255 // See if there is a #line directive before this. If so, get it.
1256 if (const LineEntry *Entry =
1257 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second)) {
Chris Lattnerfc391332009-02-04 02:00:59 +00001258 // If the LineEntry indicates a filename, use it.
Chris Lattner3cd949c2009-02-04 01:55:42 +00001259 if (Entry->FilenameID != -1)
1260 Filename = LineTable->getFilename(Entry->FilenameID);
Chris Lattnerfc391332009-02-04 02:00:59 +00001261
1262 // Use the line number specified by the LineEntry. This line number may
1263 // be multiple lines down from the line entry. Add the difference in
1264 // physical line numbers from the query point and the line marker to the
1265 // total.
1266 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1267 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001268
Chris Lattner0e0e5da2009-02-04 02:15:40 +00001269 // Note that column numbers are not molested by line markers.
Mike Stump1eb44332009-09-09 15:08:12 +00001270
Chris Lattner137b6a62009-02-04 06:25:26 +00001271 // Handle virtual #include manipulation.
1272 if (Entry->IncludeOffset) {
1273 IncludeLoc = getLocForStartOfFile(LocInfo.first);
1274 IncludeLoc = IncludeLoc.getFileLocWithOffset(Entry->IncludeOffset);
1275 }
Chris Lattner3cd949c2009-02-04 01:55:42 +00001276 }
1277 }
1278
1279 return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc);
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001280}
1281
1282//===----------------------------------------------------------------------===//
1283// Other miscellaneous methods.
1284//===----------------------------------------------------------------------===//
1285
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001286/// \brief Retrieve the inode for the given file entry, if possible.
1287///
1288/// This routine involves a system call, and therefore should only be used
1289/// in non-performance-critical code.
1290static llvm::Optional<ino_t> getActualFileInode(const FileEntry *File) {
1291 if (!File)
1292 return llvm::Optional<ino_t>();
1293
1294 struct stat StatBuf;
1295 if (::stat(File->getName(), &StatBuf))
1296 return llvm::Optional<ino_t>();
1297
1298 return StatBuf.st_ino;
1299}
1300
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001301/// \brief Get the source location for the given file:line:col triplet.
1302///
1303/// If the source file is included multiple times, the source location will
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001304/// be based upon an arbitrary inclusion.
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001305SourceLocation SourceManager::getLocation(const FileEntry *SourceFile,
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001306 unsigned Line, unsigned Col) {
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001307 assert(SourceFile && "Null source file!");
1308 assert(Line && Col && "Line and column should start from 1!");
1309
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001310 // Find the first file ID that corresponds to the given file.
1311 FileID FirstFID;
Mike Stump1eb44332009-09-09 15:08:12 +00001312
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001313 // First, check the main file ID, since it is common to look for a
1314 // location in the main file.
1315 llvm::Optional<ino_t> SourceFileInode;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001316 llvm::Optional<StringRef> SourceFileName;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001317 if (!MainFileID.isInvalid()) {
Douglas Gregore23ac652011-04-20 00:21:03 +00001318 bool Invalid = false;
1319 const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
1320 if (Invalid)
1321 return SourceLocation();
1322
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001323 if (MainSLoc.isFile()) {
1324 const ContentCache *MainContentCache
1325 = MainSLoc.getFile().getContentCache();
Douglas Gregorb7a18412011-02-11 18:08:15 +00001326 if (!MainContentCache) {
1327 // Can't do anything
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001328 } else if (MainContentCache->OrigEntry == SourceFile) {
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001329 FirstFID = MainFileID;
Douglas Gregorb7a18412011-02-11 18:08:15 +00001330 } else {
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001331 // Fall back: check whether we have the same base name and inode
1332 // as the main file.
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001333 const FileEntry *MainFile = MainContentCache->OrigEntry;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001334 SourceFileName = llvm::sys::path::filename(SourceFile->getName());
1335 if (*SourceFileName == llvm::sys::path::filename(MainFile->getName())) {
1336 SourceFileInode = getActualFileInode(SourceFile);
Douglas Gregor37c02bf2011-02-16 19:09:24 +00001337 if (SourceFileInode) {
1338 if (llvm::Optional<ino_t> MainFileInode
1339 = getActualFileInode(MainFile)) {
1340 if (*SourceFileInode == *MainFileInode) {
1341 FirstFID = MainFileID;
1342 SourceFile = MainFile;
1343 }
1344 }
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001345 }
1346 }
1347 }
1348 }
1349 }
1350
1351 if (FirstFID.isInvalid()) {
1352 // The location we're looking for isn't in the main file; look
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001353 // through all of the local source locations.
1354 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
Douglas Gregore23ac652011-04-20 00:21:03 +00001355 bool Invalid = false;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001356 const SLocEntry &SLoc = getLocalSLocEntry(I, &Invalid);
Douglas Gregore23ac652011-04-20 00:21:03 +00001357 if (Invalid)
1358 return SourceLocation();
1359
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001360 if (SLoc.isFile() &&
1361 SLoc.getFile().getContentCache() &&
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001362 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001363 FirstFID = FileID::get(I);
1364 break;
1365 }
1366 }
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001367 // If that still didn't help, try the modules.
1368 if (FirstFID.isInvalid()) {
1369 for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) {
1370 const SLocEntry &SLoc = getLoadedSLocEntry(I);
1371 if (SLoc.isFile() &&
1372 SLoc.getFile().getContentCache() &&
1373 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
1374 FirstFID = FileID::get(-int(I) - 2);
1375 break;
1376 }
1377 }
1378 }
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001379 }
1380
1381 // If we haven't found what we want yet, try again, but this time stat()
1382 // each of the files in case the files have changed since we originally
1383 // parsed the file.
1384 if (FirstFID.isInvalid() &&
1385 (SourceFileName ||
1386 (SourceFileName = llvm::sys::path::filename(SourceFile->getName()))) &&
1387 (SourceFileInode ||
1388 (SourceFileInode = getActualFileInode(SourceFile)))) {
Douglas Gregore23ac652011-04-20 00:21:03 +00001389 bool Invalid = false;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001390 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1391 FileID IFileID;
1392 IFileID.ID = I;
1393 const SLocEntry &SLoc = getSLocEntry(IFileID, &Invalid);
Douglas Gregore23ac652011-04-20 00:21:03 +00001394 if (Invalid)
1395 return SourceLocation();
1396
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001397 if (SLoc.isFile()) {
1398 const ContentCache *FileContentCache
1399 = SLoc.getFile().getContentCache();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001400 const FileEntry *Entry =FileContentCache? FileContentCache->OrigEntry : 0;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001401 if (Entry &&
Douglas Gregorb7a18412011-02-11 18:08:15 +00001402 *SourceFileName == llvm::sys::path::filename(Entry->getName())) {
1403 if (llvm::Optional<ino_t> EntryInode = getActualFileInode(Entry)) {
1404 if (*SourceFileInode == *EntryInode) {
1405 FirstFID = FileID::get(I);
1406 SourceFile = Entry;
1407 break;
1408 }
1409 }
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001410 }
1411 }
1412 }
1413 }
1414
1415 if (FirstFID.isInvalid())
1416 return SourceLocation();
1417
1418 if (Line == 1 && Col == 1)
1419 return getLocForStartOfFile(FirstFID);
1420
1421 ContentCache *Content
1422 = const_cast<ContentCache *>(getOrCreateContentCache(SourceFile));
1423 if (!Content)
1424 return SourceLocation();
1425
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001426 // If this is the first use of line information for this buffer, compute the
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001427 // SourceLineCache for it on demand.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001428 if (Content->SourceLineCache == 0) {
1429 bool MyInvalid = false;
Chris Lattnere127a0d2010-04-20 20:35:58 +00001430 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001431 if (MyInvalid)
1432 return SourceLocation();
1433 }
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001434
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001435 if (Line > Content->NumLines) {
Chris Lattnere127a0d2010-04-20 20:35:58 +00001436 unsigned Size = Content->getBuffer(Diag, *this)->getBufferSize();
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001437 if (Size > 0)
1438 --Size;
1439 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(Size);
1440 }
1441
1442 unsigned FilePos = Content->SourceLineCache[Line - 1];
Chris Lattnere127a0d2010-04-20 20:35:58 +00001443 const char *Buf = Content->getBuffer(Diag, *this)->getBufferStart() + FilePos;
1444 unsigned BufLength = Content->getBuffer(Diag, *this)->getBufferEnd() - Buf;
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001445 unsigned i = 0;
1446
1447 // Check that the given column is valid.
1448 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1449 ++i;
1450 if (i < Col-1)
1451 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + i);
1452
Douglas Gregor4a160e12009-12-02 05:34:39 +00001453 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + Col - 1);
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001454}
1455
Chandler Carruth3201f382011-07-26 05:17:23 +00001456/// Given a decomposed source location, move it up the include/expansion stack
1457/// to the parent source location. If this is possible, return the decomposed
1458/// version of the parent in Loc and return false. If Loc is the top-level
1459/// entry, return true and don't modify it.
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001460static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1461 const SourceManager &SM) {
1462 SourceLocation UpperLoc;
1463 const SrcMgr::SLocEntry &Entry = SM.getSLocEntry(Loc.first);
Chandler Carruth17287622011-07-26 04:56:51 +00001464 if (Entry.isExpansion())
1465 UpperLoc = Entry.getExpansion().getExpansionLocStart();
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001466 else
1467 UpperLoc = Entry.getFile().getIncludeLoc();
1468
1469 if (UpperLoc.isInvalid())
1470 return true; // We reached the top.
1471
1472 Loc = SM.getDecomposedLoc(UpperLoc);
1473 return false;
1474}
1475
1476
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001477/// \brief Determines the order of 2 source locations in the translation unit.
1478///
1479/// \returns true if LHS source location comes before RHS, false otherwise.
1480bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
1481 SourceLocation RHS) const {
1482 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
1483 if (LHS == RHS)
1484 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001485
Chandler Carruth3201f382011-07-26 05:17:23 +00001486 // If both locations are macro expansions, the order of their offsets reflect
1487 // the order that the tokens, pointed to by these locations, were expanded
1488 // (during parsing each token that is expanded by a macro, expands the
1489 // SLocEntries).
Argyrios Kyrtzidisee933e12010-12-24 02:53:53 +00001490
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001491 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
1492 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00001493
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001494 // If the source locations are in the same file, just compare offsets.
1495 if (LOffs.first == ROffs.first)
1496 return LOffs.second < ROffs.second;
1497
1498 // If we are comparing a source location with multiple locations in the same
1499 // file, we get a big win by caching the result.
Chris Lattner66a915f2010-05-07 05:10:46 +00001500 if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
1501 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001502
Chris Lattnerdcb1d682010-05-07 01:17:07 +00001503 // Okay, we missed in the cache, start updating the cache for this query.
1504 IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first);
Mike Stump1eb44332009-09-09 15:08:12 +00001505
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001506 // We need to find the common ancestor. The only way of doing this is to
1507 // build the complete include chain for one and then walking up the chain
1508 // of the other looking for a match.
1509 // We use a map from FileID to Offset to store the chain. Easier than writing
1510 // a custom set hash info that only depends on the first part of a pair.
1511 typedef llvm::DenseMap<FileID, unsigned> LocSet;
1512 LocSet LChain;
Chris Lattner48296ba2010-05-07 05:51:13 +00001513 do {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001514 LChain.insert(LOffs);
1515 // We catch the case where LOffs is in a file included by ROffs and
1516 // quit early. The other way round unfortunately remains suboptimal.
1517 } while (LOffs.first != ROffs.first && !MoveUpIncludeHierarchy(LOffs, *this));
1518 LocSet::iterator I;
1519 while((I = LChain.find(ROffs.first)) == LChain.end()) {
1520 if (MoveUpIncludeHierarchy(ROffs, *this))
1521 break; // Met at topmost file.
1522 }
1523 if (I != LChain.end())
1524 LOffs = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001525
Chris Lattner48296ba2010-05-07 05:51:13 +00001526 // If we exited because we found a nearest common ancestor, compare the
1527 // locations within the common file and cache them.
1528 if (LOffs.first == ROffs.first) {
1529 IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
1530 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001531 }
Mike Stump1eb44332009-09-09 15:08:12 +00001532
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001533 // This can happen if a location is in a built-ins buffer.
1534 // But see PR5662.
1535 // Clear the lookup cache, it depends on a common location.
1536 IsBeforeInTUCache.setQueryFIDs(FileID(), FileID());
1537 bool LIsBuiltins = strcmp("<built-in>",
1538 getBuffer(LOffs.first)->getBufferIdentifier()) == 0;
1539 bool RIsBuiltins = strcmp("<built-in>",
1540 getBuffer(ROffs.first)->getBufferIdentifier()) == 0;
1541 // built-in is before non-built-in
1542 if (LIsBuiltins != RIsBuiltins)
1543 return LIsBuiltins;
1544 assert(LIsBuiltins && RIsBuiltins &&
1545 "Non-built-in locations must be rooted in the main file");
1546 // Both are in built-in buffers, but from different files. We just claim that
1547 // lower IDs come first.
Chris Lattnerdcb1d682010-05-07 01:17:07 +00001548 return LOffs.first < ROffs.first;
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001549}
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001550
Reid Spencer5f016e22007-07-11 17:01:13 +00001551/// PrintStats - Print statistics to stderr.
1552///
1553void SourceManager::PrintStats() const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001554 llvm::errs() << "\n*** Source Manager Stats:\n";
1555 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
1556 << " mem buffers mapped.\n";
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001557 llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntry's allocated ("
1558 << LocalSLocEntryTable.capacity()*sizeof(SrcMgr::SLocEntry)
Argyrios Kyrtzidisd410e742011-07-07 03:40:24 +00001559 << " bytes of capacity), "
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001560 << NextLocalOffset << "B of Sloc address space used.\n";
1561 llvm::errs() << LoadedSLocEntryTable.size()
1562 << " loaded SLocEntries allocated, "
1563 << (1U << 31U) - CurrentLoadedOffset
1564 << "B of Sloc address space used.\n";
1565
Reid Spencer5f016e22007-07-11 17:01:13 +00001566 unsigned NumLineNumsComputed = 0;
1567 unsigned NumFileBytesMapped = 0;
Chris Lattner0d0bf8c2009-02-03 07:30:45 +00001568 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
1569 NumLineNumsComputed += I->second->SourceLineCache != 0;
1570 NumFileBytesMapped += I->second->getSizeBytesMapped();
Reid Spencer5f016e22007-07-11 17:01:13 +00001571 }
Mike Stump1eb44332009-09-09 15:08:12 +00001572
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001573 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
1574 << NumLineNumsComputed << " files with line #'s computed.\n";
1575 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
1576 << NumBinaryProbes << " binary.\n";
Reid Spencer5f016e22007-07-11 17:01:13 +00001577}
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001578
1579ExternalSLocEntrySource::~ExternalSLocEntrySource() { }
Ted Kremenekf61b8312011-04-28 20:36:42 +00001580
1581/// Return the amount of memory used by memory buffers, breaking down
1582/// by heap-backed versus mmap'ed memory.
1583SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
1584 size_t malloc_bytes = 0;
1585 size_t mmap_bytes = 0;
1586
1587 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)
1588 if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
1589 switch (MemBufferInfos[i]->getMemoryBufferKind()) {
1590 case llvm::MemoryBuffer::MemoryBuffer_MMap:
1591 mmap_bytes += sized_mapped;
1592 break;
1593 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
1594 malloc_bytes += sized_mapped;
1595 break;
1596 }
1597
1598 return MemoryBufferSizes(malloc_bytes, mmap_bytes);
1599}
1600