blob: cffdb937bf09c5d63d39fbe737c0cabcdbe5bb7b [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"
Chris Lattner8996fff2007-07-24 05:57:19 +000020#include "llvm/Support/Compiler.h"
Chris Lattner739e7392007-04-29 07:12:06 +000021#include "llvm/Support/MemoryBuffer.h"
Chris Lattner3441b4f2009-08-23 22:45:33 +000022#include "llvm/Support/raw_ostream.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000023#include "llvm/Support/Path.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000024#include <algorithm>
Douglas Gregor802b7762010-03-15 22:54:52 +000025#include <string>
Douglas Gregore0fbb832010-03-16 00:06:06 +000026#include <cstring>
Douglas Gregore6642762011-02-03 17:17:35 +000027#include <sys/stat.h>
Douglas Gregor802b7762010-03-15 22:54:52 +000028
Chris Lattner22eb9722006-06-18 05:43:12 +000029using namespace clang;
Chris Lattner5f4b1ff2006-06-20 05:02:40 +000030using namespace SrcMgr;
Chris Lattner23b7eb62007-06-15 23:05:46 +000031using llvm::MemoryBuffer;
Chris Lattner22eb9722006-06-18 05:43:12 +000032
Chris Lattner153a0f12009-02-04 00:40:31 +000033//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +000034// SourceManager Helper Classes
Chris Lattner153a0f12009-02-04 00:40:31 +000035//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +000036
Ted Kremenekc08bca62007-10-30 21:08:08 +000037ContentCache::~ContentCache() {
Douglas Gregor3f4bea02010-07-26 21:36:20 +000038 if (shouldFreeBuffer())
39 delete Buffer.getPointer();
Chris Lattner22eb9722006-06-18 05:43:12 +000040}
41
Ted Kremenek12c2af42009-01-06 01:55:26 +000042/// getSizeBytesMapped - Returns the number of bytes actually mapped for
43/// this ContentCache. This can be 0 if the MemBuffer was not actually
44/// instantiated.
45unsigned ContentCache::getSizeBytesMapped() const {
Douglas Gregor82752ec2010-03-16 22:53:51 +000046 return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 0;
Ted Kremenek12c2af42009-01-06 01:55:26 +000047}
48
49/// getSize - Returns the size of the content encapsulated by this ContentCache.
50/// This can be the size of the source file or the size of an arbitrary
51/// scratch buffer. If the ContentCache encapsulates a source file, that
Douglas Gregor53ad6b92009-12-02 06:49:09 +000052/// file is not lazily brought in from disk to satisfy this query.
Ted Kremenek12c2af42009-01-06 01:55:26 +000053unsigned ContentCache::getSize() const {
Douglas Gregor82752ec2010-03-16 22:53:51 +000054 return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize()
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +000055 : (unsigned) ContentsEntry->getSize();
Ted Kremenek12c2af42009-01-06 01:55:26 +000056}
57
Douglas Gregor3f4bea02010-07-26 21:36:20 +000058void ContentCache::replaceBuffer(const llvm::MemoryBuffer *B,
59 bool DoNotFree) {
Douglas Gregor82752ec2010-03-16 22:53:51 +000060 assert(B != Buffer.getPointer());
Douglas Gregor53ad6b92009-12-02 06:49:09 +000061
Douglas Gregor3f4bea02010-07-26 21:36:20 +000062 if (shouldFreeBuffer())
63 delete Buffer.getPointer();
Douglas Gregor82752ec2010-03-16 22:53:51 +000064 Buffer.setPointer(B);
Douglas Gregor3f4bea02010-07-26 21:36:20 +000065 Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
Douglas Gregor53ad6b92009-12-02 06:49:09 +000066}
67
Douglas Gregor874cc622010-03-16 00:35:39 +000068const llvm::MemoryBuffer *ContentCache::getBuffer(Diagnostic &Diag,
Chris Lattner8f5bc9f2010-04-20 20:49:23 +000069 const SourceManager &SM,
Chris Lattnerfb24a3a2010-04-20 20:35:58 +000070 SourceLocation Loc,
Douglas Gregor874cc622010-03-16 00:35:39 +000071 bool *Invalid) const {
Chris Lattner5631b052010-11-23 08:50:03 +000072 // Lazily create the Buffer for ContentCaches that wrap files. If we already
73 // computed it, jsut return what we have.
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +000074 if (Buffer.getPointer() || ContentsEntry == 0) {
Chris Lattner5631b052010-11-23 08:50:03 +000075 if (Invalid)
76 *Invalid = isBufferInvalid();
Chris Lattner8fbe98b2010-04-20 18:14:03 +000077
Chris Lattner5631b052010-11-23 08:50:03 +000078 return Buffer.getPointer();
79 }
Benjamin Kramer5a3f1cf2010-11-18 12:46:39 +000080
Chris Lattner5631b052010-11-23 08:50:03 +000081 std::string ErrorStr;
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +000082 Buffer.setPointer(SM.getFileManager().getBufferForFile(ContentsEntry, &ErrorStr));
Chris Lattner5631b052010-11-23 08:50:03 +000083
84 // If we were unable to open the file, then we are in an inconsistent
85 // situation where the content cache referenced a file which no longer
86 // exists. Most likely, we were using a stat cache with an invalid entry but
87 // the file could also have been removed during processing. Since we can't
88 // really deal with this situation, just create an empty buffer.
89 //
90 // FIXME: This is definitely not ideal, but our immediate clients can't
91 // currently handle returning a null entry here. Ideally we should detect
92 // that we are in an inconsistent situation and error out as quickly as
93 // possible.
94 if (!Buffer.getPointer()) {
95 const llvm::StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +000096 Buffer.setPointer(MemoryBuffer::getNewMemBuffer(ContentsEntry->getSize(),
Chris Lattner5631b052010-11-23 08:50:03 +000097 "<invalid>"));
98 char *Ptr = const_cast<char*>(Buffer.getPointer()->getBufferStart());
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +000099 for (unsigned i = 0, e = ContentsEntry->getSize(); i != e; ++i)
Chris Lattner5631b052010-11-23 08:50:03 +0000100 Ptr[i] = FillStr[i % FillStr.size()];
101
102 if (Diag.isDiagnosticInFlight())
103 Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000104 ContentsEntry->getName(), ErrorStr);
Chris Lattner5631b052010-11-23 08:50:03 +0000105 else
106 Diag.Report(Loc, diag::err_cannot_open_file)
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000107 << ContentsEntry->getName() << ErrorStr;
Chris Lattner5631b052010-11-23 08:50:03 +0000108
109 Buffer.setInt(Buffer.getInt() | InvalidFlag);
110
111 if (Invalid) *Invalid = true;
112 return Buffer.getPointer();
113 }
114
115 // Check that the file's size is the same as in the file entry (which may
116 // have come from a stat cache).
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000117 if (getRawBuffer()->getBufferSize() != (size_t)ContentsEntry->getSize()) {
Chris Lattner5631b052010-11-23 08:50:03 +0000118 if (Diag.isDiagnosticInFlight())
119 Diag.SetDelayedDiagnostic(diag::err_file_modified,
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000120 ContentsEntry->getName());
Chris Lattner5631b052010-11-23 08:50:03 +0000121 else
122 Diag.Report(Loc, diag::err_file_modified)
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000123 << ContentsEntry->getName();
Chris Lattner5631b052010-11-23 08:50:03 +0000124
125 Buffer.setInt(Buffer.getInt() | InvalidFlag);
126 if (Invalid) *Invalid = true;
127 return Buffer.getPointer();
128 }
129
130 // If the buffer is valid, check to see if it has a UTF Byte Order Mark
131 // (BOM). We only support UTF-8 without a BOM right now. See
132 // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
133 llvm::StringRef BufStr = Buffer.getPointer()->getBuffer();
134 const char *BOM = llvm::StringSwitch<const char *>(BufStr)
135 .StartsWith("\xEF\xBB\xBF", "UTF-8")
136 .StartsWith("\xFE\xFF", "UTF-16 (BE)")
137 .StartsWith("\xFF\xFE", "UTF-16 (LE)")
138 .StartsWith("\x00\x00\xFE\xFF", "UTF-32 (BE)")
139 .StartsWith("\xFF\xFE\x00\x00", "UTF-32 (LE)")
140 .StartsWith("\x2B\x2F\x76", "UTF-7")
141 .StartsWith("\xF7\x64\x4C", "UTF-1")
142 .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
143 .StartsWith("\x0E\xFE\xFF", "SDSU")
144 .StartsWith("\xFB\xEE\x28", "BOCU-1")
145 .StartsWith("\x84\x31\x95\x33", "GB-18030")
146 .Default(0);
147
148 if (BOM) {
149 Diag.Report(Loc, diag::err_unsupported_bom)
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000150 << BOM << ContentsEntry->getName();
Chris Lattner5631b052010-11-23 08:50:03 +0000151 Buffer.setInt(Buffer.getInt() | InvalidFlag);
Ted Kremenek763ea552009-01-06 22:43:04 +0000152 }
Douglas Gregor802b7762010-03-15 22:54:52 +0000153
Douglas Gregor82752ec2010-03-16 22:53:51 +0000154 if (Invalid)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000155 *Invalid = isBufferInvalid();
Douglas Gregor82752ec2010-03-16 22:53:51 +0000156
157 return Buffer.getPointer();
Ted Kremenek12c2af42009-01-06 01:55:26 +0000158}
159
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000160unsigned LineTableInfo::getLineTableFilenameID(const char *Ptr, unsigned Len) {
161 // Look up the filename in the string table, returning the pre-existing value
162 // if it exists.
Mike Stump11289f42009-09-09 15:08:12 +0000163 llvm::StringMapEntry<unsigned> &Entry =
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000164 FilenameIDs.GetOrCreateValue(Ptr, Ptr+Len, ~0U);
165 if (Entry.getValue() != ~0U)
166 return Entry.getValue();
Mike Stump11289f42009-09-09 15:08:12 +0000167
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000168 // Otherwise, assign this the next available ID.
169 Entry.setValue(FilenamesByID.size());
170 FilenamesByID.push_back(&Entry);
171 return FilenamesByID.size()-1;
172}
173
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000174/// AddLineNote - Add a line note to the line table that indicates that there
175/// is a #line at the specified FID/Offset location which changes the presumed
176/// location to LineNo/FilenameID.
Chris Lattner153a0f12009-02-04 00:40:31 +0000177void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000178 unsigned LineNo, int FilenameID) {
Chris Lattner153a0f12009-02-04 00:40:31 +0000179 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump11289f42009-09-09 15:08:12 +0000180
Chris Lattner153a0f12009-02-04 00:40:31 +0000181 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
182 "Adding line entries out of order!");
Mike Stump11289f42009-09-09 15:08:12 +0000183
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000184 SrcMgr::CharacteristicKind Kind = SrcMgr::C_User;
Chris Lattner1c967782009-02-04 06:25:26 +0000185 unsigned IncludeOffset = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000186
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000187 if (!Entries.empty()) {
188 // If this is a '#line 4' after '#line 42 "foo.h"', make sure to remember
189 // that we are still in "foo.h".
190 if (FilenameID == -1)
191 FilenameID = Entries.back().FilenameID;
Mike Stump11289f42009-09-09 15:08:12 +0000192
Chris Lattner1c967782009-02-04 06:25:26 +0000193 // If we are after a line marker that switched us to system header mode, or
194 // that set #include information, preserve it.
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000195 Kind = Entries.back().FileKind;
Chris Lattner1c967782009-02-04 06:25:26 +0000196 IncludeOffset = Entries.back().IncludeOffset;
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000197 }
Mike Stump11289f42009-09-09 15:08:12 +0000198
Chris Lattner1c967782009-02-04 06:25:26 +0000199 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, Kind,
200 IncludeOffset));
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000201}
202
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000203/// AddLineNote This is the same as the previous version of AddLineNote, but is
204/// used for GNU line markers. If EntryExit is 0, then this doesn't change the
205/// presumed #include stack. If it is 1, this is a file entry, if it is 2 then
206/// this is a file exit. FileKind specifies whether this is a system header or
207/// extern C system header.
208void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
209 unsigned LineNo, int FilenameID,
210 unsigned EntryExit,
211 SrcMgr::CharacteristicKind FileKind) {
212 assert(FilenameID != -1 && "Unspecified filename should use other accessor");
Mike Stump11289f42009-09-09 15:08:12 +0000213
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000214 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump11289f42009-09-09 15:08:12 +0000215
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000216 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
217 "Adding line entries out of order!");
218
Chris Lattner1c967782009-02-04 06:25:26 +0000219 unsigned IncludeOffset = 0;
220 if (EntryExit == 0) { // No #include stack change.
221 IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
222 } else if (EntryExit == 1) {
223 IncludeOffset = Offset-1;
224 } else if (EntryExit == 2) {
225 assert(!Entries.empty() && Entries.back().IncludeOffset &&
226 "PPDirectives should have caught case when popping empty include stack");
Mike Stump11289f42009-09-09 15:08:12 +0000227
Chris Lattner1c967782009-02-04 06:25:26 +0000228 // Get the include loc of the last entries' include loc as our include loc.
229 IncludeOffset = 0;
230 if (const LineEntry *PrevEntry =
231 FindNearestLineEntry(FID, Entries.back().IncludeOffset))
232 IncludeOffset = PrevEntry->IncludeOffset;
233 }
Mike Stump11289f42009-09-09 15:08:12 +0000234
Chris Lattner1c967782009-02-04 06:25:26 +0000235 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
236 IncludeOffset));
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000237}
238
239
Chris Lattnerd4293922009-02-04 01:55:42 +0000240/// FindNearestLineEntry - Find the line entry nearest to FID that is before
241/// it. If there is no line entry before Offset in FID, return null.
Mike Stump11289f42009-09-09 15:08:12 +0000242const LineEntry *LineTableInfo::FindNearestLineEntry(unsigned FID,
Chris Lattnerd4293922009-02-04 01:55:42 +0000243 unsigned Offset) {
244 const std::vector<LineEntry> &Entries = LineEntries[FID];
245 assert(!Entries.empty() && "No #line entries for this FID after all!");
246
Chris Lattner334a2ad2009-02-04 04:46:59 +0000247 // It is very common for the query to be after the last #line, check this
248 // first.
249 if (Entries.back().FileOffset <= Offset)
250 return &Entries.back();
Chris Lattnerd4293922009-02-04 01:55:42 +0000251
Chris Lattner334a2ad2009-02-04 04:46:59 +0000252 // Do a binary search to find the maximal element that is still before Offset.
253 std::vector<LineEntry>::const_iterator I =
254 std::upper_bound(Entries.begin(), Entries.end(), Offset);
255 if (I == Entries.begin()) return 0;
256 return &*--I;
Chris Lattnerd4293922009-02-04 01:55:42 +0000257}
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000258
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000259/// \brief Add a new line entry that has already been encoded into
260/// the internal representation of the line table.
Mike Stump11289f42009-09-09 15:08:12 +0000261void LineTableInfo::AddEntry(unsigned FID,
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000262 const std::vector<LineEntry> &Entries) {
263 LineEntries[FID] = Entries;
264}
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000265
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000266/// getLineTableFilenameID - Return the uniqued ID for the specified filename.
Mike Stump11289f42009-09-09 15:08:12 +0000267///
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000268unsigned SourceManager::getLineTableFilenameID(const char *Ptr, unsigned Len) {
269 if (LineTable == 0)
270 LineTable = new LineTableInfo();
271 return LineTable->getLineTableFilenameID(Ptr, Len);
272}
273
274
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000275/// AddLineNote - Add a line note to the line table for the FileID and offset
276/// specified by Loc. If FilenameID is -1, it is considered to be
277/// unspecified.
278void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
279 int FilenameID) {
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000280 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000281
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000282 const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile();
283
284 // Remember that this file has #line directives now if it doesn't already.
285 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump11289f42009-09-09 15:08:12 +0000286
Chris Lattner6e0e1f42009-02-03 22:13:05 +0000287 if (LineTable == 0)
288 LineTable = new LineTableInfo();
Chris Lattner153a0f12009-02-04 00:40:31 +0000289 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID);
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000290}
291
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000292/// AddLineNote - Add a GNU line marker to the line table.
293void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
294 int FilenameID, bool IsFileEntry,
295 bool IsFileExit, bool IsSystemHeader,
296 bool IsExternCHeader) {
297 // If there is no filename and no flags, this is treated just like a #line,
298 // which does not change the flags of the previous line marker.
299 if (FilenameID == -1) {
300 assert(!IsFileEntry && !IsFileExit && !IsSystemHeader && !IsExternCHeader &&
301 "Can't set flags without setting the filename!");
302 return AddLineNote(Loc, LineNo, FilenameID);
303 }
Mike Stump11289f42009-09-09 15:08:12 +0000304
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000305 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
306 const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile();
Mike Stump11289f42009-09-09 15:08:12 +0000307
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000308 // Remember that this file has #line directives now if it doesn't already.
309 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump11289f42009-09-09 15:08:12 +0000310
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000311 if (LineTable == 0)
312 LineTable = new LineTableInfo();
Mike Stump11289f42009-09-09 15:08:12 +0000313
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000314 SrcMgr::CharacteristicKind FileKind;
315 if (IsExternCHeader)
316 FileKind = SrcMgr::C_ExternCSystem;
317 else if (IsSystemHeader)
318 FileKind = SrcMgr::C_System;
319 else
320 FileKind = SrcMgr::C_User;
Mike Stump11289f42009-09-09 15:08:12 +0000321
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000322 unsigned EntryExit = 0;
323 if (IsFileEntry)
324 EntryExit = 1;
325 else if (IsFileExit)
326 EntryExit = 2;
Mike Stump11289f42009-09-09 15:08:12 +0000327
Chris Lattner0a1a8d82009-02-04 05:21:58 +0000328 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID,
329 EntryExit, FileKind);
330}
331
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000332LineTableInfo &SourceManager::getLineTable() {
333 if (LineTable == 0)
334 LineTable = new LineTableInfo();
335 return *LineTable;
336}
Chris Lattner1eaa70a2009-02-03 21:52:55 +0000337
Chris Lattner153a0f12009-02-04 00:40:31 +0000338//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +0000339// Private 'Create' methods.
Chris Lattner153a0f12009-02-04 00:40:31 +0000340//===----------------------------------------------------------------------===//
Ted Kremenek12c2af42009-01-06 01:55:26 +0000341
Chris Lattner5159f612010-11-23 08:35:12 +0000342SourceManager::SourceManager(Diagnostic &Diag, FileManager &FileMgr)
343 : Diag(Diag), FileMgr(FileMgr),
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000344 ExternalSLocEntries(0), LineTable(0), NumLinearScans(0),
345 NumBinaryProbes(0) {
346 clearIDTables();
347 Diag.setSourceManager(this);
348}
349
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000350SourceManager::~SourceManager() {
351 delete LineTable;
Mike Stump11289f42009-09-09 15:08:12 +0000352
Chris Lattnerc8233df2009-02-03 07:30:45 +0000353 // Delete FileEntry objects corresponding to content caches. Since the actual
354 // content cache objects are bump pointer allocated, we just have to run the
355 // dtors, but we call the deallocate method for completeness.
356 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
357 MemBufferInfos[i]->~ContentCache();
358 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
359 }
360 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
361 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
362 I->second->~ContentCache();
363 ContentCacheAlloc.Deallocate(I->second);
364 }
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000365}
366
367void SourceManager::clearIDTables() {
368 MainFileID = FileID();
369 SLocEntryTable.clear();
370 LastLineNoFileIDQuery = FileID();
371 LastLineNoContentCache = 0;
372 LastFileIDLookup = FileID();
Mike Stump11289f42009-09-09 15:08:12 +0000373
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000374 if (LineTable)
375 LineTable->clear();
Mike Stump11289f42009-09-09 15:08:12 +0000376
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000377 // Use up FileID #0 as an invalid instantiation.
378 NextOffset = 0;
Chris Lattner9dc9c202009-02-15 20:52:18 +0000379 createInstantiationLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1);
Chris Lattnerb5fba6f2009-01-26 07:57:50 +0000380}
381
Chris Lattner4fa23622009-01-26 00:43:02 +0000382/// getOrCreateContentCache - Create or return a cached ContentCache for the
383/// specified file.
384const ContentCache *
385SourceManager::getOrCreateContentCache(const FileEntry *FileEnt) {
Chris Lattner22eb9722006-06-18 05:43:12 +0000386 assert(FileEnt && "Didn't specify a file entry to use?");
Mike Stump11289f42009-09-09 15:08:12 +0000387
Chris Lattner22eb9722006-06-18 05:43:12 +0000388 // Do we already have information about this file?
Chris Lattnerc8233df2009-02-03 07:30:45 +0000389 ContentCache *&Entry = FileInfos[FileEnt];
390 if (Entry) return Entry;
Mike Stump11289f42009-09-09 15:08:12 +0000391
Chris Lattner9be4f6d2009-02-03 07:41:46 +0000392 // Nope, create a new Cache entry. Make sure it is at least 8-byte aligned
393 // so that FileInfo can use the low 3 bits of the pointer for its own
394 // nefarious purposes.
395 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
396 EntryAlign = std::max(8U, EntryAlign);
397 Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000398
399 // If the file contents are overridden with contents from another file,
400 // pass that file to ContentCache.
401 llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
402 overI = OverriddenFiles.find(FileEnt);
403 if (overI == OverriddenFiles.end())
404 new (Entry) ContentCache(FileEnt);
405 else
406 new (Entry) ContentCache(FileEnt, overI->second);
407
Chris Lattnerc8233df2009-02-03 07:30:45 +0000408 return Entry;
Chris Lattner22eb9722006-06-18 05:43:12 +0000409}
410
411
Ted Kremenek08bed092007-10-31 17:53:38 +0000412/// createMemBufferContentCache - Create a new ContentCache for the specified
413/// memory buffer. This does no caching.
Ted Kremenekc08bca62007-10-30 21:08:08 +0000414const ContentCache*
415SourceManager::createMemBufferContentCache(const MemoryBuffer *Buffer) {
Chris Lattner9be4f6d2009-02-03 07:41:46 +0000416 // Add a new ContentCache to the MemBufferInfos list and return it. Make sure
417 // it is at least 8-byte aligned so that FileInfo can use the low 3 bits of
418 // the pointer for its own nefarious purposes.
419 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
420 EntryAlign = std::max(8U, EntryAlign);
421 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattnerc8233df2009-02-03 07:30:45 +0000422 new (Entry) ContentCache();
423 MemBufferInfos.push_back(Entry);
424 Entry->setBuffer(Buffer);
425 return Entry;
Chris Lattner22eb9722006-06-18 05:43:12 +0000426}
427
Douglas Gregor258ae542009-04-27 06:38:32 +0000428void SourceManager::PreallocateSLocEntries(ExternalSLocEntrySource *Source,
429 unsigned NumSLocEntries,
430 unsigned NextOffset) {
431 ExternalSLocEntries = Source;
432 this->NextOffset = NextOffset;
Sebastian Redl887d6b02010-07-28 21:07:02 +0000433 unsigned CurPrealloc = SLocEntryLoaded.size();
434 // If we've ever preallocated, we must not count the dummy entry.
435 if (CurPrealloc) --CurPrealloc;
Douglas Gregor258ae542009-04-27 06:38:32 +0000436 SLocEntryLoaded.resize(NumSLocEntries + 1);
437 SLocEntryLoaded[0] = true;
Sebastian Redl887d6b02010-07-28 21:07:02 +0000438 SLocEntryTable.resize(SLocEntryTable.size() + NumSLocEntries - CurPrealloc);
Douglas Gregor258ae542009-04-27 06:38:32 +0000439}
440
Douglas Gregor0bc12932009-04-27 21:28:04 +0000441void SourceManager::ClearPreallocatedSLocEntries() {
442 unsigned I = 0;
443 for (unsigned N = SLocEntryLoaded.size(); I != N; ++I)
444 if (!SLocEntryLoaded[I])
445 break;
446
447 // We've already loaded all preallocated source location entries.
448 if (I == SLocEntryLoaded.size())
449 return;
450
451 // Remove everything from location I onward.
452 SLocEntryTable.resize(I);
453 SLocEntryLoaded.clear();
454 ExternalSLocEntries = 0;
455}
456
Douglas Gregor258ae542009-04-27 06:38:32 +0000457
Chris Lattner4fa23622009-01-26 00:43:02 +0000458//===----------------------------------------------------------------------===//
459// Methods to create new FileID's and instantiations.
460//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +0000461
Dan Gohmance46f022010-08-26 21:27:06 +0000462/// createFileID - Create a new FileID for the specified ContentCache and
Ted Kremeneke26f3c52007-10-30 22:57:35 +0000463/// include position. This works regardless of whether the ContentCache
464/// corresponds to a file or some other input source.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000465FileID SourceManager::createFileID(const ContentCache *File,
Chris Lattner4fa23622009-01-26 00:43:02 +0000466 SourceLocation IncludePos,
Douglas Gregor258ae542009-04-27 06:38:32 +0000467 SrcMgr::CharacteristicKind FileCharacter,
468 unsigned PreallocatedID,
469 unsigned Offset) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000470 if (PreallocatedID) {
471 // If we're filling in a preallocated ID, just load in the file
472 // entry and return.
Mike Stump11289f42009-09-09 15:08:12 +0000473 assert(PreallocatedID < SLocEntryLoaded.size() &&
Douglas Gregor258ae542009-04-27 06:38:32 +0000474 "Preallocate ID out-of-range");
Mike Stump11289f42009-09-09 15:08:12 +0000475 assert(!SLocEntryLoaded[PreallocatedID] &&
Douglas Gregor258ae542009-04-27 06:38:32 +0000476 "Source location entry already loaded");
477 assert(Offset && "Preallocate source location cannot have zero offset");
Mike Stump11289f42009-09-09 15:08:12 +0000478 SLocEntryTable[PreallocatedID]
Douglas Gregor258ae542009-04-27 06:38:32 +0000479 = SLocEntry::get(Offset, FileInfo::get(IncludePos, File, FileCharacter));
480 SLocEntryLoaded[PreallocatedID] = true;
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +0000481 FileID FID = FileID::get(PreallocatedID);
Douglas Gregor51c23512010-03-19 06:12:06 +0000482 return FID;
Douglas Gregor258ae542009-04-27 06:38:32 +0000483 }
484
Mike Stump11289f42009-09-09 15:08:12 +0000485 SLocEntryTable.push_back(SLocEntry::get(NextOffset,
Chris Lattner4fa23622009-01-26 00:43:02 +0000486 FileInfo::get(IncludePos, File,
487 FileCharacter)));
Ted Kremenek12c2af42009-01-06 01:55:26 +0000488 unsigned FileSize = File->getSize();
Chris Lattner4fa23622009-01-26 00:43:02 +0000489 assert(NextOffset+FileSize+1 > NextOffset && "Ran out of source locations!");
490 NextOffset += FileSize+1;
Mike Stump11289f42009-09-09 15:08:12 +0000491
Chris Lattner4fa23622009-01-26 00:43:02 +0000492 // Set LastFileIDLookup to the newly created file. The next getFileID call is
493 // almost guaranteed to be from that file.
Argyrios Kyrtzidis0152c6c2009-06-23 00:42:06 +0000494 FileID FID = FileID::get(SLocEntryTable.size()-1);
Argyrios Kyrtzidis0152c6c2009-06-23 00:42:06 +0000495 return LastFileIDLookup = FID;
Chris Lattner22eb9722006-06-18 05:43:12 +0000496}
497
Chris Lattner4fa23622009-01-26 00:43:02 +0000498/// createInstantiationLoc - Return a new SourceLocation that encodes the fact
Chris Lattner53e384f2009-01-16 07:00:02 +0000499/// that a token from SpellingLoc should actually be referenced from
Chris Lattner7d6a4f62006-06-30 06:10:08 +0000500/// InstantiationLoc.
Chris Lattner4fa23622009-01-26 00:43:02 +0000501SourceLocation SourceManager::createInstantiationLoc(SourceLocation SpellingLoc,
Chris Lattner9dc9c202009-02-15 20:52:18 +0000502 SourceLocation ILocStart,
503 SourceLocation ILocEnd,
Douglas Gregor258ae542009-04-27 06:38:32 +0000504 unsigned TokLength,
505 unsigned PreallocatedID,
506 unsigned Offset) {
Chris Lattner9dc9c202009-02-15 20:52:18 +0000507 InstantiationInfo II = InstantiationInfo::get(ILocStart,ILocEnd, SpellingLoc);
Douglas Gregor258ae542009-04-27 06:38:32 +0000508 if (PreallocatedID) {
509 // If we're filling in a preallocated ID, just load in the
510 // instantiation entry and return.
Mike Stump11289f42009-09-09 15:08:12 +0000511 assert(PreallocatedID < SLocEntryLoaded.size() &&
Douglas Gregor258ae542009-04-27 06:38:32 +0000512 "Preallocate ID out-of-range");
Mike Stump11289f42009-09-09 15:08:12 +0000513 assert(!SLocEntryLoaded[PreallocatedID] &&
Douglas Gregor258ae542009-04-27 06:38:32 +0000514 "Source location entry already loaded");
515 assert(Offset && "Preallocate source location cannot have zero offset");
516 SLocEntryTable[PreallocatedID] = SLocEntry::get(Offset, II);
517 SLocEntryLoaded[PreallocatedID] = true;
518 return SourceLocation::getMacroLoc(Offset);
519 }
Chris Lattner9dc9c202009-02-15 20:52:18 +0000520 SLocEntryTable.push_back(SLocEntry::get(NextOffset, II));
Chris Lattner4fa23622009-01-26 00:43:02 +0000521 assert(NextOffset+TokLength+1 > NextOffset && "Ran out of source locations!");
522 NextOffset += TokLength+1;
523 return SourceLocation::getMacroLoc(NextOffset-(TokLength+1));
Chris Lattner7d6a4f62006-06-30 06:10:08 +0000524}
525
Douglas Gregor874cc622010-03-16 00:35:39 +0000526const llvm::MemoryBuffer *
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000527SourceManager::getMemoryBufferForFile(const FileEntry *File,
528 bool *Invalid) {
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000529 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
Douglas Gregor802b7762010-03-15 22:54:52 +0000530 assert(IR && "getOrCreateContentCache() cannot return NULL");
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000531 return IR->getBuffer(Diag, *this, SourceLocation(), Invalid);
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000532}
533
Dan Gohman5d223dc2010-10-26 20:47:28 +0000534void SourceManager::overrideFileContents(const FileEntry *SourceFile,
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000535 const llvm::MemoryBuffer *Buffer,
536 bool DoNotFree) {
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000537 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
Dan Gohman5d223dc2010-10-26 20:47:28 +0000538 assert(IR && "getOrCreateContentCache() cannot return NULL");
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000539
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000540 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree);
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000541}
542
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +0000543void SourceManager::overrideFileContents(const FileEntry *SourceFile,
544 const FileEntry *NewFile) {
545 assert(SourceFile->getSize() == NewFile->getSize() &&
546 "Different sizes, use the FileManager to create a virtual file with "
547 "the correct size");
548 assert(FileInfos.count(SourceFile) == 0 &&
549 "This function should be called at the initialization stage, before "
550 "any parsing occurs.");
551 OverriddenFiles[SourceFile] = NewFile;
552}
553
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000554llvm::StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
Douglas Gregor4fb7fbe2010-03-16 20:01:30 +0000555 bool MyInvalid = false;
Douglas Gregor86af9842011-01-31 22:42:36 +0000556 const SLocEntry &SLoc = getSLocEntry(FID.ID);
557 if (!SLoc.isFile()) {
558 if (Invalid)
559 *Invalid = true;
560 return "<<<<<INVALID SOURCE LOCATION>>>>>";
561 }
562
563 const llvm::MemoryBuffer *Buf
564 = SLoc.getFile().getContentCache()->getBuffer(Diag, *this, SourceLocation(),
565 &MyInvalid);
Douglas Gregore0fbb832010-03-16 00:06:06 +0000566 if (Invalid)
Douglas Gregor4fb7fbe2010-03-16 20:01:30 +0000567 *Invalid = MyInvalid;
568
569 if (MyInvalid)
Douglas Gregor86af9842011-01-31 22:42:36 +0000570 return "<<<<<INVALID SOURCE LOCATION>>>>>";
Douglas Gregor4fb7fbe2010-03-16 20:01:30 +0000571
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000572 return Buf->getBuffer();
Douglas Gregor802b7762010-03-15 22:54:52 +0000573}
Chris Lattnerd32480d2009-01-17 06:22:33 +0000574
Chris Lattner153a0f12009-02-04 00:40:31 +0000575//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +0000576// SourceLocation manipulation methods.
Chris Lattner153a0f12009-02-04 00:40:31 +0000577//===----------------------------------------------------------------------===//
Chris Lattner4fa23622009-01-26 00:43:02 +0000578
579/// getFileIDSlow - Return the FileID for a SourceLocation. This is a very hot
580/// method that is used for all SourceManager queries that start with a
581/// SourceLocation object. It is responsible for finding the entry in
582/// SLocEntryTable which contains the specified location.
583///
584FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
585 assert(SLocOffset && "Invalid FileID");
Mike Stump11289f42009-09-09 15:08:12 +0000586
Chris Lattner4fa23622009-01-26 00:43:02 +0000587 // After the first and second level caches, I see two common sorts of
588 // behavior: 1) a lot of searched FileID's are "near" the cached file location
589 // or are "near" the cached instantiation location. 2) others are just
590 // completely random and may be a very long way away.
591 //
592 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
593 // then we fall back to a less cache efficient, but more scalable, binary
594 // search to find the location.
Mike Stump11289f42009-09-09 15:08:12 +0000595
Chris Lattner4fa23622009-01-26 00:43:02 +0000596 // See if this is near the file point - worst case we start scanning from the
597 // most newly created FileID.
598 std::vector<SrcMgr::SLocEntry>::const_iterator I;
Mike Stump11289f42009-09-09 15:08:12 +0000599
Chris Lattner4fa23622009-01-26 00:43:02 +0000600 if (SLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
601 // Neither loc prunes our search.
602 I = SLocEntryTable.end();
603 } else {
604 // Perhaps it is near the file point.
605 I = SLocEntryTable.begin()+LastFileIDLookup.ID;
606 }
607
608 // Find the FileID that contains this. "I" is an iterator that points to a
609 // FileID whose offset is known to be larger than SLocOffset.
610 unsigned NumProbes = 0;
611 while (1) {
612 --I;
Douglas Gregor258ae542009-04-27 06:38:32 +0000613 if (ExternalSLocEntries)
614 getSLocEntry(FileID::get(I - SLocEntryTable.begin()));
Chris Lattner4fa23622009-01-26 00:43:02 +0000615 if (I->getOffset() <= SLocOffset) {
616#if 0
617 printf("lin %d -> %d [%s] %d %d\n", SLocOffset,
618 I-SLocEntryTable.begin(),
619 I->isInstantiation() ? "inst" : "file",
620 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
621#endif
622 FileID Res = FileID::get(I-SLocEntryTable.begin());
Douglas Gregor258ae542009-04-27 06:38:32 +0000623
Chris Lattner4fa23622009-01-26 00:43:02 +0000624 // If this isn't an instantiation, remember it. We have good locality
625 // across FileID lookups.
626 if (!I->isInstantiation())
627 LastFileIDLookup = Res;
628 NumLinearScans += NumProbes+1;
629 return Res;
630 }
631 if (++NumProbes == 8)
632 break;
633 }
Mike Stump11289f42009-09-09 15:08:12 +0000634
Chris Lattner4fa23622009-01-26 00:43:02 +0000635 // Convert "I" back into an index. We know that it is an entry whose index is
636 // larger than the offset we are looking for.
637 unsigned GreaterIndex = I-SLocEntryTable.begin();
638 // LessIndex - This is the lower bound of the range that we're searching.
639 // We know that the offset corresponding to the FileID is is less than
640 // SLocOffset.
641 unsigned LessIndex = 0;
642 NumProbes = 0;
643 while (1) {
644 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
Douglas Gregor258ae542009-04-27 06:38:32 +0000645 unsigned MidOffset = getSLocEntry(FileID::get(MiddleIndex)).getOffset();
Mike Stump11289f42009-09-09 15:08:12 +0000646
Chris Lattner4fa23622009-01-26 00:43:02 +0000647 ++NumProbes;
Mike Stump11289f42009-09-09 15:08:12 +0000648
Chris Lattner4fa23622009-01-26 00:43:02 +0000649 // If the offset of the midpoint is too large, chop the high side of the
650 // range to the midpoint.
651 if (MidOffset > SLocOffset) {
652 GreaterIndex = MiddleIndex;
653 continue;
654 }
Mike Stump11289f42009-09-09 15:08:12 +0000655
Chris Lattner4fa23622009-01-26 00:43:02 +0000656 // If the middle index contains the value, succeed and return.
657 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
658#if 0
659 printf("bin %d -> %d [%s] %d %d\n", SLocOffset,
660 I-SLocEntryTable.begin(),
661 I->isInstantiation() ? "inst" : "file",
662 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
663#endif
664 FileID Res = FileID::get(MiddleIndex);
665
666 // If this isn't an instantiation, remember it. We have good locality
667 // across FileID lookups.
668 if (!I->isInstantiation())
669 LastFileIDLookup = Res;
670 NumBinaryProbes += NumProbes;
671 return Res;
672 }
Mike Stump11289f42009-09-09 15:08:12 +0000673
Chris Lattner4fa23622009-01-26 00:43:02 +0000674 // Otherwise, move the low-side up to the middle index.
675 LessIndex = MiddleIndex;
676 }
677}
678
Chris Lattner659ac5f2009-01-26 20:04:19 +0000679SourceLocation SourceManager::
680getInstantiationLocSlowCase(SourceLocation Loc) const {
681 do {
Chris Lattner5647d312010-02-12 19:31:35 +0000682 // Note: If Loc indicates an offset into a token that came from a macro
683 // expansion (e.g. the 5th character of the token) we do not want to add
684 // this offset when going to the instantiation location. The instatiation
685 // location is the macro invocation, which the offset has nothing to do
686 // with. This is unlike when we get the spelling loc, because the offset
687 // directly correspond to the token whose spelling we're inspecting.
688 Loc = getSLocEntry(getFileID(Loc)).getInstantiation()
Chris Lattner9dc9c202009-02-15 20:52:18 +0000689 .getInstantiationLocStart();
Chris Lattner659ac5f2009-01-26 20:04:19 +0000690 } while (!Loc.isFileID());
691
692 return Loc;
693}
694
695SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
696 do {
697 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
698 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
699 Loc = Loc.getFileLocWithOffset(LocInfo.second);
700 } while (!Loc.isFileID());
701 return Loc;
702}
703
704
Chris Lattner4fa23622009-01-26 00:43:02 +0000705std::pair<FileID, unsigned>
706SourceManager::getDecomposedInstantiationLocSlowCase(const SrcMgr::SLocEntry *E,
707 unsigned Offset) const {
708 // If this is an instantiation record, walk through all the instantiation
709 // points.
710 FileID FID;
711 SourceLocation Loc;
712 do {
Chris Lattner9dc9c202009-02-15 20:52:18 +0000713 Loc = E->getInstantiation().getInstantiationLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000714
Chris Lattner4fa23622009-01-26 00:43:02 +0000715 FID = getFileID(Loc);
716 E = &getSLocEntry(FID);
717 Offset += Loc.getOffset()-E->getOffset();
Chris Lattner31af4e02009-01-26 19:41:58 +0000718 } while (!Loc.isFileID());
Mike Stump11289f42009-09-09 15:08:12 +0000719
Chris Lattner4fa23622009-01-26 00:43:02 +0000720 return std::make_pair(FID, Offset);
721}
722
723std::pair<FileID, unsigned>
724SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
725 unsigned Offset) const {
Chris Lattner31af4e02009-01-26 19:41:58 +0000726 // If this is an instantiation record, walk through all the instantiation
727 // points.
728 FileID FID;
729 SourceLocation Loc;
730 do {
731 Loc = E->getInstantiation().getSpellingLoc();
Mike Stump11289f42009-09-09 15:08:12 +0000732
Chris Lattner31af4e02009-01-26 19:41:58 +0000733 FID = getFileID(Loc);
734 E = &getSLocEntry(FID);
735 Offset += Loc.getOffset()-E->getOffset();
736 } while (!Loc.isFileID());
Mike Stump11289f42009-09-09 15:08:12 +0000737
Chris Lattner4fa23622009-01-26 00:43:02 +0000738 return std::make_pair(FID, Offset);
739}
740
Chris Lattner8ad52d52009-02-17 08:04:48 +0000741/// getImmediateSpellingLoc - Given a SourceLocation object, return the
742/// spelling location referenced by the ID. This is the first level down
743/// towards the place where the characters that make up the lexed token can be
744/// found. This should not generally be used by clients.
745SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
746 if (Loc.isFileID()) return Loc;
747 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
748 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
749 return Loc.getFileLocWithOffset(LocInfo.second);
750}
751
752
Chris Lattner9dc9c202009-02-15 20:52:18 +0000753/// getImmediateInstantiationRange - Loc is required to be an instantiation
754/// location. Return the start/end of the instantiation information.
755std::pair<SourceLocation,SourceLocation>
756SourceManager::getImmediateInstantiationRange(SourceLocation Loc) const {
757 assert(Loc.isMacroID() && "Not an instantiation loc!");
758 const InstantiationInfo &II = getSLocEntry(getFileID(Loc)).getInstantiation();
759 return II.getInstantiationLocRange();
760}
761
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000762/// getInstantiationRange - Given a SourceLocation object, return the
763/// range of tokens covered by the instantiation in the ultimate file.
764std::pair<SourceLocation,SourceLocation>
765SourceManager::getInstantiationRange(SourceLocation Loc) const {
766 if (Loc.isFileID()) return std::make_pair(Loc, Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000767
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000768 std::pair<SourceLocation,SourceLocation> Res =
769 getImmediateInstantiationRange(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000770
Chris Lattnerf52c0b22009-02-15 21:26:50 +0000771 // Fully resolve the start and end locations to their ultimate instantiation
772 // points.
773 while (!Res.first.isFileID())
774 Res.first = getImmediateInstantiationRange(Res.first).first;
775 while (!Res.second.isFileID())
776 Res.second = getImmediateInstantiationRange(Res.second).second;
777 return Res;
778}
779
Chris Lattner9dc9c202009-02-15 20:52:18 +0000780
Chris Lattner4fa23622009-01-26 00:43:02 +0000781
782//===----------------------------------------------------------------------===//
783// Queries about the code at a SourceLocation.
784//===----------------------------------------------------------------------===//
Chris Lattner30709b032006-06-21 03:01:55 +0000785
Chris Lattnerd01e2912006-06-18 16:22:51 +0000786/// getCharacterData - Return a pointer to the start of the specified location
Chris Lattner739e7392007-04-29 07:12:06 +0000787/// in the appropriate MemoryBuffer.
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000788const char *SourceManager::getCharacterData(SourceLocation SL,
789 bool *Invalid) const {
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000790 // Note that this is a hot function in the getSpelling() path, which is
791 // heavily used by -E mode.
Chris Lattner4fa23622009-01-26 00:43:02 +0000792 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
Mike Stump11289f42009-09-09 15:08:12 +0000793
Ted Kremenek12c2af42009-01-06 01:55:26 +0000794 // Note that calling 'getBuffer()' may lazily page in a source file.
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000795 bool CharDataInvalid = false;
796 const llvm::MemoryBuffer *Buffer
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000797 = getSLocEntry(LocInfo.first).getFile().getContentCache()
798 ->getBuffer(Diag, *this, SourceLocation(), &CharDataInvalid);
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000799 if (Invalid)
800 *Invalid = CharDataInvalid;
801 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000802}
803
Chris Lattner685730f2006-06-26 01:36:22 +0000804
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000805/// getColumnNumber - Return the column # for the specified file position.
Chris Lattnere4ad4172009-02-04 00:55:58 +0000806/// this is significantly cheaper to compute than the line number.
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000807unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
808 bool *Invalid) const {
809 bool MyInvalid = false;
810 const char *Buf = getBuffer(FID, &MyInvalid)->getBufferStart();
811 if (Invalid)
812 *Invalid = MyInvalid;
813
814 if (MyInvalid)
815 return 1;
Mike Stump11289f42009-09-09 15:08:12 +0000816
Chris Lattner22eb9722006-06-18 05:43:12 +0000817 unsigned LineStart = FilePos;
818 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
819 --LineStart;
820 return FilePos-LineStart+1;
821}
822
Zhanyong Wanea6d7f32010-10-05 17:56:33 +0000823// isInvalid - Return the result of calling loc.isInvalid(), and
824// if Invalid is not null, set its value to same.
825static bool isInvalid(SourceLocation Loc, bool *Invalid) {
826 bool MyInvalid = Loc.isInvalid();
827 if (Invalid)
828 *Invalid = MyInvalid;
829 return MyInvalid;
830}
831
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000832unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
833 bool *Invalid) const {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +0000834 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattnere4ad4172009-02-04 00:55:58 +0000835 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000836 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattnere4ad4172009-02-04 00:55:58 +0000837}
838
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000839unsigned SourceManager::getInstantiationColumnNumber(SourceLocation Loc,
840 bool *Invalid) const {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +0000841 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattnere4ad4172009-02-04 00:55:58 +0000842 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000843 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattnere4ad4172009-02-04 00:55:58 +0000844}
845
Chandler Carruth1aef0c52011-02-23 00:47:48 +0000846unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
847 bool *Invalid) const {
848 if (isInvalid(Loc, Invalid)) return 0;
849 return getPresumedLoc(Loc).getColumn();
850}
851
Chandler Carruthc3ce5842010-10-23 08:44:57 +0000852static LLVM_ATTRIBUTE_NOINLINE void
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000853ComputeLineNumbers(Diagnostic &Diag, ContentCache *FI,
854 llvm::BumpPtrAllocator &Alloc,
855 const SourceManager &SM, bool &Invalid);
856static void ComputeLineNumbers(Diagnostic &Diag, ContentCache *FI,
857 llvm::BumpPtrAllocator &Alloc,
858 const SourceManager &SM, bool &Invalid) {
Ted Kremenek12c2af42009-01-06 01:55:26 +0000859 // Note that calling 'getBuffer()' may lazily page in the file.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000860 const MemoryBuffer *Buffer = FI->getBuffer(Diag, SM, SourceLocation(),
861 &Invalid);
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000862 if (Invalid)
863 return;
Mike Stump11289f42009-09-09 15:08:12 +0000864
Chris Lattner8996fff2007-07-24 05:57:19 +0000865 // Find the file offsets of all of the *physical* source lines. This does
866 // not look at trigraphs, escaped newlines, or anything else tricky.
867 std::vector<unsigned> LineOffsets;
Mike Stump11289f42009-09-09 15:08:12 +0000868
Chris Lattner8996fff2007-07-24 05:57:19 +0000869 // Line #1 starts at char 0.
870 LineOffsets.push_back(0);
Mike Stump11289f42009-09-09 15:08:12 +0000871
Chris Lattner8996fff2007-07-24 05:57:19 +0000872 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
873 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
874 unsigned Offs = 0;
875 while (1) {
876 // Skip over the contents of the line.
877 // TODO: Vectorize this? This is very performance sensitive for programs
878 // with lots of diagnostics and in -E mode.
879 const unsigned char *NextBuf = (const unsigned char *)Buf;
880 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
881 ++NextBuf;
882 Offs += NextBuf-Buf;
883 Buf = NextBuf;
Mike Stump11289f42009-09-09 15:08:12 +0000884
Chris Lattner8996fff2007-07-24 05:57:19 +0000885 if (Buf[0] == '\n' || Buf[0] == '\r') {
886 // If this is \n\r or \r\n, skip both characters.
887 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
888 ++Offs, ++Buf;
889 ++Offs, ++Buf;
890 LineOffsets.push_back(Offs);
891 } else {
892 // Otherwise, this is a null. If end of file, exit.
893 if (Buf == End) break;
894 // Otherwise, skip the null.
895 ++Offs, ++Buf;
896 }
897 }
Mike Stump11289f42009-09-09 15:08:12 +0000898
Chris Lattner8996fff2007-07-24 05:57:19 +0000899 // Copy the offsets into the FileInfo structure.
900 FI->NumLines = LineOffsets.size();
Chris Lattnerc8233df2009-02-03 07:30:45 +0000901 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
Chris Lattner8996fff2007-07-24 05:57:19 +0000902 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
903}
Chris Lattner9a13bde2006-06-21 04:57:09 +0000904
Chris Lattner53e384f2009-01-16 07:00:02 +0000905/// getLineNumber - Given a SourceLocation, return the spelling line number
Chris Lattner22eb9722006-06-18 05:43:12 +0000906/// for the position indicated. This requires building and caching a table of
Chris Lattner739e7392007-04-29 07:12:06 +0000907/// line offsets for the MemoryBuffer, so this is not cheap: use only when
Chris Lattner22eb9722006-06-18 05:43:12 +0000908/// about to emit a diagnostic.
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000909unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
910 bool *Invalid) const {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000911 ContentCache *Content;
Chris Lattner88ea93e2009-02-04 01:06:56 +0000912 if (LastLineNoFileIDQuery == FID)
Ted Kremenekc08bca62007-10-30 21:08:08 +0000913 Content = LastLineNoContentCache;
Chris Lattner8996fff2007-07-24 05:57:19 +0000914 else
Chris Lattner88ea93e2009-02-04 01:06:56 +0000915 Content = const_cast<ContentCache*>(getSLocEntry(FID)
Chris Lattner4fa23622009-01-26 00:43:02 +0000916 .getFile().getContentCache());
Mike Stump11289f42009-09-09 15:08:12 +0000917
Chris Lattner22eb9722006-06-18 05:43:12 +0000918 // If this is the first use of line information for this buffer, compute the
Chris Lattner8996fff2007-07-24 05:57:19 +0000919 /// SourceLineCache for it on demand.
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000920 if (Content->SourceLineCache == 0) {
921 bool MyInvalid = false;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000922 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000923 if (Invalid)
924 *Invalid = MyInvalid;
925 if (MyInvalid)
926 return 1;
927 } else if (Invalid)
928 *Invalid = false;
Chris Lattner22eb9722006-06-18 05:43:12 +0000929
930 // Okay, we know we have a line number table. Do a binary search to find the
931 // line number that this character position lands on.
Ted Kremenekc08bca62007-10-30 21:08:08 +0000932 unsigned *SourceLineCache = Content->SourceLineCache;
Chris Lattner8996fff2007-07-24 05:57:19 +0000933 unsigned *SourceLineCacheStart = SourceLineCache;
Ted Kremenekc08bca62007-10-30 21:08:08 +0000934 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
Mike Stump11289f42009-09-09 15:08:12 +0000935
Chris Lattner88ea93e2009-02-04 01:06:56 +0000936 unsigned QueriedFilePos = FilePos+1;
Chris Lattner8996fff2007-07-24 05:57:19 +0000937
Daniel Dunbar70f924df82009-05-18 17:30:52 +0000938 // FIXME: I would like to be convinced that this code is worth being as
Mike Stump11289f42009-09-09 15:08:12 +0000939 // complicated as it is, binary search isn't that slow.
Daniel Dunbar70f924df82009-05-18 17:30:52 +0000940 //
941 // If it is worth being optimized, then in my opinion it could be more
942 // performant, simpler, and more obviously correct by just "galloping" outward
943 // from the queried file position. In fact, this could be incorporated into a
944 // generic algorithm such as lower_bound_with_hint.
945 //
946 // If someone gives me a test case where this matters, and I will do it! - DWD
947
Chris Lattner8996fff2007-07-24 05:57:19 +0000948 // If the previous query was to the same file, we know both the file pos from
949 // that query and the line number returned. This allows us to narrow the
950 // search space from the entire file to something near the match.
Chris Lattner88ea93e2009-02-04 01:06:56 +0000951 if (LastLineNoFileIDQuery == FID) {
Chris Lattner8996fff2007-07-24 05:57:19 +0000952 if (QueriedFilePos >= LastLineNoFilePos) {
Daniel Dunbar70f924df82009-05-18 17:30:52 +0000953 // FIXME: Potential overflow?
Chris Lattner8996fff2007-07-24 05:57:19 +0000954 SourceLineCache = SourceLineCache+LastLineNoResult-1;
Mike Stump11289f42009-09-09 15:08:12 +0000955
Chris Lattner8996fff2007-07-24 05:57:19 +0000956 // The query is likely to be nearby the previous one. Here we check to
957 // see if it is within 5, 10 or 20 lines. It can be far away in cases
958 // where big comment blocks and vertical whitespace eat up lines but
959 // contribute no tokens.
960 if (SourceLineCache+5 < SourceLineCacheEnd) {
961 if (SourceLineCache[5] > QueriedFilePos)
962 SourceLineCacheEnd = SourceLineCache+5;
963 else if (SourceLineCache+10 < SourceLineCacheEnd) {
964 if (SourceLineCache[10] > QueriedFilePos)
965 SourceLineCacheEnd = SourceLineCache+10;
966 else if (SourceLineCache+20 < SourceLineCacheEnd) {
967 if (SourceLineCache[20] > QueriedFilePos)
968 SourceLineCacheEnd = SourceLineCache+20;
969 }
970 }
971 }
972 } else {
Daniel Dunbar70f924df82009-05-18 17:30:52 +0000973 if (LastLineNoResult < Content->NumLines)
974 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
Chris Lattner8996fff2007-07-24 05:57:19 +0000975 }
976 }
Mike Stump11289f42009-09-09 15:08:12 +0000977
Chris Lattner830a77f2007-07-24 06:43:46 +0000978 // If the spread is large, do a "radix" test as our initial guess, based on
979 // the assumption that lines average to approximately the same length.
980 // NOTE: This is currently disabled, as it does not appear to be profitable in
981 // initial measurements.
982 if (0 && SourceLineCacheEnd-SourceLineCache > 20) {
Ted Kremenekc08bca62007-10-30 21:08:08 +0000983 unsigned FileLen = Content->SourceLineCache[Content->NumLines-1];
Mike Stump11289f42009-09-09 15:08:12 +0000984
Chris Lattner830a77f2007-07-24 06:43:46 +0000985 // Take a stab at guessing where it is.
Ted Kremenekc08bca62007-10-30 21:08:08 +0000986 unsigned ApproxPos = Content->NumLines*QueriedFilePos / FileLen;
Mike Stump11289f42009-09-09 15:08:12 +0000987
Chris Lattner830a77f2007-07-24 06:43:46 +0000988 // Check for -10 and +10 lines.
989 unsigned LowerBound = std::max(int(ApproxPos-10), 0);
990 unsigned UpperBound = std::min(ApproxPos+10, FileLen);
991
992 // If the computed lower bound is less than the query location, move it in.
993 if (SourceLineCache < SourceLineCacheStart+LowerBound &&
994 SourceLineCacheStart[LowerBound] < QueriedFilePos)
995 SourceLineCache = SourceLineCacheStart+LowerBound;
Mike Stump11289f42009-09-09 15:08:12 +0000996
Chris Lattner830a77f2007-07-24 06:43:46 +0000997 // If the computed upper bound is greater than the query location, move it.
998 if (SourceLineCacheEnd > SourceLineCacheStart+UpperBound &&
999 SourceLineCacheStart[UpperBound] >= QueriedFilePos)
1000 SourceLineCacheEnd = SourceLineCacheStart+UpperBound;
1001 }
Mike Stump11289f42009-09-09 15:08:12 +00001002
Chris Lattner830a77f2007-07-24 06:43:46 +00001003 unsigned *Pos
1004 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
Chris Lattner8996fff2007-07-24 05:57:19 +00001005 unsigned LineNo = Pos-SourceLineCacheStart;
Mike Stump11289f42009-09-09 15:08:12 +00001006
Chris Lattner88ea93e2009-02-04 01:06:56 +00001007 LastLineNoFileIDQuery = FID;
Ted Kremenekc08bca62007-10-30 21:08:08 +00001008 LastLineNoContentCache = Content;
Chris Lattner8996fff2007-07-24 05:57:19 +00001009 LastLineNoFilePos = QueriedFilePos;
1010 LastLineNoResult = LineNo;
1011 return LineNo;
Chris Lattner22eb9722006-06-18 05:43:12 +00001012}
1013
Chandler Carruth1aef0c52011-02-23 00:47:48 +00001014unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
1015 bool *Invalid) const {
1016 if (isInvalid(Loc, Invalid)) return 0;
1017 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1018 return getLineNumber(LocInfo.first, LocInfo.second);
1019}
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001020unsigned SourceManager::getInstantiationLineNumber(SourceLocation Loc,
1021 bool *Invalid) const {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +00001022 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattner88ea93e2009-02-04 01:06:56 +00001023 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
1024 return getLineNumber(LocInfo.first, LocInfo.second);
1025}
Chandler Carruth1aef0c52011-02-23 00:47:48 +00001026unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001027 bool *Invalid) const {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +00001028 if (isInvalid(Loc, Invalid)) return 0;
Chandler Carruth1aef0c52011-02-23 00:47:48 +00001029 return getPresumedLoc(Loc).getLine();
Chris Lattner88ea93e2009-02-04 01:06:56 +00001030}
1031
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001032/// getFileCharacteristic - return the file characteristic of the specified
Mike Stump11289f42009-09-09 15:08:12 +00001033/// source location, indicating whether this is a normal file, a system
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001034/// header, or an "implicit extern C" system header.
1035///
1036/// This state can be modified with flags on GNU linemarker directives like:
1037/// # 4 "foo.h" 3
1038/// which changes all source locations in the current file after that to be
1039/// considered to be from a system header.
Mike Stump11289f42009-09-09 15:08:12 +00001040SrcMgr::CharacteristicKind
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001041SourceManager::getFileCharacteristic(SourceLocation Loc) const {
1042 assert(!Loc.isInvalid() && "Can't get file characteristic of invalid loc!");
1043 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
1044 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile();
1045
1046 // If there are no #line directives in this file, just return the whole-file
1047 // state.
1048 if (!FI.hasLineDirectives())
1049 return FI.getFileCharacteristic();
Mike Stump11289f42009-09-09 15:08:12 +00001050
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001051 assert(LineTable && "Can't have linetable entries without a LineTable!");
1052 // See if there is a #line directive before the location.
1053 const LineEntry *Entry =
1054 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second);
Mike Stump11289f42009-09-09 15:08:12 +00001055
Chris Lattner95d9c5e2009-02-04 05:33:01 +00001056 // If this is before the first line marker, use the file characteristic.
1057 if (!Entry)
1058 return FI.getFileCharacteristic();
1059
1060 return Entry->FileKind;
1061}
1062
Chris Lattnera6f037c2009-02-17 08:39:06 +00001063/// Return the filename or buffer identifier of the buffer the location is in.
1064/// Note that this name does not respect #line directives. Use getPresumedLoc
1065/// for normal clients.
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001066const char *SourceManager::getBufferName(SourceLocation Loc,
1067 bool *Invalid) const {
Zhanyong Wanea6d7f32010-10-05 17:56:33 +00001068 if (isInvalid(Loc, Invalid)) return "<invalid loc>";
Mike Stump11289f42009-09-09 15:08:12 +00001069
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001070 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
Chris Lattnera6f037c2009-02-17 08:39:06 +00001071}
1072
Chris Lattner88ea93e2009-02-04 01:06:56 +00001073
Chris Lattnerf1ca7d32009-01-27 07:57:44 +00001074/// getPresumedLoc - This method returns the "presumed" location of a
1075/// SourceLocation specifies. A "presumed location" can be modified by #line
1076/// or GNU line marker directives. This provides a view on the data that a
1077/// user should see in diagnostics, for example.
1078///
1079/// Note that a presumed location is always given as the instantiation point
1080/// of an instantiation location, not at the spelling location.
1081PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc) const {
1082 if (Loc.isInvalid()) return PresumedLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001083
Chris Lattnerf1ca7d32009-01-27 07:57:44 +00001084 // Presumed locations are always for instantiation points.
Chris Lattnere4ad4172009-02-04 00:55:58 +00001085 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +00001086
Chris Lattner88ea93e2009-02-04 01:06:56 +00001087 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile();
Chris Lattnerf1ca7d32009-01-27 07:57:44 +00001088 const SrcMgr::ContentCache *C = FI.getContentCache();
Mike Stump11289f42009-09-09 15:08:12 +00001089
Chris Lattnerd4293922009-02-04 01:55:42 +00001090 // To get the source name, first consult the FileEntry (if one exists)
1091 // before the MemBuffer as this will avoid unnecessarily paging in the
1092 // MemBuffer.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001093 const char *Filename;
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001094 if (C->OrigEntry)
1095 Filename = C->OrigEntry->getName();
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001096 else
1097 Filename = C->getBuffer(Diag, *this)->getBufferIdentifier();
Douglas Gregor75f26d62010-11-02 00:39:22 +00001098 bool Invalid = false;
1099 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1100 if (Invalid)
1101 return PresumedLoc();
1102 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1103 if (Invalid)
1104 return PresumedLoc();
1105
Chris Lattnerd4293922009-02-04 01:55:42 +00001106 SourceLocation IncludeLoc = FI.getIncludeLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001107
Chris Lattnerd4293922009-02-04 01:55:42 +00001108 // If we have #line directives in this file, update and overwrite the physical
1109 // location info if appropriate.
1110 if (FI.hasLineDirectives()) {
1111 assert(LineTable && "Can't have linetable entries without a LineTable!");
1112 // See if there is a #line directive before this. If so, get it.
1113 if (const LineEntry *Entry =
1114 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second)) {
Chris Lattnerc1219ff2009-02-04 02:00:59 +00001115 // If the LineEntry indicates a filename, use it.
Chris Lattnerd4293922009-02-04 01:55:42 +00001116 if (Entry->FilenameID != -1)
1117 Filename = LineTable->getFilename(Entry->FilenameID);
Chris Lattnerc1219ff2009-02-04 02:00:59 +00001118
1119 // Use the line number specified by the LineEntry. This line number may
1120 // be multiple lines down from the line entry. Add the difference in
1121 // physical line numbers from the query point and the line marker to the
1122 // total.
1123 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1124 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
Mike Stump11289f42009-09-09 15:08:12 +00001125
Chris Lattner20c50ba2009-02-04 02:15:40 +00001126 // Note that column numbers are not molested by line markers.
Mike Stump11289f42009-09-09 15:08:12 +00001127
Chris Lattner1c967782009-02-04 06:25:26 +00001128 // Handle virtual #include manipulation.
1129 if (Entry->IncludeOffset) {
1130 IncludeLoc = getLocForStartOfFile(LocInfo.first);
1131 IncludeLoc = IncludeLoc.getFileLocWithOffset(Entry->IncludeOffset);
1132 }
Chris Lattnerd4293922009-02-04 01:55:42 +00001133 }
1134 }
1135
1136 return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc);
Chris Lattner4fa23622009-01-26 00:43:02 +00001137}
1138
1139//===----------------------------------------------------------------------===//
1140// Other miscellaneous methods.
1141//===----------------------------------------------------------------------===//
1142
Douglas Gregore6642762011-02-03 17:17:35 +00001143/// \brief Retrieve the inode for the given file entry, if possible.
1144///
1145/// This routine involves a system call, and therefore should only be used
1146/// in non-performance-critical code.
1147static llvm::Optional<ino_t> getActualFileInode(const FileEntry *File) {
1148 if (!File)
1149 return llvm::Optional<ino_t>();
1150
1151 struct stat StatBuf;
1152 if (::stat(File->getName(), &StatBuf))
1153 return llvm::Optional<ino_t>();
1154
1155 return StatBuf.st_ino;
1156}
1157
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001158/// \brief Get the source location for the given file:line:col triplet.
1159///
1160/// If the source file is included multiple times, the source location will
1161/// be based upon the first inclusion.
1162SourceLocation SourceManager::getLocation(const FileEntry *SourceFile,
Douglas Gregore6642762011-02-03 17:17:35 +00001163 unsigned Line, unsigned Col) {
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001164 assert(SourceFile && "Null source file!");
1165 assert(Line && Col && "Line and column should start from 1!");
1166
Douglas Gregore6642762011-02-03 17:17:35 +00001167 // Find the first file ID that corresponds to the given file.
1168 FileID FirstFID;
Mike Stump11289f42009-09-09 15:08:12 +00001169
Douglas Gregore6642762011-02-03 17:17:35 +00001170 // First, check the main file ID, since it is common to look for a
1171 // location in the main file.
1172 llvm::Optional<ino_t> SourceFileInode;
1173 llvm::Optional<llvm::StringRef> SourceFileName;
1174 if (!MainFileID.isInvalid()) {
1175 const SLocEntry &MainSLoc = getSLocEntry(MainFileID);
1176 if (MainSLoc.isFile()) {
1177 const ContentCache *MainContentCache
1178 = MainSLoc.getFile().getContentCache();
Douglas Gregor6a5be932011-02-11 18:08:15 +00001179 if (!MainContentCache) {
1180 // Can't do anything
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001181 } else if (MainContentCache->OrigEntry == SourceFile) {
Douglas Gregore6642762011-02-03 17:17:35 +00001182 FirstFID = MainFileID;
Douglas Gregor6a5be932011-02-11 18:08:15 +00001183 } else {
Douglas Gregore6642762011-02-03 17:17:35 +00001184 // Fall back: check whether we have the same base name and inode
1185 // as the main file.
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001186 const FileEntry *MainFile = MainContentCache->OrigEntry;
Douglas Gregore6642762011-02-03 17:17:35 +00001187 SourceFileName = llvm::sys::path::filename(SourceFile->getName());
1188 if (*SourceFileName == llvm::sys::path::filename(MainFile->getName())) {
1189 SourceFileInode = getActualFileInode(SourceFile);
Douglas Gregord766be62011-02-16 19:09:24 +00001190 if (SourceFileInode) {
1191 if (llvm::Optional<ino_t> MainFileInode
1192 = getActualFileInode(MainFile)) {
1193 if (*SourceFileInode == *MainFileInode) {
1194 FirstFID = MainFileID;
1195 SourceFile = MainFile;
1196 }
1197 }
Douglas Gregore6642762011-02-03 17:17:35 +00001198 }
1199 }
1200 }
1201 }
1202 }
1203
1204 if (FirstFID.isInvalid()) {
1205 // The location we're looking for isn't in the main file; look
1206 // through all of the source locations.
1207 for (unsigned I = 0, N = sloc_entry_size(); I != N; ++I) {
1208 const SLocEntry &SLoc = getSLocEntry(I);
1209 if (SLoc.isFile() &&
1210 SLoc.getFile().getContentCache() &&
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001211 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
Douglas Gregore6642762011-02-03 17:17:35 +00001212 FirstFID = FileID::get(I);
1213 break;
1214 }
1215 }
1216 }
1217
1218 // If we haven't found what we want yet, try again, but this time stat()
1219 // each of the files in case the files have changed since we originally
1220 // parsed the file.
1221 if (FirstFID.isInvalid() &&
1222 (SourceFileName ||
1223 (SourceFileName = llvm::sys::path::filename(SourceFile->getName()))) &&
1224 (SourceFileInode ||
1225 (SourceFileInode = getActualFileInode(SourceFile)))) {
1226 for (unsigned I = 0, N = sloc_entry_size(); I != N; ++I) {
1227 const SLocEntry &SLoc = getSLocEntry(I);
1228 if (SLoc.isFile()) {
1229 const ContentCache *FileContentCache
1230 = SLoc.getFile().getContentCache();
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001231 const FileEntry *Entry =FileContentCache? FileContentCache->OrigEntry : 0;
Douglas Gregore6642762011-02-03 17:17:35 +00001232 if (Entry &&
Douglas Gregor6a5be932011-02-11 18:08:15 +00001233 *SourceFileName == llvm::sys::path::filename(Entry->getName())) {
1234 if (llvm::Optional<ino_t> EntryInode = getActualFileInode(Entry)) {
1235 if (*SourceFileInode == *EntryInode) {
1236 FirstFID = FileID::get(I);
1237 SourceFile = Entry;
1238 break;
1239 }
1240 }
Douglas Gregore6642762011-02-03 17:17:35 +00001241 }
1242 }
1243 }
1244 }
1245
1246 if (FirstFID.isInvalid())
1247 return SourceLocation();
1248
1249 if (Line == 1 && Col == 1)
1250 return getLocForStartOfFile(FirstFID);
1251
1252 ContentCache *Content
1253 = const_cast<ContentCache *>(getOrCreateContentCache(SourceFile));
1254 if (!Content)
1255 return SourceLocation();
1256
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001257 // If this is the first use of line information for this buffer, compute the
1258 /// SourceLineCache for it on demand.
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001259 if (Content->SourceLineCache == 0) {
1260 bool MyInvalid = false;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001261 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor7bda4b82010-03-16 05:20:39 +00001262 if (MyInvalid)
1263 return SourceLocation();
1264 }
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001265
Douglas Gregorb8b9f282010-02-27 02:42:25 +00001266 if (Line > Content->NumLines) {
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001267 unsigned Size = Content->getBuffer(Diag, *this)->getBufferSize();
Douglas Gregorb8b9f282010-02-27 02:42:25 +00001268 if (Size > 0)
1269 --Size;
1270 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(Size);
1271 }
1272
1273 unsigned FilePos = Content->SourceLineCache[Line - 1];
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001274 const char *Buf = Content->getBuffer(Diag, *this)->getBufferStart() + FilePos;
1275 unsigned BufLength = Content->getBuffer(Diag, *this)->getBufferEnd() - Buf;
Douglas Gregorb8b9f282010-02-27 02:42:25 +00001276 unsigned i = 0;
1277
1278 // Check that the given column is valid.
1279 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1280 ++i;
1281 if (i < Col-1)
1282 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + i);
1283
Douglas Gregor2a1b6912009-12-02 05:34:39 +00001284 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + Col - 1);
Argyrios Kyrtzidis88f663c02009-06-20 08:09:57 +00001285}
1286
Chris Lattnera99fa1a2010-05-07 20:35:24 +00001287/// Given a decomposed source location, move it up the include/instantiation
1288/// stack to the parent source location. If this is possible, return the
1289/// decomposed version of the parent in Loc and return false. If Loc is the
1290/// top-level entry, return true and don't modify it.
1291static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1292 const SourceManager &SM) {
1293 SourceLocation UpperLoc;
1294 const SrcMgr::SLocEntry &Entry = SM.getSLocEntry(Loc.first);
1295 if (Entry.isInstantiation())
1296 UpperLoc = Entry.getInstantiation().getInstantiationLocStart();
1297 else
1298 UpperLoc = Entry.getFile().getIncludeLoc();
1299
1300 if (UpperLoc.isInvalid())
1301 return true; // We reached the top.
1302
1303 Loc = SM.getDecomposedLoc(UpperLoc);
1304 return false;
1305}
1306
1307
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001308/// \brief Determines the order of 2 source locations in the translation unit.
1309///
1310/// \returns true if LHS source location comes before RHS, false otherwise.
1311bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
1312 SourceLocation RHS) const {
1313 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
1314 if (LHS == RHS)
1315 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001316
Argyrios Kyrtzidis338f9aa2010-12-24 02:53:53 +00001317 // If both locations are macro instantiations, the order of their offsets
1318 // reflect the order that the tokens, pointed to by these locations, were
1319 // instantiated (during parsing each token that is instantiated by a macro,
1320 // expands the SLocEntries).
1321 if (LHS.isMacroID() && RHS.isMacroID())
1322 return LHS.getOffset() < RHS.getOffset();
1323
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001324 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
1325 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00001326
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001327 // If the source locations are in the same file, just compare offsets.
1328 if (LOffs.first == ROffs.first)
1329 return LOffs.second < ROffs.second;
1330
1331 // If we are comparing a source location with multiple locations in the same
1332 // file, we get a big win by caching the result.
Chris Lattner46e3b482010-05-07 05:10:46 +00001333 if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
1334 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
Mike Stump11289f42009-09-09 15:08:12 +00001335
Chris Lattner66d2f922010-05-07 01:17:07 +00001336 // Okay, we missed in the cache, start updating the cache for this query.
1337 IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first);
Mike Stump11289f42009-09-09 15:08:12 +00001338
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001339 // "Traverse" the include/instantiation stacks of both locations and try to
Chris Lattner06821c92010-05-07 05:51:13 +00001340 // find a common "ancestor". FileIDs build a tree-like structure that
1341 // reflects the #include hierarchy, and this algorithm needs to find the
1342 // nearest common ancestor between the two locations. For example, if you
1343 // have a.c that includes b.h and c.h, and are comparing a location in b.h to
1344 // a location in c.h, we need to find that their nearest common ancestor is
1345 // a.c, and compare the locations of the two #includes to find their relative
1346 // ordering.
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001347 //
Chris Lattner06821c92010-05-07 05:51:13 +00001348 // SourceManager assigns FileIDs in order of parsing. This means that an
1349 // includee always has a larger FileID than an includer. While you might
1350 // think that we could just compare the FileID's here, that doesn't work to
1351 // compare a point at the end of a.c with a point within c.h. Though c.h has
1352 // a larger FileID, we have to compare the include point of c.h to the
1353 // location in a.c.
1354 //
1355 // Despite not being able to directly compare FileID's, we can tell that a
1356 // larger FileID is necessarily more deeply nested than a lower one and use
1357 // this information to walk up the tree to the nearest common ancestor.
1358 do {
1359 // If LOffs is larger than ROffs, then LOffs must be more deeply nested than
1360 // ROffs, walk up the #include chain.
1361 if (LOffs.first.ID > ROffs.first.ID) {
Chris Lattnera99fa1a2010-05-07 20:35:24 +00001362 if (MoveUpIncludeHierarchy(LOffs, *this))
Chris Lattner06821c92010-05-07 05:51:13 +00001363 break; // We reached the top.
1364
Chris Lattner06821c92010-05-07 05:51:13 +00001365 } else {
1366 // Otherwise, ROffs is larger than LOffs, so ROffs must be more deeply
1367 // nested than LOffs, walk up the #include chain.
Chris Lattnera99fa1a2010-05-07 20:35:24 +00001368 if (MoveUpIncludeHierarchy(ROffs, *this))
Chris Lattner06821c92010-05-07 05:51:13 +00001369 break; // We reached the top.
Chris Lattner66d2f922010-05-07 01:17:07 +00001370 }
Chris Lattner06821c92010-05-07 05:51:13 +00001371 } while (LOffs.first != ROffs.first);
Mike Stump11289f42009-09-09 15:08:12 +00001372
Chris Lattner06821c92010-05-07 05:51:13 +00001373 // If we exited because we found a nearest common ancestor, compare the
1374 // locations within the common file and cache them.
1375 if (LOffs.first == ROffs.first) {
1376 IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
1377 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001378 }
Mike Stump11289f42009-09-09 15:08:12 +00001379
Daniel Dunbar465f4c42009-12-01 23:07:57 +00001380 // There is no common ancestor, most probably because one location is in the
Sebastian Redld44cd6a2010-08-18 23:57:06 +00001381 // predefines buffer or an AST file.
Daniel Dunbar465f4c42009-12-01 23:07:57 +00001382 // FIXME: We should rearrange the external interface so this simply never
1383 // happens; it can't conceptually happen. Also see PR5662.
Chris Lattnera99fa1a2010-05-07 20:35:24 +00001384 IsBeforeInTUCache.setQueryFIDs(FileID(), FileID()); // Don't try caching.
1385
1386 // Zip both entries up to the top level record.
1387 while (!MoveUpIncludeHierarchy(LOffs, *this)) /*empty*/;
1388 while (!MoveUpIncludeHierarchy(ROffs, *this)) /*empty*/;
Chris Lattner06821c92010-05-07 05:51:13 +00001389
Daniel Dunbar465f4c42009-12-01 23:07:57 +00001390 // If exactly one location is a memory buffer, assume it preceeds the other.
Chris Lattnera99fa1a2010-05-07 20:35:24 +00001391
1392 // Strip off macro instantation locations, going up to the top-level File
1393 // SLocEntry.
1394 bool LIsMB = getFileEntryForID(LOffs.first) == 0;
1395 bool RIsMB = getFileEntryForID(ROffs.first) == 0;
Chris Lattner06821c92010-05-07 05:51:13 +00001396 if (LIsMB != RIsMB)
Chris Lattner66d2f922010-05-07 01:17:07 +00001397 return LIsMB;
Mike Stump11289f42009-09-09 15:08:12 +00001398
Daniel Dunbar465f4c42009-12-01 23:07:57 +00001399 // Otherwise, just assume FileIDs were created in order.
Chris Lattner66d2f922010-05-07 01:17:07 +00001400 return LOffs.first < ROffs.first;
Argyrios Kyrtzidis33661d92009-06-23 22:01:48 +00001401}
Chris Lattner4fa23622009-01-26 00:43:02 +00001402
Chris Lattner22eb9722006-06-18 05:43:12 +00001403/// PrintStats - Print statistics to stderr.
1404///
1405void SourceManager::PrintStats() const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +00001406 llvm::errs() << "\n*** Source Manager Stats:\n";
1407 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
1408 << " mem buffers mapped.\n";
1409 llvm::errs() << SLocEntryTable.size() << " SLocEntry's allocated, "
1410 << NextOffset << "B of Sloc address space used.\n";
Mike Stump11289f42009-09-09 15:08:12 +00001411
Chris Lattner22eb9722006-06-18 05:43:12 +00001412 unsigned NumLineNumsComputed = 0;
1413 unsigned NumFileBytesMapped = 0;
Chris Lattnerc8233df2009-02-03 07:30:45 +00001414 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
1415 NumLineNumsComputed += I->second->SourceLineCache != 0;
1416 NumFileBytesMapped += I->second->getSizeBytesMapped();
Chris Lattner22eb9722006-06-18 05:43:12 +00001417 }
Mike Stump11289f42009-09-09 15:08:12 +00001418
Benjamin Kramer89b422c2009-08-23 12:08:50 +00001419 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
1420 << NumLineNumsComputed << " files with line #'s computed.\n";
1421 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
1422 << NumBinaryProbes << " binary.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +00001423}
Douglas Gregor258ae542009-04-27 06:38:32 +00001424
1425ExternalSLocEntrySource::~ExternalSLocEntrySource() { }