blob: b6939ec7d55512cb320c1dfc1fb9d0b861bf0b58 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SourceManager.cpp - Track and cache source files -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the SourceManager interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Basic/SourceManager.h"
Douglas Gregord4f77aa2009-04-13 15:31:25 +000015#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregoraea67db2010-03-15 22:54:52 +000016#include "clang/Basic/Diagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/Basic/FileManager.h"
Benjamin Kramer5807d9c2010-11-18 12:46:39 +000018#include "llvm/ADT/StringSwitch.h"
Douglas Gregor86a4d0d2011-02-03 17:17:35 +000019#include "llvm/ADT/Optional.h"
Chris Lattner5e36a7a2007-07-24 05:57:19 +000020#include "llvm/Support/Compiler.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000021#include "llvm/Support/MemoryBuffer.h"
Chris Lattnerd57a7ef2009-08-23 22:45:33 +000022#include "llvm/Support/raw_ostream.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000023#include "llvm/Support/Path.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024#include <algorithm>
Douglas Gregoraea67db2010-03-15 22:54:52 +000025#include <string>
Douglas Gregorf715ca12010-03-16 00:06:06 +000026#include <cstring>
Douglas Gregor86a4d0d2011-02-03 17:17:35 +000027#include <sys/stat.h>
Douglas Gregoraea67db2010-03-15 22:54:52 +000028
Reid Spencer5f016e22007-07-11 17:01:13 +000029using namespace clang;
30using namespace SrcMgr;
31using llvm::MemoryBuffer;
32
Chris Lattner23b5dc62009-02-04 00:40:31 +000033//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +000034// SourceManager Helper Classes
Chris Lattner23b5dc62009-02-04 00:40:31 +000035//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +000036
Ted Kremenek78d85f52007-10-30 21:08:08 +000037ContentCache::~ContentCache() {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000038 if (shouldFreeBuffer())
39 delete Buffer.getPointer();
Reid Spencer5f016e22007-07-11 17:01:13 +000040}
41
Ted Kremenekc16c2082009-01-06 01:55:26 +000042/// getSizeBytesMapped - Returns the number of bytes actually mapped for
43/// this ContentCache. This can be 0 if the MemBuffer was not actually
44/// instantiated.
45unsigned ContentCache::getSizeBytesMapped() const {
Douglas Gregorc8151082010-03-16 22:53:51 +000046 return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 0;
Ted Kremenekc16c2082009-01-06 01:55:26 +000047}
48
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 Gregor29684422009-12-02 06:49:09 +000052/// file is not lazily brought in from disk to satisfy this query.
Ted Kremenekc16c2082009-01-06 01:55:26 +000053unsigned ContentCache::getSize() const {
Douglas Gregorc8151082010-03-16 22:53:51 +000054 return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize()
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +000055 : (unsigned) ContentsEntry->getSize();
Ted Kremenekc16c2082009-01-06 01:55:26 +000056}
57
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000058void ContentCache::replaceBuffer(const llvm::MemoryBuffer *B,
59 bool DoNotFree) {
Douglas Gregorc8151082010-03-16 22:53:51 +000060 assert(B != Buffer.getPointer());
Douglas Gregor29684422009-12-02 06:49:09 +000061
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000062 if (shouldFreeBuffer())
63 delete Buffer.getPointer();
Douglas Gregorc8151082010-03-16 22:53:51 +000064 Buffer.setPointer(B);
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000065 Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
Douglas Gregor29684422009-12-02 06:49:09 +000066}
67
Douglas Gregor36c35ba2010-03-16 00:35:39 +000068const llvm::MemoryBuffer *ContentCache::getBuffer(Diagnostic &Diag,
Chris Lattner5c5db4e2010-04-20 20:49:23 +000069 const SourceManager &SM,
Chris Lattnere127a0d2010-04-20 20:35:58 +000070 SourceLocation Loc,
Douglas Gregor36c35ba2010-03-16 00:35:39 +000071 bool *Invalid) const {
Chris Lattnerb088cd32010-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 Kyrtzidisb1c86492011-03-05 01:03:53 +000074 if (Buffer.getPointer() || ContentsEntry == 0) {
Chris Lattnerb088cd32010-11-23 08:50:03 +000075 if (Invalid)
76 *Invalid = isBufferInvalid();
Chris Lattner38caec42010-04-20 18:14:03 +000077
Chris Lattnerb088cd32010-11-23 08:50:03 +000078 return Buffer.getPointer();
79 }
Benjamin Kramer5807d9c2010-11-18 12:46:39 +000080
Chris Lattnerb088cd32010-11-23 08:50:03 +000081 std::string ErrorStr;
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +000082 Buffer.setPointer(SM.getFileManager().getBufferForFile(ContentsEntry, &ErrorStr));
Chris Lattnerb088cd32010-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 Kyrtzidisb1c86492011-03-05 01:03:53 +000096 Buffer.setPointer(MemoryBuffer::getNewMemBuffer(ContentsEntry->getSize(),
Chris Lattnerb088cd32010-11-23 08:50:03 +000097 "<invalid>"));
98 char *Ptr = const_cast<char*>(Buffer.getPointer()->getBufferStart());
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +000099 for (unsigned i = 0, e = ContentsEntry->getSize(); i != e; ++i)
Chris Lattnerb088cd32010-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 Kyrtzidisb1c86492011-03-05 01:03:53 +0000104 ContentsEntry->getName(), ErrorStr);
Chris Lattnerb088cd32010-11-23 08:50:03 +0000105 else
106 Diag.Report(Loc, diag::err_cannot_open_file)
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000107 << ContentsEntry->getName() << ErrorStr;
Chris Lattnerb088cd32010-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 Kyrtzidisb1c86492011-03-05 01:03:53 +0000117 if (getRawBuffer()->getBufferSize() != (size_t)ContentsEntry->getSize()) {
Chris Lattnerb088cd32010-11-23 08:50:03 +0000118 if (Diag.isDiagnosticInFlight())
119 Diag.SetDelayedDiagnostic(diag::err_file_modified,
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000120 ContentsEntry->getName());
Chris Lattnerb088cd32010-11-23 08:50:03 +0000121 else
122 Diag.Report(Loc, diag::err_file_modified)
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000123 << ContentsEntry->getName();
Chris Lattnerb088cd32010-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 Kyrtzidisb1c86492011-03-05 01:03:53 +0000150 << BOM << ContentsEntry->getName();
Chris Lattnerb088cd32010-11-23 08:50:03 +0000151 Buffer.setInt(Buffer.getInt() | InvalidFlag);
Ted Kremenek5b034ad2009-01-06 22:43:04 +0000152 }
Douglas Gregoraea67db2010-03-15 22:54:52 +0000153
Douglas Gregorc8151082010-03-16 22:53:51 +0000154 if (Invalid)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000155 *Invalid = isBufferInvalid();
Douglas Gregorc8151082010-03-16 22:53:51 +0000156
157 return Buffer.getPointer();
Ted Kremenekc16c2082009-01-06 01:55:26 +0000158}
159
Chris Lattner5b9a5042009-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 Stump1eb44332009-09-09 15:08:12 +0000163 llvm::StringMapEntry<unsigned> &Entry =
Chris Lattner5b9a5042009-01-26 07:57:50 +0000164 FilenameIDs.GetOrCreateValue(Ptr, Ptr+Len, ~0U);
165 if (Entry.getValue() != ~0U)
166 return Entry.getValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000167
Chris Lattner5b9a5042009-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 Lattnerac50e342009-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 Lattner23b5dc62009-02-04 00:40:31 +0000177void LineTableInfo::AddLineNote(unsigned FID, unsigned Offset,
Chris Lattnerac50e342009-02-03 22:13:05 +0000178 unsigned LineNo, int FilenameID) {
Chris Lattner23b5dc62009-02-04 00:40:31 +0000179 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump1eb44332009-09-09 15:08:12 +0000180
Chris Lattner23b5dc62009-02-04 00:40:31 +0000181 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
182 "Adding line entries out of order!");
Mike Stump1eb44332009-09-09 15:08:12 +0000183
Chris Lattner9d79eba2009-02-04 05:21:58 +0000184 SrcMgr::CharacteristicKind Kind = SrcMgr::C_User;
Chris Lattner137b6a62009-02-04 06:25:26 +0000185 unsigned IncludeOffset = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000186
Chris Lattner9d79eba2009-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 Stump1eb44332009-09-09 15:08:12 +0000192
Chris Lattner137b6a62009-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 Lattner9d79eba2009-02-04 05:21:58 +0000195 Kind = Entries.back().FileKind;
Chris Lattner137b6a62009-02-04 06:25:26 +0000196 IncludeOffset = Entries.back().IncludeOffset;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000197 }
Mike Stump1eb44332009-09-09 15:08:12 +0000198
Chris Lattner137b6a62009-02-04 06:25:26 +0000199 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, Kind,
200 IncludeOffset));
Chris Lattnerac50e342009-02-03 22:13:05 +0000201}
202
Chris Lattner9d79eba2009-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 Stump1eb44332009-09-09 15:08:12 +0000213
Chris Lattner9d79eba2009-02-04 05:21:58 +0000214 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump1eb44332009-09-09 15:08:12 +0000215
Chris Lattner9d79eba2009-02-04 05:21:58 +0000216 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
217 "Adding line entries out of order!");
218
Chris Lattner137b6a62009-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 Stump1eb44332009-09-09 15:08:12 +0000227
Chris Lattner137b6a62009-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 Stump1eb44332009-09-09 15:08:12 +0000234
Chris Lattner137b6a62009-02-04 06:25:26 +0000235 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
236 IncludeOffset));
Chris Lattner9d79eba2009-02-04 05:21:58 +0000237}
238
239
Chris Lattner3cd949c2009-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 Stump1eb44332009-09-09 15:08:12 +0000242const LineEntry *LineTableInfo::FindNearestLineEntry(unsigned FID,
Chris Lattner3cd949c2009-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 Lattner6c1fbe02009-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 Lattner3cd949c2009-02-04 01:55:42 +0000251
Chris Lattner6c1fbe02009-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 Lattner3cd949c2009-02-04 01:55:42 +0000257}
Chris Lattnerac50e342009-02-03 22:13:05 +0000258
Douglas Gregorbd945002009-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 Stump1eb44332009-09-09 15:08:12 +0000261void LineTableInfo::AddEntry(unsigned FID,
Douglas Gregorbd945002009-04-13 16:31:14 +0000262 const std::vector<LineEntry> &Entries) {
263 LineEntries[FID] = Entries;
264}
Chris Lattnerac50e342009-02-03 22:13:05 +0000265
Chris Lattner5b9a5042009-01-26 07:57:50 +0000266/// getLineTableFilenameID - Return the uniqued ID for the specified filename.
Mike Stump1eb44332009-09-09 15:08:12 +0000267///
Chris Lattner5b9a5042009-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 Lattner4c4ea172009-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 Lattnerac50e342009-02-03 22:13:05 +0000280 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000281
Chris Lattnerac50e342009-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 Stump1eb44332009-09-09 15:08:12 +0000286
Chris Lattnerac50e342009-02-03 22:13:05 +0000287 if (LineTable == 0)
288 LineTable = new LineTableInfo();
Chris Lattner23b5dc62009-02-04 00:40:31 +0000289 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID);
Chris Lattner4c4ea172009-02-03 21:52:55 +0000290}
291
Chris Lattner9d79eba2009-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 Stump1eb44332009-09-09 15:08:12 +0000304
Chris Lattner9d79eba2009-02-04 05:21:58 +0000305 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
306 const SrcMgr::FileInfo &FileInfo = getSLocEntry(LocInfo.first).getFile();
Mike Stump1eb44332009-09-09 15:08:12 +0000307
Chris Lattner9d79eba2009-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 Stump1eb44332009-09-09 15:08:12 +0000310
Chris Lattner9d79eba2009-02-04 05:21:58 +0000311 if (LineTable == 0)
312 LineTable = new LineTableInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000313
Chris Lattner9d79eba2009-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 Stump1eb44332009-09-09 15:08:12 +0000321
Chris Lattner9d79eba2009-02-04 05:21:58 +0000322 unsigned EntryExit = 0;
323 if (IsFileEntry)
324 EntryExit = 1;
325 else if (IsFileExit)
326 EntryExit = 2;
Mike Stump1eb44332009-09-09 15:08:12 +0000327
Chris Lattner9d79eba2009-02-04 05:21:58 +0000328 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID,
329 EntryExit, FileKind);
330}
331
Douglas Gregorbd945002009-04-13 16:31:14 +0000332LineTableInfo &SourceManager::getLineTable() {
333 if (LineTable == 0)
334 LineTable = new LineTableInfo();
335 return *LineTable;
336}
Chris Lattner4c4ea172009-02-03 21:52:55 +0000337
Chris Lattner23b5dc62009-02-04 00:40:31 +0000338//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000339// Private 'Create' methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000340//===----------------------------------------------------------------------===//
Ted Kremenekc16c2082009-01-06 01:55:26 +0000341
Chris Lattner39b49bc2010-11-23 08:35:12 +0000342SourceManager::SourceManager(Diagnostic &Diag, FileManager &FileMgr)
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +0000343 : Diag(Diag), FileMgr(FileMgr), OverridenFilesKeepOriginalName(true),
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000344 ExternalSLocEntries(0), LineTable(0), NumLinearScans(0),
345 NumBinaryProbes(0) {
346 clearIDTables();
347 Diag.setSourceManager(this);
348}
349
Chris Lattner5b9a5042009-01-26 07:57:50 +0000350SourceManager::~SourceManager() {
351 delete LineTable;
Mike Stump1eb44332009-09-09 15:08:12 +0000352
Chris Lattner0d0bf8c2009-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 Lattner5b9a5042009-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 Stump1eb44332009-09-09 15:08:12 +0000373
Chris Lattner5b9a5042009-01-26 07:57:50 +0000374 if (LineTable)
375 LineTable->clear();
Mike Stump1eb44332009-09-09 15:08:12 +0000376
Chris Lattner5b9a5042009-01-26 07:57:50 +0000377 // Use up FileID #0 as an invalid instantiation.
378 NextOffset = 0;
Chris Lattnere7fb4842009-02-15 20:52:18 +0000379 createInstantiationLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000380}
381
Chris Lattnerde7aeef2009-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) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000386 assert(FileEnt && "Didn't specify a file entry to use?");
Mike Stump1eb44332009-09-09 15:08:12 +0000387
Reid Spencer5f016e22007-07-11 17:01:13 +0000388 // Do we already have information about this file?
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000389 ContentCache *&Entry = FileInfos[FileEnt];
390 if (Entry) return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +0000391
Chris Lattner00282d62009-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 Kyrtzidisb1c86492011-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
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +0000406 new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt
407 : overI->second,
408 overI->second);
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000409
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000410 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000411}
412
413
Ted Kremenekd1c0eee2007-10-31 17:53:38 +0000414/// createMemBufferContentCache - Create a new ContentCache for the specified
415/// memory buffer. This does no caching.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000416const ContentCache*
417SourceManager::createMemBufferContentCache(const MemoryBuffer *Buffer) {
Chris Lattner00282d62009-02-03 07:41:46 +0000418 // Add a new ContentCache to the MemBufferInfos list and return it. Make sure
419 // it is at least 8-byte aligned so that FileInfo can use the low 3 bits of
420 // the pointer for its own nefarious purposes.
421 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
422 EntryAlign = std::max(8U, EntryAlign);
423 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000424 new (Entry) ContentCache();
425 MemBufferInfos.push_back(Entry);
426 Entry->setBuffer(Buffer);
427 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000428}
429
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000430void SourceManager::PreallocateSLocEntries(ExternalSLocEntrySource *Source,
431 unsigned NumSLocEntries,
432 unsigned NextOffset) {
433 ExternalSLocEntries = Source;
434 this->NextOffset = NextOffset;
Sebastian Redlb86238d2010-07-28 21:07:02 +0000435 unsigned CurPrealloc = SLocEntryLoaded.size();
436 // If we've ever preallocated, we must not count the dummy entry.
437 if (CurPrealloc) --CurPrealloc;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000438 SLocEntryLoaded.resize(NumSLocEntries + 1);
439 SLocEntryLoaded[0] = true;
Sebastian Redlb86238d2010-07-28 21:07:02 +0000440 SLocEntryTable.resize(SLocEntryTable.size() + NumSLocEntries - CurPrealloc);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000441}
442
Douglas Gregor2bf1eb02009-04-27 21:28:04 +0000443void SourceManager::ClearPreallocatedSLocEntries() {
444 unsigned I = 0;
445 for (unsigned N = SLocEntryLoaded.size(); I != N; ++I)
446 if (!SLocEntryLoaded[I])
447 break;
448
449 // We've already loaded all preallocated source location entries.
450 if (I == SLocEntryLoaded.size())
451 return;
452
453 // Remove everything from location I onward.
454 SLocEntryTable.resize(I);
455 SLocEntryLoaded.clear();
456 ExternalSLocEntries = 0;
457}
458
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000459
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000460//===----------------------------------------------------------------------===//
461// Methods to create new FileID's and instantiations.
462//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000463
Dan Gohman3f86b782010-08-26 21:27:06 +0000464/// createFileID - Create a new FileID for the specified ContentCache and
Ted Kremenek0d892d82007-10-30 22:57:35 +0000465/// include position. This works regardless of whether the ContentCache
466/// corresponds to a file or some other input source.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000467FileID SourceManager::createFileID(const ContentCache *File,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000468 SourceLocation IncludePos,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000469 SrcMgr::CharacteristicKind FileCharacter,
470 unsigned PreallocatedID,
471 unsigned Offset) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000472 if (PreallocatedID) {
473 // If we're filling in a preallocated ID, just load in the file
474 // entry and return.
Mike Stump1eb44332009-09-09 15:08:12 +0000475 assert(PreallocatedID < SLocEntryLoaded.size() &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000476 "Preallocate ID out-of-range");
Mike Stump1eb44332009-09-09 15:08:12 +0000477 assert(!SLocEntryLoaded[PreallocatedID] &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000478 "Source location entry already loaded");
479 assert(Offset && "Preallocate source location cannot have zero offset");
Mike Stump1eb44332009-09-09 15:08:12 +0000480 SLocEntryTable[PreallocatedID]
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000481 = SLocEntry::get(Offset, FileInfo::get(IncludePos, File, FileCharacter));
482 SLocEntryLoaded[PreallocatedID] = true;
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +0000483 FileID FID = FileID::get(PreallocatedID);
Douglas Gregor5de65722010-03-19 06:12:06 +0000484 return FID;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000485 }
486
Mike Stump1eb44332009-09-09 15:08:12 +0000487 SLocEntryTable.push_back(SLocEntry::get(NextOffset,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000488 FileInfo::get(IncludePos, File,
489 FileCharacter)));
Ted Kremenekc16c2082009-01-06 01:55:26 +0000490 unsigned FileSize = File->getSize();
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000491 assert(NextOffset+FileSize+1 > NextOffset && "Ran out of source locations!");
492 NextOffset += FileSize+1;
Mike Stump1eb44332009-09-09 15:08:12 +0000493
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000494 // Set LastFileIDLookup to the newly created file. The next getFileID call is
495 // almost guaranteed to be from that file.
Argyrios Kyrtzidisea703f12009-06-23 00:42:06 +0000496 FileID FID = FileID::get(SLocEntryTable.size()-1);
Argyrios Kyrtzidisea703f12009-06-23 00:42:06 +0000497 return LastFileIDLookup = FID;
Reid Spencer5f016e22007-07-11 17:01:13 +0000498}
499
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000500/// createInstantiationLoc - Return a new SourceLocation that encodes the fact
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000501/// that a token from SpellingLoc should actually be referenced from
Reid Spencer5f016e22007-07-11 17:01:13 +0000502/// InstantiationLoc.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000503SourceLocation SourceManager::createInstantiationLoc(SourceLocation SpellingLoc,
Chris Lattnere7fb4842009-02-15 20:52:18 +0000504 SourceLocation ILocStart,
505 SourceLocation ILocEnd,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000506 unsigned TokLength,
507 unsigned PreallocatedID,
508 unsigned Offset) {
Chris Lattnere7fb4842009-02-15 20:52:18 +0000509 InstantiationInfo II = InstantiationInfo::get(ILocStart,ILocEnd, SpellingLoc);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000510 if (PreallocatedID) {
511 // If we're filling in a preallocated ID, just load in the
512 // instantiation entry and return.
Mike Stump1eb44332009-09-09 15:08:12 +0000513 assert(PreallocatedID < SLocEntryLoaded.size() &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000514 "Preallocate ID out-of-range");
Mike Stump1eb44332009-09-09 15:08:12 +0000515 assert(!SLocEntryLoaded[PreallocatedID] &&
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000516 "Source location entry already loaded");
517 assert(Offset && "Preallocate source location cannot have zero offset");
518 SLocEntryTable[PreallocatedID] = SLocEntry::get(Offset, II);
519 SLocEntryLoaded[PreallocatedID] = true;
520 return SourceLocation::getMacroLoc(Offset);
521 }
Chris Lattnere7fb4842009-02-15 20:52:18 +0000522 SLocEntryTable.push_back(SLocEntry::get(NextOffset, II));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000523 assert(NextOffset+TokLength+1 > NextOffset && "Ran out of source locations!");
524 NextOffset += TokLength+1;
525 return SourceLocation::getMacroLoc(NextOffset-(TokLength+1));
Reid Spencer5f016e22007-07-11 17:01:13 +0000526}
527
Douglas Gregor36c35ba2010-03-16 00:35:39 +0000528const llvm::MemoryBuffer *
Douglas Gregor50f6af72010-03-16 05:20:39 +0000529SourceManager::getMemoryBufferForFile(const FileEntry *File,
530 bool *Invalid) {
Douglas Gregor29684422009-12-02 06:49:09 +0000531 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
Douglas Gregoraea67db2010-03-15 22:54:52 +0000532 assert(IR && "getOrCreateContentCache() cannot return NULL");
Chris Lattnere127a0d2010-04-20 20:35:58 +0000533 return IR->getBuffer(Diag, *this, SourceLocation(), Invalid);
Douglas Gregor29684422009-12-02 06:49:09 +0000534}
535
Dan Gohman0d06e992010-10-26 20:47:28 +0000536void SourceManager::overrideFileContents(const FileEntry *SourceFile,
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000537 const llvm::MemoryBuffer *Buffer,
538 bool DoNotFree) {
Douglas Gregor29684422009-12-02 06:49:09 +0000539 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
Dan Gohman0d06e992010-10-26 20:47:28 +0000540 assert(IR && "getOrCreateContentCache() cannot return NULL");
Douglas Gregor29684422009-12-02 06:49:09 +0000541
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000542 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree);
Douglas Gregor29684422009-12-02 06:49:09 +0000543}
544
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000545void SourceManager::overrideFileContents(const FileEntry *SourceFile,
546 const FileEntry *NewFile) {
547 assert(SourceFile->getSize() == NewFile->getSize() &&
548 "Different sizes, use the FileManager to create a virtual file with "
549 "the correct size");
550 assert(FileInfos.count(SourceFile) == 0 &&
551 "This function should be called at the initialization stage, before "
552 "any parsing occurs.");
553 OverriddenFiles[SourceFile] = NewFile;
554}
555
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000556llvm::StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
Douglas Gregoraae58b02010-03-16 20:01:30 +0000557 bool MyInvalid = false;
Douglas Gregor3de84242011-01-31 22:42:36 +0000558 const SLocEntry &SLoc = getSLocEntry(FID.ID);
559 if (!SLoc.isFile()) {
560 if (Invalid)
561 *Invalid = true;
562 return "<<<<<INVALID SOURCE LOCATION>>>>>";
563 }
564
565 const llvm::MemoryBuffer *Buf
566 = SLoc.getFile().getContentCache()->getBuffer(Diag, *this, SourceLocation(),
567 &MyInvalid);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000568 if (Invalid)
Douglas Gregoraae58b02010-03-16 20:01:30 +0000569 *Invalid = MyInvalid;
570
571 if (MyInvalid)
Douglas Gregor3de84242011-01-31 22:42:36 +0000572 return "<<<<<INVALID SOURCE LOCATION>>>>>";
Douglas Gregoraae58b02010-03-16 20:01:30 +0000573
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000574 return Buf->getBuffer();
Douglas Gregoraea67db2010-03-15 22:54:52 +0000575}
Chris Lattner2b2453a2009-01-17 06:22:33 +0000576
Chris Lattner23b5dc62009-02-04 00:40:31 +0000577//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000578// SourceLocation manipulation methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000579//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000580
581/// getFileIDSlow - Return the FileID for a SourceLocation. This is a very hot
582/// method that is used for all SourceManager queries that start with a
583/// SourceLocation object. It is responsible for finding the entry in
584/// SLocEntryTable which contains the specified location.
585///
586FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
587 assert(SLocOffset && "Invalid FileID");
Mike Stump1eb44332009-09-09 15:08:12 +0000588
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000589 // After the first and second level caches, I see two common sorts of
590 // behavior: 1) a lot of searched FileID's are "near" the cached file location
591 // or are "near" the cached instantiation location. 2) others are just
592 // completely random and may be a very long way away.
593 //
594 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
595 // then we fall back to a less cache efficient, but more scalable, binary
596 // search to find the location.
Mike Stump1eb44332009-09-09 15:08:12 +0000597
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000598 // See if this is near the file point - worst case we start scanning from the
599 // most newly created FileID.
600 std::vector<SrcMgr::SLocEntry>::const_iterator I;
Mike Stump1eb44332009-09-09 15:08:12 +0000601
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000602 if (SLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
603 // Neither loc prunes our search.
604 I = SLocEntryTable.end();
605 } else {
606 // Perhaps it is near the file point.
607 I = SLocEntryTable.begin()+LastFileIDLookup.ID;
608 }
609
610 // Find the FileID that contains this. "I" is an iterator that points to a
611 // FileID whose offset is known to be larger than SLocOffset.
612 unsigned NumProbes = 0;
613 while (1) {
614 --I;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000615 if (ExternalSLocEntries)
616 getSLocEntry(FileID::get(I - SLocEntryTable.begin()));
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000617 if (I->getOffset() <= SLocOffset) {
618#if 0
619 printf("lin %d -> %d [%s] %d %d\n", SLocOffset,
620 I-SLocEntryTable.begin(),
621 I->isInstantiation() ? "inst" : "file",
622 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
623#endif
624 FileID Res = FileID::get(I-SLocEntryTable.begin());
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000625
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000626 // If this isn't an instantiation, remember it. We have good locality
627 // across FileID lookups.
628 if (!I->isInstantiation())
629 LastFileIDLookup = Res;
630 NumLinearScans += NumProbes+1;
631 return Res;
632 }
633 if (++NumProbes == 8)
634 break;
635 }
Mike Stump1eb44332009-09-09 15:08:12 +0000636
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000637 // Convert "I" back into an index. We know that it is an entry whose index is
638 // larger than the offset we are looking for.
639 unsigned GreaterIndex = I-SLocEntryTable.begin();
640 // LessIndex - This is the lower bound of the range that we're searching.
641 // We know that the offset corresponding to the FileID is is less than
642 // SLocOffset.
643 unsigned LessIndex = 0;
644 NumProbes = 0;
645 while (1) {
646 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000647 unsigned MidOffset = getSLocEntry(FileID::get(MiddleIndex)).getOffset();
Mike Stump1eb44332009-09-09 15:08:12 +0000648
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000649 ++NumProbes;
Mike Stump1eb44332009-09-09 15:08:12 +0000650
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000651 // If the offset of the midpoint is too large, chop the high side of the
652 // range to the midpoint.
653 if (MidOffset > SLocOffset) {
654 GreaterIndex = MiddleIndex;
655 continue;
656 }
Mike Stump1eb44332009-09-09 15:08:12 +0000657
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000658 // If the middle index contains the value, succeed and return.
659 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
660#if 0
661 printf("bin %d -> %d [%s] %d %d\n", SLocOffset,
662 I-SLocEntryTable.begin(),
663 I->isInstantiation() ? "inst" : "file",
664 LastFileIDLookup.ID, int(SLocEntryTable.end()-I));
665#endif
666 FileID Res = FileID::get(MiddleIndex);
667
668 // If this isn't an instantiation, remember it. We have good locality
669 // across FileID lookups.
670 if (!I->isInstantiation())
671 LastFileIDLookup = Res;
672 NumBinaryProbes += NumProbes;
673 return Res;
674 }
Mike Stump1eb44332009-09-09 15:08:12 +0000675
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000676 // Otherwise, move the low-side up to the middle index.
677 LessIndex = MiddleIndex;
678 }
679}
680
Chris Lattneraddb7972009-01-26 20:04:19 +0000681SourceLocation SourceManager::
682getInstantiationLocSlowCase(SourceLocation Loc) const {
683 do {
Chris Lattnera5c6c582010-02-12 19:31:35 +0000684 // Note: If Loc indicates an offset into a token that came from a macro
685 // expansion (e.g. the 5th character of the token) we do not want to add
686 // this offset when going to the instantiation location. The instatiation
687 // location is the macro invocation, which the offset has nothing to do
688 // with. This is unlike when we get the spelling loc, because the offset
689 // directly correspond to the token whose spelling we're inspecting.
690 Loc = getSLocEntry(getFileID(Loc)).getInstantiation()
Chris Lattnere7fb4842009-02-15 20:52:18 +0000691 .getInstantiationLocStart();
Chris Lattneraddb7972009-01-26 20:04:19 +0000692 } while (!Loc.isFileID());
693
694 return Loc;
695}
696
697SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
698 do {
699 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
700 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
701 Loc = Loc.getFileLocWithOffset(LocInfo.second);
702 } while (!Loc.isFileID());
703 return Loc;
704}
705
706
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000707std::pair<FileID, unsigned>
708SourceManager::getDecomposedInstantiationLocSlowCase(const SrcMgr::SLocEntry *E,
709 unsigned Offset) const {
710 // If this is an instantiation record, walk through all the instantiation
711 // points.
712 FileID FID;
713 SourceLocation Loc;
714 do {
Chris Lattnere7fb4842009-02-15 20:52:18 +0000715 Loc = E->getInstantiation().getInstantiationLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000716
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000717 FID = getFileID(Loc);
718 E = &getSLocEntry(FID);
719 Offset += Loc.getOffset()-E->getOffset();
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000720 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000721
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000722 return std::make_pair(FID, Offset);
723}
724
725std::pair<FileID, unsigned>
726SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
727 unsigned Offset) const {
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000728 // If this is an instantiation record, walk through all the instantiation
729 // points.
730 FileID FID;
731 SourceLocation Loc;
732 do {
733 Loc = E->getInstantiation().getSpellingLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000734
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000735 FID = getFileID(Loc);
736 E = &getSLocEntry(FID);
737 Offset += Loc.getOffset()-E->getOffset();
738 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000739
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000740 return std::make_pair(FID, Offset);
741}
742
Chris Lattner387616e2009-02-17 08:04:48 +0000743/// getImmediateSpellingLoc - Given a SourceLocation object, return the
744/// spelling location referenced by the ID. This is the first level down
745/// towards the place where the characters that make up the lexed token can be
746/// found. This should not generally be used by clients.
747SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
748 if (Loc.isFileID()) return Loc;
749 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
750 Loc = getSLocEntry(LocInfo.first).getInstantiation().getSpellingLoc();
751 return Loc.getFileLocWithOffset(LocInfo.second);
752}
753
754
Chris Lattnere7fb4842009-02-15 20:52:18 +0000755/// getImmediateInstantiationRange - Loc is required to be an instantiation
756/// location. Return the start/end of the instantiation information.
757std::pair<SourceLocation,SourceLocation>
758SourceManager::getImmediateInstantiationRange(SourceLocation Loc) const {
759 assert(Loc.isMacroID() && "Not an instantiation loc!");
760 const InstantiationInfo &II = getSLocEntry(getFileID(Loc)).getInstantiation();
761 return II.getInstantiationLocRange();
762}
763
Chris Lattner66781332009-02-15 21:26:50 +0000764/// getInstantiationRange - Given a SourceLocation object, return the
765/// range of tokens covered by the instantiation in the ultimate file.
766std::pair<SourceLocation,SourceLocation>
767SourceManager::getInstantiationRange(SourceLocation Loc) const {
768 if (Loc.isFileID()) return std::make_pair(Loc, Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000769
Chris Lattner66781332009-02-15 21:26:50 +0000770 std::pair<SourceLocation,SourceLocation> Res =
771 getImmediateInstantiationRange(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000772
Chris Lattner66781332009-02-15 21:26:50 +0000773 // Fully resolve the start and end locations to their ultimate instantiation
774 // points.
775 while (!Res.first.isFileID())
776 Res.first = getImmediateInstantiationRange(Res.first).first;
777 while (!Res.second.isFileID())
778 Res.second = getImmediateInstantiationRange(Res.second).second;
779 return Res;
780}
781
Chris Lattnere7fb4842009-02-15 20:52:18 +0000782
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000783
784//===----------------------------------------------------------------------===//
785// Queries about the code at a SourceLocation.
786//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000787
788/// getCharacterData - Return a pointer to the start of the specified location
789/// in the appropriate MemoryBuffer.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000790const char *SourceManager::getCharacterData(SourceLocation SL,
791 bool *Invalid) const {
Reid Spencer5f016e22007-07-11 17:01:13 +0000792 // Note that this is a hot function in the getSpelling() path, which is
793 // heavily used by -E mode.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000794 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
Mike Stump1eb44332009-09-09 15:08:12 +0000795
Ted Kremenekc16c2082009-01-06 01:55:26 +0000796 // Note that calling 'getBuffer()' may lazily page in a source file.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000797 bool CharDataInvalid = false;
798 const llvm::MemoryBuffer *Buffer
Chris Lattnere127a0d2010-04-20 20:35:58 +0000799 = getSLocEntry(LocInfo.first).getFile().getContentCache()
800 ->getBuffer(Diag, *this, SourceLocation(), &CharDataInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000801 if (Invalid)
802 *Invalid = CharDataInvalid;
803 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
Reid Spencer5f016e22007-07-11 17:01:13 +0000804}
805
Reid Spencer5f016e22007-07-11 17:01:13 +0000806
Chris Lattner9dc1f532007-07-20 16:37:10 +0000807/// getColumnNumber - Return the column # for the specified file position.
Chris Lattner7da5aea2009-02-04 00:55:58 +0000808/// this is significantly cheaper to compute than the line number.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000809unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
810 bool *Invalid) const {
811 bool MyInvalid = false;
812 const char *Buf = getBuffer(FID, &MyInvalid)->getBufferStart();
813 if (Invalid)
814 *Invalid = MyInvalid;
815
816 if (MyInvalid)
817 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000818
Reid Spencer5f016e22007-07-11 17:01:13 +0000819 unsigned LineStart = FilePos;
820 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
821 --LineStart;
822 return FilePos-LineStart+1;
823}
824
Zhanyong Wan1f24e112010-10-05 17:56:33 +0000825// isInvalid - Return the result of calling loc.isInvalid(), and
826// if Invalid is not null, set its value to same.
827static bool isInvalid(SourceLocation Loc, bool *Invalid) {
828 bool MyInvalid = Loc.isInvalid();
829 if (Invalid)
830 *Invalid = MyInvalid;
831 return MyInvalid;
832}
833
Douglas Gregor50f6af72010-03-16 05:20:39 +0000834unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
835 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +0000836 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +0000837 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000838 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +0000839}
840
Douglas Gregor50f6af72010-03-16 05:20:39 +0000841unsigned SourceManager::getInstantiationColumnNumber(SourceLocation Loc,
842 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +0000843 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +0000844 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000845 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +0000846}
847
Chandler Carruth5ef04ee2011-02-23 00:47:48 +0000848unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
849 bool *Invalid) const {
850 if (isInvalid(Loc, Invalid)) return 0;
851 return getPresumedLoc(Loc).getColumn();
852}
853
Chandler Carruth14bd9652010-10-23 08:44:57 +0000854static LLVM_ATTRIBUTE_NOINLINE void
Chris Lattnere127a0d2010-04-20 20:35:58 +0000855ComputeLineNumbers(Diagnostic &Diag, ContentCache *FI,
856 llvm::BumpPtrAllocator &Alloc,
857 const SourceManager &SM, bool &Invalid);
858static void ComputeLineNumbers(Diagnostic &Diag, ContentCache *FI,
859 llvm::BumpPtrAllocator &Alloc,
860 const SourceManager &SM, bool &Invalid) {
Ted Kremenekc16c2082009-01-06 01:55:26 +0000861 // Note that calling 'getBuffer()' may lazily page in the file.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000862 const MemoryBuffer *Buffer = FI->getBuffer(Diag, SM, SourceLocation(),
863 &Invalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000864 if (Invalid)
865 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000866
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000867 // Find the file offsets of all of the *physical* source lines. This does
868 // not look at trigraphs, escaped newlines, or anything else tricky.
869 std::vector<unsigned> LineOffsets;
Mike Stump1eb44332009-09-09 15:08:12 +0000870
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000871 // Line #1 starts at char 0.
872 LineOffsets.push_back(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000873
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000874 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
875 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
876 unsigned Offs = 0;
877 while (1) {
878 // Skip over the contents of the line.
879 // TODO: Vectorize this? This is very performance sensitive for programs
880 // with lots of diagnostics and in -E mode.
881 const unsigned char *NextBuf = (const unsigned char *)Buf;
882 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
883 ++NextBuf;
884 Offs += NextBuf-Buf;
885 Buf = NextBuf;
Mike Stump1eb44332009-09-09 15:08:12 +0000886
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000887 if (Buf[0] == '\n' || Buf[0] == '\r') {
888 // If this is \n\r or \r\n, skip both characters.
889 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
890 ++Offs, ++Buf;
891 ++Offs, ++Buf;
892 LineOffsets.push_back(Offs);
893 } else {
894 // Otherwise, this is a null. If end of file, exit.
895 if (Buf == End) break;
896 // Otherwise, skip the null.
897 ++Offs, ++Buf;
898 }
899 }
Mike Stump1eb44332009-09-09 15:08:12 +0000900
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000901 // Copy the offsets into the FileInfo structure.
902 FI->NumLines = LineOffsets.size();
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000903 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000904 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
905}
Reid Spencer5f016e22007-07-11 17:01:13 +0000906
Chris Lattnerdf7c17a2009-01-16 07:00:02 +0000907/// getLineNumber - Given a SourceLocation, return the spelling line number
Reid Spencer5f016e22007-07-11 17:01:13 +0000908/// for the position indicated. This requires building and caching a table of
909/// line offsets for the MemoryBuffer, so this is not cheap: use only when
910/// about to emit a diagnostic.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000911unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
912 bool *Invalid) const {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000913 ContentCache *Content;
Chris Lattner30fc9332009-02-04 01:06:56 +0000914 if (LastLineNoFileIDQuery == FID)
Ted Kremenek78d85f52007-10-30 21:08:08 +0000915 Content = LastLineNoContentCache;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000916 else
Chris Lattner30fc9332009-02-04 01:06:56 +0000917 Content = const_cast<ContentCache*>(getSLocEntry(FID)
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000918 .getFile().getContentCache());
Mike Stump1eb44332009-09-09 15:08:12 +0000919
Reid Spencer5f016e22007-07-11 17:01:13 +0000920 // If this is the first use of line information for this buffer, compute the
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000921 /// SourceLineCache for it on demand.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000922 if (Content->SourceLineCache == 0) {
923 bool MyInvalid = false;
Chris Lattnere127a0d2010-04-20 20:35:58 +0000924 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000925 if (Invalid)
926 *Invalid = MyInvalid;
927 if (MyInvalid)
928 return 1;
929 } else if (Invalid)
930 *Invalid = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000931
932 // Okay, we know we have a line number table. Do a binary search to find the
933 // line number that this character position lands on.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000934 unsigned *SourceLineCache = Content->SourceLineCache;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000935 unsigned *SourceLineCacheStart = SourceLineCache;
Ted Kremenek78d85f52007-10-30 21:08:08 +0000936 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
Mike Stump1eb44332009-09-09 15:08:12 +0000937
Chris Lattner30fc9332009-02-04 01:06:56 +0000938 unsigned QueriedFilePos = FilePos+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000939
Daniel Dunbar4106d692009-05-18 17:30:52 +0000940 // FIXME: I would like to be convinced that this code is worth being as
Mike Stump1eb44332009-09-09 15:08:12 +0000941 // complicated as it is, binary search isn't that slow.
Daniel Dunbar4106d692009-05-18 17:30:52 +0000942 //
943 // If it is worth being optimized, then in my opinion it could be more
944 // performant, simpler, and more obviously correct by just "galloping" outward
945 // from the queried file position. In fact, this could be incorporated into a
946 // generic algorithm such as lower_bound_with_hint.
947 //
948 // If someone gives me a test case where this matters, and I will do it! - DWD
949
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000950 // If the previous query was to the same file, we know both the file pos from
951 // that query and the line number returned. This allows us to narrow the
952 // search space from the entire file to something near the match.
Chris Lattner30fc9332009-02-04 01:06:56 +0000953 if (LastLineNoFileIDQuery == FID) {
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000954 if (QueriedFilePos >= LastLineNoFilePos) {
Daniel Dunbar4106d692009-05-18 17:30:52 +0000955 // FIXME: Potential overflow?
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000956 SourceLineCache = SourceLineCache+LastLineNoResult-1;
Mike Stump1eb44332009-09-09 15:08:12 +0000957
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000958 // The query is likely to be nearby the previous one. Here we check to
959 // see if it is within 5, 10 or 20 lines. It can be far away in cases
960 // where big comment blocks and vertical whitespace eat up lines but
961 // contribute no tokens.
962 if (SourceLineCache+5 < SourceLineCacheEnd) {
963 if (SourceLineCache[5] > QueriedFilePos)
964 SourceLineCacheEnd = SourceLineCache+5;
965 else if (SourceLineCache+10 < SourceLineCacheEnd) {
966 if (SourceLineCache[10] > QueriedFilePos)
967 SourceLineCacheEnd = SourceLineCache+10;
968 else if (SourceLineCache+20 < SourceLineCacheEnd) {
969 if (SourceLineCache[20] > QueriedFilePos)
970 SourceLineCacheEnd = SourceLineCache+20;
971 }
972 }
973 }
974 } else {
Daniel Dunbar4106d692009-05-18 17:30:52 +0000975 if (LastLineNoResult < Content->NumLines)
976 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +0000977 }
978 }
Mike Stump1eb44332009-09-09 15:08:12 +0000979
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000980 // If the spread is large, do a "radix" test as our initial guess, based on
981 // the assumption that lines average to approximately the same length.
982 // NOTE: This is currently disabled, as it does not appear to be profitable in
983 // initial measurements.
984 if (0 && SourceLineCacheEnd-SourceLineCache > 20) {
Ted Kremenek78d85f52007-10-30 21:08:08 +0000985 unsigned FileLen = Content->SourceLineCache[Content->NumLines-1];
Mike Stump1eb44332009-09-09 15:08:12 +0000986
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000987 // Take a stab at guessing where it is.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000988 unsigned ApproxPos = Content->NumLines*QueriedFilePos / FileLen;
Mike Stump1eb44332009-09-09 15:08:12 +0000989
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000990 // Check for -10 and +10 lines.
991 unsigned LowerBound = std::max(int(ApproxPos-10), 0);
992 unsigned UpperBound = std::min(ApproxPos+10, FileLen);
993
994 // If the computed lower bound is less than the query location, move it in.
995 if (SourceLineCache < SourceLineCacheStart+LowerBound &&
996 SourceLineCacheStart[LowerBound] < QueriedFilePos)
997 SourceLineCache = SourceLineCacheStart+LowerBound;
Mike Stump1eb44332009-09-09 15:08:12 +0000998
Chris Lattner1cf12bf2007-07-24 06:43:46 +0000999 // If the computed upper bound is greater than the query location, move it.
1000 if (SourceLineCacheEnd > SourceLineCacheStart+UpperBound &&
1001 SourceLineCacheStart[UpperBound] >= QueriedFilePos)
1002 SourceLineCacheEnd = SourceLineCacheStart+UpperBound;
1003 }
Mike Stump1eb44332009-09-09 15:08:12 +00001004
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001005 unsigned *Pos
1006 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001007 unsigned LineNo = Pos-SourceLineCacheStart;
Mike Stump1eb44332009-09-09 15:08:12 +00001008
Chris Lattner30fc9332009-02-04 01:06:56 +00001009 LastLineNoFileIDQuery = FID;
Ted Kremenek78d85f52007-10-30 21:08:08 +00001010 LastLineNoContentCache = Content;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001011 LastLineNoFilePos = QueriedFilePos;
1012 LastLineNoResult = LineNo;
1013 return LineNo;
Reid Spencer5f016e22007-07-11 17:01:13 +00001014}
1015
Chandler Carruth5ef04ee2011-02-23 00:47:48 +00001016unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
1017 bool *Invalid) const {
1018 if (isInvalid(Loc, Invalid)) return 0;
1019 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1020 return getLineNumber(LocInfo.first, LocInfo.second);
1021}
Douglas Gregor50f6af72010-03-16 05:20:39 +00001022unsigned SourceManager::getInstantiationLineNumber(SourceLocation Loc,
1023 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001024 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattner30fc9332009-02-04 01:06:56 +00001025 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
1026 return getLineNumber(LocInfo.first, LocInfo.second);
1027}
Chandler Carruth5ef04ee2011-02-23 00:47:48 +00001028unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
Douglas Gregor50f6af72010-03-16 05:20:39 +00001029 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001030 if (isInvalid(Loc, Invalid)) return 0;
Chandler Carruth5ef04ee2011-02-23 00:47:48 +00001031 return getPresumedLoc(Loc).getLine();
Chris Lattner30fc9332009-02-04 01:06:56 +00001032}
1033
Chris Lattner6b306672009-02-04 05:33:01 +00001034/// getFileCharacteristic - return the file characteristic of the specified
Mike Stump1eb44332009-09-09 15:08:12 +00001035/// source location, indicating whether this is a normal file, a system
Chris Lattner6b306672009-02-04 05:33:01 +00001036/// header, or an "implicit extern C" system header.
1037///
1038/// This state can be modified with flags on GNU linemarker directives like:
1039/// # 4 "foo.h" 3
1040/// which changes all source locations in the current file after that to be
1041/// considered to be from a system header.
Mike Stump1eb44332009-09-09 15:08:12 +00001042SrcMgr::CharacteristicKind
Chris Lattner6b306672009-02-04 05:33:01 +00001043SourceManager::getFileCharacteristic(SourceLocation Loc) const {
1044 assert(!Loc.isInvalid() && "Can't get file characteristic of invalid loc!");
1045 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
1046 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile();
1047
1048 // If there are no #line directives in this file, just return the whole-file
1049 // state.
1050 if (!FI.hasLineDirectives())
1051 return FI.getFileCharacteristic();
Mike Stump1eb44332009-09-09 15:08:12 +00001052
Chris Lattner6b306672009-02-04 05:33:01 +00001053 assert(LineTable && "Can't have linetable entries without a LineTable!");
1054 // See if there is a #line directive before the location.
1055 const LineEntry *Entry =
1056 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001057
Chris Lattner6b306672009-02-04 05:33:01 +00001058 // If this is before the first line marker, use the file characteristic.
1059 if (!Entry)
1060 return FI.getFileCharacteristic();
1061
1062 return Entry->FileKind;
1063}
1064
Chris Lattnerbff5c512009-02-17 08:39:06 +00001065/// Return the filename or buffer identifier of the buffer the location is in.
1066/// Note that this name does not respect #line directives. Use getPresumedLoc
1067/// for normal clients.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001068const char *SourceManager::getBufferName(SourceLocation Loc,
1069 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001070 if (isInvalid(Loc, Invalid)) return "<invalid loc>";
Mike Stump1eb44332009-09-09 15:08:12 +00001071
Douglas Gregor50f6af72010-03-16 05:20:39 +00001072 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
Chris Lattnerbff5c512009-02-17 08:39:06 +00001073}
1074
Chris Lattner30fc9332009-02-04 01:06:56 +00001075
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001076/// getPresumedLoc - This method returns the "presumed" location of a
1077/// SourceLocation specifies. A "presumed location" can be modified by #line
1078/// or GNU line marker directives. This provides a view on the data that a
1079/// user should see in diagnostics, for example.
1080///
1081/// Note that a presumed location is always given as the instantiation point
1082/// of an instantiation location, not at the spelling location.
1083PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc) const {
1084 if (Loc.isInvalid()) return PresumedLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001085
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001086 // Presumed locations are always for instantiation points.
Chris Lattner7da5aea2009-02-04 00:55:58 +00001087 std::pair<FileID, unsigned> LocInfo = getDecomposedInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +00001088
Chris Lattner30fc9332009-02-04 01:06:56 +00001089 const SrcMgr::FileInfo &FI = getSLocEntry(LocInfo.first).getFile();
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001090 const SrcMgr::ContentCache *C = FI.getContentCache();
Mike Stump1eb44332009-09-09 15:08:12 +00001091
Chris Lattner3cd949c2009-02-04 01:55:42 +00001092 // To get the source name, first consult the FileEntry (if one exists)
1093 // before the MemBuffer as this will avoid unnecessarily paging in the
1094 // MemBuffer.
Chris Lattnere127a0d2010-04-20 20:35:58 +00001095 const char *Filename;
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001096 if (C->OrigEntry)
1097 Filename = C->OrigEntry->getName();
Chris Lattnere127a0d2010-04-20 20:35:58 +00001098 else
1099 Filename = C->getBuffer(Diag, *this)->getBufferIdentifier();
Douglas Gregorc417fa02010-11-02 00:39:22 +00001100 bool Invalid = false;
1101 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1102 if (Invalid)
1103 return PresumedLoc();
1104 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1105 if (Invalid)
1106 return PresumedLoc();
1107
Chris Lattner3cd949c2009-02-04 01:55:42 +00001108 SourceLocation IncludeLoc = FI.getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001109
Chris Lattner3cd949c2009-02-04 01:55:42 +00001110 // If we have #line directives in this file, update and overwrite the physical
1111 // location info if appropriate.
1112 if (FI.hasLineDirectives()) {
1113 assert(LineTable && "Can't have linetable entries without a LineTable!");
1114 // See if there is a #line directive before this. If so, get it.
1115 if (const LineEntry *Entry =
1116 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second)) {
Chris Lattnerfc391332009-02-04 02:00:59 +00001117 // If the LineEntry indicates a filename, use it.
Chris Lattner3cd949c2009-02-04 01:55:42 +00001118 if (Entry->FilenameID != -1)
1119 Filename = LineTable->getFilename(Entry->FilenameID);
Chris Lattnerfc391332009-02-04 02:00:59 +00001120
1121 // Use the line number specified by the LineEntry. This line number may
1122 // be multiple lines down from the line entry. Add the difference in
1123 // physical line numbers from the query point and the line marker to the
1124 // total.
1125 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1126 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001127
Chris Lattner0e0e5da2009-02-04 02:15:40 +00001128 // Note that column numbers are not molested by line markers.
Mike Stump1eb44332009-09-09 15:08:12 +00001129
Chris Lattner137b6a62009-02-04 06:25:26 +00001130 // Handle virtual #include manipulation.
1131 if (Entry->IncludeOffset) {
1132 IncludeLoc = getLocForStartOfFile(LocInfo.first);
1133 IncludeLoc = IncludeLoc.getFileLocWithOffset(Entry->IncludeOffset);
1134 }
Chris Lattner3cd949c2009-02-04 01:55:42 +00001135 }
1136 }
1137
1138 return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc);
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001139}
1140
1141//===----------------------------------------------------------------------===//
1142// Other miscellaneous methods.
1143//===----------------------------------------------------------------------===//
1144
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001145/// \brief Retrieve the inode for the given file entry, if possible.
1146///
1147/// This routine involves a system call, and therefore should only be used
1148/// in non-performance-critical code.
1149static llvm::Optional<ino_t> getActualFileInode(const FileEntry *File) {
1150 if (!File)
1151 return llvm::Optional<ino_t>();
1152
1153 struct stat StatBuf;
1154 if (::stat(File->getName(), &StatBuf))
1155 return llvm::Optional<ino_t>();
1156
1157 return StatBuf.st_ino;
1158}
1159
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001160/// \brief Get the source location for the given file:line:col triplet.
1161///
1162/// If the source file is included multiple times, the source location will
1163/// be based upon the first inclusion.
1164SourceLocation SourceManager::getLocation(const FileEntry *SourceFile,
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001165 unsigned Line, unsigned Col) {
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001166 assert(SourceFile && "Null source file!");
1167 assert(Line && Col && "Line and column should start from 1!");
1168
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001169 // Find the first file ID that corresponds to the given file.
1170 FileID FirstFID;
Mike Stump1eb44332009-09-09 15:08:12 +00001171
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001172 // First, check the main file ID, since it is common to look for a
1173 // location in the main file.
1174 llvm::Optional<ino_t> SourceFileInode;
1175 llvm::Optional<llvm::StringRef> SourceFileName;
1176 if (!MainFileID.isInvalid()) {
1177 const SLocEntry &MainSLoc = getSLocEntry(MainFileID);
1178 if (MainSLoc.isFile()) {
1179 const ContentCache *MainContentCache
1180 = MainSLoc.getFile().getContentCache();
Douglas Gregorb7a18412011-02-11 18:08:15 +00001181 if (!MainContentCache) {
1182 // Can't do anything
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001183 } else if (MainContentCache->OrigEntry == SourceFile) {
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001184 FirstFID = MainFileID;
Douglas Gregorb7a18412011-02-11 18:08:15 +00001185 } else {
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001186 // Fall back: check whether we have the same base name and inode
1187 // as the main file.
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001188 const FileEntry *MainFile = MainContentCache->OrigEntry;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001189 SourceFileName = llvm::sys::path::filename(SourceFile->getName());
1190 if (*SourceFileName == llvm::sys::path::filename(MainFile->getName())) {
1191 SourceFileInode = getActualFileInode(SourceFile);
Douglas Gregor37c02bf2011-02-16 19:09:24 +00001192 if (SourceFileInode) {
1193 if (llvm::Optional<ino_t> MainFileInode
1194 = getActualFileInode(MainFile)) {
1195 if (*SourceFileInode == *MainFileInode) {
1196 FirstFID = MainFileID;
1197 SourceFile = MainFile;
1198 }
1199 }
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001200 }
1201 }
1202 }
1203 }
1204 }
1205
1206 if (FirstFID.isInvalid()) {
1207 // The location we're looking for isn't in the main file; look
1208 // through all of the source locations.
1209 for (unsigned I = 0, N = sloc_entry_size(); I != N; ++I) {
1210 const SLocEntry &SLoc = getSLocEntry(I);
1211 if (SLoc.isFile() &&
1212 SLoc.getFile().getContentCache() &&
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001213 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001214 FirstFID = FileID::get(I);
1215 break;
1216 }
1217 }
1218 }
1219
1220 // If we haven't found what we want yet, try again, but this time stat()
1221 // each of the files in case the files have changed since we originally
1222 // parsed the file.
1223 if (FirstFID.isInvalid() &&
1224 (SourceFileName ||
1225 (SourceFileName = llvm::sys::path::filename(SourceFile->getName()))) &&
1226 (SourceFileInode ||
1227 (SourceFileInode = getActualFileInode(SourceFile)))) {
1228 for (unsigned I = 0, N = sloc_entry_size(); I != N; ++I) {
1229 const SLocEntry &SLoc = getSLocEntry(I);
1230 if (SLoc.isFile()) {
1231 const ContentCache *FileContentCache
1232 = SLoc.getFile().getContentCache();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001233 const FileEntry *Entry =FileContentCache? FileContentCache->OrigEntry : 0;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001234 if (Entry &&
Douglas Gregorb7a18412011-02-11 18:08:15 +00001235 *SourceFileName == llvm::sys::path::filename(Entry->getName())) {
1236 if (llvm::Optional<ino_t> EntryInode = getActualFileInode(Entry)) {
1237 if (*SourceFileInode == *EntryInode) {
1238 FirstFID = FileID::get(I);
1239 SourceFile = Entry;
1240 break;
1241 }
1242 }
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001243 }
1244 }
1245 }
1246 }
1247
1248 if (FirstFID.isInvalid())
1249 return SourceLocation();
1250
1251 if (Line == 1 && Col == 1)
1252 return getLocForStartOfFile(FirstFID);
1253
1254 ContentCache *Content
1255 = const_cast<ContentCache *>(getOrCreateContentCache(SourceFile));
1256 if (!Content)
1257 return SourceLocation();
1258
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001259 // If this is the first use of line information for this buffer, compute the
1260 /// SourceLineCache for it on demand.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001261 if (Content->SourceLineCache == 0) {
1262 bool MyInvalid = false;
Chris Lattnere127a0d2010-04-20 20:35:58 +00001263 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001264 if (MyInvalid)
1265 return SourceLocation();
1266 }
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001267
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001268 if (Line > Content->NumLines) {
Chris Lattnere127a0d2010-04-20 20:35:58 +00001269 unsigned Size = Content->getBuffer(Diag, *this)->getBufferSize();
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001270 if (Size > 0)
1271 --Size;
1272 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(Size);
1273 }
1274
1275 unsigned FilePos = Content->SourceLineCache[Line - 1];
Chris Lattnere127a0d2010-04-20 20:35:58 +00001276 const char *Buf = Content->getBuffer(Diag, *this)->getBufferStart() + FilePos;
1277 unsigned BufLength = Content->getBuffer(Diag, *this)->getBufferEnd() - Buf;
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001278 unsigned i = 0;
1279
1280 // Check that the given column is valid.
1281 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1282 ++i;
1283 if (i < Col-1)
1284 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + i);
1285
Douglas Gregor4a160e12009-12-02 05:34:39 +00001286 return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + Col - 1);
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001287}
1288
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001289/// Given a decomposed source location, move it up the include/instantiation
1290/// stack to the parent source location. If this is possible, return the
1291/// decomposed version of the parent in Loc and return false. If Loc is the
1292/// top-level entry, return true and don't modify it.
1293static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1294 const SourceManager &SM) {
1295 SourceLocation UpperLoc;
1296 const SrcMgr::SLocEntry &Entry = SM.getSLocEntry(Loc.first);
1297 if (Entry.isInstantiation())
1298 UpperLoc = Entry.getInstantiation().getInstantiationLocStart();
1299 else
1300 UpperLoc = Entry.getFile().getIncludeLoc();
1301
1302 if (UpperLoc.isInvalid())
1303 return true; // We reached the top.
1304
1305 Loc = SM.getDecomposedLoc(UpperLoc);
1306 return false;
1307}
1308
1309
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001310/// \brief Determines the order of 2 source locations in the translation unit.
1311///
1312/// \returns true if LHS source location comes before RHS, false otherwise.
1313bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
1314 SourceLocation RHS) const {
1315 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
1316 if (LHS == RHS)
1317 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001318
Argyrios Kyrtzidisee933e12010-12-24 02:53:53 +00001319 // If both locations are macro instantiations, the order of their offsets
1320 // reflect the order that the tokens, pointed to by these locations, were
1321 // instantiated (during parsing each token that is instantiated by a macro,
1322 // expands the SLocEntries).
1323 if (LHS.isMacroID() && RHS.isMacroID())
1324 return LHS.getOffset() < RHS.getOffset();
1325
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001326 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
1327 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00001328
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001329 // If the source locations are in the same file, just compare offsets.
1330 if (LOffs.first == ROffs.first)
1331 return LOffs.second < ROffs.second;
1332
1333 // If we are comparing a source location with multiple locations in the same
1334 // file, we get a big win by caching the result.
Chris Lattner66a915f2010-05-07 05:10:46 +00001335 if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
1336 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001337
Chris Lattnerdcb1d682010-05-07 01:17:07 +00001338 // Okay, we missed in the cache, start updating the cache for this query.
1339 IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first);
Mike Stump1eb44332009-09-09 15:08:12 +00001340
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001341 // "Traverse" the include/instantiation stacks of both locations and try to
Chris Lattner48296ba2010-05-07 05:51:13 +00001342 // find a common "ancestor". FileIDs build a tree-like structure that
1343 // reflects the #include hierarchy, and this algorithm needs to find the
1344 // nearest common ancestor between the two locations. For example, if you
1345 // have a.c that includes b.h and c.h, and are comparing a location in b.h to
1346 // a location in c.h, we need to find that their nearest common ancestor is
1347 // a.c, and compare the locations of the two #includes to find their relative
1348 // ordering.
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001349 //
Chris Lattner48296ba2010-05-07 05:51:13 +00001350 // SourceManager assigns FileIDs in order of parsing. This means that an
1351 // includee always has a larger FileID than an includer. While you might
1352 // think that we could just compare the FileID's here, that doesn't work to
1353 // compare a point at the end of a.c with a point within c.h. Though c.h has
1354 // a larger FileID, we have to compare the include point of c.h to the
1355 // location in a.c.
1356 //
1357 // Despite not being able to directly compare FileID's, we can tell that a
1358 // larger FileID is necessarily more deeply nested than a lower one and use
1359 // this information to walk up the tree to the nearest common ancestor.
1360 do {
1361 // If LOffs is larger than ROffs, then LOffs must be more deeply nested than
1362 // ROffs, walk up the #include chain.
1363 if (LOffs.first.ID > ROffs.first.ID) {
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001364 if (MoveUpIncludeHierarchy(LOffs, *this))
Chris Lattner48296ba2010-05-07 05:51:13 +00001365 break; // We reached the top.
1366
Chris Lattner48296ba2010-05-07 05:51:13 +00001367 } else {
1368 // Otherwise, ROffs is larger than LOffs, so ROffs must be more deeply
1369 // nested than LOffs, walk up the #include chain.
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001370 if (MoveUpIncludeHierarchy(ROffs, *this))
Chris Lattner48296ba2010-05-07 05:51:13 +00001371 break; // We reached the top.
Chris Lattnerdcb1d682010-05-07 01:17:07 +00001372 }
Chris Lattner48296ba2010-05-07 05:51:13 +00001373 } while (LOffs.first != ROffs.first);
Mike Stump1eb44332009-09-09 15:08:12 +00001374
Chris Lattner48296ba2010-05-07 05:51:13 +00001375 // If we exited because we found a nearest common ancestor, compare the
1376 // locations within the common file and cache them.
1377 if (LOffs.first == ROffs.first) {
1378 IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
1379 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001380 }
Mike Stump1eb44332009-09-09 15:08:12 +00001381
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001382 // There is no common ancestor, most probably because one location is in the
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001383 // predefines buffer or an AST file.
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001384 // FIXME: We should rearrange the external interface so this simply never
1385 // happens; it can't conceptually happen. Also see PR5662.
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001386 IsBeforeInTUCache.setQueryFIDs(FileID(), FileID()); // Don't try caching.
1387
1388 // Zip both entries up to the top level record.
1389 while (!MoveUpIncludeHierarchy(LOffs, *this)) /*empty*/;
1390 while (!MoveUpIncludeHierarchy(ROffs, *this)) /*empty*/;
Chris Lattner48296ba2010-05-07 05:51:13 +00001391
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001392 // If exactly one location is a memory buffer, assume it preceeds the other.
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001393
1394 // Strip off macro instantation locations, going up to the top-level File
1395 // SLocEntry.
1396 bool LIsMB = getFileEntryForID(LOffs.first) == 0;
1397 bool RIsMB = getFileEntryForID(ROffs.first) == 0;
Chris Lattner48296ba2010-05-07 05:51:13 +00001398 if (LIsMB != RIsMB)
Chris Lattnerdcb1d682010-05-07 01:17:07 +00001399 return LIsMB;
Mike Stump1eb44332009-09-09 15:08:12 +00001400
Daniel Dunbarfbcc7be2009-12-01 23:07:57 +00001401 // Otherwise, just assume FileIDs were created in order.
Chris Lattnerdcb1d682010-05-07 01:17:07 +00001402 return LOffs.first < ROffs.first;
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001403}
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001404
Reid Spencer5f016e22007-07-11 17:01:13 +00001405/// PrintStats - Print statistics to stderr.
1406///
1407void SourceManager::PrintStats() const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001408 llvm::errs() << "\n*** Source Manager Stats:\n";
1409 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
1410 << " mem buffers mapped.\n";
1411 llvm::errs() << SLocEntryTable.size() << " SLocEntry's allocated, "
1412 << NextOffset << "B of Sloc address space used.\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001413
Reid Spencer5f016e22007-07-11 17:01:13 +00001414 unsigned NumLineNumsComputed = 0;
1415 unsigned NumFileBytesMapped = 0;
Chris Lattner0d0bf8c2009-02-03 07:30:45 +00001416 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
1417 NumLineNumsComputed += I->second->SourceLineCache != 0;
1418 NumFileBytesMapped += I->second->getSizeBytesMapped();
Reid Spencer5f016e22007-07-11 17:01:13 +00001419 }
Mike Stump1eb44332009-09-09 15:08:12 +00001420
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001421 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
1422 << NumLineNumsComputed << " files with line #'s computed.\n";
1423 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
1424 << NumBinaryProbes << " binary.\n";
Reid Spencer5f016e22007-07-11 17:01:13 +00001425}
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001426
1427ExternalSLocEntrySource::~ExternalSLocEntrySource() { }