blob: aad23ad6db3714ca1a7e404f4e2ee7edda999c9b [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
Ted Kremenekc16c2082009-01-06 01:55:26 +000042/// getSizeBytesMapped - Returns the number of bytes actually mapped for
43/// this ContentCache. This can be 0 if the MemBuffer was not actually
44/// instantiated.
45unsigned ContentCache::getSizeBytesMapped() const {
Douglas Gregorc8151082010-03-16 22:53:51 +000046 return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 0;
Ted Kremenekc16c2082009-01-06 01:55:26 +000047}
48
Ted Kremenekf61b8312011-04-28 20:36:42 +000049/// Returns the kind of memory used to back the memory buffer for
50/// this content cache. This is used for performance analysis.
51llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const {
52 assert(Buffer.getPointer());
53
54 // Should be unreachable, but keep for sanity.
55 if (!Buffer.getPointer())
56 return llvm::MemoryBuffer::MemoryBuffer_Malloc;
57
58 const llvm::MemoryBuffer *buf = Buffer.getPointer();
59 return buf->getBufferKind();
60}
61
Ted Kremenekc16c2082009-01-06 01:55:26 +000062/// getSize - Returns the size of the content encapsulated by this ContentCache.
63/// This can be the size of the source file or the size of an arbitrary
64/// scratch buffer. If the ContentCache encapsulates a source file, that
Douglas Gregor29684422009-12-02 06:49:09 +000065/// file is not lazily brought in from disk to satisfy this query.
Ted Kremenekc16c2082009-01-06 01:55:26 +000066unsigned ContentCache::getSize() const {
Douglas Gregorc8151082010-03-16 22:53:51 +000067 return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize()
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +000068 : (unsigned) ContentsEntry->getSize();
Ted Kremenekc16c2082009-01-06 01:55:26 +000069}
70
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000071void ContentCache::replaceBuffer(const llvm::MemoryBuffer *B,
72 bool DoNotFree) {
Douglas Gregorc8151082010-03-16 22:53:51 +000073 assert(B != Buffer.getPointer());
Douglas Gregor29684422009-12-02 06:49:09 +000074
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000075 if (shouldFreeBuffer())
76 delete Buffer.getPointer();
Douglas Gregorc8151082010-03-16 22:53:51 +000077 Buffer.setPointer(B);
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000078 Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
Douglas Gregor29684422009-12-02 06:49:09 +000079}
80
Douglas Gregor36c35ba2010-03-16 00:35:39 +000081const llvm::MemoryBuffer *ContentCache::getBuffer(Diagnostic &Diag,
Chris Lattner5c5db4e2010-04-20 20:49:23 +000082 const SourceManager &SM,
Chris Lattnere127a0d2010-04-20 20:35:58 +000083 SourceLocation Loc,
Douglas Gregor36c35ba2010-03-16 00:35:39 +000084 bool *Invalid) const {
Chris Lattnerb088cd32010-11-23 08:50:03 +000085 // Lazily create the Buffer for ContentCaches that wrap files. If we already
Chris Lattnerfc8f0e12011-04-15 05:22:18 +000086 // computed it, just return what we have.
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +000087 if (Buffer.getPointer() || ContentsEntry == 0) {
Chris Lattnerb088cd32010-11-23 08:50:03 +000088 if (Invalid)
89 *Invalid = isBufferInvalid();
Chris Lattner38caec42010-04-20 18:14:03 +000090
Chris Lattnerb088cd32010-11-23 08:50:03 +000091 return Buffer.getPointer();
92 }
Benjamin Kramer5807d9c2010-11-18 12:46:39 +000093
Chris Lattnerb088cd32010-11-23 08:50:03 +000094 std::string ErrorStr;
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +000095 Buffer.setPointer(SM.getFileManager().getBufferForFile(ContentsEntry, &ErrorStr));
Chris Lattnerb088cd32010-11-23 08:50:03 +000096
97 // If we were unable to open the file, then we are in an inconsistent
98 // situation where the content cache referenced a file which no longer
99 // exists. Most likely, we were using a stat cache with an invalid entry but
100 // the file could also have been removed during processing. Since we can't
101 // really deal with this situation, just create an empty buffer.
102 //
103 // FIXME: This is definitely not ideal, but our immediate clients can't
104 // currently handle returning a null entry here. Ideally we should detect
105 // that we are in an inconsistent situation and error out as quickly as
106 // possible.
107 if (!Buffer.getPointer()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000108 const StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000109 Buffer.setPointer(MemoryBuffer::getNewMemBuffer(ContentsEntry->getSize(),
Chris Lattnerb088cd32010-11-23 08:50:03 +0000110 "<invalid>"));
111 char *Ptr = const_cast<char*>(Buffer.getPointer()->getBufferStart());
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000112 for (unsigned i = 0, e = ContentsEntry->getSize(); i != e; ++i)
Chris Lattnerb088cd32010-11-23 08:50:03 +0000113 Ptr[i] = FillStr[i % FillStr.size()];
114
115 if (Diag.isDiagnosticInFlight())
116 Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000117 ContentsEntry->getName(), ErrorStr);
Chris Lattnerb088cd32010-11-23 08:50:03 +0000118 else
119 Diag.Report(Loc, diag::err_cannot_open_file)
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000120 << ContentsEntry->getName() << ErrorStr;
Chris Lattnerb088cd32010-11-23 08:50:03 +0000121
122 Buffer.setInt(Buffer.getInt() | InvalidFlag);
123
124 if (Invalid) *Invalid = true;
125 return Buffer.getPointer();
126 }
127
128 // Check that the file's size is the same as in the file entry (which may
129 // have come from a stat cache).
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000130 if (getRawBuffer()->getBufferSize() != (size_t)ContentsEntry->getSize()) {
Chris Lattnerb088cd32010-11-23 08:50:03 +0000131 if (Diag.isDiagnosticInFlight())
132 Diag.SetDelayedDiagnostic(diag::err_file_modified,
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000133 ContentsEntry->getName());
Chris Lattnerb088cd32010-11-23 08:50:03 +0000134 else
135 Diag.Report(Loc, diag::err_file_modified)
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000136 << ContentsEntry->getName();
Chris Lattnerb088cd32010-11-23 08:50:03 +0000137
138 Buffer.setInt(Buffer.getInt() | InvalidFlag);
139 if (Invalid) *Invalid = true;
140 return Buffer.getPointer();
141 }
Eric Christopher156119d2011-04-09 00:01:04 +0000142
Chris Lattnerb088cd32010-11-23 08:50:03 +0000143 // If the buffer is valid, check to see if it has a UTF Byte Order Mark
Eric Christopher156119d2011-04-09 00:01:04 +0000144 // (BOM). We only support UTF-8 with and without a BOM right now. See
Chris Lattnerb088cd32010-11-23 08:50:03 +0000145 // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000146 StringRef BufStr = Buffer.getPointer()->getBuffer();
Eric Christopher156119d2011-04-09 00:01:04 +0000147 const char *InvalidBOM = llvm::StringSwitch<const char *>(BufStr)
Chris Lattnerb088cd32010-11-23 08:50:03 +0000148 .StartsWith("\xFE\xFF", "UTF-16 (BE)")
149 .StartsWith("\xFF\xFE", "UTF-16 (LE)")
150 .StartsWith("\x00\x00\xFE\xFF", "UTF-32 (BE)")
151 .StartsWith("\xFF\xFE\x00\x00", "UTF-32 (LE)")
152 .StartsWith("\x2B\x2F\x76", "UTF-7")
153 .StartsWith("\xF7\x64\x4C", "UTF-1")
154 .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
155 .StartsWith("\x0E\xFE\xFF", "SDSU")
156 .StartsWith("\xFB\xEE\x28", "BOCU-1")
157 .StartsWith("\x84\x31\x95\x33", "GB-18030")
158 .Default(0);
159
Eric Christopher156119d2011-04-09 00:01:04 +0000160 if (InvalidBOM) {
Chris Lattnerb088cd32010-11-23 08:50:03 +0000161 Diag.Report(Loc, diag::err_unsupported_bom)
Eric Christopher156119d2011-04-09 00:01:04 +0000162 << InvalidBOM << ContentsEntry->getName();
Chris Lattnerb088cd32010-11-23 08:50:03 +0000163 Buffer.setInt(Buffer.getInt() | InvalidFlag);
Ted Kremenek5b034ad2009-01-06 22:43:04 +0000164 }
Douglas Gregoraea67db2010-03-15 22:54:52 +0000165
Douglas Gregorc8151082010-03-16 22:53:51 +0000166 if (Invalid)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000167 *Invalid = isBufferInvalid();
Douglas Gregorc8151082010-03-16 22:53:51 +0000168
169 return Buffer.getPointer();
Ted Kremenekc16c2082009-01-06 01:55:26 +0000170}
171
Chris Lattner5f9e2722011-07-23 10:55:15 +0000172unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000173 // Look up the filename in the string table, returning the pre-existing value
174 // if it exists.
Mike Stump1eb44332009-09-09 15:08:12 +0000175 llvm::StringMapEntry<unsigned> &Entry =
Jay Foad65aa6882011-06-21 15:13:30 +0000176 FilenameIDs.GetOrCreateValue(Name, ~0U);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000177 if (Entry.getValue() != ~0U)
178 return Entry.getValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000179
Chris Lattner5b9a5042009-01-26 07:57:50 +0000180 // Otherwise, assign this the next available ID.
181 Entry.setValue(FilenamesByID.size());
182 FilenamesByID.push_back(&Entry);
183 return FilenamesByID.size()-1;
184}
185
Chris Lattnerac50e342009-02-03 22:13:05 +0000186/// AddLineNote - Add a line note to the line table that indicates that there
187/// is a #line at the specified FID/Offset location which changes the presumed
188/// location to LineNo/FilenameID.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000189void LineTableInfo::AddLineNote(int FID, unsigned Offset,
Chris Lattnerac50e342009-02-03 22:13:05 +0000190 unsigned LineNo, int FilenameID) {
Chris Lattner23b5dc62009-02-04 00:40:31 +0000191 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump1eb44332009-09-09 15:08:12 +0000192
Chris Lattner23b5dc62009-02-04 00:40:31 +0000193 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
194 "Adding line entries out of order!");
Mike Stump1eb44332009-09-09 15:08:12 +0000195
Chris Lattner9d79eba2009-02-04 05:21:58 +0000196 SrcMgr::CharacteristicKind Kind = SrcMgr::C_User;
Chris Lattner137b6a62009-02-04 06:25:26 +0000197 unsigned IncludeOffset = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000198
Chris Lattner9d79eba2009-02-04 05:21:58 +0000199 if (!Entries.empty()) {
200 // If this is a '#line 4' after '#line 42 "foo.h"', make sure to remember
201 // that we are still in "foo.h".
202 if (FilenameID == -1)
203 FilenameID = Entries.back().FilenameID;
Mike Stump1eb44332009-09-09 15:08:12 +0000204
Chris Lattner137b6a62009-02-04 06:25:26 +0000205 // If we are after a line marker that switched us to system header mode, or
206 // that set #include information, preserve it.
Chris Lattner9d79eba2009-02-04 05:21:58 +0000207 Kind = Entries.back().FileKind;
Chris Lattner137b6a62009-02-04 06:25:26 +0000208 IncludeOffset = Entries.back().IncludeOffset;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000209 }
Mike Stump1eb44332009-09-09 15:08:12 +0000210
Chris Lattner137b6a62009-02-04 06:25:26 +0000211 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, Kind,
212 IncludeOffset));
Chris Lattnerac50e342009-02-03 22:13:05 +0000213}
214
Chris Lattner9d79eba2009-02-04 05:21:58 +0000215/// AddLineNote This is the same as the previous version of AddLineNote, but is
216/// used for GNU line markers. If EntryExit is 0, then this doesn't change the
217/// presumed #include stack. If it is 1, this is a file entry, if it is 2 then
218/// this is a file exit. FileKind specifies whether this is a system header or
219/// extern C system header.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000220void LineTableInfo::AddLineNote(int FID, unsigned Offset,
Chris Lattner9d79eba2009-02-04 05:21:58 +0000221 unsigned LineNo, int FilenameID,
222 unsigned EntryExit,
223 SrcMgr::CharacteristicKind FileKind) {
224 assert(FilenameID != -1 && "Unspecified filename should use other accessor");
Mike Stump1eb44332009-09-09 15:08:12 +0000225
Chris Lattner9d79eba2009-02-04 05:21:58 +0000226 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump1eb44332009-09-09 15:08:12 +0000227
Chris Lattner9d79eba2009-02-04 05:21:58 +0000228 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
229 "Adding line entries out of order!");
230
Chris Lattner137b6a62009-02-04 06:25:26 +0000231 unsigned IncludeOffset = 0;
232 if (EntryExit == 0) { // No #include stack change.
233 IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
234 } else if (EntryExit == 1) {
235 IncludeOffset = Offset-1;
236 } else if (EntryExit == 2) {
237 assert(!Entries.empty() && Entries.back().IncludeOffset &&
238 "PPDirectives should have caught case when popping empty include stack");
Mike Stump1eb44332009-09-09 15:08:12 +0000239
Chris Lattner137b6a62009-02-04 06:25:26 +0000240 // Get the include loc of the last entries' include loc as our include loc.
241 IncludeOffset = 0;
242 if (const LineEntry *PrevEntry =
243 FindNearestLineEntry(FID, Entries.back().IncludeOffset))
244 IncludeOffset = PrevEntry->IncludeOffset;
245 }
Mike Stump1eb44332009-09-09 15:08:12 +0000246
Chris Lattner137b6a62009-02-04 06:25:26 +0000247 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
248 IncludeOffset));
Chris Lattner9d79eba2009-02-04 05:21:58 +0000249}
250
251
Chris Lattner3cd949c2009-02-04 01:55:42 +0000252/// FindNearestLineEntry - Find the line entry nearest to FID that is before
253/// it. If there is no line entry before Offset in FID, return null.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000254const LineEntry *LineTableInfo::FindNearestLineEntry(int FID,
Chris Lattner3cd949c2009-02-04 01:55:42 +0000255 unsigned Offset) {
256 const std::vector<LineEntry> &Entries = LineEntries[FID];
257 assert(!Entries.empty() && "No #line entries for this FID after all!");
258
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000259 // It is very common for the query to be after the last #line, check this
260 // first.
261 if (Entries.back().FileOffset <= Offset)
262 return &Entries.back();
Chris Lattner3cd949c2009-02-04 01:55:42 +0000263
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000264 // Do a binary search to find the maximal element that is still before Offset.
265 std::vector<LineEntry>::const_iterator I =
266 std::upper_bound(Entries.begin(), Entries.end(), Offset);
267 if (I == Entries.begin()) return 0;
268 return &*--I;
Chris Lattner3cd949c2009-02-04 01:55:42 +0000269}
Chris Lattnerac50e342009-02-03 22:13:05 +0000270
Douglas Gregorbd945002009-04-13 16:31:14 +0000271/// \brief Add a new line entry that has already been encoded into
272/// the internal representation of the line table.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000273void LineTableInfo::AddEntry(int FID,
Douglas Gregorbd945002009-04-13 16:31:14 +0000274 const std::vector<LineEntry> &Entries) {
275 LineEntries[FID] = Entries;
276}
Chris Lattnerac50e342009-02-03 22:13:05 +0000277
Chris Lattner5b9a5042009-01-26 07:57:50 +0000278/// getLineTableFilenameID - Return the uniqued ID for the specified filename.
Mike Stump1eb44332009-09-09 15:08:12 +0000279///
Chris Lattner5f9e2722011-07-23 10:55:15 +0000280unsigned SourceManager::getLineTableFilenameID(StringRef Name) {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000281 if (LineTable == 0)
282 LineTable = new LineTableInfo();
Jay Foad65aa6882011-06-21 15:13:30 +0000283 return LineTable->getLineTableFilenameID(Name);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000284}
285
286
Chris Lattner4c4ea172009-02-03 21:52:55 +0000287/// AddLineNote - Add a line note to the line table for the FileID and offset
288/// specified by Loc. If FilenameID is -1, it is considered to be
289/// unspecified.
290void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
291 int FilenameID) {
Chris Lattnerac50e342009-02-03 22:13:05 +0000292 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000293
Douglas Gregore23ac652011-04-20 00:21:03 +0000294 bool Invalid = false;
295 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
296 if (!Entry.isFile() || Invalid)
297 return;
298
299 const SrcMgr::FileInfo &FileInfo = Entry.getFile();
Chris Lattnerac50e342009-02-03 22:13:05 +0000300
301 // Remember that this file has #line directives now if it doesn't already.
302 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump1eb44332009-09-09 15:08:12 +0000303
Chris Lattnerac50e342009-02-03 22:13:05 +0000304 if (LineTable == 0)
305 LineTable = new LineTableInfo();
Chris Lattner23b5dc62009-02-04 00:40:31 +0000306 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID);
Chris Lattner4c4ea172009-02-03 21:52:55 +0000307}
308
Chris Lattner9d79eba2009-02-04 05:21:58 +0000309/// AddLineNote - Add a GNU line marker to the line table.
310void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
311 int FilenameID, bool IsFileEntry,
312 bool IsFileExit, bool IsSystemHeader,
313 bool IsExternCHeader) {
314 // If there is no filename and no flags, this is treated just like a #line,
315 // which does not change the flags of the previous line marker.
316 if (FilenameID == -1) {
317 assert(!IsFileEntry && !IsFileExit && !IsSystemHeader && !IsExternCHeader &&
318 "Can't set flags without setting the filename!");
319 return AddLineNote(Loc, LineNo, FilenameID);
320 }
Mike Stump1eb44332009-09-09 15:08:12 +0000321
Chris Lattner9d79eba2009-02-04 05:21:58 +0000322 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Douglas Gregore23ac652011-04-20 00:21:03 +0000323
324 bool Invalid = false;
325 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
326 if (!Entry.isFile() || Invalid)
327 return;
328
329 const SrcMgr::FileInfo &FileInfo = Entry.getFile();
Mike Stump1eb44332009-09-09 15:08:12 +0000330
Chris Lattner9d79eba2009-02-04 05:21:58 +0000331 // Remember that this file has #line directives now if it doesn't already.
332 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump1eb44332009-09-09 15:08:12 +0000333
Chris Lattner9d79eba2009-02-04 05:21:58 +0000334 if (LineTable == 0)
335 LineTable = new LineTableInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000336
Chris Lattner9d79eba2009-02-04 05:21:58 +0000337 SrcMgr::CharacteristicKind FileKind;
338 if (IsExternCHeader)
339 FileKind = SrcMgr::C_ExternCSystem;
340 else if (IsSystemHeader)
341 FileKind = SrcMgr::C_System;
342 else
343 FileKind = SrcMgr::C_User;
Mike Stump1eb44332009-09-09 15:08:12 +0000344
Chris Lattner9d79eba2009-02-04 05:21:58 +0000345 unsigned EntryExit = 0;
346 if (IsFileEntry)
347 EntryExit = 1;
348 else if (IsFileExit)
349 EntryExit = 2;
Mike Stump1eb44332009-09-09 15:08:12 +0000350
Chris Lattner9d79eba2009-02-04 05:21:58 +0000351 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID,
352 EntryExit, FileKind);
353}
354
Douglas Gregorbd945002009-04-13 16:31:14 +0000355LineTableInfo &SourceManager::getLineTable() {
356 if (LineTable == 0)
357 LineTable = new LineTableInfo();
358 return *LineTable;
359}
Chris Lattner4c4ea172009-02-03 21:52:55 +0000360
Chris Lattner23b5dc62009-02-04 00:40:31 +0000361//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000362// Private 'Create' methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000363//===----------------------------------------------------------------------===//
Ted Kremenekc16c2082009-01-06 01:55:26 +0000364
Chris Lattner39b49bc2010-11-23 08:35:12 +0000365SourceManager::SourceManager(Diagnostic &Diag, FileManager &FileMgr)
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +0000366 : Diag(Diag), FileMgr(FileMgr), OverridenFilesKeepOriginalName(true),
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000367 ExternalSLocEntries(0), LineTable(0), NumLinearScans(0),
Douglas Gregore23ac652011-04-20 00:21:03 +0000368 NumBinaryProbes(0), FakeBufferForRecovery(0) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000369 clearIDTables();
370 Diag.setSourceManager(this);
371}
372
Chris Lattner5b9a5042009-01-26 07:57:50 +0000373SourceManager::~SourceManager() {
374 delete LineTable;
Mike Stump1eb44332009-09-09 15:08:12 +0000375
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000376 // Delete FileEntry objects corresponding to content caches. Since the actual
377 // content cache objects are bump pointer allocated, we just have to run the
378 // dtors, but we call the deallocate method for completeness.
379 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
380 MemBufferInfos[i]->~ContentCache();
381 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
382 }
383 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
384 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
385 I->second->~ContentCache();
386 ContentCacheAlloc.Deallocate(I->second);
387 }
Douglas Gregore23ac652011-04-20 00:21:03 +0000388
389 delete FakeBufferForRecovery;
Chris Lattner5b9a5042009-01-26 07:57:50 +0000390}
391
392void SourceManager::clearIDTables() {
393 MainFileID = FileID();
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000394 LocalSLocEntryTable.clear();
395 LoadedSLocEntryTable.clear();
396 SLocEntryLoaded.clear();
Chris Lattner5b9a5042009-01-26 07:57:50 +0000397 LastLineNoFileIDQuery = FileID();
398 LastLineNoContentCache = 0;
399 LastFileIDLookup = FileID();
Mike Stump1eb44332009-09-09 15:08:12 +0000400
Chris Lattner5b9a5042009-01-26 07:57:50 +0000401 if (LineTable)
402 LineTable->clear();
Mike Stump1eb44332009-09-09 15:08:12 +0000403
Chris Lattner5b9a5042009-01-26 07:57:50 +0000404 // Use up FileID #0 as an invalid instantiation.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000405 NextLocalOffset = 0;
406 // The highest possible offset is 2^31-1, so CurrentLoadedOffset starts at
407 // 2^31.
408 CurrentLoadedOffset = 1U << 31U;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000409 createInstantiationLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000410}
411
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000412/// getOrCreateContentCache - Create or return a cached ContentCache for the
413/// specified file.
414const ContentCache *
415SourceManager::getOrCreateContentCache(const FileEntry *FileEnt) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000416 assert(FileEnt && "Didn't specify a file entry to use?");
Mike Stump1eb44332009-09-09 15:08:12 +0000417
Reid Spencer5f016e22007-07-11 17:01:13 +0000418 // Do we already have information about this file?
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000419 ContentCache *&Entry = FileInfos[FileEnt];
420 if (Entry) return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +0000421
Chris Lattner00282d62009-02-03 07:41:46 +0000422 // Nope, create a new Cache entry. Make sure it is at least 8-byte aligned
423 // so that FileInfo can use the low 3 bits of the pointer for its own
424 // nefarious purposes.
425 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
426 EntryAlign = std::max(8U, EntryAlign);
427 Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000428
429 // If the file contents are overridden with contents from another file,
430 // pass that file to ContentCache.
431 llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
432 overI = OverriddenFiles.find(FileEnt);
433 if (overI == OverriddenFiles.end())
434 new (Entry) ContentCache(FileEnt);
435 else
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +0000436 new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt
437 : overI->second,
438 overI->second);
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000439
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000440 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000441}
442
443
Ted Kremenekd1c0eee2007-10-31 17:53:38 +0000444/// createMemBufferContentCache - Create a new ContentCache for the specified
445/// memory buffer. This does no caching.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000446const ContentCache*
447SourceManager::createMemBufferContentCache(const MemoryBuffer *Buffer) {
Chris Lattner00282d62009-02-03 07:41:46 +0000448 // Add a new ContentCache to the MemBufferInfos list and return it. Make sure
449 // it is at least 8-byte aligned so that FileInfo can use the low 3 bits of
450 // the pointer for its own nefarious purposes.
451 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
452 EntryAlign = std::max(8U, EntryAlign);
453 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000454 new (Entry) ContentCache();
455 MemBufferInfos.push_back(Entry);
456 Entry->setBuffer(Buffer);
457 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000458}
459
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000460std::pair<int, unsigned>
461SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries,
462 unsigned TotalSize) {
463 assert(ExternalSLocEntries && "Don't have an external sloc source");
464 LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries);
465 SLocEntryLoaded.resize(LoadedSLocEntryTable.size());
466 CurrentLoadedOffset -= TotalSize;
467 assert(CurrentLoadedOffset >= NextLocalOffset && "Out of source locations");
468 int ID = LoadedSLocEntryTable.size();
469 return std::make_pair(-ID - 1, CurrentLoadedOffset);
Douglas Gregor2bf1eb02009-04-27 21:28:04 +0000470}
471
Douglas Gregore23ac652011-04-20 00:21:03 +0000472/// \brief As part of recovering from missing or changed content, produce a
473/// fake, non-empty buffer.
474const llvm::MemoryBuffer *SourceManager::getFakeBufferForRecovery() const {
475 if (!FakeBufferForRecovery)
476 FakeBufferForRecovery
477 = llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");
478
479 return FakeBufferForRecovery;
480}
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000481
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000482//===----------------------------------------------------------------------===//
483// Methods to create new FileID's and instantiations.
484//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000485
Dan Gohman3f86b782010-08-26 21:27:06 +0000486/// createFileID - Create a new FileID for the specified ContentCache and
Ted Kremenek0d892d82007-10-30 22:57:35 +0000487/// include position. This works regardless of whether the ContentCache
488/// corresponds to a file or some other input source.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000489FileID SourceManager::createFileID(const ContentCache *File,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000490 SourceLocation IncludePos,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000491 SrcMgr::CharacteristicKind FileCharacter,
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000492 int LoadedID, unsigned LoadedOffset) {
493 if (LoadedID < 0) {
494 assert(LoadedID != -1 && "Loading sentinel FileID");
495 unsigned Index = unsigned(-LoadedID) - 2;
496 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
497 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
498 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset,
499 FileInfo::get(IncludePos, File, FileCharacter));
500 SLocEntryLoaded[Index] = true;
501 return FileID::get(LoadedID);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000502 }
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000503 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset,
504 FileInfo::get(IncludePos, File,
505 FileCharacter)));
Ted Kremenekc16c2082009-01-06 01:55:26 +0000506 unsigned FileSize = File->getSize();
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000507 assert(NextLocalOffset + FileSize + 1 > NextLocalOffset &&
508 NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset &&
509 "Ran out of source locations!");
510 // We do a +1 here because we want a SourceLocation that means "the end of the
511 // file", e.g. for the "no newline at the end of the file" diagnostic.
512 NextLocalOffset += FileSize + 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000513
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000514 // Set LastFileIDLookup to the newly created file. The next getFileID call is
515 // almost guaranteed to be from that file.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000516 FileID FID = FileID::get(LocalSLocEntryTable.size()-1);
Argyrios Kyrtzidisea703f12009-06-23 00:42:06 +0000517 return LastFileIDLookup = FID;
Reid Spencer5f016e22007-07-11 17:01:13 +0000518}
519
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000520SourceLocation
521SourceManager::createMacroArgInstantiationLoc(SourceLocation SpellingLoc,
522 SourceLocation ILoc,
523 unsigned TokLength) {
524 InstantiationInfo II =
525 InstantiationInfo::createForMacroArg(SpellingLoc, ILoc);
526 return createInstantiationLocImpl(II, TokLength);
527}
528
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000529SourceLocation SourceManager::createInstantiationLoc(SourceLocation SpellingLoc,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000530 SourceLocation ILocStart,
531 SourceLocation ILocEnd,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000532 unsigned TokLength,
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000533 int LoadedID,
534 unsigned LoadedOffset) {
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000535 InstantiationInfo II =
536 InstantiationInfo::create(SpellingLoc, ILocStart, ILocEnd);
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000537 return createInstantiationLocImpl(II, TokLength, LoadedID, LoadedOffset);
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000538}
539
540SourceLocation
541SourceManager::createInstantiationLocImpl(const InstantiationInfo &II,
542 unsigned TokLength,
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000543 int LoadedID,
544 unsigned LoadedOffset) {
545 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");
550 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, II);
551 SLocEntryLoaded[Index] = true;
552 return SourceLocation::getMacroLoc(LoadedOffset);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000553 }
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000554 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, II));
555 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
640 // behavior: 1) a lot of searched FileID's are "near" the cached file location
641 // or are "near" the cached instantiation location. 2) others are just
642 // 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
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000669 // If this isn't an instantiation, remember it. We have good locality
670 // across FileID lookups.
671 if (!I->isInstantiation())
672 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
710 // If this isn't an instantiation, remember it. We have good locality
711 // across FileID lookups.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000712 if (!LocalSLocEntryTable[MiddleIndex].isInstantiation())
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
748 if (!E.isInstantiation())
749 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);
775 if (!E.isInstantiation())
776 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::
786getInstantiationLocSlowCase(SourceLocation Loc) const {
787 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
790 // this offset when going to the instantiation location. The instatiation
791 // 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.
794 Loc = getSLocEntry(getFileID(Loc)).getInstantiation()
Chris Lattnere7fb4842009-02-15 20:52:18 +0000795 .getInstantiationLocStart();
Chris Lattneraddb7972009-01-26 20:04:19 +0000796 } while (!Loc.isFileID());
797
798 return Loc;
799}
800
801SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
802 do {
803 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
804 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
805 Loc = Loc.getFileLocWithOffset(LocInfo.second);
806 } while (!Loc.isFileID());
807 return Loc;
808}
809
810
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000811std::pair<FileID, unsigned>
Argyrios Kyrtzidis8b86ef02011-07-07 03:40:27 +0000812SourceManager::getDecomposedInstantiationLocSlowCase(
813 const SrcMgr::SLocEntry *E) const {
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000814 // If this is an instantiation record, walk through all the instantiation
815 // points.
816 FileID FID;
817 SourceLocation Loc;
Argyrios Kyrtzidis8b86ef02011-07-07 03:40:27 +0000818 unsigned Offset;
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000819 do {
Chris Lattnere7fb4842009-02-15 20:52:18 +0000820 Loc = E->getInstantiation().getInstantiationLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000821
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000822 FID = getFileID(Loc);
823 E = &getSLocEntry(FID);
Argyrios Kyrtzidis8b86ef02011-07-07 03:40:27 +0000824 Offset = Loc.getOffset()-E->getOffset();
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000825 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000826
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000827 return std::make_pair(FID, Offset);
828}
829
830std::pair<FileID, unsigned>
831SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
832 unsigned Offset) const {
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000833 // If this is an instantiation record, walk through all the instantiation
834 // points.
835 FileID FID;
836 SourceLocation Loc;
837 do {
838 Loc = E->getInstantiation().getSpellingLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000839
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000840 FID = getFileID(Loc);
841 E = &getSLocEntry(FID);
842 Offset += Loc.getOffset()-E->getOffset();
843 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000844
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000845 return std::make_pair(FID, Offset);
846}
847
Chris Lattner387616e2009-02-17 08:04:48 +0000848/// getImmediateSpellingLoc - Given a SourceLocation object, return the
849/// spelling location referenced by the ID. This is the first level down
850/// towards the place where the characters that make up the lexed token can be
851/// found. This should not generally be used by clients.
852SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
853 if (Loc.isFileID()) return Loc;
854 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
855 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
856 return Loc.getFileLocWithOffset(LocInfo.second);
857}
858
859
Chris Lattnere7fb4842009-02-15 20:52:18 +0000860/// getImmediateInstantiationRange - Loc is required to be an instantiation
861/// location. Return the start/end of the instantiation information.
862std::pair<SourceLocation,SourceLocation>
863SourceManager::getImmediateInstantiationRange(SourceLocation Loc) const {
864 assert(Loc.isMacroID() && "Not an instantiation loc!");
865 const InstantiationInfo &II = getSLocEntry(getFileID(Loc)).getInstantiation();
866 return II.getInstantiationLocRange();
867}
868
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000869/// getExpansionRange - Given a SourceLocation object, return the range of
870/// tokens covered by the expansion in the ultimate file.
Chris Lattner66781332009-02-15 21:26:50 +0000871std::pair<SourceLocation,SourceLocation>
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000872SourceManager::getExpansionRange(SourceLocation Loc) const {
Chris Lattner66781332009-02-15 21:26:50 +0000873 if (Loc.isFileID()) return std::make_pair(Loc, Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000874
Chris Lattner66781332009-02-15 21:26:50 +0000875 std::pair<SourceLocation,SourceLocation> Res =
876 getImmediateInstantiationRange(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000877
Chris Lattner66781332009-02-15 21:26:50 +0000878 // Fully resolve the start and end locations to their ultimate instantiation
879 // points.
880 while (!Res.first.isFileID())
881 Res.first = getImmediateInstantiationRange(Res.first).first;
882 while (!Res.second.isFileID())
883 Res.second = getImmediateInstantiationRange(Res.second).second;
884 return Res;
885}
886
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000887bool SourceManager::isMacroArgInstantiation(SourceLocation Loc) const {
888 if (!Loc.isMacroID()) return false;
889
890 FileID FID = getFileID(Loc);
891 const SrcMgr::SLocEntry *E = &getSLocEntry(FID);
892 const SrcMgr::InstantiationInfo &II = E->getInstantiation();
893 return II.isMacroArgInstantiation();
894}
Chris Lattnere7fb4842009-02-15 20:52:18 +0000895
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000896
897//===----------------------------------------------------------------------===//
898// Queries about the code at a SourceLocation.
899//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000900
901/// getCharacterData - Return a pointer to the start of the specified location
902/// in the appropriate MemoryBuffer.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000903const char *SourceManager::getCharacterData(SourceLocation SL,
904 bool *Invalid) const {
Reid Spencer5f016e22007-07-11 17:01:13 +0000905 // Note that this is a hot function in the getSpelling() path, which is
906 // heavily used by -E mode.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000907 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
Mike Stump1eb44332009-09-09 15:08:12 +0000908
Ted Kremenekc16c2082009-01-06 01:55:26 +0000909 // Note that calling 'getBuffer()' may lazily page in a source file.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000910 bool CharDataInvalid = false;
Douglas Gregore23ac652011-04-20 00:21:03 +0000911 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
912 if (CharDataInvalid || !Entry.isFile()) {
913 if (Invalid)
914 *Invalid = true;
915
916 return "<<<<INVALID BUFFER>>>>";
917 }
Douglas Gregor50f6af72010-03-16 05:20:39 +0000918 const llvm::MemoryBuffer *Buffer
Douglas Gregore23ac652011-04-20 00:21:03 +0000919 = Entry.getFile().getContentCache()
920 ->getBuffer(Diag, *this, SourceLocation(), &CharDataInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000921 if (Invalid)
922 *Invalid = CharDataInvalid;
923 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
Reid Spencer5f016e22007-07-11 17:01:13 +0000924}
925
Reid Spencer5f016e22007-07-11 17:01:13 +0000926
Chris Lattner9dc1f532007-07-20 16:37:10 +0000927/// getColumnNumber - Return the column # for the specified file position.
Chris Lattner7da5aea2009-02-04 00:55:58 +0000928/// this is significantly cheaper to compute than the line number.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000929unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
930 bool *Invalid) const {
931 bool MyInvalid = false;
932 const char *Buf = getBuffer(FID, &MyInvalid)->getBufferStart();
933 if (Invalid)
934 *Invalid = MyInvalid;
935
936 if (MyInvalid)
937 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000938
Reid Spencer5f016e22007-07-11 17:01:13 +0000939 unsigned LineStart = FilePos;
940 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
941 --LineStart;
942 return FilePos-LineStart+1;
943}
944
Zhanyong Wan1f24e112010-10-05 17:56:33 +0000945// isInvalid - Return the result of calling loc.isInvalid(), and
946// if Invalid is not null, set its value to same.
947static bool isInvalid(SourceLocation Loc, bool *Invalid) {
948 bool MyInvalid = Loc.isInvalid();
949 if (Invalid)
950 *Invalid = MyInvalid;
951 return MyInvalid;
952}
953
Douglas Gregor50f6af72010-03-16 05:20:39 +0000954unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
955 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +0000956 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +0000957 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000958 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +0000959}
960
Douglas Gregor50f6af72010-03-16 05:20:39 +0000961unsigned SourceManager::getInstantiationColumnNumber(SourceLocation Loc,
962 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +0000963 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +0000964 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000965 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +0000966}
967
Chandler Carruth5ef04ee2011-02-23 00:47:48 +0000968unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
969 bool *Invalid) const {
970 if (isInvalid(Loc, Invalid)) return 0;
971 return getPresumedLoc(Loc).getColumn();
972}
973
Chandler Carruth14bd9652010-10-23 08:44:57 +0000974static LLVM_ATTRIBUTE_NOINLINE void
Chris Lattnere127a0d2010-04-20 20:35:58 +0000975ComputeLineNumbers(Diagnostic &Diag, ContentCache *FI,
976 llvm::BumpPtrAllocator &Alloc,
977 const SourceManager &SM, bool &Invalid);
978static void ComputeLineNumbers(Diagnostic &Diag, ContentCache *FI,
979 llvm::BumpPtrAllocator &Alloc,
980 const SourceManager &SM, bool &Invalid) {
Ted Kremenekc16c2082009-01-06 01:55:26 +0000981 // Note that calling 'getBuffer()' may lazily page in the file.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000982 const MemoryBuffer *Buffer = FI->getBuffer(Diag, SM, SourceLocation(),
983 &Invalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000984 if (Invalid)
985 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000986
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000987 // Find the file offsets of all of the *physical* source lines. This does
988 // not look at trigraphs, escaped newlines, or anything else tricky.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000989 SmallVector<unsigned, 256> LineOffsets;
Mike Stump1eb44332009-09-09 15:08:12 +0000990
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000991 // Line #1 starts at char 0.
992 LineOffsets.push_back(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000993
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000994 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
995 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
996 unsigned Offs = 0;
997 while (1) {
998 // Skip over the contents of the line.
999 // TODO: Vectorize this? This is very performance sensitive for programs
1000 // with lots of diagnostics and in -E mode.
1001 const unsigned char *NextBuf = (const unsigned char *)Buf;
1002 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
1003 ++NextBuf;
1004 Offs += NextBuf-Buf;
1005 Buf = NextBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00001006
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001007 if (Buf[0] == '\n' || Buf[0] == '\r') {
1008 // If this is \n\r or \r\n, skip both characters.
1009 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
1010 ++Offs, ++Buf;
1011 ++Offs, ++Buf;
1012 LineOffsets.push_back(Offs);
1013 } else {
1014 // Otherwise, this is a null. If end of file, exit.
1015 if (Buf == End) break;
1016 // Otherwise, skip the null.
1017 ++Offs, ++Buf;
1018 }
1019 }
Mike Stump1eb44332009-09-09 15:08:12 +00001020
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001021 // Copy the offsets into the FileInfo structure.
1022 FI->NumLines = LineOffsets.size();
Chris Lattner0d0bf8c2009-02-03 07:30:45 +00001023 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001024 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
1025}
Reid Spencer5f016e22007-07-11 17:01:13 +00001026
Chris Lattnerdf7c17a2009-01-16 07:00:02 +00001027/// getLineNumber - Given a SourceLocation, return the spelling line number
Reid Spencer5f016e22007-07-11 17:01:13 +00001028/// for the position indicated. This requires building and caching a table of
1029/// line offsets for the MemoryBuffer, so this is not cheap: use only when
1030/// about to emit a diagnostic.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001031unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
1032 bool *Invalid) const {
Argyrios Kyrtzidis5adc0512011-05-17 22:09:53 +00001033 if (FID.isInvalid()) {
1034 if (Invalid)
1035 *Invalid = true;
1036 return 1;
1037 }
1038
Chris Lattner2b2453a2009-01-17 06:22:33 +00001039 ContentCache *Content;
Chris Lattner30fc9332009-02-04 01:06:56 +00001040 if (LastLineNoFileIDQuery == FID)
Ted Kremenek78d85f52007-10-30 21:08:08 +00001041 Content = LastLineNoContentCache;
Douglas Gregore23ac652011-04-20 00:21:03 +00001042 else {
1043 bool MyInvalid = false;
1044 const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
1045 if (MyInvalid || !Entry.isFile()) {
1046 if (Invalid)
1047 *Invalid = true;
1048 return 1;
1049 }
1050
1051 Content = const_cast<ContentCache*>(Entry.getFile().getContentCache());
1052 }
1053
Reid Spencer5f016e22007-07-11 17:01:13 +00001054 // If this is the first use of line information for this buffer, compute the
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001055 /// SourceLineCache for it on demand.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001056 if (Content->SourceLineCache == 0) {
1057 bool MyInvalid = false;
Chris Lattnere127a0d2010-04-20 20:35:58 +00001058 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001059 if (Invalid)
1060 *Invalid = MyInvalid;
1061 if (MyInvalid)
1062 return 1;
1063 } else if (Invalid)
1064 *Invalid = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001065
1066 // Okay, we know we have a line number table. Do a binary search to find the
1067 // line number that this character position lands on.
Ted Kremenek78d85f52007-10-30 21:08:08 +00001068 unsigned *SourceLineCache = Content->SourceLineCache;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001069 unsigned *SourceLineCacheStart = SourceLineCache;
Ted Kremenek78d85f52007-10-30 21:08:08 +00001070 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
Mike Stump1eb44332009-09-09 15:08:12 +00001071
Chris Lattner30fc9332009-02-04 01:06:56 +00001072 unsigned QueriedFilePos = FilePos+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001073
Daniel Dunbar4106d692009-05-18 17:30:52 +00001074 // FIXME: I would like to be convinced that this code is worth being as
Mike Stump1eb44332009-09-09 15:08:12 +00001075 // complicated as it is, binary search isn't that slow.
Daniel Dunbar4106d692009-05-18 17:30:52 +00001076 //
1077 // If it is worth being optimized, then in my opinion it could be more
1078 // performant, simpler, and more obviously correct by just "galloping" outward
1079 // from the queried file position. In fact, this could be incorporated into a
1080 // generic algorithm such as lower_bound_with_hint.
1081 //
1082 // If someone gives me a test case where this matters, and I will do it! - DWD
1083
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001084 // If the previous query was to the same file, we know both the file pos from
1085 // that query and the line number returned. This allows us to narrow the
1086 // search space from the entire file to something near the match.
Chris Lattner30fc9332009-02-04 01:06:56 +00001087 if (LastLineNoFileIDQuery == FID) {
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001088 if (QueriedFilePos >= LastLineNoFilePos) {
Daniel Dunbar4106d692009-05-18 17:30:52 +00001089 // FIXME: Potential overflow?
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001090 SourceLineCache = SourceLineCache+LastLineNoResult-1;
Mike Stump1eb44332009-09-09 15:08:12 +00001091
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001092 // The query is likely to be nearby the previous one. Here we check to
1093 // see if it is within 5, 10 or 20 lines. It can be far away in cases
1094 // where big comment blocks and vertical whitespace eat up lines but
1095 // contribute no tokens.
1096 if (SourceLineCache+5 < SourceLineCacheEnd) {
1097 if (SourceLineCache[5] > QueriedFilePos)
1098 SourceLineCacheEnd = SourceLineCache+5;
1099 else if (SourceLineCache+10 < SourceLineCacheEnd) {
1100 if (SourceLineCache[10] > QueriedFilePos)
1101 SourceLineCacheEnd = SourceLineCache+10;
1102 else if (SourceLineCache+20 < SourceLineCacheEnd) {
1103 if (SourceLineCache[20] > QueriedFilePos)
1104 SourceLineCacheEnd = SourceLineCache+20;
1105 }
1106 }
1107 }
1108 } else {
Daniel Dunbar4106d692009-05-18 17:30:52 +00001109 if (LastLineNoResult < Content->NumLines)
1110 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001111 }
1112 }
Mike Stump1eb44332009-09-09 15:08:12 +00001113
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001114 // If the spread is large, do a "radix" test as our initial guess, based on
1115 // the assumption that lines average to approximately the same length.
1116 // NOTE: This is currently disabled, as it does not appear to be profitable in
1117 // initial measurements.
1118 if (0 && SourceLineCacheEnd-SourceLineCache > 20) {
Ted Kremenek78d85f52007-10-30 21:08:08 +00001119 unsigned FileLen = Content->SourceLineCache[Content->NumLines-1];
Mike Stump1eb44332009-09-09 15:08:12 +00001120
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001121 // Take a stab at guessing where it is.
Ted Kremenek78d85f52007-10-30 21:08:08 +00001122 unsigned ApproxPos = Content->NumLines*QueriedFilePos / FileLen;
Mike Stump1eb44332009-09-09 15:08:12 +00001123
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001124 // Check for -10 and +10 lines.
1125 unsigned LowerBound = std::max(int(ApproxPos-10), 0);
1126 unsigned UpperBound = std::min(ApproxPos+10, FileLen);
1127
1128 // If the computed lower bound is less than the query location, move it in.
1129 if (SourceLineCache < SourceLineCacheStart+LowerBound &&
1130 SourceLineCacheStart[LowerBound] < QueriedFilePos)
1131 SourceLineCache = SourceLineCacheStart+LowerBound;
Mike Stump1eb44332009-09-09 15:08:12 +00001132
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001133 // If the computed upper bound is greater than the query location, move it.
1134 if (SourceLineCacheEnd > SourceLineCacheStart+UpperBound &&
1135 SourceLineCacheStart[UpperBound] >= QueriedFilePos)
1136 SourceLineCacheEnd = SourceLineCacheStart+UpperBound;
1137 }
Mike Stump1eb44332009-09-09 15:08:12 +00001138
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001139 unsigned *Pos
1140 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001141 unsigned LineNo = Pos-SourceLineCacheStart;
Mike Stump1eb44332009-09-09 15:08:12 +00001142
Chris Lattner30fc9332009-02-04 01:06:56 +00001143 LastLineNoFileIDQuery = FID;
Ted Kremenek78d85f52007-10-30 21:08:08 +00001144 LastLineNoContentCache = Content;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001145 LastLineNoFilePos = QueriedFilePos;
1146 LastLineNoResult = LineNo;
1147 return LineNo;
Reid Spencer5f016e22007-07-11 17:01:13 +00001148}
1149
Chandler Carruth5ef04ee2011-02-23 00:47:48 +00001150unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
1151 bool *Invalid) const {
1152 if (isInvalid(Loc, Invalid)) return 0;
1153 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1154 return getLineNumber(LocInfo.first, LocInfo.second);
1155}
Douglas Gregor50f6af72010-03-16 05:20:39 +00001156unsigned SourceManager::getInstantiationLineNumber(SourceLocation Loc,
1157 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001158 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattner30fc9332009-02-04 01:06:56 +00001159 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
1160 return getLineNumber(LocInfo.first, LocInfo.second);
1161}
Chandler Carruth5ef04ee2011-02-23 00:47:48 +00001162unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
Douglas Gregor50f6af72010-03-16 05:20:39 +00001163 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001164 if (isInvalid(Loc, Invalid)) return 0;
Chandler Carruth5ef04ee2011-02-23 00:47:48 +00001165 return getPresumedLoc(Loc).getLine();
Chris Lattner30fc9332009-02-04 01:06:56 +00001166}
1167
Chris Lattner6b306672009-02-04 05:33:01 +00001168/// getFileCharacteristic - return the file characteristic of the specified
Mike Stump1eb44332009-09-09 15:08:12 +00001169/// source location, indicating whether this is a normal file, a system
Chris Lattner6b306672009-02-04 05:33:01 +00001170/// header, or an "implicit extern C" system header.
1171///
1172/// This state can be modified with flags on GNU linemarker directives like:
1173/// # 4 "foo.h" 3
1174/// which changes all source locations in the current file after that to be
1175/// considered to be from a system header.
Mike Stump1eb44332009-09-09 15:08:12 +00001176SrcMgr::CharacteristicKind
Chris Lattner6b306672009-02-04 05:33:01 +00001177SourceManager::getFileCharacteristic(SourceLocation Loc) const {
1178 assert(!Loc.isInvalid() && "Can't get file characteristic of invalid loc!");
1179 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Douglas Gregore23ac652011-04-20 00:21:03 +00001180 bool Invalid = false;
1181 const SLocEntry &SEntry = getSLocEntry(LocInfo.first, &Invalid);
1182 if (Invalid || !SEntry.isFile())
1183 return C_User;
1184
1185 const SrcMgr::FileInfo &FI = SEntry.getFile();
Chris Lattner6b306672009-02-04 05:33:01 +00001186
1187 // If there are no #line directives in this file, just return the whole-file
1188 // state.
1189 if (!FI.hasLineDirectives())
1190 return FI.getFileCharacteristic();
Mike Stump1eb44332009-09-09 15:08:12 +00001191
Chris Lattner6b306672009-02-04 05:33:01 +00001192 assert(LineTable && "Can't have linetable entries without a LineTable!");
1193 // See if there is a #line directive before the location.
1194 const LineEntry *Entry =
1195 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001196
Chris Lattner6b306672009-02-04 05:33:01 +00001197 // If this is before the first line marker, use the file characteristic.
1198 if (!Entry)
1199 return FI.getFileCharacteristic();
1200
1201 return Entry->FileKind;
1202}
1203
Chris Lattnerbff5c512009-02-17 08:39:06 +00001204/// Return the filename or buffer identifier of the buffer the location is in.
1205/// Note that this name does not respect #line directives. Use getPresumedLoc
1206/// for normal clients.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001207const char *SourceManager::getBufferName(SourceLocation Loc,
1208 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001209 if (isInvalid(Loc, Invalid)) return "<invalid loc>";
Mike Stump1eb44332009-09-09 15:08:12 +00001210
Douglas Gregor50f6af72010-03-16 05:20:39 +00001211 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
Chris Lattnerbff5c512009-02-17 08:39:06 +00001212}
1213
Chris Lattner30fc9332009-02-04 01:06:56 +00001214
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001215/// getPresumedLoc - This method returns the "presumed" location of a
1216/// SourceLocation specifies. A "presumed location" can be modified by #line
1217/// or GNU line marker directives. This provides a view on the data that a
1218/// user should see in diagnostics, for example.
1219///
1220/// Note that a presumed location is always given as the instantiation point
1221/// of an instantiation location, not at the spelling location.
1222PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc) const {
1223 if (Loc.isInvalid()) return PresumedLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001224
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001225 // Presumed locations are always for instantiation points.
Chris Lattner7da5aea2009-02-04 00:55:58 +00001226 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +00001227
Douglas Gregore23ac652011-04-20 00:21:03 +00001228 bool Invalid = false;
1229 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1230 if (Invalid || !Entry.isFile())
1231 return PresumedLoc();
1232
1233 const SrcMgr::FileInfo &FI = Entry.getFile();
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001234 const SrcMgr::ContentCache *C = FI.getContentCache();
Mike Stump1eb44332009-09-09 15:08:12 +00001235
Chris Lattner3cd949c2009-02-04 01:55:42 +00001236 // To get the source name, first consult the FileEntry (if one exists)
1237 // before the MemBuffer as this will avoid unnecessarily paging in the
1238 // MemBuffer.
Chris Lattnere127a0d2010-04-20 20:35:58 +00001239 const char *Filename;
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001240 if (C->OrigEntry)
1241 Filename = C->OrigEntry->getName();
Chris Lattnere127a0d2010-04-20 20:35:58 +00001242 else
1243 Filename = C->getBuffer(Diag, *this)->getBufferIdentifier();
Douglas Gregore23ac652011-04-20 00:21:03 +00001244
Douglas Gregorc417fa02010-11-02 00:39:22 +00001245 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1246 if (Invalid)
1247 return PresumedLoc();
1248 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1249 if (Invalid)
1250 return PresumedLoc();
1251
Chris Lattner3cd949c2009-02-04 01:55:42 +00001252 SourceLocation IncludeLoc = FI.getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001253
Chris Lattner3cd949c2009-02-04 01:55:42 +00001254 // If we have #line directives in this file, update and overwrite the physical
1255 // location info if appropriate.
1256 if (FI.hasLineDirectives()) {
1257 assert(LineTable && "Can't have linetable entries without a LineTable!");
1258 // See if there is a #line directive before this. If so, get it.
1259 if (const LineEntry *Entry =
1260 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second)) {
Chris Lattnerfc391332009-02-04 02:00:59 +00001261 // If the LineEntry indicates a filename, use it.
Chris Lattner3cd949c2009-02-04 01:55:42 +00001262 if (Entry->FilenameID != -1)
1263 Filename = LineTable->getFilename(Entry->FilenameID);
Chris Lattnerfc391332009-02-04 02:00:59 +00001264
1265 // Use the line number specified by the LineEntry. This line number may
1266 // be multiple lines down from the line entry. Add the difference in
1267 // physical line numbers from the query point and the line marker to the
1268 // total.
1269 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1270 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001271
Chris Lattner0e0e5da2009-02-04 02:15:40 +00001272 // Note that column numbers are not molested by line markers.
Mike Stump1eb44332009-09-09 15:08:12 +00001273
Chris Lattner137b6a62009-02-04 06:25:26 +00001274 // Handle virtual #include manipulation.
1275 if (Entry->IncludeOffset) {
1276 IncludeLoc = getLocForStartOfFile(LocInfo.first);
1277 IncludeLoc = IncludeLoc.getFileLocWithOffset(Entry->IncludeOffset);
1278 }
Chris Lattner3cd949c2009-02-04 01:55:42 +00001279 }
1280 }
1281
1282 return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc);
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001283}
1284
1285//===----------------------------------------------------------------------===//
1286// Other miscellaneous methods.
1287//===----------------------------------------------------------------------===//
1288
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001289/// \brief Retrieve the inode for the given file entry, if possible.
1290///
1291/// This routine involves a system call, and therefore should only be used
1292/// in non-performance-critical code.
1293static llvm::Optional<ino_t> getActualFileInode(const FileEntry *File) {
1294 if (!File)
1295 return llvm::Optional<ino_t>();
1296
1297 struct stat StatBuf;
1298 if (::stat(File->getName(), &StatBuf))
1299 return llvm::Optional<ino_t>();
1300
1301 return StatBuf.st_ino;
1302}
1303
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001304/// \brief Get the source location for the given file:line:col triplet.
1305///
1306/// If the source file is included multiple times, the source location will
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001307/// be based upon an arbitrary inclusion.
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001308SourceLocation SourceManager::getLocation(const FileEntry *SourceFile,
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001309 unsigned Line, unsigned Col) {
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001310 assert(SourceFile && "Null source file!");
1311 assert(Line && Col && "Line and column should start from 1!");
1312
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001313 // Find the first file ID that corresponds to the given file.
1314 FileID FirstFID;
Mike Stump1eb44332009-09-09 15:08:12 +00001315
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001316 // First, check the main file ID, since it is common to look for a
1317 // location in the main file.
1318 llvm::Optional<ino_t> SourceFileInode;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001319 llvm::Optional<StringRef> SourceFileName;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001320 if (!MainFileID.isInvalid()) {
Douglas Gregore23ac652011-04-20 00:21:03 +00001321 bool Invalid = false;
1322 const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
1323 if (Invalid)
1324 return SourceLocation();
1325
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001326 if (MainSLoc.isFile()) {
1327 const ContentCache *MainContentCache
1328 = MainSLoc.getFile().getContentCache();
Douglas Gregorb7a18412011-02-11 18:08:15 +00001329 if (!MainContentCache) {
1330 // Can't do anything
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001331 } else if (MainContentCache->OrigEntry == SourceFile) {
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001332 FirstFID = MainFileID;
Douglas Gregorb7a18412011-02-11 18:08:15 +00001333 } else {
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001334 // Fall back: check whether we have the same base name and inode
1335 // as the main file.
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001336 const FileEntry *MainFile = MainContentCache->OrigEntry;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001337 SourceFileName = llvm::sys::path::filename(SourceFile->getName());
1338 if (*SourceFileName == llvm::sys::path::filename(MainFile->getName())) {
1339 SourceFileInode = getActualFileInode(SourceFile);
Douglas Gregor37c02bf2011-02-16 19:09:24 +00001340 if (SourceFileInode) {
1341 if (llvm::Optional<ino_t> MainFileInode
1342 = getActualFileInode(MainFile)) {
1343 if (*SourceFileInode == *MainFileInode) {
1344 FirstFID = MainFileID;
1345 SourceFile = MainFile;
1346 }
1347 }
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001348 }
1349 }
1350 }
1351 }
1352 }
1353
1354 if (FirstFID.isInvalid()) {
1355 // The location we're looking for isn't in the main file; look
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001356 // through all of the local source locations.
1357 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
Douglas Gregore23ac652011-04-20 00:21:03 +00001358 bool Invalid = false;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001359 const SLocEntry &SLoc = getLocalSLocEntry(I, &Invalid);
Douglas Gregore23ac652011-04-20 00:21:03 +00001360 if (Invalid)
1361 return SourceLocation();
1362
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001363 if (SLoc.isFile() &&
1364 SLoc.getFile().getContentCache() &&
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001365 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001366 FirstFID = FileID::get(I);
1367 break;
1368 }
1369 }
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001370 // If that still didn't help, try the modules.
1371 if (FirstFID.isInvalid()) {
1372 for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) {
1373 const SLocEntry &SLoc = getLoadedSLocEntry(I);
1374 if (SLoc.isFile() &&
1375 SLoc.getFile().getContentCache() &&
1376 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
1377 FirstFID = FileID::get(-int(I) - 2);
1378 break;
1379 }
1380 }
1381 }
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001382 }
1383
1384 // If we haven't found what we want yet, try again, but this time stat()
1385 // each of the files in case the files have changed since we originally
1386 // parsed the file.
1387 if (FirstFID.isInvalid() &&
1388 (SourceFileName ||
1389 (SourceFileName = llvm::sys::path::filename(SourceFile->getName()))) &&
1390 (SourceFileInode ||
1391 (SourceFileInode = getActualFileInode(SourceFile)))) {
Douglas Gregore23ac652011-04-20 00:21:03 +00001392 bool Invalid = false;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001393 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1394 FileID IFileID;
1395 IFileID.ID = I;
1396 const SLocEntry &SLoc = getSLocEntry(IFileID, &Invalid);
Douglas Gregore23ac652011-04-20 00:21:03 +00001397 if (Invalid)
1398 return SourceLocation();
1399
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001400 if (SLoc.isFile()) {
1401 const ContentCache *FileContentCache
1402 = SLoc.getFile().getContentCache();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001403 const FileEntry *Entry =FileContentCache? FileContentCache->OrigEntry : 0;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001404 if (Entry &&
Douglas Gregorb7a18412011-02-11 18:08:15 +00001405 *SourceFileName == llvm::sys::path::filename(Entry->getName())) {
1406 if (llvm::Optional<ino_t> EntryInode = getActualFileInode(Entry)) {
1407 if (*SourceFileInode == *EntryInode) {
1408 FirstFID = FileID::get(I);
1409 SourceFile = Entry;
1410 break;
1411 }
1412 }
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001413 }
1414 }
1415 }
1416 }
1417
1418 if (FirstFID.isInvalid())
1419 return SourceLocation();
1420
1421 if (Line == 1 && Col == 1)
1422 return getLocForStartOfFile(FirstFID);
1423
1424 ContentCache *Content
1425 = const_cast<ContentCache *>(getOrCreateContentCache(SourceFile));
1426 if (!Content)
1427 return SourceLocation();
1428
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001429 // If this is the first use of line information for this buffer, compute the
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001430 // SourceLineCache for it on demand.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001431 if (Content->SourceLineCache == 0) {
1432 bool MyInvalid = false;
Chris Lattnere127a0d2010-04-20 20:35:58 +00001433 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001434 if (MyInvalid)
1435 return SourceLocation();
1436 }
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001437
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001438 if (Line > Content->NumLines) {
Chris Lattnere127a0d2010-04-20 20:35:58 +00001439 unsigned Size = Content->getBuffer(Diag, *this)->getBufferSize();
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001440 if (Size > 0)
1441 --Size;
1442 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(Size);
1443 }
1444
1445 unsigned FilePos = Content->SourceLineCache[Line - 1];
Chris Lattnere127a0d2010-04-20 20:35:58 +00001446 const char *Buf = Content->getBuffer(Diag, *this)->getBufferStart() + FilePos;
1447 unsigned BufLength = Content->getBuffer(Diag, *this)->getBufferEnd() - Buf;
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001448 unsigned i = 0;
1449
1450 // Check that the given column is valid.
1451 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1452 ++i;
1453 if (i < Col-1)
1454 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + i);
1455
Douglas Gregor4a160e12009-12-02 05:34:39 +00001456 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + Col - 1);
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001457}
1458
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001459/// Given a decomposed source location, move it up the include/instantiation
1460/// stack to the parent source location. If this is possible, return the
1461/// decomposed version of the parent in Loc and return false. If Loc is the
1462/// top-level entry, return true and don't modify it.
1463static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1464 const SourceManager &SM) {
1465 SourceLocation UpperLoc;
1466 const SrcMgr::SLocEntry &Entry = SM.getSLocEntry(Loc.first);
1467 if (Entry.isInstantiation())
1468 UpperLoc = Entry.getInstantiation().getInstantiationLocStart();
1469 else
1470 UpperLoc = Entry.getFile().getIncludeLoc();
1471
1472 if (UpperLoc.isInvalid())
1473 return true; // We reached the top.
1474
1475 Loc = SM.getDecomposedLoc(UpperLoc);
1476 return false;
1477}
1478
1479
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001480/// \brief Determines the order of 2 source locations in the translation unit.
1481///
1482/// \returns true if LHS source location comes before RHS, false otherwise.
1483bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
1484 SourceLocation RHS) const {
1485 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
1486 if (LHS == RHS)
1487 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001488
Argyrios Kyrtzidisee933e12010-12-24 02:53:53 +00001489 // If both locations are macro instantiations, the order of their offsets
1490 // reflect the order that the tokens, pointed to by these locations, were
1491 // instantiated (during parsing each token that is instantiated by a macro,
1492 // expands the SLocEntries).
Argyrios Kyrtzidisee933e12010-12-24 02:53:53 +00001493
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001494 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
1495 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00001496
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001497 // If the source locations are in the same file, just compare offsets.
1498 if (LOffs.first == ROffs.first)
1499 return LOffs.second < ROffs.second;
1500
1501 // If we are comparing a source location with multiple locations in the same
1502 // file, we get a big win by caching the result.
Chris Lattner66a915f2010-05-07 05:10:46 +00001503 if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
1504 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001505
Chris Lattnerdcb1d682010-05-07 01:17:07 +00001506 // Okay, we missed in the cache, start updating the cache for this query.
1507 IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first);
Mike Stump1eb44332009-09-09 15:08:12 +00001508
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001509 // We need to find the common ancestor. The only way of doing this is to
1510 // build the complete include chain for one and then walking up the chain
1511 // of the other looking for a match.
1512 // We use a map from FileID to Offset to store the chain. Easier than writing
1513 // a custom set hash info that only depends on the first part of a pair.
1514 typedef llvm::DenseMap<FileID, unsigned> LocSet;
1515 LocSet LChain;
Chris Lattner48296ba2010-05-07 05:51:13 +00001516 do {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001517 LChain.insert(LOffs);
1518 // We catch the case where LOffs is in a file included by ROffs and
1519 // quit early. The other way round unfortunately remains suboptimal.
1520 } while (LOffs.first != ROffs.first && !MoveUpIncludeHierarchy(LOffs, *this));
1521 LocSet::iterator I;
1522 while((I = LChain.find(ROffs.first)) == LChain.end()) {
1523 if (MoveUpIncludeHierarchy(ROffs, *this))
1524 break; // Met at topmost file.
1525 }
1526 if (I != LChain.end())
1527 LOffs = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001528
Chris Lattner48296ba2010-05-07 05:51:13 +00001529 // If we exited because we found a nearest common ancestor, compare the
1530 // locations within the common file and cache them.
1531 if (LOffs.first == ROffs.first) {
1532 IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
1533 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001534 }
Mike Stump1eb44332009-09-09 15:08:12 +00001535
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001536 // This can happen if a location is in a built-ins buffer.
1537 // But see PR5662.
1538 // Clear the lookup cache, it depends on a common location.
1539 IsBeforeInTUCache.setQueryFIDs(FileID(), FileID());
1540 bool LIsBuiltins = strcmp("<built-in>",
1541 getBuffer(LOffs.first)->getBufferIdentifier()) == 0;
1542 bool RIsBuiltins = strcmp("<built-in>",
1543 getBuffer(ROffs.first)->getBufferIdentifier()) == 0;
1544 // built-in is before non-built-in
1545 if (LIsBuiltins != RIsBuiltins)
1546 return LIsBuiltins;
1547 assert(LIsBuiltins && RIsBuiltins &&
1548 "Non-built-in locations must be rooted in the main file");
1549 // Both are in built-in buffers, but from different files. We just claim that
1550 // lower IDs come first.
Chris Lattnerdcb1d682010-05-07 01:17:07 +00001551 return LOffs.first < ROffs.first;
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001552}
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001553
Reid Spencer5f016e22007-07-11 17:01:13 +00001554/// PrintStats - Print statistics to stderr.
1555///
1556void SourceManager::PrintStats() const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001557 llvm::errs() << "\n*** Source Manager Stats:\n";
1558 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
1559 << " mem buffers mapped.\n";
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001560 llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntry's allocated ("
1561 << LocalSLocEntryTable.capacity()*sizeof(SrcMgr::SLocEntry)
Argyrios Kyrtzidisd410e742011-07-07 03:40:24 +00001562 << " bytes of capacity), "
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001563 << NextLocalOffset << "B of Sloc address space used.\n";
1564 llvm::errs() << LoadedSLocEntryTable.size()
1565 << " loaded SLocEntries allocated, "
1566 << (1U << 31U) - CurrentLoadedOffset
1567 << "B of Sloc address space used.\n";
1568
Reid Spencer5f016e22007-07-11 17:01:13 +00001569 unsigned NumLineNumsComputed = 0;
1570 unsigned NumFileBytesMapped = 0;
Chris Lattner0d0bf8c2009-02-03 07:30:45 +00001571 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
1572 NumLineNumsComputed += I->second->SourceLineCache != 0;
1573 NumFileBytesMapped += I->second->getSizeBytesMapped();
Reid Spencer5f016e22007-07-11 17:01:13 +00001574 }
Mike Stump1eb44332009-09-09 15:08:12 +00001575
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001576 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
1577 << NumLineNumsComputed << " files with line #'s computed.\n";
1578 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
1579 << NumBinaryProbes << " binary.\n";
Reid Spencer5f016e22007-07-11 17:01:13 +00001580}
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001581
1582ExternalSLocEntrySource::~ExternalSLocEntrySource() { }
Ted Kremenekf61b8312011-04-28 20:36:42 +00001583
1584/// Return the amount of memory used by memory buffers, breaking down
1585/// by heap-backed versus mmap'ed memory.
1586SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
1587 size_t malloc_bytes = 0;
1588 size_t mmap_bytes = 0;
1589
1590 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)
1591 if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
1592 switch (MemBufferInfos[i]->getMemoryBufferKind()) {
1593 case llvm::MemoryBuffer::MemoryBuffer_MMap:
1594 mmap_bytes += sized_mapped;
1595 break;
1596 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
1597 malloc_bytes += sized_mapped;
1598 break;
1599 }
1600
1601 return MemoryBufferSizes(malloc_bytes, mmap_bytes);
1602}
1603