blob: bf2c8be467957114f4a649130d9e3ebfd6f7010a [file] [log] [blame]
Chris Lattner22eb9722006-06-18 05:43:12 +00001//===--- SourceManager.cpp - Track and cache source files -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner22eb9722006-06-18 05:43:12 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the SourceManager interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Basic/SourceManager.h"
Douglas Gregora07ebc52009-04-13 15:31:25 +000015#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregor802b7762010-03-15 22:54:52 +000016#include "clang/Basic/Diagnostic.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000017#include "clang/Basic/FileManager.h"
Benjamin Kramer5a3f1cf2010-11-18 12:46:39 +000018#include "llvm/ADT/StringSwitch.h"
Douglas Gregore6642762011-02-03 17:17:35 +000019#include "llvm/ADT/Optional.h"
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +000020#include "llvm/ADT/STLExtras.h"
Chris Lattner8996fff2007-07-24 05:57:19 +000021#include "llvm/Support/Compiler.h"
Chris Lattner739e7392007-04-29 07:12:06 +000022#include "llvm/Support/MemoryBuffer.h"
Chris Lattner3441b4f2009-08-23 22:45:33 +000023#include "llvm/Support/raw_ostream.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000024#include "llvm/Support/Path.h"
Ted Kremenek43e0c4a2011-07-27 18:41:16 +000025#include "llvm/Support/Capacity.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000026#include <algorithm>
Douglas Gregor802b7762010-03-15 22:54:52 +000027#include <string>
Douglas Gregore0fbb832010-03-16 00:06:06 +000028#include <cstring>
Douglas Gregore6642762011-02-03 17:17:35 +000029#include <sys/stat.h>
Douglas Gregor802b7762010-03-15 22:54:52 +000030
Chris Lattner22eb9722006-06-18 05:43:12 +000031using namespace clang;
Chris Lattner5f4b1ff2006-06-20 05:02:40 +000032using namespace SrcMgr;
Chris Lattner23b7eb62007-06-15 23:05:46 +000033using llvm::MemoryBuffer;
Chris Lattner22eb9722006-06-18 05:43:12 +000034
Chris Lattner153a0f12009-02-04 00:40:31 +000035//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +000036// SourceManager Helper Classes
Chris Lattner153a0f12009-02-04 00:40:31 +000037//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +000038
Ted Kremenekc08bca62007-10-30 21:08:08 +000039ContentCache::~ContentCache() {
Douglas Gregor3f4bea02010-07-26 21:36:20 +000040 if (shouldFreeBuffer())
41 delete Buffer.getPointer();
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +000042 delete MacroArgsCache;
Chris Lattner22eb9722006-06-18 05:43:12 +000043}
44
Chandler Carruth64ee7822011-07-26 05:17:23 +000045/// getSizeBytesMapped - Returns the number of bytes actually mapped for this
46/// ContentCache. This can be 0 if the MemBuffer was not actually expanded.
Ted Kremenek12c2af42009-01-06 01:55:26 +000047unsigned ContentCache::getSizeBytesMapped() const {
Douglas Gregor82752ec2010-03-16 22:53:51 +000048 return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 0;
Ted Kremenek12c2af42009-01-06 01:55:26 +000049}
50
Ted Kremenek8d587902011-04-28 20:36:42 +000051/// Returns the kind of memory used to back the memory buffer for
52/// this content cache. This is used for performance analysis.
53llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const {
54 assert(Buffer.getPointer());
55
56 // Should be unreachable, but keep for sanity.
57 if (!Buffer.getPointer())
58 return llvm::MemoryBuffer::MemoryBuffer_Malloc;
59
60 const llvm::MemoryBuffer *buf = Buffer.getPointer();
61 return buf->getBufferKind();
62}
63
Ted Kremenek12c2af42009-01-06 01:55:26 +000064/// getSize - Returns the size of the content encapsulated by this ContentCache.
65/// This can be the size of the source file or the size of an arbitrary
66/// scratch buffer. If the ContentCache encapsulates a source file, that
Douglas Gregor53ad6b92009-12-02 06:49:09 +000067/// file is not lazily brought in from disk to satisfy this query.
Ted Kremenek12c2af42009-01-06 01:55:26 +000068unsigned ContentCache::getSize() const {
Douglas Gregor82752ec2010-03-16 22:53:51 +000069 return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize()
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +000070 : (unsigned) ContentsEntry->getSize();
Ted Kremenek12c2af42009-01-06 01:55:26 +000071}
72
Douglas Gregor3f4bea02010-07-26 21:36:20 +000073void ContentCache::replaceBuffer(const llvm::MemoryBuffer *B,
74 bool DoNotFree) {
Douglas Gregor82752ec2010-03-16 22:53:51 +000075 assert(B != Buffer.getPointer());
Douglas Gregor53ad6b92009-12-02 06:49:09 +000076
Douglas Gregor3f4bea02010-07-26 21:36:20 +000077 if (shouldFreeBuffer())
78 delete Buffer.getPointer();
Douglas Gregor82752ec2010-03-16 22:53:51 +000079 Buffer.setPointer(B);
Douglas Gregor3f4bea02010-07-26 21:36:20 +000080 Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
Douglas Gregor53ad6b92009-12-02 06:49:09 +000081}
82
Douglas Gregor874cc622010-03-16 00:35:39 +000083const llvm::MemoryBuffer *ContentCache::getBuffer(Diagnostic &Diag,
Chris Lattner8f5bc9f2010-04-20 20:49:23 +000084 const SourceManager &SM,
Chris Lattnerfb24a3a2010-04-20 20:35:58 +000085 SourceLocation Loc,
Douglas Gregor874cc622010-03-16 00:35:39 +000086 bool *Invalid) const {
Chris Lattner5631b052010-11-23 08:50:03 +000087 // Lazily create the Buffer for ContentCaches that wrap files. If we already
Chris Lattner57540c52011-04-15 05:22:18 +000088 // computed it, just return what we have.
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +000089 if (Buffer.getPointer() || ContentsEntry == 0) {
Chris Lattner5631b052010-11-23 08:50:03 +000090 if (Invalid)
91 *Invalid = isBufferInvalid();
Chris Lattner8fbe98b2010-04-20 18:14:03 +000092
Chris Lattner5631b052010-11-23 08:50:03 +000093 return Buffer.getPointer();
94 }
Benjamin Kramer5a3f1cf2010-11-18 12:46:39 +000095
Chris Lattner5631b052010-11-23 08:50:03 +000096 std::string ErrorStr;
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +000097 Buffer.setPointer(SM.getFileManager().getBufferForFile(ContentsEntry, &ErrorStr));
Chris Lattner5631b052010-11-23 08:50:03 +000098
99 // If we were unable to open the file, then we are in an inconsistent
100 // situation where the content cache referenced a file which no longer
101 // exists. Most likely, we were using a stat cache with an invalid entry but
102 // the file could also have been removed during processing. Since we can't
103 // really deal with this situation, just create an empty buffer.
104 //
105 // FIXME: This is definitely not ideal, but our immediate clients can't
106 // currently handle returning a null entry here. Ideally we should detect
107 // that we are in an inconsistent situation and error out as quickly as
108 // possible.
109 if (!Buffer.getPointer()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000110 const StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000111 Buffer.setPointer(MemoryBuffer::getNewMemBuffer(ContentsEntry->getSize(),
Chris Lattner5631b052010-11-23 08:50:03 +0000112 "<invalid>"));
113 char *Ptr = const_cast<char*>(Buffer.getPointer()->getBufferStart());
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000114 for (unsigned i = 0, e = ContentsEntry->getSize(); i != e; ++i)
Chris Lattner5631b052010-11-23 08:50:03 +0000115 Ptr[i] = FillStr[i % FillStr.size()];
116
117 if (Diag.isDiagnosticInFlight())
118 Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000119 ContentsEntry->getName(), ErrorStr);
Chris Lattner5631b052010-11-23 08:50:03 +0000120 else
121 Diag.Report(Loc, diag::err_cannot_open_file)
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000122 << ContentsEntry->getName() << ErrorStr;
Chris Lattner5631b052010-11-23 08:50:03 +0000123
124 Buffer.setInt(Buffer.getInt() | InvalidFlag);
125
126 if (Invalid) *Invalid = true;
127 return Buffer.getPointer();
128 }
129
130 // Check that the file's size is the same as in the file entry (which may
131 // have come from a stat cache).
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000132 if (getRawBuffer()->getBufferSize() != (size_t)ContentsEntry->getSize()) {
Chris Lattner5631b052010-11-23 08:50:03 +0000133 if (Diag.isDiagnosticInFlight())
134 Diag.SetDelayedDiagnostic(diag::err_file_modified,
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000135 ContentsEntry->getName());
Chris Lattner5631b052010-11-23 08:50:03 +0000136 else
137 Diag.Report(Loc, diag::err_file_modified)
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000138 << ContentsEntry->getName();
Chris Lattner5631b052010-11-23 08:50:03 +0000139
140 Buffer.setInt(Buffer.getInt() | InvalidFlag);
141 if (Invalid) *Invalid = true;
142 return Buffer.getPointer();
143 }
Eric Christopher7f36a792011-04-09 00:01:04 +0000144
Chris Lattner5631b052010-11-23 08:50:03 +0000145 // If the buffer is valid, check to see if it has a UTF Byte Order Mark
Eric Christopher7f36a792011-04-09 00:01:04 +0000146 // (BOM). We only support UTF-8 with and without a BOM right now. See
Chris Lattner5631b052010-11-23 08:50:03 +0000147 // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000148 StringRef BufStr = Buffer.getPointer()->getBuffer();
Eric Christopher7f36a792011-04-09 00:01:04 +0000149 const char *InvalidBOM = llvm::StringSwitch<const char *>(BufStr)
Chris Lattner5631b052010-11-23 08:50:03 +0000150 .StartsWith("\xFE\xFF", "UTF-16 (BE)")
151 .StartsWith("\xFF\xFE", "UTF-16 (LE)")
152 .StartsWith("\x00\x00\xFE\xFF", "UTF-32 (BE)")
153 .StartsWith("\xFF\xFE\x00\x00", "UTF-32 (LE)")
154 .StartsWith("\x2B\x2F\x76", "UTF-7")
155 .StartsWith("\xF7\x64\x4C", "UTF-1")
156 .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
157 .StartsWith("\x0E\xFE\xFF", "SDSU")
158 .StartsWith("\xFB\xEE\x28", "BOCU-1")
159 .StartsWith("\x84\x31\x95\x33", "GB-18030")
160 .Default(0);
161
Eric Christopher7f36a792011-04-09 00:01:04 +0000162 if (InvalidBOM) {
Chris Lattner5631b052010-11-23 08:50:03 +0000163 Diag.Report(Loc, diag::err_unsupported_bom)
Eric Christopher7f36a792011-04-09 00:01:04 +0000164 << InvalidBOM << ContentsEntry->getName();
Chris Lattner5631b052010-11-23 08:50:03 +0000165 Buffer.setInt(Buffer.getInt() | InvalidFlag);
Ted Kremenek763ea552009-01-06 22:43:04 +0000166 }
Douglas Gregor802b7762010-03-15 22:54:52 +0000167
Douglas Gregor82752ec2010-03-16 22:53:51 +0000168 if (Invalid)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000169 *Invalid = isBufferInvalid();
Douglas Gregor82752ec2010-03-16 22:53:51 +0000170
171 return Buffer.getPointer();
Ted Kremenek12c2af42009-01-06 01:55:26 +0000172}
173
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000174unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000175 // Look up the filename in the string table, returning the pre-existing value
176 // if it exists.
Mike Stump11289f42009-09-09 15:08:12 +0000177 llvm::StringMapEntry<unsigned> &Entry =
Jay Foad9a6b0982011-06-21 15:13:30 +0000178 FilenameIDs.GetOrCreateValue(Name, ~0U);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000179 if (Entry.getValue() != ~0U)
180 return Entry.getValue();
Mike Stump11289f42009-09-09 15:08:12 +0000181
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000182 // Otherwise, assign this the next available ID.
183 Entry.setValue(FilenamesByID.size());
184 FilenamesByID.push_back(&Entry);
185 return FilenamesByID.size()-1;
186}
187
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000188/// AddLineNote - Add a line note to the line table that indicates that there
189/// is a #line at the specified FID/Offset location which changes the presumed
190/// location to LineNo/FilenameID.
Douglas Gregor925296b2011-07-19 16:10:42 +0000191void LineTableInfo::AddLineNote(int FID, unsigned Offset,
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000192 unsigned LineNo, int FilenameID) {
Chris Lattner153a0f12009-02-04 00:40:31 +0000193 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump11289f42009-09-09 15:08:12 +0000194
Chris Lattner153a0f12009-02-04 00:40:31 +0000195 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
196 "Adding line entries out of order!");
Mike Stump11289f42009-09-09 15:08:12 +0000197
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000198 SrcMgr::CharacteristicKind Kind = SrcMgr::C_User;
Chris Lattner1c967782009-02-04 06:25:26 +0000199 unsigned IncludeOffset = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000200
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000201 if (!Entries.empty()) {
202 // If this is a '#line 4' after '#line 42 "foo.h"', make sure to remember
203 // that we are still in "foo.h".
204 if (FilenameID == -1)
205 FilenameID = Entries.back().FilenameID;
Mike Stump11289f42009-09-09 15:08:12 +0000206
Chris Lattner1c967782009-02-04 06:25:26 +0000207 // If we are after a line marker that switched us to system header mode, or
208 // that set #include information, preserve it.
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000209 Kind = Entries.back().FileKind;
Chris Lattner1c967782009-02-04 06:25:26 +0000210 IncludeOffset = Entries.back().IncludeOffset;
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000211 }
Mike Stump11289f42009-09-09 15:08:12 +0000212
Chris Lattner1c967782009-02-04 06:25:26 +0000213 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, Kind,
214 IncludeOffset));
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000215}
216
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000217/// AddLineNote This is the same as the previous version of AddLineNote, but is
218/// used for GNU line markers. If EntryExit is 0, then this doesn't change the
219/// presumed #include stack. If it is 1, this is a file entry, if it is 2 then
220/// this is a file exit. FileKind specifies whether this is a system header or
221/// extern C system header.
Douglas Gregor925296b2011-07-19 16:10:42 +0000222void LineTableInfo::AddLineNote(int FID, unsigned Offset,
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000223 unsigned LineNo, int FilenameID,
224 unsigned EntryExit,
225 SrcMgr::CharacteristicKind FileKind) {
226 assert(FilenameID != -1 && "Unspecified filename should use other accessor");
Mike Stump11289f42009-09-09 15:08:12 +0000227
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000228 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump11289f42009-09-09 15:08:12 +0000229
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000230 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
231 "Adding line entries out of order!");
232
Chris Lattner1c967782009-02-04 06:25:26 +0000233 unsigned IncludeOffset = 0;
234 if (EntryExit == 0) { // No #include stack change.
235 IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
236 } else if (EntryExit == 1) {
237 IncludeOffset = Offset-1;
238 } else if (EntryExit == 2) {
239 assert(!Entries.empty() && Entries.back().IncludeOffset &&
240 "PPDirectives should have caught case when popping empty include stack");
Mike Stump11289f42009-09-09 15:08:12 +0000241
Chris Lattner1c967782009-02-04 06:25:26 +0000242 // Get the include loc of the last entries' include loc as our include loc.
243 IncludeOffset = 0;
244 if (const LineEntry *PrevEntry =
245 FindNearestLineEntry(FID, Entries.back().IncludeOffset))
246 IncludeOffset = PrevEntry->IncludeOffset;
247 }
Mike Stump11289f42009-09-09 15:08:12 +0000248
Chris Lattner1c967782009-02-04 06:25:26 +0000249 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
250 IncludeOffset));
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000251}
252
253
Chris Lattnerd4293922009-02-04 01:55:42 +0000254/// FindNearestLineEntry - Find the line entry nearest to FID that is before
255/// it. If there is no line entry before Offset in FID, return null.
Douglas Gregor925296b2011-07-19 16:10:42 +0000256const LineEntry *LineTableInfo::FindNearestLineEntry(int FID,
Chris Lattnerd4293922009-02-04 01:55:42 +0000257 unsigned Offset) {
258 const std::vector<LineEntry> &Entries = LineEntries[FID];
259 assert(!Entries.empty() && "No #line entries for this FID after all!");
260
Chris Lattner334a2ad2009-02-04 04:46:59 +0000261 // It is very common for the query to be after the last #line, check this
262 // first.
263 if (Entries.back().FileOffset <= Offset)
264 return &Entries.back();
Chris Lattnerd4293922009-02-04 01:55:42 +0000265
Chris Lattner334a2ad2009-02-04 04:46:59 +0000266 // Do a binary search to find the maximal element that is still before Offset.
267 std::vector<LineEntry>::const_iterator I =
268 std::upper_bound(Entries.begin(), Entries.end(), Offset);
269 if (I == Entries.begin()) return 0;
270 return &*--I;
Chris Lattnerd4293922009-02-04 01:55:42 +0000271}
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000272
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000273/// \brief Add a new line entry that has already been encoded into
274/// the internal representation of the line table.
Douglas Gregor925296b2011-07-19 16:10:42 +0000275void LineTableInfo::AddEntry(int FID,
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000276 const std::vector<LineEntry> &Entries) {
277 LineEntries[FID] = Entries;
278}
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000279
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000280/// getLineTableFilenameID - Return the uniqued ID for the specified filename.
Mike Stump11289f42009-09-09 15:08:12 +0000281///
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000282unsigned SourceManager::getLineTableFilenameID(StringRef Name) {
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000283 if (LineTable == 0)
284 LineTable = new LineTableInfo();
Jay Foad9a6b0982011-06-21 15:13:30 +0000285 return LineTable->getLineTableFilenameID(Name);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000286}
287
288
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000289/// AddLineNote - Add a line note to the line table for the FileID and offset
290/// specified by Loc. If FilenameID is -1, it is considered to be
291/// unspecified.
292void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
293 int FilenameID) {
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000294 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000295
Douglas Gregor49f754f2011-04-20 00:21:03 +0000296 bool Invalid = false;
297 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
298 if (!Entry.isFile() || Invalid)
299 return;
300
301 const SrcMgr::FileInfo &FileInfo = Entry.getFile();
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000302
303 // Remember that this file has #line directives now if it doesn't already.
304 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump11289f42009-09-09 15:08:12 +0000305
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000306 if (LineTable == 0)
307 LineTable = new LineTableInfo();
Chris Lattner153a0f12009-02-04 00:40:31 +0000308 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID);
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000309}
310
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000311/// AddLineNote - Add a GNU line marker to the line table.
312void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
313 int FilenameID, bool IsFileEntry,
314 bool IsFileExit, bool IsSystemHeader,
315 bool IsExternCHeader) {
316 // If there is no filename and no flags, this is treated just like a #line,
317 // which does not change the flags of the previous line marker.
318 if (FilenameID == -1) {
319 assert(!IsFileEntry && !IsFileExit && !IsSystemHeader && !IsExternCHeader &&
320 "Can't set flags without setting the filename!");
321 return AddLineNote(Loc, LineNo, FilenameID);
322 }
Mike Stump11289f42009-09-09 15:08:12 +0000323
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000324 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Douglas Gregor49f754f2011-04-20 00:21:03 +0000325
326 bool Invalid = false;
327 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
328 if (!Entry.isFile() || Invalid)
329 return;
330
331 const SrcMgr::FileInfo &FileInfo = Entry.getFile();
Mike Stump11289f42009-09-09 15:08:12 +0000332
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000333 // Remember that this file has #line directives now if it doesn't already.
334 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump11289f42009-09-09 15:08:12 +0000335
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000336 if (LineTable == 0)
337 LineTable = new LineTableInfo();
Mike Stump11289f42009-09-09 15:08:12 +0000338
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000339 SrcMgr::CharacteristicKind FileKind;
340 if (IsExternCHeader)
341 FileKind = SrcMgr::C_ExternCSystem;
342 else if (IsSystemHeader)
343 FileKind = SrcMgr::C_System;
344 else
345 FileKind = SrcMgr::C_User;
Mike Stump11289f42009-09-09 15:08:12 +0000346
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000347 unsigned EntryExit = 0;
348 if (IsFileEntry)
349 EntryExit = 1;
350 else if (IsFileExit)
351 EntryExit = 2;
Mike Stump11289f42009-09-09 15:08:12 +0000352
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000353 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID,
354 EntryExit, FileKind);
355}
356
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000357LineTableInfo &SourceManager::getLineTable() {
358 if (LineTable == 0)
359 LineTable = new LineTableInfo();
360 return *LineTable;
361}
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000362
Chris Lattner153a0f12009-02-04 00:40:31 +0000363//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +0000364// Private 'Create' methods.
Chris Lattner153a0f12009-02-04 00:40:31 +0000365//===----------------------------------------------------------------------===//
Ted Kremenek12c2af42009-01-06 01:55:26 +0000366
Chris Lattner5159f612010-11-23 08:35:12 +0000367SourceManager::SourceManager(Diagnostic &Diag, FileManager &FileMgr)
Argyrios Kyrtzidis97d3a382011-03-08 23:35:24 +0000368 : Diag(Diag), FileMgr(FileMgr), OverridenFilesKeepOriginalName(true),
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000369 ExternalSLocEntries(0), LineTable(0), NumLinearScans(0),
Douglas Gregor49f754f2011-04-20 00:21:03 +0000370 NumBinaryProbes(0), FakeBufferForRecovery(0) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000371 clearIDTables();
372 Diag.setSourceManager(this);
373}
374
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000375SourceManager::~SourceManager() {
376 delete LineTable;
Mike Stump11289f42009-09-09 15:08:12 +0000377
Chris Lattnerc8233df2009-02-03 07:30:45 +0000378 // Delete FileEntry objects corresponding to content caches. Since the actual
379 // content cache objects are bump pointer allocated, we just have to run the
380 // dtors, but we call the deallocate method for completeness.
381 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
382 MemBufferInfos[i]->~ContentCache();
383 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
384 }
385 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
386 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
387 I->second->~ContentCache();
388 ContentCacheAlloc.Deallocate(I->second);
389 }
Douglas Gregor49f754f2011-04-20 00:21:03 +0000390
391 delete FakeBufferForRecovery;
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000392}
393
394void SourceManager::clearIDTables() {
395 MainFileID = FileID();
Douglas Gregor925296b2011-07-19 16:10:42 +0000396 LocalSLocEntryTable.clear();
397 LoadedSLocEntryTable.clear();
398 SLocEntryLoaded.clear();
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000399 LastLineNoFileIDQuery = FileID();
400 LastLineNoContentCache = 0;
401 LastFileIDLookup = FileID();
Mike Stump11289f42009-09-09 15:08:12 +0000402
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000403 if (LineTable)
404 LineTable->clear();
Mike Stump11289f42009-09-09 15:08:12 +0000405
Chandler Carruth64ee7822011-07-26 05:17:23 +0000406 // Use up FileID #0 as an invalid expansion.
Douglas Gregor925296b2011-07-19 16:10:42 +0000407 NextLocalOffset = 0;
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +0000408 CurrentLoadedOffset = MaxLoadedOffset;
Chandler Carruth115b0772011-07-26 03:03:05 +0000409 createExpansionLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000410}
411
Chris Lattner4fa23622009-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) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000416 assert(FileEnt && "Didn't specify a file entry to use?");
Mike Stump11289f42009-09-09 15:08:12 +0000417
Chris Lattner22eb9722006-06-18 05:43:12 +0000418 // Do we already have information about this file?
Chris Lattnerc8233df2009-02-03 07:30:45 +0000419 ContentCache *&Entry = FileInfos[FileEnt];
420 if (Entry) return Entry;
Mike Stump11289f42009-09-09 15:08:12 +0000421
Chris Lattner9be4f6d2009-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 Kyrtzidis11e6f0a2011-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 Kyrtzidis97d3a382011-03-08 23:35:24 +0000436 new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt
437 : overI->second,
438 overI->second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000439
Chris Lattnerc8233df2009-02-03 07:30:45 +0000440 return Entry;
Chris Lattner22eb9722006-06-18 05:43:12 +0000441}
442
443
Ted Kremenek08bed092007-10-31 17:53:38 +0000444/// createMemBufferContentCache - Create a new ContentCache for the specified
445/// memory buffer. This does no caching.
Ted Kremenekc08bca62007-10-30 21:08:08 +0000446const ContentCache*
447SourceManager::createMemBufferContentCache(const MemoryBuffer *Buffer) {
Chris Lattner9be4f6d2009-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 Lattnerc8233df2009-02-03 07:30:45 +0000454 new (Entry) ContentCache();
455 MemBufferInfos.push_back(Entry);
456 Entry->setBuffer(Buffer);
457 return Entry;
Chris Lattner22eb9722006-06-18 05:43:12 +0000458}
459
Douglas Gregor925296b2011-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 Gregor0bc12932009-04-27 21:28:04 +0000470}
471
Douglas Gregor49f754f2011-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 Gregor258ae542009-04-27 06:38:32 +0000481
Chris Lattner4fa23622009-01-26 00:43:02 +0000482//===----------------------------------------------------------------------===//
Chandler Carruth64ee7822011-07-26 05:17:23 +0000483// Methods to create new FileID's and macro expansions.
Chris Lattner4fa23622009-01-26 00:43:02 +0000484//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000485
Dan Gohmance46f022010-08-26 21:27:06 +0000486/// createFileID - Create a new FileID for the specified ContentCache and
Ted Kremeneke26f3c52007-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 Lattnerd32480d2009-01-17 06:22:33 +0000489FileID SourceManager::createFileID(const ContentCache *File,
Chris Lattner4fa23622009-01-26 00:43:02 +0000490 SourceLocation IncludePos,
Douglas Gregor258ae542009-04-27 06:38:32 +0000491 SrcMgr::CharacteristicKind FileCharacter,
Douglas Gregor925296b2011-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 Gregor258ae542009-04-27 06:38:32 +0000502 }
Douglas Gregor925296b2011-07-19 16:10:42 +0000503 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset,
504 FileInfo::get(IncludePos, File,
505 FileCharacter)));
Ted Kremenek12c2af42009-01-06 01:55:26 +0000506 unsigned FileSize = File->getSize();
Douglas Gregor925296b2011-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 Stump11289f42009-09-09 15:08:12 +0000513
Chris Lattner4fa23622009-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 Gregor925296b2011-07-19 16:10:42 +0000516 FileID FID = FileID::get(LocalSLocEntryTable.size()-1);
Argyrios Kyrtzidis0152c6c2009-06-23 00:42:06 +0000517 return LastFileIDLookup = FID;
Chris Lattner22eb9722006-06-18 05:43:12 +0000518}
519
Chandler Carruth402bb382011-07-07 23:56:36 +0000520SourceLocation
Chandler Carruth115b0772011-07-26 03:03:05 +0000521SourceManager::createMacroArgExpansionLoc(SourceLocation SpellingLoc,
522 SourceLocation ExpansionLoc,
523 unsigned TokLength) {
Chandler Carruth73ee5d72011-07-26 04:41:47 +0000524 ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc,
525 ExpansionLoc);
526 return createExpansionLocImpl(Info, TokLength);
Chandler Carruth402bb382011-07-07 23:56:36 +0000527}
528
529SourceLocation
Chandler Carruth115b0772011-07-26 03:03:05 +0000530SourceManager::createExpansionLoc(SourceLocation SpellingLoc,
531 SourceLocation ExpansionLocStart,
532 SourceLocation ExpansionLocEnd,
533 unsigned TokLength,
534 int LoadedID,
535 unsigned LoadedOffset) {
Chandler Carruth73ee5d72011-07-26 04:41:47 +0000536 ExpansionInfo Info = ExpansionInfo::create(SpellingLoc, ExpansionLocStart,
537 ExpansionLocEnd);
538 return createExpansionLocImpl(Info, TokLength, LoadedID, LoadedOffset);
Chandler Carruth115b0772011-07-26 03:03:05 +0000539}
540
541SourceLocation
Chandler Carruth73ee5d72011-07-26 04:41:47 +0000542SourceManager::createExpansionLocImpl(const ExpansionInfo &Info,
Chandler Carruth115b0772011-07-26 03:03:05 +0000543 unsigned TokLength,
544 int LoadedID,
545 unsigned LoadedOffset) {
Douglas Gregor925296b2011-07-19 16:10:42 +0000546 if (LoadedID < 0) {
547 assert(LoadedID != -1 && "Loading sentinel FileID");
548 unsigned Index = unsigned(-LoadedID) - 2;
549 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
550 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
Chandler Carruth73ee5d72011-07-26 04:41:47 +0000551 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info);
Douglas Gregor925296b2011-07-19 16:10:42 +0000552 SLocEntryLoaded[Index] = true;
553 return SourceLocation::getMacroLoc(LoadedOffset);
Douglas Gregor258ae542009-04-27 06:38:32 +0000554 }
Chandler Carruth73ee5d72011-07-26 04:41:47 +0000555 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));
Douglas Gregor925296b2011-07-19 16:10:42 +0000556 assert(NextLocalOffset + TokLength + 1 > NextLocalOffset &&
557 NextLocalOffset + TokLength + 1 <= CurrentLoadedOffset &&
558 "Ran out of source locations!");
559 // See createFileID for that +1.
560 NextLocalOffset += TokLength + 1;
561 return SourceLocation::getMacroLoc(NextLocalOffset - (TokLength + 1));
Chris Lattner7d6a4f62006-06-30 06:10:08 +0000562}
563
Douglas Gregor874cc622010-03-16 00:35:39 +0000564const llvm::MemoryBuffer *
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000565SourceManager::getMemoryBufferForFile(const FileEntry *File,
566 bool *Invalid) {
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000567 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
Douglas Gregor802b7762010-03-15 22:54:52 +0000568 assert(IR && "getOrCreateContentCache() cannot return NULL");
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000569 return IR->getBuffer(Diag, *this, SourceLocation(), Invalid);
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000570}
571
Dan Gohman5d223dc2010-10-26 20:47:28 +0000572void SourceManager::overrideFileContents(const FileEntry *SourceFile,
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000573 const llvm::MemoryBuffer *Buffer,
574 bool DoNotFree) {
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000575 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
Dan Gohman5d223dc2010-10-26 20:47:28 +0000576 assert(IR && "getOrCreateContentCache() cannot return NULL");
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000577
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000578 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree);
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000579}
580
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000581void SourceManager::overrideFileContents(const FileEntry *SourceFile,
582 const FileEntry *NewFile) {
583 assert(SourceFile->getSize() == NewFile->getSize() &&
584 "Different sizes, use the FileManager to create a virtual file with "
585 "the correct size");
586 assert(FileInfos.count(SourceFile) == 0 &&
587 "This function should be called at the initialization stage, before "
588 "any parsing occurs.");
589 OverriddenFiles[SourceFile] = NewFile;
590}
591
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000592StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
Douglas Gregor4fb7fbe2010-03-16 20:01:30 +0000593 bool MyInvalid = false;
Douglas Gregor925296b2011-07-19 16:10:42 +0000594 const SLocEntry &SLoc = getSLocEntry(FID, &MyInvalid);
Douglas Gregor49f754f2011-04-20 00:21:03 +0000595 if (!SLoc.isFile() || MyInvalid) {
Douglas Gregor86af9842011-01-31 22:42:36 +0000596 if (Invalid)
597 *Invalid = true;
598 return "<<<<<INVALID SOURCE LOCATION>>>>>";
599 }
600
601 const llvm::MemoryBuffer *Buf
602 = SLoc.getFile().getContentCache()->getBuffer(Diag, *this, SourceLocation(),
603 &MyInvalid);
Douglas Gregore0fbb832010-03-16 00:06:06 +0000604 if (Invalid)
Douglas Gregor4fb7fbe2010-03-16 20:01:30 +0000605 *Invalid = MyInvalid;
606
607 if (MyInvalid)
Douglas Gregor86af9842011-01-31 22:42:36 +0000608 return "<<<<<INVALID SOURCE LOCATION>>>>>";
Douglas Gregor4fb7fbe2010-03-16 20:01:30 +0000609
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000610 return Buf->getBuffer();
Douglas Gregor802b7762010-03-15 22:54:52 +0000611}
Chris Lattnerd32480d2009-01-17 06:22:33 +0000612
Chris Lattner153a0f12009-02-04 00:40:31 +0000613//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +0000614// SourceLocation manipulation methods.
Chris Lattner153a0f12009-02-04 00:40:31 +0000615//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +0000616
Douglas Gregor925296b2011-07-19 16:10:42 +0000617/// \brief Return the FileID for a SourceLocation.
Chris Lattner4fa23622009-01-26 00:43:02 +0000618///
Douglas Gregor925296b2011-07-19 16:10:42 +0000619/// This is the cache-miss path of getFileID. Not as hot as that function, but
620/// still very important. It is responsible for finding the entry in the
621/// SLocEntry tables that contains the specified location.
Chris Lattner4fa23622009-01-26 00:43:02 +0000622FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
Douglas Gregor49f754f2011-04-20 00:21:03 +0000623 if (!SLocOffset)
624 return FileID::get(0);
Mike Stump11289f42009-09-09 15:08:12 +0000625
Douglas Gregor925296b2011-07-19 16:10:42 +0000626 // Now it is time to search for the correct file. See where the SLocOffset
627 // sits in the global view and consult local or loaded buffers for it.
628 if (SLocOffset < NextLocalOffset)
629 return getFileIDLocal(SLocOffset);
630 return getFileIDLoaded(SLocOffset);
631}
632
633/// \brief Return the FileID for a SourceLocation with a low offset.
634///
635/// This function knows that the SourceLocation is in a local buffer, not a
636/// loaded one.
637FileID SourceManager::getFileIDLocal(unsigned SLocOffset) const {
638 assert(SLocOffset < NextLocalOffset && "Bad function choice");
639
Chris Lattner4fa23622009-01-26 00:43:02 +0000640 // After the first and second level caches, I see two common sorts of
Chandler Carruth64ee7822011-07-26 05:17:23 +0000641 // behavior: 1) a lot of searched FileID's are "near" the cached file
642 // location or are "near" the cached expansion location. 2) others are just
Chris Lattner4fa23622009-01-26 00:43:02 +0000643 // completely random and may be a very long way away.
644 //
645 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
646 // then we fall back to a less cache efficient, but more scalable, binary
647 // search to find the location.
Mike Stump11289f42009-09-09 15:08:12 +0000648
Chris Lattner4fa23622009-01-26 00:43:02 +0000649 // See if this is near the file point - worst case we start scanning from the
650 // most newly created FileID.
651 std::vector<SrcMgr::SLocEntry>::const_iterator I;
Mike Stump11289f42009-09-09 15:08:12 +0000652
Douglas Gregor925296b2011-07-19 16:10:42 +0000653 if (LastFileIDLookup.ID < 0 ||
654 LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
Chris Lattner4fa23622009-01-26 00:43:02 +0000655 // Neither loc prunes our search.
Douglas Gregor925296b2011-07-19 16:10:42 +0000656 I = LocalSLocEntryTable.end();
Chris Lattner4fa23622009-01-26 00:43:02 +0000657 } else {
658 // Perhaps it is near the file point.
Douglas Gregor925296b2011-07-19 16:10:42 +0000659 I = LocalSLocEntryTable.begin()+LastFileIDLookup.ID;
Chris Lattner4fa23622009-01-26 00:43:02 +0000660 }
661
662 // Find the FileID that contains this. "I" is an iterator that points to a
663 // FileID whose offset is known to be larger than SLocOffset.
664 unsigned NumProbes = 0;
665 while (1) {
666 --I;
667 if (I->getOffset() <= SLocOffset) {
Douglas Gregor925296b2011-07-19 16:10:42 +0000668 FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin()));
Douglas Gregor258ae542009-04-27 06:38:32 +0000669
Chandler Carruth64ee7822011-07-26 05:17:23 +0000670 // If this isn't an expansion, remember it. We have good locality across
671 // FileID lookups.
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000672 if (!I->isExpansion())
Chris Lattner4fa23622009-01-26 00:43:02 +0000673 LastFileIDLookup = Res;
674 NumLinearScans += NumProbes+1;
675 return Res;
676 }
677 if (++NumProbes == 8)
678 break;
679 }
Mike Stump11289f42009-09-09 15:08:12 +0000680
Chris Lattner4fa23622009-01-26 00:43:02 +0000681 // Convert "I" back into an index. We know that it is an entry whose index is
682 // larger than the offset we are looking for.
Douglas Gregor925296b2011-07-19 16:10:42 +0000683 unsigned GreaterIndex = I - LocalSLocEntryTable.begin();
Chris Lattner4fa23622009-01-26 00:43:02 +0000684 // LessIndex - This is the lower bound of the range that we're searching.
685 // We know that the offset corresponding to the FileID is is less than
686 // SLocOffset.
687 unsigned LessIndex = 0;
688 NumProbes = 0;
689 while (1) {
Douglas Gregor49f754f2011-04-20 00:21:03 +0000690 bool Invalid = false;
Chris Lattner4fa23622009-01-26 00:43:02 +0000691 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
Douglas Gregor925296b2011-07-19 16:10:42 +0000692 unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset();
Douglas Gregor49f754f2011-04-20 00:21:03 +0000693 if (Invalid)
694 return FileID::get(0);
695
Chris Lattner4fa23622009-01-26 00:43:02 +0000696 ++NumProbes;
Mike Stump11289f42009-09-09 15:08:12 +0000697
Chris Lattner4fa23622009-01-26 00:43:02 +0000698 // If the offset of the midpoint is too large, chop the high side of the
699 // range to the midpoint.
700 if (MidOffset > SLocOffset) {
701 GreaterIndex = MiddleIndex;
702 continue;
703 }
Mike Stump11289f42009-09-09 15:08:12 +0000704
Chris Lattner4fa23622009-01-26 00:43:02 +0000705 // If the middle index contains the value, succeed and return.
Douglas Gregor925296b2011-07-19 16:10:42 +0000706 // FIXME: This could be made faster by using a function that's aware of
707 // being in the local area.
Chris Lattner4fa23622009-01-26 00:43:02 +0000708 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
Chris Lattner4fa23622009-01-26 00:43:02 +0000709 FileID Res = FileID::get(MiddleIndex);
710
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000711 // If this isn't a macro expansion, remember it. We have good locality
Chris Lattner4fa23622009-01-26 00:43:02 +0000712 // across FileID lookups.
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000713 if (!LocalSLocEntryTable[MiddleIndex].isExpansion())
Chris Lattner4fa23622009-01-26 00:43:02 +0000714 LastFileIDLookup = Res;
715 NumBinaryProbes += NumProbes;
716 return Res;
717 }
Mike Stump11289f42009-09-09 15:08:12 +0000718
Chris Lattner4fa23622009-01-26 00:43:02 +0000719 // Otherwise, move the low-side up to the middle index.
720 LessIndex = MiddleIndex;
721 }
722}
723
Douglas Gregor925296b2011-07-19 16:10:42 +0000724/// \brief Return the FileID for a SourceLocation with a high offset.
725///
726/// This function knows that the SourceLocation is in a loaded buffer, not a
727/// local one.
728FileID SourceManager::getFileIDLoaded(unsigned SLocOffset) const {
729 assert(SLocOffset >= CurrentLoadedOffset && "Bad function choice");
730
731 // Essentially the same as the local case, but the loaded array is sorted
732 // in the other direction.
733
734 // First do a linear scan from the last lookup position, if possible.
735 unsigned I;
736 int LastID = LastFileIDLookup.ID;
737 if (LastID >= 0 || getLoadedSLocEntryByID(LastID).getOffset() < SLocOffset)
738 I = 0;
739 else
740 I = (-LastID - 2) + 1;
741
742 unsigned NumProbes;
743 for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++I) {
744 // Make sure the entry is loaded!
745 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(I);
746 if (E.getOffset() <= SLocOffset) {
747 FileID Res = FileID::get(-int(I) - 2);
748
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000749 if (!E.isExpansion())
Douglas Gregor925296b2011-07-19 16:10:42 +0000750 LastFileIDLookup = Res;
751 NumLinearScans += NumProbes + 1;
752 return Res;
753 }
754 }
755
756 // Linear scan failed. Do the binary search. Note the reverse sorting of the
757 // table: GreaterIndex is the one where the offset is greater, which is
758 // actually a lower index!
759 unsigned GreaterIndex = I;
760 unsigned LessIndex = LoadedSLocEntryTable.size();
761 NumProbes = 0;
762 while (1) {
763 ++NumProbes;
764 unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex;
765 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(MiddleIndex);
766
767 ++NumProbes;
768
769 if (E.getOffset() > SLocOffset) {
770 GreaterIndex = MiddleIndex;
771 continue;
772 }
773
774 if (isOffsetInFileID(FileID::get(-int(MiddleIndex) - 2), SLocOffset)) {
775 FileID Res = FileID::get(-int(MiddleIndex) - 2);
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000776 if (!E.isExpansion())
Douglas Gregor925296b2011-07-19 16:10:42 +0000777 LastFileIDLookup = Res;
778 NumBinaryProbes += NumProbes;
779 return Res;
780 }
781
782 LessIndex = MiddleIndex;
783 }
784}
785
Chris Lattner659ac5f2009-01-26 20:04:19 +0000786SourceLocation SourceManager::
Chandler Carruthc84d7692011-07-25 20:52:26 +0000787getExpansionLocSlowCase(SourceLocation Loc) const {
Chris Lattner659ac5f2009-01-26 20:04:19 +0000788 do {
Chris Lattner5647d312010-02-12 19:31:35 +0000789 // Note: If Loc indicates an offset into a token that came from a macro
790 // expansion (e.g. the 5th character of the token) we do not want to add
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000791 // this offset when going to the expansion location. The expansion
Chris Lattner5647d312010-02-12 19:31:35 +0000792 // location is the macro invocation, which the offset has nothing to do
793 // with. This is unlike when we get the spelling loc, because the offset
794 // directly correspond to the token whose spelling we're inspecting.
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000795 Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart();
Chris Lattner659ac5f2009-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);
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000804 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
Chris Lattner659ac5f2009-01-26 20:04:19 +0000805 Loc = Loc.getFileLocWithOffset(LocInfo.second);
806 } while (!Loc.isFileID());
807 return Loc;
808}
809
810
Chris Lattner4fa23622009-01-26 00:43:02 +0000811std::pair<FileID, unsigned>
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000812SourceManager::getDecomposedExpansionLocSlowCase(
Argyrios Kyrtzidisc8f7e212011-07-07 03:40:27 +0000813 const SrcMgr::SLocEntry *E) const {
Chandler Carruth64ee7822011-07-26 05:17:23 +0000814 // If this is an expansion record, walk through all the expansion points.
Chris Lattner4fa23622009-01-26 00:43:02 +0000815 FileID FID;
816 SourceLocation Loc;
Argyrios Kyrtzidisc8f7e212011-07-07 03:40:27 +0000817 unsigned Offset;
Chris Lattner4fa23622009-01-26 00:43:02 +0000818 do {
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000819 Loc = E->getExpansion().getExpansionLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000820
Chris Lattner4fa23622009-01-26 00:43:02 +0000821 FID = getFileID(Loc);
822 E = &getSLocEntry(FID);
Argyrios Kyrtzidisc8f7e212011-07-07 03:40:27 +0000823 Offset = Loc.getOffset()-E->getOffset();
Chris Lattner31af4e02009-01-26 19:41:58 +0000824 } while (!Loc.isFileID());
Mike Stump11289f42009-09-09 15:08:12 +0000825
Chris Lattner4fa23622009-01-26 00:43:02 +0000826 return std::make_pair(FID, Offset);
827}
828
829std::pair<FileID, unsigned>
830SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
831 unsigned Offset) const {
Chandler Carruth64ee7822011-07-26 05:17:23 +0000832 // If this is an expansion record, walk through all the expansion points.
Chris Lattner31af4e02009-01-26 19:41:58 +0000833 FileID FID;
834 SourceLocation Loc;
835 do {
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000836 Loc = E->getExpansion().getSpellingLoc();
Mike Stump11289f42009-09-09 15:08:12 +0000837
Chris Lattner31af4e02009-01-26 19:41:58 +0000838 FID = getFileID(Loc);
839 E = &getSLocEntry(FID);
840 Offset += Loc.getOffset()-E->getOffset();
841 } while (!Loc.isFileID());
Mike Stump11289f42009-09-09 15:08:12 +0000842
Chris Lattner4fa23622009-01-26 00:43:02 +0000843 return std::make_pair(FID, Offset);
844}
845
Chris Lattner8ad52d52009-02-17 08:04:48 +0000846/// getImmediateSpellingLoc - Given a SourceLocation object, return the
847/// spelling location referenced by the ID. This is the first level down
848/// towards the place where the characters that make up the lexed token can be
849/// found. This should not generally be used by clients.
850SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
851 if (Loc.isFileID()) return Loc;
852 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000853 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
Chris Lattner8ad52d52009-02-17 08:04:48 +0000854 return Loc.getFileLocWithOffset(LocInfo.second);
855}
856
857
Chandler Carruth64ee7822011-07-26 05:17:23 +0000858/// getImmediateExpansionRange - Loc is required to be an expansion location.
859/// Return the start/end of the expansion information.
Chris Lattner9dc9c202009-02-15 20:52:18 +0000860std::pair<SourceLocation,SourceLocation>
Chandler Carruthca757582011-07-25 20:52:21 +0000861SourceManager::getImmediateExpansionRange(SourceLocation Loc) const {
Chandler Carruth64ee7822011-07-26 05:17:23 +0000862 assert(Loc.isMacroID() && "Not a macro expansion loc!");
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000863 const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion();
Chandler Carruth73ee5d72011-07-26 04:41:47 +0000864 return Expansion.getExpansionLocRange();
Chris Lattner9dc9c202009-02-15 20:52:18 +0000865}
866
Chandler Carruth6d28d7f2011-07-25 16:56:02 +0000867/// getExpansionRange - Given a SourceLocation object, return the range of
868/// tokens covered by the expansion in the ultimate file.
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000869std::pair<SourceLocation,SourceLocation>
Chandler Carruth6d28d7f2011-07-25 16:56:02 +0000870SourceManager::getExpansionRange(SourceLocation Loc) const {
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000871 if (Loc.isFileID()) return std::make_pair(Loc, Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000872
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000873 std::pair<SourceLocation,SourceLocation> Res =
Chandler Carruthca757582011-07-25 20:52:21 +0000874 getImmediateExpansionRange(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000875
Chandler Carruth64ee7822011-07-26 05:17:23 +0000876 // Fully resolve the start and end locations to their ultimate expansion
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000877 // points.
878 while (!Res.first.isFileID())
Chandler Carruthca757582011-07-25 20:52:21 +0000879 Res.first = getImmediateExpansionRange(Res.first).first;
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000880 while (!Res.second.isFileID())
Chandler Carruthca757582011-07-25 20:52:21 +0000881 Res.second = getImmediateExpansionRange(Res.second).second;
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000882 return Res;
883}
884
Chandler Carruthaa631532011-07-26 03:03:00 +0000885bool SourceManager::isMacroArgExpansion(SourceLocation Loc) const {
Chandler Carruth402bb382011-07-07 23:56:36 +0000886 if (!Loc.isMacroID()) return false;
887
888 FileID FID = getFileID(Loc);
889 const SrcMgr::SLocEntry *E = &getSLocEntry(FID);
Chandler Carruthee4c1d12011-07-26 04:56:51 +0000890 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
Chandler Carruth73ee5d72011-07-26 04:41:47 +0000891 return Expansion.isMacroArgExpansion();
Chandler Carruth402bb382011-07-07 23:56:36 +0000892}
Chris Lattner9dc9c202009-02-15 20:52:18 +0000893
Chris Lattner4fa23622009-01-26 00:43:02 +0000894
895//===----------------------------------------------------------------------===//
896// Queries about the code at a SourceLocation.
897//===----------------------------------------------------------------------===//
Chris Lattner30709b032006-06-21 03:01:55 +0000898
Chris Lattnerd01e2912006-06-18 16:22:51 +0000899/// getCharacterData - Return a pointer to the start of the specified location
Chris Lattner739e7392007-04-29 07:12:06 +0000900/// in the appropriate MemoryBuffer.
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000901const char *SourceManager::getCharacterData(SourceLocation SL,
902 bool *Invalid) const {
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000903 // Note that this is a hot function in the getSpelling() path, which is
904 // heavily used by -E mode.
Chris Lattner4fa23622009-01-26 00:43:02 +0000905 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
Mike Stump11289f42009-09-09 15:08:12 +0000906
Ted Kremenek12c2af42009-01-06 01:55:26 +0000907 // Note that calling 'getBuffer()' may lazily page in a source file.
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000908 bool CharDataInvalid = false;
Douglas Gregor49f754f2011-04-20 00:21:03 +0000909 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
910 if (CharDataInvalid || !Entry.isFile()) {
911 if (Invalid)
912 *Invalid = true;
913
914 return "<<<<INVALID BUFFER>>>>";
915 }
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000916 const llvm::MemoryBuffer *Buffer
Douglas Gregor49f754f2011-04-20 00:21:03 +0000917 = Entry.getFile().getContentCache()
918 ->getBuffer(Diag, *this, SourceLocation(), &CharDataInvalid);
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000919 if (Invalid)
920 *Invalid = CharDataInvalid;
921 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000922}
923
Chris Lattner685730f2006-06-26 01:36:22 +0000924
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000925/// getColumnNumber - Return the column # for the specified file position.
Chris Lattnere4ad4172009-02-04 00:55:58 +0000926/// this is significantly cheaper to compute than the line number.
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000927unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
928 bool *Invalid) const {
929 bool MyInvalid = false;
930 const char *Buf = getBuffer(FID, &MyInvalid)->getBufferStart();
931 if (Invalid)
932 *Invalid = MyInvalid;
933
934 if (MyInvalid)
935 return 1;
Mike Stump11289f42009-09-09 15:08:12 +0000936
Chris Lattner22eb9722006-06-18 05:43:12 +0000937 unsigned LineStart = FilePos;
938 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
939 --LineStart;
940 return FilePos-LineStart+1;
941}
942
Zhanyong Wanea6d7f32010-10-05 17:56:33 +0000943// isInvalid - Return the result of calling loc.isInvalid(), and
944// if Invalid is not null, set its value to same.
945static bool isInvalid(SourceLocation Loc, bool *Invalid) {
946 bool MyInvalid = Loc.isInvalid();
947 if (Invalid)
948 *Invalid = MyInvalid;
949 return MyInvalid;
950}
951
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000952unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
953 bool *Invalid) const {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +0000954 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattnere4ad4172009-02-04 00:55:58 +0000955 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000956 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattnere4ad4172009-02-04 00:55:58 +0000957}
958
Chandler Carruth42f35f92011-07-25 20:57:57 +0000959unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc,
960 bool *Invalid) const {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +0000961 if (isInvalid(Loc, Invalid)) return 0;
Chandler Carruthc7ca5212011-07-25 20:52:32 +0000962 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000963 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattnere4ad4172009-02-04 00:55:58 +0000964}
965
Chandler Carruth1aef0c52011-02-23 00:47:48 +0000966unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
967 bool *Invalid) const {
968 if (isInvalid(Loc, Invalid)) return 0;
969 return getPresumedLoc(Loc).getColumn();
970}
971
Chandler Carruthc3ce5842010-10-23 08:44:57 +0000972static LLVM_ATTRIBUTE_NOINLINE void
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000973ComputeLineNumbers(Diagnostic &Diag, ContentCache *FI,
974 llvm::BumpPtrAllocator &Alloc,
975 const SourceManager &SM, bool &Invalid);
976static void ComputeLineNumbers(Diagnostic &Diag, ContentCache *FI,
977 llvm::BumpPtrAllocator &Alloc,
978 const SourceManager &SM, bool &Invalid) {
Ted Kremenek12c2af42009-01-06 01:55:26 +0000979 // Note that calling 'getBuffer()' may lazily page in the file.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000980 const MemoryBuffer *Buffer = FI->getBuffer(Diag, SM, SourceLocation(),
981 &Invalid);
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000982 if (Invalid)
983 return;
Mike Stump11289f42009-09-09 15:08:12 +0000984
Chris Lattner8996fff2007-07-24 05:57:19 +0000985 // Find the file offsets of all of the *physical* source lines. This does
986 // not look at trigraphs, escaped newlines, or anything else tricky.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000987 SmallVector<unsigned, 256> LineOffsets;
Mike Stump11289f42009-09-09 15:08:12 +0000988
Chris Lattner8996fff2007-07-24 05:57:19 +0000989 // Line #1 starts at char 0.
990 LineOffsets.push_back(0);
Mike Stump11289f42009-09-09 15:08:12 +0000991
Chris Lattner8996fff2007-07-24 05:57:19 +0000992 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
993 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
994 unsigned Offs = 0;
995 while (1) {
996 // Skip over the contents of the line.
997 // TODO: Vectorize this? This is very performance sensitive for programs
998 // with lots of diagnostics and in -E mode.
999 const unsigned char *NextBuf = (const unsigned char *)Buf;
1000 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
1001 ++NextBuf;
1002 Offs += NextBuf-Buf;
1003 Buf = NextBuf;
Mike Stump11289f42009-09-09 15:08:12 +00001004
Chris Lattner8996fff2007-07-24 05:57:19 +00001005 if (Buf[0] == '\n' || Buf[0] == '\r') {
1006 // If this is \n\r or \r\n, skip both characters.
1007 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
1008 ++Offs, ++Buf;
1009 ++Offs, ++Buf;
1010 LineOffsets.push_back(Offs);
1011 } else {
1012 // Otherwise, this is a null. If end of file, exit.
1013 if (Buf == End) break;
1014 // Otherwise, skip the null.
1015 ++Offs, ++Buf;
1016 }
1017 }
Mike Stump11289f42009-09-09 15:08:12 +00001018
Chris Lattner8996fff2007-07-24 05:57:19 +00001019 // Copy the offsets into the FileInfo structure.
1020 FI->NumLines = LineOffsets.size();
Chris Lattnerc8233df2009-02-03 07:30:45 +00001021 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
Chris Lattner8996fff2007-07-24 05:57:19 +00001022 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
1023}
Chris Lattner9a13bde2006-06-21 04:57:09 +00001024
Chris Lattner53e384f2009-01-16 07:00:02 +00001025/// getLineNumber - Given a SourceLocation, return the spelling line number
Chris Lattner22eb9722006-06-18 05:43:12 +00001026/// for the position indicated. This requires building and caching a table of
Chris Lattner739e7392007-04-29 07:12:06 +00001027/// line offsets for the MemoryBuffer, so this is not cheap: use only when
Chris Lattner22eb9722006-06-18 05:43:12 +00001028/// about to emit a diagnostic.
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001029unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
1030 bool *Invalid) const {
Argyrios Kyrtzidisf15eac12011-05-17 22:09:53 +00001031 if (FID.isInvalid()) {
1032 if (Invalid)
1033 *Invalid = true;
1034 return 1;
1035 }
1036
Chris Lattnerd32480d2009-01-17 06:22:33 +00001037 ContentCache *Content;
Chris Lattner88ea93e2009-02-04 01:06:56 +00001038 if (LastLineNoFileIDQuery == FID)
Ted Kremenekc08bca62007-10-30 21:08:08 +00001039 Content = LastLineNoContentCache;
Douglas Gregor49f754f2011-04-20 00:21:03 +00001040 else {
1041 bool MyInvalid = false;
1042 const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
1043 if (MyInvalid || !Entry.isFile()) {
1044 if (Invalid)
1045 *Invalid = true;
1046 return 1;
1047 }
1048
1049 Content = const_cast<ContentCache*>(Entry.getFile().getContentCache());
1050 }
1051
Chris Lattner22eb9722006-06-18 05:43:12 +00001052 // If this is the first use of line information for this buffer, compute the
Chris Lattner8996fff2007-07-24 05:57:19 +00001053 /// SourceLineCache for it on demand.
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001054 if (Content->SourceLineCache == 0) {
1055 bool MyInvalid = false;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001056 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001057 if (Invalid)
1058 *Invalid = MyInvalid;
1059 if (MyInvalid)
1060 return 1;
1061 } else if (Invalid)
1062 *Invalid = false;
Chris Lattner22eb9722006-06-18 05:43:12 +00001063
1064 // Okay, we know we have a line number table. Do a binary search to find the
1065 // line number that this character position lands on.
Ted Kremenekc08bca62007-10-30 21:08:08 +00001066 unsigned *SourceLineCache = Content->SourceLineCache;
Chris Lattner8996fff2007-07-24 05:57:19 +00001067 unsigned *SourceLineCacheStart = SourceLineCache;
Ted Kremenekc08bca62007-10-30 21:08:08 +00001068 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
Mike Stump11289f42009-09-09 15:08:12 +00001069
Chris Lattner88ea93e2009-02-04 01:06:56 +00001070 unsigned QueriedFilePos = FilePos+1;
Chris Lattner8996fff2007-07-24 05:57:19 +00001071
Daniel Dunbar70f924df82009-05-18 17:30:52 +00001072 // FIXME: I would like to be convinced that this code is worth being as
Mike Stump11289f42009-09-09 15:08:12 +00001073 // complicated as it is, binary search isn't that slow.
Daniel Dunbar70f924df82009-05-18 17:30:52 +00001074 //
1075 // If it is worth being optimized, then in my opinion it could be more
1076 // performant, simpler, and more obviously correct by just "galloping" outward
1077 // from the queried file position. In fact, this could be incorporated into a
1078 // generic algorithm such as lower_bound_with_hint.
1079 //
1080 // If someone gives me a test case where this matters, and I will do it! - DWD
1081
Chris Lattner8996fff2007-07-24 05:57:19 +00001082 // If the previous query was to the same file, we know both the file pos from
1083 // that query and the line number returned. This allows us to narrow the
1084 // search space from the entire file to something near the match.
Chris Lattner88ea93e2009-02-04 01:06:56 +00001085 if (LastLineNoFileIDQuery == FID) {
Chris Lattner8996fff2007-07-24 05:57:19 +00001086 if (QueriedFilePos >= LastLineNoFilePos) {
Daniel Dunbar70f924df82009-05-18 17:30:52 +00001087 // FIXME: Potential overflow?
Chris Lattner8996fff2007-07-24 05:57:19 +00001088 SourceLineCache = SourceLineCache+LastLineNoResult-1;
Mike Stump11289f42009-09-09 15:08:12 +00001089
Chris Lattner8996fff2007-07-24 05:57:19 +00001090 // The query is likely to be nearby the previous one. Here we check to
1091 // see if it is within 5, 10 or 20 lines. It can be far away in cases
1092 // where big comment blocks and vertical whitespace eat up lines but
1093 // contribute no tokens.
1094 if (SourceLineCache+5 < SourceLineCacheEnd) {
1095 if (SourceLineCache[5] > QueriedFilePos)
1096 SourceLineCacheEnd = SourceLineCache+5;
1097 else if (SourceLineCache+10 < SourceLineCacheEnd) {
1098 if (SourceLineCache[10] > QueriedFilePos)
1099 SourceLineCacheEnd = SourceLineCache+10;
1100 else if (SourceLineCache+20 < SourceLineCacheEnd) {
1101 if (SourceLineCache[20] > QueriedFilePos)
1102 SourceLineCacheEnd = SourceLineCache+20;
1103 }
1104 }
1105 }
1106 } else {
Daniel Dunbar70f924df82009-05-18 17:30:52 +00001107 if (LastLineNoResult < Content->NumLines)
1108 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
Chris Lattner8996fff2007-07-24 05:57:19 +00001109 }
1110 }
Mike Stump11289f42009-09-09 15:08:12 +00001111
Chris Lattner830a77f2007-07-24 06:43:46 +00001112 // If the spread is large, do a "radix" test as our initial guess, based on
1113 // the assumption that lines average to approximately the same length.
1114 // NOTE: This is currently disabled, as it does not appear to be profitable in
1115 // initial measurements.
1116 if (0 && SourceLineCacheEnd-SourceLineCache > 20) {
Ted Kremenekc08bca62007-10-30 21:08:08 +00001117 unsigned FileLen = Content->SourceLineCache[Content->NumLines-1];
Mike Stump11289f42009-09-09 15:08:12 +00001118
Chris Lattner830a77f2007-07-24 06:43:46 +00001119 // Take a stab at guessing where it is.
Ted Kremenekc08bca62007-10-30 21:08:08 +00001120 unsigned ApproxPos = Content->NumLines*QueriedFilePos / FileLen;
Mike Stump11289f42009-09-09 15:08:12 +00001121
Chris Lattner830a77f2007-07-24 06:43:46 +00001122 // Check for -10 and +10 lines.
1123 unsigned LowerBound = std::max(int(ApproxPos-10), 0);
1124 unsigned UpperBound = std::min(ApproxPos+10, FileLen);
1125
1126 // If the computed lower bound is less than the query location, move it in.
1127 if (SourceLineCache < SourceLineCacheStart+LowerBound &&
1128 SourceLineCacheStart[LowerBound] < QueriedFilePos)
1129 SourceLineCache = SourceLineCacheStart+LowerBound;
Mike Stump11289f42009-09-09 15:08:12 +00001130
Chris Lattner830a77f2007-07-24 06:43:46 +00001131 // If the computed upper bound is greater than the query location, move it.
1132 if (SourceLineCacheEnd > SourceLineCacheStart+UpperBound &&
1133 SourceLineCacheStart[UpperBound] >= QueriedFilePos)
1134 SourceLineCacheEnd = SourceLineCacheStart+UpperBound;
1135 }
Mike Stump11289f42009-09-09 15:08:12 +00001136
Chris Lattner830a77f2007-07-24 06:43:46 +00001137 unsigned *Pos
1138 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
Chris Lattner8996fff2007-07-24 05:57:19 +00001139 unsigned LineNo = Pos-SourceLineCacheStart;
Mike Stump11289f42009-09-09 15:08:12 +00001140
Chris Lattner88ea93e2009-02-04 01:06:56 +00001141 LastLineNoFileIDQuery = FID;
Ted Kremenekc08bca62007-10-30 21:08:08 +00001142 LastLineNoContentCache = Content;
Chris Lattner8996fff2007-07-24 05:57:19 +00001143 LastLineNoFilePos = QueriedFilePos;
1144 LastLineNoResult = LineNo;
1145 return LineNo;
Chris Lattner22eb9722006-06-18 05:43:12 +00001146}
1147
Chandler Carruth1aef0c52011-02-23 00:47:48 +00001148unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
1149 bool *Invalid) const {
1150 if (isInvalid(Loc, Invalid)) return 0;
1151 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1152 return getLineNumber(LocInfo.first, LocInfo.second);
1153}
Chandler Carruthd48db212011-07-25 21:09:52 +00001154unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc,
1155 bool *Invalid) const {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +00001156 if (isInvalid(Loc, Invalid)) return 0;
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001157 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Chris Lattner88ea93e2009-02-04 01:06:56 +00001158 return getLineNumber(LocInfo.first, LocInfo.second);
1159}
Chandler Carruth1aef0c52011-02-23 00:47:48 +00001160unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001161 bool *Invalid) const {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +00001162 if (isInvalid(Loc, Invalid)) return 0;
Chandler Carruth1aef0c52011-02-23 00:47:48 +00001163 return getPresumedLoc(Loc).getLine();
Chris Lattner88ea93e2009-02-04 01:06:56 +00001164}
1165
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001166/// getFileCharacteristic - return the file characteristic of the specified
Mike Stump11289f42009-09-09 15:08:12 +00001167/// source location, indicating whether this is a normal file, a system
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001168/// header, or an "implicit extern C" system header.
1169///
1170/// This state can be modified with flags on GNU linemarker directives like:
1171/// # 4 "foo.h" 3
1172/// which changes all source locations in the current file after that to be
1173/// considered to be from a system header.
Mike Stump11289f42009-09-09 15:08:12 +00001174SrcMgr::CharacteristicKind
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001175SourceManager::getFileCharacteristic(SourceLocation Loc) const {
1176 assert(!Loc.isInvalid() && "Can't get file characteristic of invalid loc!");
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001177 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Douglas Gregor49f754f2011-04-20 00:21:03 +00001178 bool Invalid = false;
1179 const SLocEntry &SEntry = getSLocEntry(LocInfo.first, &Invalid);
1180 if (Invalid || !SEntry.isFile())
1181 return C_User;
1182
1183 const SrcMgr::FileInfo &FI = SEntry.getFile();
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001184
1185 // If there are no #line directives in this file, just return the whole-file
1186 // state.
1187 if (!FI.hasLineDirectives())
1188 return FI.getFileCharacteristic();
Mike Stump11289f42009-09-09 15:08:12 +00001189
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001190 assert(LineTable && "Can't have linetable entries without a LineTable!");
1191 // See if there is a #line directive before the location.
1192 const LineEntry *Entry =
1193 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second);
Mike Stump11289f42009-09-09 15:08:12 +00001194
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001195 // If this is before the first line marker, use the file characteristic.
1196 if (!Entry)
1197 return FI.getFileCharacteristic();
1198
1199 return Entry->FileKind;
1200}
1201
Chris Lattnera6f037c2009-02-17 08:39:06 +00001202/// Return the filename or buffer identifier of the buffer the location is in.
1203/// Note that this name does not respect #line directives. Use getPresumedLoc
1204/// for normal clients.
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001205const char *SourceManager::getBufferName(SourceLocation Loc,
1206 bool *Invalid) const {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +00001207 if (isInvalid(Loc, Invalid)) return "<invalid loc>";
Mike Stump11289f42009-09-09 15:08:12 +00001208
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001209 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
Chris Lattnera6f037c2009-02-17 08:39:06 +00001210}
1211
Chris Lattner88ea93e2009-02-04 01:06:56 +00001212
Chris Lattnerf1ca7d32009-01-27 07:57:44 +00001213/// getPresumedLoc - This method returns the "presumed" location of a
1214/// SourceLocation specifies. A "presumed location" can be modified by #line
1215/// or GNU line marker directives. This provides a view on the data that a
1216/// user should see in diagnostics, for example.
1217///
Chandler Carruth64ee7822011-07-26 05:17:23 +00001218/// Note that a presumed location is always given as the expansion point of an
1219/// expansion location, not at the spelling location.
Chris Lattnerf1ca7d32009-01-27 07:57:44 +00001220PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc) const {
1221 if (Loc.isInvalid()) return PresumedLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001222
Chandler Carruth64ee7822011-07-26 05:17:23 +00001223 // Presumed locations are always for expansion points.
Chandler Carruthc7ca5212011-07-25 20:52:32 +00001224 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +00001225
Douglas Gregor49f754f2011-04-20 00:21:03 +00001226 bool Invalid = false;
1227 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1228 if (Invalid || !Entry.isFile())
1229 return PresumedLoc();
1230
1231 const SrcMgr::FileInfo &FI = Entry.getFile();
Chris Lattnerf1ca7d32009-01-27 07:57:44 +00001232 const SrcMgr::ContentCache *C = FI.getContentCache();
Mike Stump11289f42009-09-09 15:08:12 +00001233
Chris Lattnerd4293922009-02-04 01:55:42 +00001234 // To get the source name, first consult the FileEntry (if one exists)
1235 // before the MemBuffer as this will avoid unnecessarily paging in the
1236 // MemBuffer.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001237 const char *Filename;
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001238 if (C->OrigEntry)
1239 Filename = C->OrigEntry->getName();
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001240 else
1241 Filename = C->getBuffer(Diag, *this)->getBufferIdentifier();
Douglas Gregor49f754f2011-04-20 00:21:03 +00001242
Douglas Gregor75f26d62010-11-02 00:39:22 +00001243 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1244 if (Invalid)
1245 return PresumedLoc();
1246 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1247 if (Invalid)
1248 return PresumedLoc();
1249
Chris Lattnerd4293922009-02-04 01:55:42 +00001250 SourceLocation IncludeLoc = FI.getIncludeLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001251
Chris Lattnerd4293922009-02-04 01:55:42 +00001252 // If we have #line directives in this file, update and overwrite the physical
1253 // location info if appropriate.
1254 if (FI.hasLineDirectives()) {
1255 assert(LineTable && "Can't have linetable entries without a LineTable!");
1256 // See if there is a #line directive before this. If so, get it.
1257 if (const LineEntry *Entry =
1258 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second)) {
Chris Lattnerc1219ff2009-02-04 02:00:59 +00001259 // If the LineEntry indicates a filename, use it.
Chris Lattnerd4293922009-02-04 01:55:42 +00001260 if (Entry->FilenameID != -1)
1261 Filename = LineTable->getFilename(Entry->FilenameID);
Chris Lattnerc1219ff2009-02-04 02:00:59 +00001262
1263 // Use the line number specified by the LineEntry. This line number may
1264 // be multiple lines down from the line entry. Add the difference in
1265 // physical line numbers from the query point and the line marker to the
1266 // total.
1267 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1268 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
Mike Stump11289f42009-09-09 15:08:12 +00001269
Chris Lattner20c50ba2009-02-04 02:15:40 +00001270 // Note that column numbers are not molested by line markers.
Mike Stump11289f42009-09-09 15:08:12 +00001271
Chris Lattner1c967782009-02-04 06:25:26 +00001272 // Handle virtual #include manipulation.
1273 if (Entry->IncludeOffset) {
1274 IncludeLoc = getLocForStartOfFile(LocInfo.first);
1275 IncludeLoc = IncludeLoc.getFileLocWithOffset(Entry->IncludeOffset);
1276 }
Chris Lattnerd4293922009-02-04 01:55:42 +00001277 }
1278 }
1279
1280 return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc);
Chris Lattner4fa23622009-01-26 00:43:02 +00001281}
1282
Argyrios Kyrtzidis296374b52011-08-23 21:02:28 +00001283/// \brief The size of the SLocEnty that \arg FID represents.
1284unsigned SourceManager::getFileIDSize(FileID FID) const {
1285 bool Invalid = false;
1286 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1287 if (Invalid)
1288 return 0;
1289
1290 int ID = FID.ID;
1291 unsigned NextOffset;
1292 if ((ID > 0 && unsigned(ID+1) == local_sloc_entry_size()))
1293 NextOffset = getNextLocalOffset();
1294 else if (ID+1 == -1)
1295 NextOffset = MaxLoadedOffset;
1296 else
1297 NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset();
1298
1299 return NextOffset - Entry.getOffset() - 1;
1300}
1301
1302bool SourceManager::isInFileID(SourceLocation Loc,
1303 FileID FID, unsigned offset, unsigned length,
1304 unsigned *relativeOffset) const {
1305 assert(!FID.isInvalid());
1306 if (Loc.isInvalid())
1307 return false;
1308
1309 unsigned FIDOffs = getSLocEntry(FID).getOffset();
1310 unsigned start = FIDOffs + offset;
1311 unsigned end = start + length;
1312
1313 // Make sure offset/length describe a chunk inside the given FileID.
1314 assert(start < FIDOffs + getFileIDSize(FID));
1315 assert(end <= FIDOffs + getFileIDSize(FID));
1316
1317 if (Loc.getOffset() >= start && Loc.getOffset() < end) {
1318 if (relativeOffset)
1319 *relativeOffset = Loc.getOffset() - start;
1320 return true;
1321 }
1322
1323 return false;
1324}
1325
Chris Lattner4fa23622009-01-26 00:43:02 +00001326//===----------------------------------------------------------------------===//
1327// Other miscellaneous methods.
1328//===----------------------------------------------------------------------===//
1329
Douglas Gregore6642762011-02-03 17:17:35 +00001330/// \brief Retrieve the inode for the given file entry, if possible.
1331///
1332/// This routine involves a system call, and therefore should only be used
1333/// in non-performance-critical code.
1334static llvm::Optional<ino_t> getActualFileInode(const FileEntry *File) {
1335 if (!File)
1336 return llvm::Optional<ino_t>();
1337
1338 struct stat StatBuf;
1339 if (::stat(File->getName(), &StatBuf))
1340 return llvm::Optional<ino_t>();
1341
1342 return StatBuf.st_ino;
1343}
1344
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001345/// \brief Get the source location for the given file:line:col triplet.
1346///
1347/// If the source file is included multiple times, the source location will
Douglas Gregor925296b2011-07-19 16:10:42 +00001348/// be based upon an arbitrary inclusion.
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001349SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile,
1350 unsigned Line, unsigned Col) {
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001351 assert(SourceFile && "Null source file!");
1352 assert(Line && Col && "Line and column should start from 1!");
1353
Douglas Gregore6642762011-02-03 17:17:35 +00001354 // Find the first file ID that corresponds to the given file.
1355 FileID FirstFID;
Mike Stump11289f42009-09-09 15:08:12 +00001356
Douglas Gregore6642762011-02-03 17:17:35 +00001357 // First, check the main file ID, since it is common to look for a
1358 // location in the main file.
1359 llvm::Optional<ino_t> SourceFileInode;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001360 llvm::Optional<StringRef> SourceFileName;
Douglas Gregore6642762011-02-03 17:17:35 +00001361 if (!MainFileID.isInvalid()) {
Douglas Gregor49f754f2011-04-20 00:21:03 +00001362 bool Invalid = false;
1363 const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
1364 if (Invalid)
1365 return SourceLocation();
1366
Douglas Gregore6642762011-02-03 17:17:35 +00001367 if (MainSLoc.isFile()) {
1368 const ContentCache *MainContentCache
1369 = MainSLoc.getFile().getContentCache();
Douglas Gregor6a5be932011-02-11 18:08:15 +00001370 if (!MainContentCache) {
1371 // Can't do anything
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001372 } else if (MainContentCache->OrigEntry == SourceFile) {
Douglas Gregore6642762011-02-03 17:17:35 +00001373 FirstFID = MainFileID;
Douglas Gregor6a5be932011-02-11 18:08:15 +00001374 } else {
Douglas Gregore6642762011-02-03 17:17:35 +00001375 // Fall back: check whether we have the same base name and inode
1376 // as the main file.
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001377 const FileEntry *MainFile = MainContentCache->OrigEntry;
Douglas Gregore6642762011-02-03 17:17:35 +00001378 SourceFileName = llvm::sys::path::filename(SourceFile->getName());
1379 if (*SourceFileName == llvm::sys::path::filename(MainFile->getName())) {
1380 SourceFileInode = getActualFileInode(SourceFile);
Douglas Gregord766be62011-02-16 19:09:24 +00001381 if (SourceFileInode) {
1382 if (llvm::Optional<ino_t> MainFileInode
1383 = getActualFileInode(MainFile)) {
1384 if (*SourceFileInode == *MainFileInode) {
1385 FirstFID = MainFileID;
1386 SourceFile = MainFile;
1387 }
1388 }
Douglas Gregore6642762011-02-03 17:17:35 +00001389 }
1390 }
1391 }
1392 }
1393 }
1394
1395 if (FirstFID.isInvalid()) {
1396 // The location we're looking for isn't in the main file; look
Douglas Gregor925296b2011-07-19 16:10:42 +00001397 // through all of the local source locations.
1398 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
Douglas Gregor49f754f2011-04-20 00:21:03 +00001399 bool Invalid = false;
Douglas Gregor925296b2011-07-19 16:10:42 +00001400 const SLocEntry &SLoc = getLocalSLocEntry(I, &Invalid);
Douglas Gregor49f754f2011-04-20 00:21:03 +00001401 if (Invalid)
1402 return SourceLocation();
1403
Douglas Gregore6642762011-02-03 17:17:35 +00001404 if (SLoc.isFile() &&
1405 SLoc.getFile().getContentCache() &&
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001406 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
Douglas Gregore6642762011-02-03 17:17:35 +00001407 FirstFID = FileID::get(I);
1408 break;
1409 }
1410 }
Douglas Gregor925296b2011-07-19 16:10:42 +00001411 // If that still didn't help, try the modules.
1412 if (FirstFID.isInvalid()) {
1413 for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) {
1414 const SLocEntry &SLoc = getLoadedSLocEntry(I);
1415 if (SLoc.isFile() &&
1416 SLoc.getFile().getContentCache() &&
1417 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
1418 FirstFID = FileID::get(-int(I) - 2);
1419 break;
1420 }
1421 }
1422 }
Douglas Gregore6642762011-02-03 17:17:35 +00001423 }
1424
1425 // If we haven't found what we want yet, try again, but this time stat()
1426 // each of the files in case the files have changed since we originally
1427 // parsed the file.
1428 if (FirstFID.isInvalid() &&
1429 (SourceFileName ||
1430 (SourceFileName = llvm::sys::path::filename(SourceFile->getName()))) &&
1431 (SourceFileInode ||
1432 (SourceFileInode = getActualFileInode(SourceFile)))) {
Douglas Gregor49f754f2011-04-20 00:21:03 +00001433 bool Invalid = false;
Douglas Gregor925296b2011-07-19 16:10:42 +00001434 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1435 FileID IFileID;
1436 IFileID.ID = I;
1437 const SLocEntry &SLoc = getSLocEntry(IFileID, &Invalid);
Douglas Gregor49f754f2011-04-20 00:21:03 +00001438 if (Invalid)
1439 return SourceLocation();
1440
Douglas Gregore6642762011-02-03 17:17:35 +00001441 if (SLoc.isFile()) {
1442 const ContentCache *FileContentCache
1443 = SLoc.getFile().getContentCache();
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001444 const FileEntry *Entry =FileContentCache? FileContentCache->OrigEntry : 0;
Douglas Gregore6642762011-02-03 17:17:35 +00001445 if (Entry &&
Douglas Gregor6a5be932011-02-11 18:08:15 +00001446 *SourceFileName == llvm::sys::path::filename(Entry->getName())) {
1447 if (llvm::Optional<ino_t> EntryInode = getActualFileInode(Entry)) {
1448 if (*SourceFileInode == *EntryInode) {
1449 FirstFID = FileID::get(I);
1450 SourceFile = Entry;
1451 break;
1452 }
1453 }
Douglas Gregore6642762011-02-03 17:17:35 +00001454 }
1455 }
1456 }
1457 }
1458
1459 if (FirstFID.isInvalid())
1460 return SourceLocation();
1461
1462 if (Line == 1 && Col == 1)
1463 return getLocForStartOfFile(FirstFID);
1464
1465 ContentCache *Content
1466 = const_cast<ContentCache *>(getOrCreateContentCache(SourceFile));
1467 if (!Content)
1468 return SourceLocation();
1469
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001470 // If this is the first use of line information for this buffer, compute the
Douglas Gregor925296b2011-07-19 16:10:42 +00001471 // SourceLineCache for it on demand.
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001472 if (Content->SourceLineCache == 0) {
1473 bool MyInvalid = false;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001474 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001475 if (MyInvalid)
1476 return SourceLocation();
1477 }
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001478
Douglas Gregorb8b9f282010-02-27 02:42:25 +00001479 if (Line > Content->NumLines) {
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001480 unsigned Size = Content->getBuffer(Diag, *this)->getBufferSize();
Douglas Gregorb8b9f282010-02-27 02:42:25 +00001481 if (Size > 0)
1482 --Size;
1483 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(Size);
1484 }
1485
1486 unsigned FilePos = Content->SourceLineCache[Line - 1];
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001487 const char *Buf = Content->getBuffer(Diag, *this)->getBufferStart() + FilePos;
1488 unsigned BufLength = Content->getBuffer(Diag, *this)->getBufferEnd() - Buf;
Douglas Gregorb8b9f282010-02-27 02:42:25 +00001489 unsigned i = 0;
1490
1491 // Check that the given column is valid.
1492 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1493 ++i;
1494 if (i < Col-1)
1495 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + i);
1496
Douglas Gregor2a1b6912009-12-02 05:34:39 +00001497 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + Col - 1);
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001498}
1499
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001500/// \brief Compute a map of macro argument chunks to their expanded source
1501/// location. Chunks that are not part of a macro argument will map to an
1502/// invalid source location. e.g. if a file contains one macro argument at
1503/// offset 100 with length 10, this is how the map will be formed:
1504/// 0 -> SourceLocation()
1505/// 100 -> Expanded macro arg location
1506/// 110 -> SourceLocation()
1507void SourceManager::computeMacroArgsCache(ContentCache *Content, FileID FID) {
1508 assert(!Content->MacroArgsCache);
1509 assert(!FID.isInvalid());
1510
1511 Content->MacroArgsCache = new ContentCache::MacroArgsMap();
1512 ContentCache::MacroArgsMap &MacroArgsCache = *Content->MacroArgsCache;
1513 // Initially no macro argument chunk is present.
1514 MacroArgsCache.insert(std::make_pair(0, SourceLocation()));
1515
1516 int ID = FID.ID;
1517 while (1) {
1518 ++ID;
1519 // Stop if there are no more FileIDs to check.
1520 if (ID > 0) {
1521 if (unsigned(ID) >= local_sloc_entry_size())
1522 return;
1523 } else if (ID == -1) {
1524 return;
1525 }
1526
1527 const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID);
1528 if (Entry.isFile()) {
1529 SourceLocation IncludeLoc = Entry.getFile().getIncludeLoc();
1530 if (IncludeLoc.isInvalid())
1531 continue;
1532 if (!isInFileID(IncludeLoc, FID))
1533 return; // No more files/macros that may be "contained" in this file.
1534
1535 // Skip the files/macros of the #include'd file, we only care about macros
1536 // that lexed macro arguments from our file.
1537 if (Entry.getFile().NumCreatedFIDs)
1538 ID += Entry.getFile().NumCreatedFIDs - 1/*because of next ++ID*/;
1539 continue;
1540 }
1541
1542 if (!Entry.getExpansion().isMacroArgExpansion())
1543 continue;
1544
1545 SourceLocation SpellLoc =
1546 getSpellingLoc(Entry.getExpansion().getSpellingLoc());
1547 unsigned BeginOffs;
1548 if (!isInFileID(SpellLoc, FID, &BeginOffs))
1549 return; // No more files/macros that may be "contained" in this file.
1550 unsigned EndOffs = BeginOffs + getFileIDSize(FileID::get(ID));
1551
1552 // Add a new chunk for this macro argument. A previous macro argument chunk
1553 // may have been lexed again, so e.g. if the map is
1554 // 0 -> SourceLocation()
1555 // 100 -> Expanded loc #1
1556 // 110 -> SourceLocation()
1557 // and we found a new macro FileID that lexed from offet 105 with length 3,
1558 // the new map will be:
1559 // 0 -> SourceLocation()
1560 // 100 -> Expanded loc #1
1561 // 105 -> Expanded loc #2
1562 // 108 -> Expanded loc #1
1563 // 110 -> SourceLocation()
1564 //
1565 // Since re-lexed macro chunks will always be the same size or less of
1566 // previous chunks, we only need to find where the ending of the new macro
1567 // chunk is mapped to and update the map with new begin/end mappings.
1568
1569 ContentCache::MacroArgsMap::iterator I= MacroArgsCache.upper_bound(EndOffs);
1570 --I;
1571 SourceLocation EndOffsMappedLoc = I->second;
1572 MacroArgsCache[BeginOffs] = SourceLocation::getMacroLoc(Entry.getOffset());
1573 MacroArgsCache[EndOffs] = EndOffsMappedLoc;
1574 }
1575}
1576
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001577/// \brief If \arg Loc points inside a function macro argument, the returned
1578/// location will be the macro location in which the argument was expanded.
1579/// If a macro argument is used multiple times, the expanded location will
1580/// be at the first expansion of the argument.
1581/// e.g.
1582/// MY_MACRO(foo);
1583/// ^
1584/// Passing a file location pointing at 'foo', will yield a macro location
1585/// where 'foo' was expanded into.
1586SourceLocation SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) {
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001587 if (Loc.isInvalid() || !Loc.isFileID())
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001588 return Loc;
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001589
1590 FileID FID;
1591 unsigned Offset;
1592 llvm::tie(FID, Offset) = getDecomposedLoc(Loc);
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001593 if (FID.isInvalid())
1594 return Loc;
1595
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001596 ContentCache *Content
1597 = const_cast<ContentCache *>(getSLocEntry(FID).getFile().getContentCache());
1598 if (!Content->MacroArgsCache)
1599 computeMacroArgsCache(Content, FID);
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001600
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001601 assert(Content->MacroArgsCache);
1602 assert(!Content->MacroArgsCache->empty());
1603 ContentCache::MacroArgsMap::iterator
1604 I = Content->MacroArgsCache->upper_bound(Offset);
1605 --I;
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001606
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001607 unsigned MacroArgBeginOffs = I->first;
1608 SourceLocation MacroArgExpandedLoc = I->second;
1609 if (MacroArgExpandedLoc.isValid())
1610 return MacroArgExpandedLoc.getFileLocWithOffset(Offset - MacroArgBeginOffs);
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001611
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001612 return Loc;
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001613}
1614
Chandler Carruth64ee7822011-07-26 05:17:23 +00001615/// Given a decomposed source location, move it up the include/expansion stack
1616/// to the parent source location. If this is possible, return the decomposed
1617/// version of the parent in Loc and return false. If Loc is the top-level
1618/// entry, return true and don't modify it.
Chris Lattnera99fa1a2010-05-07 20:35:24 +00001619static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1620 const SourceManager &SM) {
1621 SourceLocation UpperLoc;
1622 const SrcMgr::SLocEntry &Entry = SM.getSLocEntry(Loc.first);
Chandler Carruthee4c1d12011-07-26 04:56:51 +00001623 if (Entry.isExpansion())
1624 UpperLoc = Entry.getExpansion().getExpansionLocStart();
Chris Lattnera99fa1a2010-05-07 20:35:24 +00001625 else
1626 UpperLoc = Entry.getFile().getIncludeLoc();
1627
1628 if (UpperLoc.isInvalid())
1629 return true; // We reached the top.
1630
1631 Loc = SM.getDecomposedLoc(UpperLoc);
1632 return false;
1633}
1634
1635
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001636/// \brief Determines the order of 2 source locations in the translation unit.
1637///
1638/// \returns true if LHS source location comes before RHS, false otherwise.
1639bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
1640 SourceLocation RHS) const {
1641 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
1642 if (LHS == RHS)
1643 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001644
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001645 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
1646 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00001647
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001648 // If the source locations are in the same file, just compare offsets.
1649 if (LOffs.first == ROffs.first)
1650 return LOffs.second < ROffs.second;
1651
1652 // If we are comparing a source location with multiple locations in the same
1653 // file, we get a big win by caching the result.
Chris Lattner46e3b482010-05-07 05:10:46 +00001654 if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
1655 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
Mike Stump11289f42009-09-09 15:08:12 +00001656
Chris Lattner66d2f922010-05-07 01:17:07 +00001657 // Okay, we missed in the cache, start updating the cache for this query.
Argyrios Kyrtzidisac199bf2011-08-17 00:31:18 +00001658 IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first,
1659 /*isLFIDBeforeRFID=*/LOffs.first.ID < ROffs.first.ID);
Mike Stump11289f42009-09-09 15:08:12 +00001660
Douglas Gregor925296b2011-07-19 16:10:42 +00001661 // We need to find the common ancestor. The only way of doing this is to
1662 // build the complete include chain for one and then walking up the chain
1663 // of the other looking for a match.
1664 // We use a map from FileID to Offset to store the chain. Easier than writing
1665 // a custom set hash info that only depends on the first part of a pair.
1666 typedef llvm::DenseMap<FileID, unsigned> LocSet;
1667 LocSet LChain;
Chris Lattner06821c92010-05-07 05:51:13 +00001668 do {
Douglas Gregor925296b2011-07-19 16:10:42 +00001669 LChain.insert(LOffs);
1670 // We catch the case where LOffs is in a file included by ROffs and
1671 // quit early. The other way round unfortunately remains suboptimal.
1672 } while (LOffs.first != ROffs.first && !MoveUpIncludeHierarchy(LOffs, *this));
1673 LocSet::iterator I;
1674 while((I = LChain.find(ROffs.first)) == LChain.end()) {
1675 if (MoveUpIncludeHierarchy(ROffs, *this))
1676 break; // Met at topmost file.
1677 }
1678 if (I != LChain.end())
1679 LOffs = *I;
Mike Stump11289f42009-09-09 15:08:12 +00001680
Chris Lattner06821c92010-05-07 05:51:13 +00001681 // If we exited because we found a nearest common ancestor, compare the
1682 // locations within the common file and cache them.
1683 if (LOffs.first == ROffs.first) {
1684 IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
1685 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001686 }
Mike Stump11289f42009-09-09 15:08:12 +00001687
Douglas Gregor925296b2011-07-19 16:10:42 +00001688 // This can happen if a location is in a built-ins buffer.
1689 // But see PR5662.
1690 // Clear the lookup cache, it depends on a common location.
Argyrios Kyrtzidisac199bf2011-08-17 00:31:18 +00001691 IsBeforeInTUCache.clear();
Douglas Gregor925296b2011-07-19 16:10:42 +00001692 bool LIsBuiltins = strcmp("<built-in>",
1693 getBuffer(LOffs.first)->getBufferIdentifier()) == 0;
1694 bool RIsBuiltins = strcmp("<built-in>",
1695 getBuffer(ROffs.first)->getBufferIdentifier()) == 0;
1696 // built-in is before non-built-in
1697 if (LIsBuiltins != RIsBuiltins)
1698 return LIsBuiltins;
1699 assert(LIsBuiltins && RIsBuiltins &&
1700 "Non-built-in locations must be rooted in the main file");
1701 // Both are in built-in buffers, but from different files. We just claim that
1702 // lower IDs come first.
Chris Lattner66d2f922010-05-07 01:17:07 +00001703 return LOffs.first < ROffs.first;
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001704}
Chris Lattner4fa23622009-01-26 00:43:02 +00001705
Chris Lattner22eb9722006-06-18 05:43:12 +00001706/// PrintStats - Print statistics to stderr.
1707///
1708void SourceManager::PrintStats() const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +00001709 llvm::errs() << "\n*** Source Manager Stats:\n";
1710 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
1711 << " mem buffers mapped.\n";
Douglas Gregor925296b2011-07-19 16:10:42 +00001712 llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntry's allocated ("
Ted Kremenek43e0c4a2011-07-27 18:41:16 +00001713 << llvm::capacity_in_bytes(LocalSLocEntryTable)
Argyrios Kyrtzidis2cc62092011-07-07 03:40:24 +00001714 << " bytes of capacity), "
Douglas Gregor925296b2011-07-19 16:10:42 +00001715 << NextLocalOffset << "B of Sloc address space used.\n";
1716 llvm::errs() << LoadedSLocEntryTable.size()
1717 << " loaded SLocEntries allocated, "
Argyrios Kyrtzidis92a47bd2011-08-17 00:31:20 +00001718 << MaxLoadedOffset - CurrentLoadedOffset
Douglas Gregor925296b2011-07-19 16:10:42 +00001719 << "B of Sloc address space used.\n";
1720
Chris Lattner22eb9722006-06-18 05:43:12 +00001721 unsigned NumLineNumsComputed = 0;
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001722 unsigned NumMacroArgsComputed = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +00001723 unsigned NumFileBytesMapped = 0;
Chris Lattnerc8233df2009-02-03 07:30:45 +00001724 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
1725 NumLineNumsComputed += I->second->SourceLineCache != 0;
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001726 NumMacroArgsComputed += I->second->MacroArgsCache != 0;
Chris Lattnerc8233df2009-02-03 07:30:45 +00001727 NumFileBytesMapped += I->second->getSizeBytesMapped();
Chris Lattner22eb9722006-06-18 05:43:12 +00001728 }
Mike Stump11289f42009-09-09 15:08:12 +00001729
Benjamin Kramer89b422c2009-08-23 12:08:50 +00001730 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001731 << NumLineNumsComputed << " files with line #'s computed, "
1732 << NumMacroArgsComputed << " files with macro args computed.\n";
Benjamin Kramer89b422c2009-08-23 12:08:50 +00001733 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
1734 << NumBinaryProbes << " binary.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +00001735}
Douglas Gregor258ae542009-04-27 06:38:32 +00001736
1737ExternalSLocEntrySource::~ExternalSLocEntrySource() { }
Ted Kremenek8d587902011-04-28 20:36:42 +00001738
1739/// Return the amount of memory used by memory buffers, breaking down
1740/// by heap-backed versus mmap'ed memory.
1741SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
1742 size_t malloc_bytes = 0;
1743 size_t mmap_bytes = 0;
1744
1745 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)
1746 if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
1747 switch (MemBufferInfos[i]->getMemoryBufferKind()) {
1748 case llvm::MemoryBuffer::MemoryBuffer_MMap:
1749 mmap_bytes += sized_mapped;
1750 break;
1751 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
1752 malloc_bytes += sized_mapped;
1753 break;
1754 }
1755
1756 return MemoryBufferSizes(malloc_bytes, mmap_bytes);
1757}
1758
Ted Kremenek120992a2011-07-26 23:46:06 +00001759size_t SourceManager::getDataStructureSizes() const {
Ted Kremenek43e0c4a2011-07-27 18:41:16 +00001760 return llvm::capacity_in_bytes(MemBufferInfos)
1761 + llvm::capacity_in_bytes(LocalSLocEntryTable)
1762 + llvm::capacity_in_bytes(LoadedSLocEntryTable)
1763 + llvm::capacity_in_bytes(SLocEntryLoaded)
1764 + llvm::capacity_in_bytes(FileInfos)
1765 + llvm::capacity_in_bytes(OverriddenFiles);
Ted Kremenek120992a2011-07-26 23:46:06 +00001766}