blob: 61dfe35e22579fb6df8ad4717af018b56aac7888 [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 Gregoraea67db2010-03-15 22:54:52 +000015#include "clang/Basic/Diagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#include "clang/Basic/FileManager.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000017#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregor86a4d0d2011-02-03 17:17:35 +000018#include "llvm/ADT/Optional.h"
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +000019#include "llvm/ADT/STLExtras.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "llvm/ADT/StringSwitch.h"
21#include "llvm/Support/Capacity.h"
Chris Lattner5e36a7a2007-07-24 05:57:19 +000022#include "llvm/Support/Compiler.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000024#include "llvm/Support/Path.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000025#include "llvm/Support/raw_ostream.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000026#include <algorithm>
Douglas Gregorf715ca12010-03-16 00:06:06 +000027#include <cstring>
Chandler Carruth55fc8732012-12-04 09:13:33 +000028#include <string>
Douglas Gregoraea67db2010-03-15 22:54:52 +000029
Reid Spencer5f016e22007-07-11 17:01:13 +000030using namespace clang;
31using namespace SrcMgr;
32using llvm::MemoryBuffer;
33
Chris Lattner23b5dc62009-02-04 00:40:31 +000034//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +000035// SourceManager Helper Classes
Chris Lattner23b5dc62009-02-04 00:40:31 +000036//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +000037
Ted Kremenek78d85f52007-10-30 21:08:08 +000038ContentCache::~ContentCache() {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000039 if (shouldFreeBuffer())
40 delete Buffer.getPointer();
Reid Spencer5f016e22007-07-11 17:01:13 +000041}
42
Chandler Carruth3201f382011-07-26 05:17:23 +000043/// getSizeBytesMapped - Returns the number of bytes actually mapped for this
44/// ContentCache. This can be 0 if the MemBuffer was not actually expanded.
Ted Kremenekc16c2082009-01-06 01:55:26 +000045unsigned ContentCache::getSizeBytesMapped() const {
Douglas Gregorc8151082010-03-16 22:53:51 +000046 return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 0;
Ted Kremenekc16c2082009-01-06 01:55:26 +000047}
48
Ted Kremenekf61b8312011-04-28 20:36:42 +000049/// Returns the kind of memory used to back the memory buffer for
50/// this content cache. This is used for performance analysis.
51llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const {
52 assert(Buffer.getPointer());
53
54 // Should be unreachable, but keep for sanity.
55 if (!Buffer.getPointer())
56 return llvm::MemoryBuffer::MemoryBuffer_Malloc;
Stephen Hinesc568f1e2014-07-21 00:47:37 -070057
58 llvm::MemoryBuffer *buf = Buffer.getPointer();
Ted Kremenekf61b8312011-04-28 20:36:42 +000059 return buf->getBufferKind();
60}
61
Ted Kremenekc16c2082009-01-06 01:55:26 +000062/// getSize - Returns the size of the content encapsulated by this ContentCache.
63/// This can be the size of the source file or the size of an arbitrary
64/// scratch buffer. If the ContentCache encapsulates a source file, that
Douglas Gregor29684422009-12-02 06:49:09 +000065/// file is not lazily brought in from disk to satisfy this query.
Ted Kremenekc16c2082009-01-06 01:55:26 +000066unsigned ContentCache::getSize() const {
Douglas Gregorc8151082010-03-16 22:53:51 +000067 return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize()
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +000068 : (unsigned) ContentsEntry->getSize();
Ted Kremenekc16c2082009-01-06 01:55:26 +000069}
70
Stephen Hinesc568f1e2014-07-21 00:47:37 -070071void ContentCache::replaceBuffer(llvm::MemoryBuffer *B, bool DoNotFree) {
Argyrios Kyrtzidisd54dff02012-05-03 21:50:39 +000072 if (B && B == Buffer.getPointer()) {
Argyrios Kyrtzidisa4288c42011-12-10 01:38:26 +000073 assert(0 && "Replacing with the same buffer");
74 Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
75 return;
76 }
Douglas Gregor29684422009-12-02 06:49:09 +000077
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000078 if (shouldFreeBuffer())
79 delete Buffer.getPointer();
Douglas Gregorc8151082010-03-16 22:53:51 +000080 Buffer.setPointer(B);
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000081 Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
Douglas Gregor29684422009-12-02 06:49:09 +000082}
83
Stephen Hinesc568f1e2014-07-21 00:47:37 -070084llvm::MemoryBuffer *ContentCache::getBuffer(DiagnosticsEngine &Diag,
85 const SourceManager &SM,
86 SourceLocation Loc,
87 bool *Invalid) const {
Chris Lattnerb088cd32010-11-23 08:50:03 +000088 // Lazily create the Buffer for ContentCaches that wrap files. If we already
Chris Lattnerfc8f0e12011-04-15 05:22:18 +000089 // computed it, just return what we have.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070090 if (Buffer.getPointer() || !ContentsEntry) {
Chris Lattnerb088cd32010-11-23 08:50:03 +000091 if (Invalid)
92 *Invalid = isBufferInvalid();
Chris Lattner38caec42010-04-20 18:14:03 +000093
Chris Lattnerb088cd32010-11-23 08:50:03 +000094 return Buffer.getPointer();
95 }
Benjamin Kramer5807d9c2010-11-18 12:46:39 +000096
Chris Lattnerb088cd32010-11-23 08:50:03 +000097 std::string ErrorStr;
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +000098 bool isVolatile = SM.userFilesAreVolatile() && !IsSystemFile;
99 Buffer.setPointer(SM.getFileManager().getBufferForFile(ContentsEntry,
100 &ErrorStr,
101 isVolatile));
Chris Lattnerb088cd32010-11-23 08:50:03 +0000102
103 // If we were unable to open the file, then we are in an inconsistent
104 // situation where the content cache referenced a file which no longer
105 // exists. Most likely, we were using a stat cache with an invalid entry but
106 // the file could also have been removed during processing. Since we can't
107 // really deal with this situation, just create an empty buffer.
108 //
109 // FIXME: This is definitely not ideal, but our immediate clients can't
110 // currently handle returning a null entry here. Ideally we should detect
111 // that we are in an inconsistent situation and error out as quickly as
112 // possible.
113 if (!Buffer.getPointer()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000114 const StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000115 Buffer.setPointer(MemoryBuffer::getNewMemBuffer(ContentsEntry->getSize(),
Chris Lattnerb088cd32010-11-23 08:50:03 +0000116 "<invalid>"));
117 char *Ptr = const_cast<char*>(Buffer.getPointer()->getBufferStart());
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000118 for (unsigned i = 0, e = ContentsEntry->getSize(); i != e; ++i)
Chris Lattnerb088cd32010-11-23 08:50:03 +0000119 Ptr[i] = FillStr[i % FillStr.size()];
120
121 if (Diag.isDiagnosticInFlight())
122 Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000123 ContentsEntry->getName(), ErrorStr);
Chris Lattnerb088cd32010-11-23 08:50:03 +0000124 else
125 Diag.Report(Loc, diag::err_cannot_open_file)
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000126 << ContentsEntry->getName() << ErrorStr;
Chris Lattnerb088cd32010-11-23 08:50:03 +0000127
128 Buffer.setInt(Buffer.getInt() | InvalidFlag);
129
130 if (Invalid) *Invalid = true;
131 return Buffer.getPointer();
132 }
133
134 // Check that the file's size is the same as in the file entry (which may
135 // have come from a stat cache).
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000136 if (getRawBuffer()->getBufferSize() != (size_t)ContentsEntry->getSize()) {
Chris Lattnerb088cd32010-11-23 08:50:03 +0000137 if (Diag.isDiagnosticInFlight())
138 Diag.SetDelayedDiagnostic(diag::err_file_modified,
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000139 ContentsEntry->getName());
Chris Lattnerb088cd32010-11-23 08:50:03 +0000140 else
141 Diag.Report(Loc, diag::err_file_modified)
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000142 << ContentsEntry->getName();
Chris Lattnerb088cd32010-11-23 08:50:03 +0000143
144 Buffer.setInt(Buffer.getInt() | InvalidFlag);
145 if (Invalid) *Invalid = true;
146 return Buffer.getPointer();
147 }
Eric Christopher156119d2011-04-09 00:01:04 +0000148
Chris Lattnerb088cd32010-11-23 08:50:03 +0000149 // If the buffer is valid, check to see if it has a UTF Byte Order Mark
Eric Christopher156119d2011-04-09 00:01:04 +0000150 // (BOM). We only support UTF-8 with and without a BOM right now. See
Chris Lattnerb088cd32010-11-23 08:50:03 +0000151 // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000152 StringRef BufStr = Buffer.getPointer()->getBuffer();
Eric Christopher156119d2011-04-09 00:01:04 +0000153 const char *InvalidBOM = llvm::StringSwitch<const char *>(BufStr)
Chris Lattnerb088cd32010-11-23 08:50:03 +0000154 .StartsWith("\xFE\xFF", "UTF-16 (BE)")
155 .StartsWith("\xFF\xFE", "UTF-16 (LE)")
156 .StartsWith("\x00\x00\xFE\xFF", "UTF-32 (BE)")
157 .StartsWith("\xFF\xFE\x00\x00", "UTF-32 (LE)")
158 .StartsWith("\x2B\x2F\x76", "UTF-7")
159 .StartsWith("\xF7\x64\x4C", "UTF-1")
160 .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
161 .StartsWith("\x0E\xFE\xFF", "SDSU")
162 .StartsWith("\xFB\xEE\x28", "BOCU-1")
163 .StartsWith("\x84\x31\x95\x33", "GB-18030")
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700164 .Default(nullptr);
Chris Lattnerb088cd32010-11-23 08:50:03 +0000165
Eric Christopher156119d2011-04-09 00:01:04 +0000166 if (InvalidBOM) {
Chris Lattnerb088cd32010-11-23 08:50:03 +0000167 Diag.Report(Loc, diag::err_unsupported_bom)
Eric Christopher156119d2011-04-09 00:01:04 +0000168 << InvalidBOM << ContentsEntry->getName();
Chris Lattnerb088cd32010-11-23 08:50:03 +0000169 Buffer.setInt(Buffer.getInt() | InvalidFlag);
Ted Kremenek5b034ad2009-01-06 22:43:04 +0000170 }
Douglas Gregoraea67db2010-03-15 22:54:52 +0000171
Douglas Gregorc8151082010-03-16 22:53:51 +0000172 if (Invalid)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000173 *Invalid = isBufferInvalid();
Douglas Gregorc8151082010-03-16 22:53:51 +0000174
175 return Buffer.getPointer();
Ted Kremenekc16c2082009-01-06 01:55:26 +0000176}
177
Chris Lattner5f9e2722011-07-23 10:55:15 +0000178unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000179 // Look up the filename in the string table, returning the pre-existing value
180 // if it exists.
Mike Stump1eb44332009-09-09 15:08:12 +0000181 llvm::StringMapEntry<unsigned> &Entry =
Jay Foad65aa6882011-06-21 15:13:30 +0000182 FilenameIDs.GetOrCreateValue(Name, ~0U);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000183 if (Entry.getValue() != ~0U)
184 return Entry.getValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000185
Chris Lattner5b9a5042009-01-26 07:57:50 +0000186 // Otherwise, assign this the next available ID.
187 Entry.setValue(FilenamesByID.size());
188 FilenamesByID.push_back(&Entry);
189 return FilenamesByID.size()-1;
190}
191
Chris Lattnerac50e342009-02-03 22:13:05 +0000192/// AddLineNote - Add a line note to the line table that indicates that there
James Dennett7285a062012-06-15 21:28:23 +0000193/// is a \#line at the specified FID/Offset location which changes the presumed
Chris Lattnerac50e342009-02-03 22:13:05 +0000194/// location to LineNo/FilenameID.
Douglas Gregor47d9de62012-06-08 16:40:28 +0000195void LineTableInfo::AddLineNote(FileID FID, unsigned Offset,
Chris Lattnerac50e342009-02-03 22:13:05 +0000196 unsigned LineNo, int FilenameID) {
Chris Lattner23b5dc62009-02-04 00:40:31 +0000197 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump1eb44332009-09-09 15:08:12 +0000198
Chris Lattner23b5dc62009-02-04 00:40:31 +0000199 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
200 "Adding line entries out of order!");
Mike Stump1eb44332009-09-09 15:08:12 +0000201
Chris Lattner9d79eba2009-02-04 05:21:58 +0000202 SrcMgr::CharacteristicKind Kind = SrcMgr::C_User;
Chris Lattner137b6a62009-02-04 06:25:26 +0000203 unsigned IncludeOffset = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000204
Chris Lattner9d79eba2009-02-04 05:21:58 +0000205 if (!Entries.empty()) {
206 // If this is a '#line 4' after '#line 42 "foo.h"', make sure to remember
207 // that we are still in "foo.h".
208 if (FilenameID == -1)
209 FilenameID = Entries.back().FilenameID;
Mike Stump1eb44332009-09-09 15:08:12 +0000210
Chris Lattner137b6a62009-02-04 06:25:26 +0000211 // If we are after a line marker that switched us to system header mode, or
212 // that set #include information, preserve it.
Chris Lattner9d79eba2009-02-04 05:21:58 +0000213 Kind = Entries.back().FileKind;
Chris Lattner137b6a62009-02-04 06:25:26 +0000214 IncludeOffset = Entries.back().IncludeOffset;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000215 }
Mike Stump1eb44332009-09-09 15:08:12 +0000216
Chris Lattner137b6a62009-02-04 06:25:26 +0000217 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, Kind,
218 IncludeOffset));
Chris Lattnerac50e342009-02-03 22:13:05 +0000219}
220
Chris Lattner9d79eba2009-02-04 05:21:58 +0000221/// AddLineNote This is the same as the previous version of AddLineNote, but is
222/// used for GNU line markers. If EntryExit is 0, then this doesn't change the
James Dennettb8950b82012-06-17 03:22:59 +0000223/// presumed \#include stack. If it is 1, this is a file entry, if it is 2 then
Chris Lattner9d79eba2009-02-04 05:21:58 +0000224/// this is a file exit. FileKind specifies whether this is a system header or
225/// extern C system header.
Douglas Gregor47d9de62012-06-08 16:40:28 +0000226void LineTableInfo::AddLineNote(FileID FID, unsigned Offset,
Chris Lattner9d79eba2009-02-04 05:21:58 +0000227 unsigned LineNo, int FilenameID,
228 unsigned EntryExit,
229 SrcMgr::CharacteristicKind FileKind) {
230 assert(FilenameID != -1 && "Unspecified filename should use other accessor");
Mike Stump1eb44332009-09-09 15:08:12 +0000231
Chris Lattner9d79eba2009-02-04 05:21:58 +0000232 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump1eb44332009-09-09 15:08:12 +0000233
Chris Lattner9d79eba2009-02-04 05:21:58 +0000234 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
235 "Adding line entries out of order!");
236
Chris Lattner137b6a62009-02-04 06:25:26 +0000237 unsigned IncludeOffset = 0;
238 if (EntryExit == 0) { // No #include stack change.
239 IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
240 } else if (EntryExit == 1) {
241 IncludeOffset = Offset-1;
242 } else if (EntryExit == 2) {
243 assert(!Entries.empty() && Entries.back().IncludeOffset &&
244 "PPDirectives should have caught case when popping empty include stack");
Mike Stump1eb44332009-09-09 15:08:12 +0000245
Chris Lattner137b6a62009-02-04 06:25:26 +0000246 // Get the include loc of the last entries' include loc as our include loc.
247 IncludeOffset = 0;
248 if (const LineEntry *PrevEntry =
249 FindNearestLineEntry(FID, Entries.back().IncludeOffset))
250 IncludeOffset = PrevEntry->IncludeOffset;
251 }
Mike Stump1eb44332009-09-09 15:08:12 +0000252
Chris Lattner137b6a62009-02-04 06:25:26 +0000253 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
254 IncludeOffset));
Chris Lattner9d79eba2009-02-04 05:21:58 +0000255}
256
257
Chris Lattner3cd949c2009-02-04 01:55:42 +0000258/// FindNearestLineEntry - Find the line entry nearest to FID that is before
259/// it. If there is no line entry before Offset in FID, return null.
Douglas Gregor47d9de62012-06-08 16:40:28 +0000260const LineEntry *LineTableInfo::FindNearestLineEntry(FileID FID,
Chris Lattner3cd949c2009-02-04 01:55:42 +0000261 unsigned Offset) {
262 const std::vector<LineEntry> &Entries = LineEntries[FID];
263 assert(!Entries.empty() && "No #line entries for this FID after all!");
264
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000265 // It is very common for the query to be after the last #line, check this
266 // first.
267 if (Entries.back().FileOffset <= Offset)
268 return &Entries.back();
Chris Lattner3cd949c2009-02-04 01:55:42 +0000269
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000270 // Do a binary search to find the maximal element that is still before Offset.
271 std::vector<LineEntry>::const_iterator I =
272 std::upper_bound(Entries.begin(), Entries.end(), Offset);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700273 if (I == Entries.begin()) return nullptr;
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000274 return &*--I;
Chris Lattner3cd949c2009-02-04 01:55:42 +0000275}
Chris Lattnerac50e342009-02-03 22:13:05 +0000276
Douglas Gregorbd945002009-04-13 16:31:14 +0000277/// \brief Add a new line entry that has already been encoded into
278/// the internal representation of the line table.
Douglas Gregor47d9de62012-06-08 16:40:28 +0000279void LineTableInfo::AddEntry(FileID FID,
Douglas Gregorbd945002009-04-13 16:31:14 +0000280 const std::vector<LineEntry> &Entries) {
281 LineEntries[FID] = Entries;
282}
Chris Lattnerac50e342009-02-03 22:13:05 +0000283
Chris Lattner5b9a5042009-01-26 07:57:50 +0000284/// getLineTableFilenameID - Return the uniqued ID for the specified filename.
Mike Stump1eb44332009-09-09 15:08:12 +0000285///
Chris Lattner5f9e2722011-07-23 10:55:15 +0000286unsigned SourceManager::getLineTableFilenameID(StringRef Name) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700287 if (!LineTable)
Chris Lattner5b9a5042009-01-26 07:57:50 +0000288 LineTable = new LineTableInfo();
Jay Foad65aa6882011-06-21 15:13:30 +0000289 return LineTable->getLineTableFilenameID(Name);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000290}
291
292
Chris Lattner4c4ea172009-02-03 21:52:55 +0000293/// AddLineNote - Add a line note to the line table for the FileID and offset
294/// specified by Loc. If FilenameID is -1, it is considered to be
295/// unspecified.
296void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
297 int FilenameID) {
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000298 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000299
Douglas Gregore23ac652011-04-20 00:21:03 +0000300 bool Invalid = false;
301 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
302 if (!Entry.isFile() || Invalid)
303 return;
304
305 const SrcMgr::FileInfo &FileInfo = Entry.getFile();
Chris Lattnerac50e342009-02-03 22:13:05 +0000306
307 // Remember that this file has #line directives now if it doesn't already.
308 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump1eb44332009-09-09 15:08:12 +0000309
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700310 if (!LineTable)
Chris Lattnerac50e342009-02-03 22:13:05 +0000311 LineTable = new LineTableInfo();
Douglas Gregor47d9de62012-06-08 16:40:28 +0000312 LineTable->AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID);
Chris Lattner4c4ea172009-02-03 21:52:55 +0000313}
314
Chris Lattner9d79eba2009-02-04 05:21:58 +0000315/// AddLineNote - Add a GNU line marker to the line table.
316void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
317 int FilenameID, bool IsFileEntry,
318 bool IsFileExit, bool IsSystemHeader,
319 bool IsExternCHeader) {
320 // If there is no filename and no flags, this is treated just like a #line,
321 // which does not change the flags of the previous line marker.
322 if (FilenameID == -1) {
323 assert(!IsFileEntry && !IsFileExit && !IsSystemHeader && !IsExternCHeader &&
324 "Can't set flags without setting the filename!");
325 return AddLineNote(Loc, LineNo, FilenameID);
326 }
Mike Stump1eb44332009-09-09 15:08:12 +0000327
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000328 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Douglas Gregore23ac652011-04-20 00:21:03 +0000329
330 bool Invalid = false;
331 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
332 if (!Entry.isFile() || Invalid)
333 return;
334
335 const SrcMgr::FileInfo &FileInfo = Entry.getFile();
Mike Stump1eb44332009-09-09 15:08:12 +0000336
Chris Lattner9d79eba2009-02-04 05:21:58 +0000337 // Remember that this file has #line directives now if it doesn't already.
338 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump1eb44332009-09-09 15:08:12 +0000339
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700340 if (!LineTable)
Chris Lattner9d79eba2009-02-04 05:21:58 +0000341 LineTable = new LineTableInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000342
Chris Lattner9d79eba2009-02-04 05:21:58 +0000343 SrcMgr::CharacteristicKind FileKind;
344 if (IsExternCHeader)
345 FileKind = SrcMgr::C_ExternCSystem;
346 else if (IsSystemHeader)
347 FileKind = SrcMgr::C_System;
348 else
349 FileKind = SrcMgr::C_User;
Mike Stump1eb44332009-09-09 15:08:12 +0000350
Chris Lattner9d79eba2009-02-04 05:21:58 +0000351 unsigned EntryExit = 0;
352 if (IsFileEntry)
353 EntryExit = 1;
354 else if (IsFileExit)
355 EntryExit = 2;
Mike Stump1eb44332009-09-09 15:08:12 +0000356
Douglas Gregor47d9de62012-06-08 16:40:28 +0000357 LineTable->AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID,
Chris Lattner9d79eba2009-02-04 05:21:58 +0000358 EntryExit, FileKind);
359}
360
Douglas Gregorbd945002009-04-13 16:31:14 +0000361LineTableInfo &SourceManager::getLineTable() {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700362 if (!LineTable)
Douglas Gregorbd945002009-04-13 16:31:14 +0000363 LineTable = new LineTableInfo();
364 return *LineTable;
365}
Chris Lattner4c4ea172009-02-03 21:52:55 +0000366
Chris Lattner23b5dc62009-02-04 00:40:31 +0000367//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000368// Private 'Create' methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000369//===----------------------------------------------------------------------===//
Ted Kremenekc16c2082009-01-06 01:55:26 +0000370
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000371SourceManager::SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr,
372 bool UserFilesAreVolatile)
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +0000373 : Diag(Diag), FileMgr(FileMgr), OverridenFilesKeepOriginalName(true),
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000374 UserFilesAreVolatile(UserFilesAreVolatile),
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700375 ExternalSLocEntries(nullptr), LineTable(nullptr), NumLinearScans(0),
376 NumBinaryProbes(0), FakeBufferForRecovery(nullptr),
377 FakeContentCacheForRecovery(nullptr) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000378 clearIDTables();
379 Diag.setSourceManager(this);
380}
381
Chris Lattner5b9a5042009-01-26 07:57:50 +0000382SourceManager::~SourceManager() {
383 delete LineTable;
Mike Stump1eb44332009-09-09 15:08:12 +0000384
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000385 // Delete FileEntry objects corresponding to content caches. Since the actual
386 // content cache objects are bump pointer allocated, we just have to run the
387 // dtors, but we call the deallocate method for completeness.
388 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
Argyrios Kyrtzidis99ee0852011-12-15 23:37:55 +0000389 if (MemBufferInfos[i]) {
390 MemBufferInfos[i]->~ContentCache();
391 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
392 }
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000393 }
394 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
395 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
Argyrios Kyrtzidis99ee0852011-12-15 23:37:55 +0000396 if (I->second) {
397 I->second->~ContentCache();
398 ContentCacheAlloc.Deallocate(I->second);
399 }
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000400 }
Douglas Gregore23ac652011-04-20 00:21:03 +0000401
402 delete FakeBufferForRecovery;
Argyrios Kyrtzidisa4c29b62012-02-20 23:58:07 +0000403 delete FakeContentCacheForRecovery;
Argyrios Kyrtzidisfb3612e2011-09-26 08:01:50 +0000404
Stephen Hines651f13c2014-04-23 16:59:28 -0700405 llvm::DeleteContainerSeconds(MacroArgsCacheMap);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000406}
407
408void SourceManager::clearIDTables() {
409 MainFileID = FileID();
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000410 LocalSLocEntryTable.clear();
411 LoadedSLocEntryTable.clear();
412 SLocEntryLoaded.clear();
Chris Lattner5b9a5042009-01-26 07:57:50 +0000413 LastLineNoFileIDQuery = FileID();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700414 LastLineNoContentCache = nullptr;
Chris Lattner5b9a5042009-01-26 07:57:50 +0000415 LastFileIDLookup = FileID();
Mike Stump1eb44332009-09-09 15:08:12 +0000416
Chris Lattner5b9a5042009-01-26 07:57:50 +0000417 if (LineTable)
418 LineTable->clear();
Mike Stump1eb44332009-09-09 15:08:12 +0000419
Chandler Carruth3201f382011-07-26 05:17:23 +0000420 // Use up FileID #0 as an invalid expansion.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000421 NextLocalOffset = 0;
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +0000422 CurrentLoadedOffset = MaxLoadedOffset;
Chandler Carruthbf340e42011-07-26 03:03:05 +0000423 createExpansionLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000424}
425
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000426/// getOrCreateContentCache - Create or return a cached ContentCache for the
427/// specified file.
428const ContentCache *
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000429SourceManager::getOrCreateContentCache(const FileEntry *FileEnt,
430 bool isSystemFile) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000431 assert(FileEnt && "Didn't specify a file entry to use?");
Mike Stump1eb44332009-09-09 15:08:12 +0000432
Reid Spencer5f016e22007-07-11 17:01:13 +0000433 // Do we already have information about this file?
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000434 ContentCache *&Entry = FileInfos[FileEnt];
435 if (Entry) return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +0000436
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700437 // Nope, create a new Cache entry.
438 Entry = ContentCacheAlloc.Allocate<ContentCache>();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000439
Argyrios Kyrtzidisd54dff02012-05-03 21:50:39 +0000440 if (OverriddenFilesInfo) {
441 // If the file contents are overridden with contents from another file,
442 // pass that file to ContentCache.
443 llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
444 overI = OverriddenFilesInfo->OverriddenFiles.find(FileEnt);
445 if (overI == OverriddenFilesInfo->OverriddenFiles.end())
446 new (Entry) ContentCache(FileEnt);
447 else
448 new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt
449 : overI->second,
450 overI->second);
451 } else {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000452 new (Entry) ContentCache(FileEnt);
Argyrios Kyrtzidisd54dff02012-05-03 21:50:39 +0000453 }
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000454
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000455 Entry->IsSystemFile = isSystemFile;
456
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000457 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000458}
459
460
Ted Kremenekd1c0eee2007-10-31 17:53:38 +0000461/// createMemBufferContentCache - Create a new ContentCache for the specified
462/// memory buffer. This does no caching.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700463const ContentCache *
464SourceManager::createMemBufferContentCache(llvm::MemoryBuffer *Buffer) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700465 // Add a new ContentCache to the MemBufferInfos list and return it.
466 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>();
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000467 new (Entry) ContentCache();
468 MemBufferInfos.push_back(Entry);
469 Entry->setBuffer(Buffer);
470 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000471}
472
Argyrios Kyrtzidisa4c29b62012-02-20 23:58:07 +0000473const SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index,
474 bool *Invalid) const {
475 assert(!SLocEntryLoaded[Index]);
476 if (ExternalSLocEntries->ReadSLocEntry(-(static_cast<int>(Index) + 2))) {
477 if (Invalid)
478 *Invalid = true;
479 // If the file of the SLocEntry changed we could still have loaded it.
480 if (!SLocEntryLoaded[Index]) {
481 // Try to recover; create a SLocEntry so the rest of clang can handle it.
482 LoadedSLocEntryTable[Index] = SLocEntry::get(0,
483 FileInfo::get(SourceLocation(),
484 getFakeContentCacheForRecovery(),
485 SrcMgr::C_User));
486 }
487 }
488
489 return LoadedSLocEntryTable[Index];
490}
491
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000492std::pair<int, unsigned>
493SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries,
494 unsigned TotalSize) {
495 assert(ExternalSLocEntries && "Don't have an external sloc source");
496 LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries);
497 SLocEntryLoaded.resize(LoadedSLocEntryTable.size());
498 CurrentLoadedOffset -= TotalSize;
499 assert(CurrentLoadedOffset >= NextLocalOffset && "Out of source locations");
500 int ID = LoadedSLocEntryTable.size();
501 return std::make_pair(-ID - 1, CurrentLoadedOffset);
Douglas Gregor2bf1eb02009-04-27 21:28:04 +0000502}
503
Douglas Gregore23ac652011-04-20 00:21:03 +0000504/// \brief As part of recovering from missing or changed content, produce a
505/// fake, non-empty buffer.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700506llvm::MemoryBuffer *SourceManager::getFakeBufferForRecovery() const {
Douglas Gregore23ac652011-04-20 00:21:03 +0000507 if (!FakeBufferForRecovery)
508 FakeBufferForRecovery
509 = llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");
510
511 return FakeBufferForRecovery;
512}
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000513
Argyrios Kyrtzidisa4c29b62012-02-20 23:58:07 +0000514/// \brief As part of recovering from missing or changed content, produce a
515/// fake content cache.
516const SrcMgr::ContentCache *
517SourceManager::getFakeContentCacheForRecovery() const {
518 if (!FakeContentCacheForRecovery) {
519 FakeContentCacheForRecovery = new ContentCache();
520 FakeContentCacheForRecovery->replaceBuffer(getFakeBufferForRecovery(),
521 /*DoNotFree=*/true);
522 }
523 return FakeContentCacheForRecovery;
524}
525
Argyrios Kyrtzidisc50c6ff2013-05-16 21:37:39 +0000526/// \brief Returns the previous in-order FileID or an invalid FileID if there
527/// is no previous one.
528FileID SourceManager::getPreviousFileID(FileID FID) const {
529 if (FID.isInvalid())
530 return FileID();
531
532 int ID = FID.ID;
533 if (ID == -1)
534 return FileID();
535
536 if (ID > 0) {
537 if (ID-1 == 0)
538 return FileID();
539 } else if (unsigned(-(ID-1) - 2) >= LoadedSLocEntryTable.size()) {
540 return FileID();
541 }
542
543 return FileID::get(ID-1);
544}
545
546/// \brief Returns the next in-order FileID or an invalid FileID if there is
547/// no next one.
548FileID SourceManager::getNextFileID(FileID FID) const {
549 if (FID.isInvalid())
550 return FileID();
551
552 int ID = FID.ID;
553 if (ID > 0) {
554 if (unsigned(ID+1) >= local_sloc_entry_size())
555 return FileID();
556 } else if (ID+1 >= -1) {
557 return FileID();
558 }
559
560 return FileID::get(ID+1);
561}
562
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000563//===----------------------------------------------------------------------===//
Chandler Carruth3201f382011-07-26 05:17:23 +0000564// Methods to create new FileID's and macro expansions.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000565//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000566
Dan Gohman3f86b782010-08-26 21:27:06 +0000567/// createFileID - Create a new FileID for the specified ContentCache and
Ted Kremenek0d892d82007-10-30 22:57:35 +0000568/// include position. This works regardless of whether the ContentCache
569/// corresponds to a file or some other input source.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000570FileID SourceManager::createFileID(const ContentCache *File,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000571 SourceLocation IncludePos,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000572 SrcMgr::CharacteristicKind FileCharacter,
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000573 int LoadedID, unsigned LoadedOffset) {
574 if (LoadedID < 0) {
575 assert(LoadedID != -1 && "Loading sentinel FileID");
576 unsigned Index = unsigned(-LoadedID) - 2;
577 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
578 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
579 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset,
580 FileInfo::get(IncludePos, File, FileCharacter));
581 SLocEntryLoaded[Index] = true;
582 return FileID::get(LoadedID);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000583 }
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000584 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset,
585 FileInfo::get(IncludePos, File,
586 FileCharacter)));
Ted Kremenekc16c2082009-01-06 01:55:26 +0000587 unsigned FileSize = File->getSize();
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000588 assert(NextLocalOffset + FileSize + 1 > NextLocalOffset &&
589 NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset &&
590 "Ran out of source locations!");
591 // We do a +1 here because we want a SourceLocation that means "the end of the
592 // file", e.g. for the "no newline at the end of the file" diagnostic.
593 NextLocalOffset += FileSize + 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000594
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000595 // Set LastFileIDLookup to the newly created file. The next getFileID call is
596 // almost guaranteed to be from that file.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000597 FileID FID = FileID::get(LocalSLocEntryTable.size()-1);
Argyrios Kyrtzidisea703f12009-06-23 00:42:06 +0000598 return LastFileIDLookup = FID;
Reid Spencer5f016e22007-07-11 17:01:13 +0000599}
600
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000601SourceLocation
Chandler Carruthbf340e42011-07-26 03:03:05 +0000602SourceManager::createMacroArgExpansionLoc(SourceLocation SpellingLoc,
603 SourceLocation ExpansionLoc,
604 unsigned TokLength) {
Chandler Carruth78df8362011-07-26 04:41:47 +0000605 ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc,
606 ExpansionLoc);
607 return createExpansionLocImpl(Info, TokLength);
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000608}
609
610SourceLocation
Chandler Carruthbf340e42011-07-26 03:03:05 +0000611SourceManager::createExpansionLoc(SourceLocation SpellingLoc,
612 SourceLocation ExpansionLocStart,
613 SourceLocation ExpansionLocEnd,
614 unsigned TokLength,
615 int LoadedID,
616 unsigned LoadedOffset) {
Chandler Carruth78df8362011-07-26 04:41:47 +0000617 ExpansionInfo Info = ExpansionInfo::create(SpellingLoc, ExpansionLocStart,
618 ExpansionLocEnd);
619 return createExpansionLocImpl(Info, TokLength, LoadedID, LoadedOffset);
Chandler Carruthbf340e42011-07-26 03:03:05 +0000620}
621
622SourceLocation
Chandler Carruth78df8362011-07-26 04:41:47 +0000623SourceManager::createExpansionLocImpl(const ExpansionInfo &Info,
Chandler Carruthbf340e42011-07-26 03:03:05 +0000624 unsigned TokLength,
625 int LoadedID,
626 unsigned LoadedOffset) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000627 if (LoadedID < 0) {
628 assert(LoadedID != -1 && "Loading sentinel FileID");
629 unsigned Index = unsigned(-LoadedID) - 2;
630 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
631 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
Chandler Carruth78df8362011-07-26 04:41:47 +0000632 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info);
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000633 SLocEntryLoaded[Index] = true;
634 return SourceLocation::getMacroLoc(LoadedOffset);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000635 }
Chandler Carruth78df8362011-07-26 04:41:47 +0000636 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000637 assert(NextLocalOffset + TokLength + 1 > NextLocalOffset &&
638 NextLocalOffset + TokLength + 1 <= CurrentLoadedOffset &&
639 "Ran out of source locations!");
640 // See createFileID for that +1.
641 NextLocalOffset += TokLength + 1;
642 return SourceLocation::getMacroLoc(NextLocalOffset - (TokLength + 1));
Reid Spencer5f016e22007-07-11 17:01:13 +0000643}
644
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700645llvm::MemoryBuffer *SourceManager::getMemoryBufferForFile(const FileEntry *File,
646 bool *Invalid) {
Douglas Gregor29684422009-12-02 06:49:09 +0000647 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
Douglas Gregoraea67db2010-03-15 22:54:52 +0000648 assert(IR && "getOrCreateContentCache() cannot return NULL");
Chris Lattnere127a0d2010-04-20 20:35:58 +0000649 return IR->getBuffer(Diag, *this, SourceLocation(), Invalid);
Douglas Gregor29684422009-12-02 06:49:09 +0000650}
651
Dan Gohman0d06e992010-10-26 20:47:28 +0000652void SourceManager::overrideFileContents(const FileEntry *SourceFile,
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700653 llvm::MemoryBuffer *Buffer,
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000654 bool DoNotFree) {
Douglas Gregor29684422009-12-02 06:49:09 +0000655 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
Dan Gohman0d06e992010-10-26 20:47:28 +0000656 assert(IR && "getOrCreateContentCache() cannot return NULL");
Douglas Gregor29684422009-12-02 06:49:09 +0000657
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000658 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree);
Douglas Gregora081da52011-11-16 20:05:18 +0000659 const_cast<SrcMgr::ContentCache *>(IR)->BufferOverridden = true;
Argyrios Kyrtzidisd54dff02012-05-03 21:50:39 +0000660
661 getOverriddenFilesInfo().OverriddenFilesWithBuffer.insert(SourceFile);
Douglas Gregor29684422009-12-02 06:49:09 +0000662}
663
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000664void SourceManager::overrideFileContents(const FileEntry *SourceFile,
665 const FileEntry *NewFile) {
666 assert(SourceFile->getSize() == NewFile->getSize() &&
667 "Different sizes, use the FileManager to create a virtual file with "
668 "the correct size");
669 assert(FileInfos.count(SourceFile) == 0 &&
670 "This function should be called at the initialization stage, before "
671 "any parsing occurs.");
Argyrios Kyrtzidisd54dff02012-05-03 21:50:39 +0000672 getOverriddenFilesInfo().OverriddenFiles[SourceFile] = NewFile;
673}
674
675void SourceManager::disableFileContentsOverride(const FileEntry *File) {
676 if (!isFileOverridden(File))
677 return;
678
679 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700680 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(nullptr);
Argyrios Kyrtzidisd54dff02012-05-03 21:50:39 +0000681 const_cast<SrcMgr::ContentCache *>(IR)->ContentsEntry = IR->OrigEntry;
682
683 assert(OverriddenFilesInfo);
684 OverriddenFilesInfo->OverriddenFiles.erase(File);
685 OverriddenFilesInfo->OverriddenFilesWithBuffer.erase(File);
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000686}
687
Chris Lattner5f9e2722011-07-23 10:55:15 +0000688StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
Douglas Gregoraae58b02010-03-16 20:01:30 +0000689 bool MyInvalid = false;
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000690 const SLocEntry &SLoc = getSLocEntry(FID, &MyInvalid);
Douglas Gregore23ac652011-04-20 00:21:03 +0000691 if (!SLoc.isFile() || MyInvalid) {
Douglas Gregor3de84242011-01-31 22:42:36 +0000692 if (Invalid)
693 *Invalid = true;
694 return "<<<<<INVALID SOURCE LOCATION>>>>>";
695 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700696
697 llvm::MemoryBuffer *Buf = SLoc.getFile().getContentCache()->getBuffer(
698 Diag, *this, SourceLocation(), &MyInvalid);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000699 if (Invalid)
Douglas Gregoraae58b02010-03-16 20:01:30 +0000700 *Invalid = MyInvalid;
701
702 if (MyInvalid)
Douglas Gregor3de84242011-01-31 22:42:36 +0000703 return "<<<<<INVALID SOURCE LOCATION>>>>>";
Douglas Gregoraae58b02010-03-16 20:01:30 +0000704
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000705 return Buf->getBuffer();
Douglas Gregoraea67db2010-03-15 22:54:52 +0000706}
Chris Lattner2b2453a2009-01-17 06:22:33 +0000707
Chris Lattner23b5dc62009-02-04 00:40:31 +0000708//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000709// SourceLocation manipulation methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000710//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000711
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000712/// \brief Return the FileID for a SourceLocation.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000713///
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000714/// This is the cache-miss path of getFileID. Not as hot as that function, but
715/// still very important. It is responsible for finding the entry in the
716/// SLocEntry tables that contains the specified location.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000717FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
Douglas Gregore23ac652011-04-20 00:21:03 +0000718 if (!SLocOffset)
719 return FileID::get(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000720
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000721 // Now it is time to search for the correct file. See where the SLocOffset
722 // sits in the global view and consult local or loaded buffers for it.
723 if (SLocOffset < NextLocalOffset)
724 return getFileIDLocal(SLocOffset);
725 return getFileIDLoaded(SLocOffset);
726}
727
728/// \brief Return the FileID for a SourceLocation with a low offset.
729///
730/// This function knows that the SourceLocation is in a local buffer, not a
731/// loaded one.
732FileID SourceManager::getFileIDLocal(unsigned SLocOffset) const {
733 assert(SLocOffset < NextLocalOffset && "Bad function choice");
734
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000735 // After the first and second level caches, I see two common sorts of
Chandler Carruth3201f382011-07-26 05:17:23 +0000736 // behavior: 1) a lot of searched FileID's are "near" the cached file
737 // location or are "near" the cached expansion location. 2) others are just
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000738 // completely random and may be a very long way away.
739 //
740 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
741 // then we fall back to a less cache efficient, but more scalable, binary
742 // search to find the location.
Mike Stump1eb44332009-09-09 15:08:12 +0000743
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000744 // See if this is near the file point - worst case we start scanning from the
745 // most newly created FileID.
Benjamin Kramerf512ace2013-02-22 18:29:39 +0000746 const SrcMgr::SLocEntry *I;
Mike Stump1eb44332009-09-09 15:08:12 +0000747
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000748 if (LastFileIDLookup.ID < 0 ||
749 LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000750 // Neither loc prunes our search.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000751 I = LocalSLocEntryTable.end();
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000752 } else {
753 // Perhaps it is near the file point.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000754 I = LocalSLocEntryTable.begin()+LastFileIDLookup.ID;
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000755 }
756
757 // Find the FileID that contains this. "I" is an iterator that points to a
758 // FileID whose offset is known to be larger than SLocOffset.
759 unsigned NumProbes = 0;
760 while (1) {
761 --I;
762 if (I->getOffset() <= SLocOffset) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000763 FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin()));
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000764
Chandler Carruth3201f382011-07-26 05:17:23 +0000765 // If this isn't an expansion, remember it. We have good locality across
766 // FileID lookups.
Chandler Carruth17287622011-07-26 04:56:51 +0000767 if (!I->isExpansion())
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000768 LastFileIDLookup = Res;
769 NumLinearScans += NumProbes+1;
770 return Res;
771 }
772 if (++NumProbes == 8)
773 break;
774 }
Mike Stump1eb44332009-09-09 15:08:12 +0000775
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000776 // Convert "I" back into an index. We know that it is an entry whose index is
777 // larger than the offset we are looking for.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000778 unsigned GreaterIndex = I - LocalSLocEntryTable.begin();
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000779 // LessIndex - This is the lower bound of the range that we're searching.
780 // We know that the offset corresponding to the FileID is is less than
781 // SLocOffset.
782 unsigned LessIndex = 0;
783 NumProbes = 0;
784 while (1) {
Douglas Gregore23ac652011-04-20 00:21:03 +0000785 bool Invalid = false;
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000786 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000787 unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset();
Douglas Gregore23ac652011-04-20 00:21:03 +0000788 if (Invalid)
789 return FileID::get(0);
790
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000791 ++NumProbes;
Mike Stump1eb44332009-09-09 15:08:12 +0000792
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000793 // If the offset of the midpoint is too large, chop the high side of the
794 // range to the midpoint.
795 if (MidOffset > SLocOffset) {
796 GreaterIndex = MiddleIndex;
797 continue;
798 }
Mike Stump1eb44332009-09-09 15:08:12 +0000799
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000800 // If the middle index contains the value, succeed and return.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000801 // FIXME: This could be made faster by using a function that's aware of
802 // being in the local area.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000803 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000804 FileID Res = FileID::get(MiddleIndex);
805
Chandler Carruth17287622011-07-26 04:56:51 +0000806 // If this isn't a macro expansion, remember it. We have good locality
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000807 // across FileID lookups.
Chandler Carruth17287622011-07-26 04:56:51 +0000808 if (!LocalSLocEntryTable[MiddleIndex].isExpansion())
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000809 LastFileIDLookup = Res;
810 NumBinaryProbes += NumProbes;
811 return Res;
812 }
Mike Stump1eb44332009-09-09 15:08:12 +0000813
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000814 // Otherwise, move the low-side up to the middle index.
815 LessIndex = MiddleIndex;
816 }
817}
818
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000819/// \brief Return the FileID for a SourceLocation with a high offset.
820///
821/// This function knows that the SourceLocation is in a loaded buffer, not a
822/// local one.
823FileID SourceManager::getFileIDLoaded(unsigned SLocOffset) const {
Argyrios Kyrtzidisc3b45752011-10-03 23:43:01 +0000824 // Sanity checking, otherwise a bug may lead to hanging in release build.
Argyrios Kyrtzidis82ccbe72011-10-25 00:29:44 +0000825 if (SLocOffset < CurrentLoadedOffset) {
826 assert(0 && "Invalid SLocOffset or bad function choice");
Argyrios Kyrtzidisc3b45752011-10-03 23:43:01 +0000827 return FileID();
Argyrios Kyrtzidis82ccbe72011-10-25 00:29:44 +0000828 }
Argyrios Kyrtzidisc3b45752011-10-03 23:43:01 +0000829
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000830 // Essentially the same as the local case, but the loaded array is sorted
831 // in the other direction.
832
833 // First do a linear scan from the last lookup position, if possible.
834 unsigned I;
835 int LastID = LastFileIDLookup.ID;
836 if (LastID >= 0 || getLoadedSLocEntryByID(LastID).getOffset() < SLocOffset)
837 I = 0;
838 else
839 I = (-LastID - 2) + 1;
840
841 unsigned NumProbes;
842 for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++I) {
843 // Make sure the entry is loaded!
844 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(I);
845 if (E.getOffset() <= SLocOffset) {
846 FileID Res = FileID::get(-int(I) - 2);
847
Chandler Carruth17287622011-07-26 04:56:51 +0000848 if (!E.isExpansion())
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000849 LastFileIDLookup = Res;
850 NumLinearScans += NumProbes + 1;
851 return Res;
852 }
853 }
854
855 // Linear scan failed. Do the binary search. Note the reverse sorting of the
856 // table: GreaterIndex is the one where the offset is greater, which is
857 // actually a lower index!
858 unsigned GreaterIndex = I;
859 unsigned LessIndex = LoadedSLocEntryTable.size();
860 NumProbes = 0;
861 while (1) {
862 ++NumProbes;
863 unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex;
864 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(MiddleIndex);
Argyrios Kyrtzidis7db4bb92013-03-01 03:26:00 +0000865 if (E.getOffset() == 0)
866 return FileID(); // invalid entry.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000867
868 ++NumProbes;
869
870 if (E.getOffset() > SLocOffset) {
Argyrios Kyrtzidis7db4bb92013-03-01 03:26:00 +0000871 // Sanity checking, otherwise a bug may lead to hanging in release build.
872 if (GreaterIndex == MiddleIndex) {
873 assert(0 && "binary search missed the entry");
874 return FileID();
875 }
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000876 GreaterIndex = MiddleIndex;
877 continue;
878 }
879
880 if (isOffsetInFileID(FileID::get(-int(MiddleIndex) - 2), SLocOffset)) {
881 FileID Res = FileID::get(-int(MiddleIndex) - 2);
Chandler Carruth17287622011-07-26 04:56:51 +0000882 if (!E.isExpansion())
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000883 LastFileIDLookup = Res;
884 NumBinaryProbes += NumProbes;
885 return Res;
886 }
887
Argyrios Kyrtzidis838a9202013-03-01 03:43:33 +0000888 // Sanity checking, otherwise a bug may lead to hanging in release build.
889 if (LessIndex == MiddleIndex) {
890 assert(0 && "binary search missed the entry");
891 return FileID();
892 }
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000893 LessIndex = MiddleIndex;
894 }
895}
896
Chris Lattneraddb7972009-01-26 20:04:19 +0000897SourceLocation SourceManager::
Chandler Carruthf84ef952011-07-25 20:52:26 +0000898getExpansionLocSlowCase(SourceLocation Loc) const {
Chris Lattneraddb7972009-01-26 20:04:19 +0000899 do {
Chris Lattnera5c6c582010-02-12 19:31:35 +0000900 // Note: If Loc indicates an offset into a token that came from a macro
901 // expansion (e.g. the 5th character of the token) we do not want to add
Chandler Carruth17287622011-07-26 04:56:51 +0000902 // this offset when going to the expansion location. The expansion
Chris Lattnera5c6c582010-02-12 19:31:35 +0000903 // location is the macro invocation, which the offset has nothing to do
904 // with. This is unlike when we get the spelling loc, because the offset
905 // directly correspond to the token whose spelling we're inspecting.
Chandler Carruth17287622011-07-26 04:56:51 +0000906 Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart();
Chris Lattneraddb7972009-01-26 20:04:19 +0000907 } while (!Loc.isFileID());
908
909 return Loc;
910}
911
912SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
913 do {
914 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
Chandler Carruth17287622011-07-26 04:56:51 +0000915 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000916 Loc = Loc.getLocWithOffset(LocInfo.second);
Chris Lattneraddb7972009-01-26 20:04:19 +0000917 } while (!Loc.isFileID());
918 return Loc;
919}
920
Argyrios Kyrtzidis796dbfb2011-10-12 07:07:40 +0000921SourceLocation SourceManager::getFileLocSlowCase(SourceLocation Loc) const {
922 do {
923 if (isMacroArgExpansion(Loc))
924 Loc = getImmediateSpellingLoc(Loc);
925 else
926 Loc = getImmediateExpansionRange(Loc).first;
927 } while (!Loc.isFileID());
928 return Loc;
929}
930
Chris Lattneraddb7972009-01-26 20:04:19 +0000931
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000932std::pair<FileID, unsigned>
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000933SourceManager::getDecomposedExpansionLocSlowCase(
Argyrios Kyrtzidis8b86ef02011-07-07 03:40:27 +0000934 const SrcMgr::SLocEntry *E) const {
Chandler Carruth3201f382011-07-26 05:17:23 +0000935 // If this is an expansion record, walk through all the expansion points.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000936 FileID FID;
937 SourceLocation Loc;
Argyrios Kyrtzidis8b86ef02011-07-07 03:40:27 +0000938 unsigned Offset;
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000939 do {
Chandler Carruth17287622011-07-26 04:56:51 +0000940 Loc = E->getExpansion().getExpansionLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000941
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000942 FID = getFileID(Loc);
943 E = &getSLocEntry(FID);
Argyrios Kyrtzidis8b86ef02011-07-07 03:40:27 +0000944 Offset = Loc.getOffset()-E->getOffset();
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000945 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000946
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000947 return std::make_pair(FID, Offset);
948}
949
950std::pair<FileID, unsigned>
951SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
952 unsigned Offset) const {
Chandler Carruth3201f382011-07-26 05:17:23 +0000953 // If this is an expansion record, walk through all the expansion points.
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000954 FileID FID;
955 SourceLocation Loc;
956 do {
Chandler Carruth17287622011-07-26 04:56:51 +0000957 Loc = E->getExpansion().getSpellingLoc();
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000958 Loc = Loc.getLocWithOffset(Offset);
Mike Stump1eb44332009-09-09 15:08:12 +0000959
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000960 FID = getFileID(Loc);
961 E = &getSLocEntry(FID);
Argyrios Kyrtzidisb6c465e2011-08-23 21:02:41 +0000962 Offset = Loc.getOffset()-E->getOffset();
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000963 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000964
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000965 return std::make_pair(FID, Offset);
966}
967
Chris Lattner387616e2009-02-17 08:04:48 +0000968/// getImmediateSpellingLoc - Given a SourceLocation object, return the
969/// spelling location referenced by the ID. This is the first level down
970/// towards the place where the characters that make up the lexed token can be
971/// found. This should not generally be used by clients.
972SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
973 if (Loc.isFileID()) return Loc;
974 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
Chandler Carruth17287622011-07-26 04:56:51 +0000975 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000976 return Loc.getLocWithOffset(LocInfo.second);
Chris Lattner387616e2009-02-17 08:04:48 +0000977}
978
979
Chandler Carruth3201f382011-07-26 05:17:23 +0000980/// getImmediateExpansionRange - Loc is required to be an expansion location.
981/// Return the start/end of the expansion information.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000982std::pair<SourceLocation,SourceLocation>
Chandler Carruth999f7392011-07-25 20:52:21 +0000983SourceManager::getImmediateExpansionRange(SourceLocation Loc) const {
Chandler Carruth3201f382011-07-26 05:17:23 +0000984 assert(Loc.isMacroID() && "Not a macro expansion loc!");
Chandler Carruth17287622011-07-26 04:56:51 +0000985 const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion();
Chandler Carruth78df8362011-07-26 04:41:47 +0000986 return Expansion.getExpansionLocRange();
Chris Lattnere7fb4842009-02-15 20:52:18 +0000987}
988
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000989/// getExpansionRange - Given a SourceLocation object, return the range of
990/// tokens covered by the expansion in the ultimate file.
Chris Lattner66781332009-02-15 21:26:50 +0000991std::pair<SourceLocation,SourceLocation>
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000992SourceManager::getExpansionRange(SourceLocation Loc) const {
Chris Lattner66781332009-02-15 21:26:50 +0000993 if (Loc.isFileID()) return std::make_pair(Loc, Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000994
Chris Lattner66781332009-02-15 21:26:50 +0000995 std::pair<SourceLocation,SourceLocation> Res =
Chandler Carruth999f7392011-07-25 20:52:21 +0000996 getImmediateExpansionRange(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000997
Chandler Carruth3201f382011-07-26 05:17:23 +0000998 // Fully resolve the start and end locations to their ultimate expansion
Chris Lattner66781332009-02-15 21:26:50 +0000999 // points.
1000 while (!Res.first.isFileID())
Chandler Carruth999f7392011-07-25 20:52:21 +00001001 Res.first = getImmediateExpansionRange(Res.first).first;
Chris Lattner66781332009-02-15 21:26:50 +00001002 while (!Res.second.isFileID())
Chandler Carruth999f7392011-07-25 20:52:21 +00001003 Res.second = getImmediateExpansionRange(Res.second).second;
Chris Lattner66781332009-02-15 21:26:50 +00001004 return Res;
1005}
1006
Chandler Carruth96d35892011-07-26 03:03:00 +00001007bool SourceManager::isMacroArgExpansion(SourceLocation Loc) const {
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +00001008 if (!Loc.isMacroID()) return false;
1009
1010 FileID FID = getFileID(Loc);
Matt Beaumont-Gayc3cd6f72013-01-12 00:54:16 +00001011 const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
Chandler Carruth78df8362011-07-26 04:41:47 +00001012 return Expansion.isMacroArgExpansion();
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +00001013}
Chris Lattnere7fb4842009-02-15 20:52:18 +00001014
Matt Beaumont-Gayc3cd6f72013-01-12 00:54:16 +00001015bool SourceManager::isMacroBodyExpansion(SourceLocation Loc) const {
1016 if (!Loc.isMacroID()) return false;
1017
1018 FileID FID = getFileID(Loc);
1019 const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
1020 return Expansion.isMacroBodyExpansion();
1021}
1022
Argyrios Kyrtzidisc50c6ff2013-05-16 21:37:39 +00001023bool SourceManager::isAtStartOfImmediateMacroExpansion(SourceLocation Loc,
1024 SourceLocation *MacroBegin) const {
1025 assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1026
1027 std::pair<FileID, unsigned> DecompLoc = getDecomposedLoc(Loc);
1028 if (DecompLoc.second > 0)
1029 return false; // Does not point at the start of expansion range.
1030
1031 bool Invalid = false;
1032 const SrcMgr::ExpansionInfo &ExpInfo =
1033 getSLocEntry(DecompLoc.first, &Invalid).getExpansion();
1034 if (Invalid)
1035 return false;
1036 SourceLocation ExpLoc = ExpInfo.getExpansionLocStart();
1037
1038 if (ExpInfo.isMacroArgExpansion()) {
1039 // For macro argument expansions, check if the previous FileID is part of
1040 // the same argument expansion, in which case this Loc is not at the
1041 // beginning of the expansion.
1042 FileID PrevFID = getPreviousFileID(DecompLoc.first);
1043 if (!PrevFID.isInvalid()) {
1044 const SrcMgr::SLocEntry &PrevEntry = getSLocEntry(PrevFID, &Invalid);
1045 if (Invalid)
1046 return false;
1047 if (PrevEntry.isExpansion() &&
1048 PrevEntry.getExpansion().getExpansionLocStart() == ExpLoc)
1049 return false;
1050 }
1051 }
1052
1053 if (MacroBegin)
1054 *MacroBegin = ExpLoc;
1055 return true;
1056}
1057
1058bool SourceManager::isAtEndOfImmediateMacroExpansion(SourceLocation Loc,
1059 SourceLocation *MacroEnd) const {
1060 assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1061
1062 FileID FID = getFileID(Loc);
1063 SourceLocation NextLoc = Loc.getLocWithOffset(1);
1064 if (isInFileID(NextLoc, FID))
1065 return false; // Does not point at the end of expansion range.
1066
1067 bool Invalid = false;
1068 const SrcMgr::ExpansionInfo &ExpInfo =
1069 getSLocEntry(FID, &Invalid).getExpansion();
1070 if (Invalid)
1071 return false;
1072
1073 if (ExpInfo.isMacroArgExpansion()) {
1074 // For macro argument expansions, check if the next FileID is part of the
1075 // same argument expansion, in which case this Loc is not at the end of the
1076 // expansion.
1077 FileID NextFID = getNextFileID(FID);
1078 if (!NextFID.isInvalid()) {
1079 const SrcMgr::SLocEntry &NextEntry = getSLocEntry(NextFID, &Invalid);
1080 if (Invalid)
1081 return false;
1082 if (NextEntry.isExpansion() &&
1083 NextEntry.getExpansion().getExpansionLocStart() ==
1084 ExpInfo.getExpansionLocStart())
1085 return false;
1086 }
1087 }
1088
1089 if (MacroEnd)
1090 *MacroEnd = ExpInfo.getExpansionLocEnd();
1091 return true;
1092}
1093
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001094
1095//===----------------------------------------------------------------------===//
1096// Queries about the code at a SourceLocation.
1097//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00001098
1099/// getCharacterData - Return a pointer to the start of the specified location
1100/// in the appropriate MemoryBuffer.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001101const char *SourceManager::getCharacterData(SourceLocation SL,
1102 bool *Invalid) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001103 // Note that this is a hot function in the getSpelling() path, which is
1104 // heavily used by -E mode.
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001105 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
Mike Stump1eb44332009-09-09 15:08:12 +00001106
Ted Kremenekc16c2082009-01-06 01:55:26 +00001107 // Note that calling 'getBuffer()' may lazily page in a source file.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001108 bool CharDataInvalid = false;
Douglas Gregore23ac652011-04-20 00:21:03 +00001109 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
1110 if (CharDataInvalid || !Entry.isFile()) {
1111 if (Invalid)
1112 *Invalid = true;
1113
1114 return "<<<<INVALID BUFFER>>>>";
1115 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001116 llvm::MemoryBuffer *Buffer = Entry.getFile().getContentCache()->getBuffer(
1117 Diag, *this, SourceLocation(), &CharDataInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001118 if (Invalid)
1119 *Invalid = CharDataInvalid;
1120 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
Reid Spencer5f016e22007-07-11 17:01:13 +00001121}
1122
Reid Spencer5f016e22007-07-11 17:01:13 +00001123
Chris Lattner9dc1f532007-07-20 16:37:10 +00001124/// getColumnNumber - Return the column # for the specified file position.
Chris Lattner7da5aea2009-02-04 00:55:58 +00001125/// this is significantly cheaper to compute than the line number.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001126unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
1127 bool *Invalid) const {
1128 bool MyInvalid = false;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001129 llvm::MemoryBuffer *MemBuf = getBuffer(FID, &MyInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001130 if (Invalid)
1131 *Invalid = MyInvalid;
1132
1133 if (MyInvalid)
1134 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00001135
Jordan Rose2e413f92012-06-19 03:09:38 +00001136 // It is okay to request a position just past the end of the buffer.
1137 if (FilePos > MemBuf->getBufferSize()) {
Argyrios Kyrtzidisd5752542011-12-10 00:30:38 +00001138 if (Invalid)
Jordan Rose2e413f92012-06-19 03:09:38 +00001139 *Invalid = true;
Argyrios Kyrtzidisd5752542011-12-10 00:30:38 +00001140 return 1;
1141 }
1142
Craig Topperd9cad402012-10-19 04:40:38 +00001143 // See if we just calculated the line number for this FilePos and can use
1144 // that to lookup the start of the line instead of searching for it.
1145 if (LastLineNoFileIDQuery == FID &&
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001146 LastLineNoContentCache->SourceLineCache != nullptr &&
Craig Topperd53c2d32012-12-16 05:58:32 +00001147 LastLineNoResult < LastLineNoContentCache->NumLines) {
Craig Topperd9cad402012-10-19 04:40:38 +00001148 unsigned *SourceLineCache = LastLineNoContentCache->SourceLineCache;
1149 unsigned LineStart = SourceLineCache[LastLineNoResult - 1];
1150 unsigned LineEnd = SourceLineCache[LastLineNoResult];
1151 if (FilePos >= LineStart && FilePos < LineEnd)
1152 return FilePos - LineStart + 1;
1153 }
1154
Dylan Noblesmith098eaff2011-12-19 08:51:05 +00001155 const char *Buf = MemBuf->getBufferStart();
Reid Spencer5f016e22007-07-11 17:01:13 +00001156 unsigned LineStart = FilePos;
1157 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
1158 --LineStart;
1159 return FilePos-LineStart+1;
1160}
1161
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001162// isInvalid - Return the result of calling loc.isInvalid(), and
1163// if Invalid is not null, set its value to same.
1164static bool isInvalid(SourceLocation Loc, bool *Invalid) {
1165 bool MyInvalid = Loc.isInvalid();
1166 if (Invalid)
1167 *Invalid = MyInvalid;
1168 return MyInvalid;
1169}
1170
Douglas Gregor50f6af72010-03-16 05:20:39 +00001171unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
1172 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001173 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +00001174 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001175 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +00001176}
1177
Chandler Carrutha77c0312011-07-25 20:57:57 +00001178unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc,
1179 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001180 if (isInvalid(Loc, Invalid)) return 0;
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +00001181 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001182 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +00001183}
1184
Chandler Carruth5ef04ee2011-02-23 00:47:48 +00001185unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
1186 bool *Invalid) const {
1187 if (isInvalid(Loc, Invalid)) return 0;
1188 return getPresumedLoc(Loc).getColumn();
1189}
1190
Benjamin Kramerd2953ce2012-04-06 20:49:55 +00001191#ifdef __SSE2__
1192#include <emmintrin.h>
1193#endif
1194
Chandler Carruth14bd9652010-10-23 08:44:57 +00001195static LLVM_ATTRIBUTE_NOINLINE void
David Blaikied6471f72011-09-25 23:23:43 +00001196ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
Chris Lattnere127a0d2010-04-20 20:35:58 +00001197 llvm::BumpPtrAllocator &Alloc,
1198 const SourceManager &SM, bool &Invalid);
David Blaikied6471f72011-09-25 23:23:43 +00001199static void ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
Chris Lattnere127a0d2010-04-20 20:35:58 +00001200 llvm::BumpPtrAllocator &Alloc,
1201 const SourceManager &SM, bool &Invalid) {
Ted Kremenekc16c2082009-01-06 01:55:26 +00001202 // Note that calling 'getBuffer()' may lazily page in the file.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001203 MemoryBuffer *Buffer = FI->getBuffer(Diag, SM, SourceLocation(), &Invalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001204 if (Invalid)
1205 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001206
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001207 // Find the file offsets of all of the *physical* source lines. This does
1208 // not look at trigraphs, escaped newlines, or anything else tricky.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001209 SmallVector<unsigned, 256> LineOffsets;
Mike Stump1eb44332009-09-09 15:08:12 +00001210
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001211 // Line #1 starts at char 0.
1212 LineOffsets.push_back(0);
Mike Stump1eb44332009-09-09 15:08:12 +00001213
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001214 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
1215 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
1216 unsigned Offs = 0;
1217 while (1) {
1218 // Skip over the contents of the line.
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001219 const unsigned char *NextBuf = (const unsigned char *)Buf;
Benjamin Kramerd2953ce2012-04-06 20:49:55 +00001220
1221#ifdef __SSE2__
1222 // Try to skip to the next newline using SSE instructions. This is very
1223 // performance sensitive for programs with lots of diagnostics and in -E
1224 // mode.
1225 __m128i CRs = _mm_set1_epi8('\r');
1226 __m128i LFs = _mm_set1_epi8('\n');
1227
1228 // First fix up the alignment to 16 bytes.
1229 while (((uintptr_t)NextBuf & 0xF) != 0) {
1230 if (*NextBuf == '\n' || *NextBuf == '\r' || *NextBuf == '\0')
1231 goto FoundSpecialChar;
1232 ++NextBuf;
1233 }
1234
1235 // Scan 16 byte chunks for '\r' and '\n'. Ignore '\0'.
1236 while (NextBuf+16 <= End) {
Roman Divacky31ba6132012-09-06 15:59:27 +00001237 const __m128i Chunk = *(const __m128i*)NextBuf;
Benjamin Kramerd2953ce2012-04-06 20:49:55 +00001238 __m128i Cmp = _mm_or_si128(_mm_cmpeq_epi8(Chunk, CRs),
1239 _mm_cmpeq_epi8(Chunk, LFs));
1240 unsigned Mask = _mm_movemask_epi8(Cmp);
1241
1242 // If we found a newline, adjust the pointer and jump to the handling code.
1243 if (Mask != 0) {
Michael J. Spencer9779fdd2013-05-24 21:42:04 +00001244 NextBuf += llvm::countTrailingZeros(Mask);
Benjamin Kramerd2953ce2012-04-06 20:49:55 +00001245 goto FoundSpecialChar;
1246 }
1247 NextBuf += 16;
1248 }
1249#endif
1250
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001251 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
1252 ++NextBuf;
Benjamin Kramerd2953ce2012-04-06 20:49:55 +00001253
1254#ifdef __SSE2__
1255FoundSpecialChar:
1256#endif
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001257 Offs += NextBuf-Buf;
1258 Buf = NextBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00001259
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001260 if (Buf[0] == '\n' || Buf[0] == '\r') {
1261 // If this is \n\r or \r\n, skip both characters.
1262 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
1263 ++Offs, ++Buf;
1264 ++Offs, ++Buf;
1265 LineOffsets.push_back(Offs);
1266 } else {
1267 // Otherwise, this is a null. If end of file, exit.
1268 if (Buf == End) break;
1269 // Otherwise, skip the null.
1270 ++Offs, ++Buf;
1271 }
1272 }
Mike Stump1eb44332009-09-09 15:08:12 +00001273
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001274 // Copy the offsets into the FileInfo structure.
1275 FI->NumLines = LineOffsets.size();
Chris Lattner0d0bf8c2009-02-03 07:30:45 +00001276 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001277 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
1278}
Reid Spencer5f016e22007-07-11 17:01:13 +00001279
Chris Lattnerdf7c17a2009-01-16 07:00:02 +00001280/// getLineNumber - Given a SourceLocation, return the spelling line number
Reid Spencer5f016e22007-07-11 17:01:13 +00001281/// for the position indicated. This requires building and caching a table of
1282/// line offsets for the MemoryBuffer, so this is not cheap: use only when
1283/// about to emit a diagnostic.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001284unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
1285 bool *Invalid) const {
Argyrios Kyrtzidis5adc0512011-05-17 22:09:53 +00001286 if (FID.isInvalid()) {
1287 if (Invalid)
1288 *Invalid = true;
1289 return 1;
1290 }
1291
Chris Lattner2b2453a2009-01-17 06:22:33 +00001292 ContentCache *Content;
Chris Lattner30fc9332009-02-04 01:06:56 +00001293 if (LastLineNoFileIDQuery == FID)
Ted Kremenek78d85f52007-10-30 21:08:08 +00001294 Content = LastLineNoContentCache;
Douglas Gregore23ac652011-04-20 00:21:03 +00001295 else {
1296 bool MyInvalid = false;
1297 const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
1298 if (MyInvalid || !Entry.isFile()) {
1299 if (Invalid)
1300 *Invalid = true;
1301 return 1;
1302 }
1303
1304 Content = const_cast<ContentCache*>(Entry.getFile().getContentCache());
1305 }
1306
Reid Spencer5f016e22007-07-11 17:01:13 +00001307 // If this is the first use of line information for this buffer, compute the
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001308 /// SourceLineCache for it on demand.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001309 if (!Content->SourceLineCache) {
Douglas Gregor50f6af72010-03-16 05:20:39 +00001310 bool MyInvalid = false;
Chris Lattnere127a0d2010-04-20 20:35:58 +00001311 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001312 if (Invalid)
1313 *Invalid = MyInvalid;
1314 if (MyInvalid)
1315 return 1;
1316 } else if (Invalid)
1317 *Invalid = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001318
1319 // Okay, we know we have a line number table. Do a binary search to find the
1320 // line number that this character position lands on.
Ted Kremenek78d85f52007-10-30 21:08:08 +00001321 unsigned *SourceLineCache = Content->SourceLineCache;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001322 unsigned *SourceLineCacheStart = SourceLineCache;
Ted Kremenek78d85f52007-10-30 21:08:08 +00001323 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
Mike Stump1eb44332009-09-09 15:08:12 +00001324
Chris Lattner30fc9332009-02-04 01:06:56 +00001325 unsigned QueriedFilePos = FilePos+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001326
Daniel Dunbar4106d692009-05-18 17:30:52 +00001327 // FIXME: I would like to be convinced that this code is worth being as
Mike Stump1eb44332009-09-09 15:08:12 +00001328 // complicated as it is, binary search isn't that slow.
Daniel Dunbar4106d692009-05-18 17:30:52 +00001329 //
1330 // If it is worth being optimized, then in my opinion it could be more
1331 // performant, simpler, and more obviously correct by just "galloping" outward
1332 // from the queried file position. In fact, this could be incorporated into a
1333 // generic algorithm such as lower_bound_with_hint.
1334 //
1335 // If someone gives me a test case where this matters, and I will do it! - DWD
1336
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001337 // If the previous query was to the same file, we know both the file pos from
1338 // that query and the line number returned. This allows us to narrow the
1339 // search space from the entire file to something near the match.
Chris Lattner30fc9332009-02-04 01:06:56 +00001340 if (LastLineNoFileIDQuery == FID) {
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001341 if (QueriedFilePos >= LastLineNoFilePos) {
Daniel Dunbar4106d692009-05-18 17:30:52 +00001342 // FIXME: Potential overflow?
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001343 SourceLineCache = SourceLineCache+LastLineNoResult-1;
Mike Stump1eb44332009-09-09 15:08:12 +00001344
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001345 // The query is likely to be nearby the previous one. Here we check to
1346 // see if it is within 5, 10 or 20 lines. It can be far away in cases
1347 // where big comment blocks and vertical whitespace eat up lines but
1348 // contribute no tokens.
1349 if (SourceLineCache+5 < SourceLineCacheEnd) {
1350 if (SourceLineCache[5] > QueriedFilePos)
1351 SourceLineCacheEnd = SourceLineCache+5;
1352 else if (SourceLineCache+10 < SourceLineCacheEnd) {
1353 if (SourceLineCache[10] > QueriedFilePos)
1354 SourceLineCacheEnd = SourceLineCache+10;
1355 else if (SourceLineCache+20 < SourceLineCacheEnd) {
1356 if (SourceLineCache[20] > QueriedFilePos)
1357 SourceLineCacheEnd = SourceLineCache+20;
1358 }
1359 }
1360 }
1361 } else {
Daniel Dunbar4106d692009-05-18 17:30:52 +00001362 if (LastLineNoResult < Content->NumLines)
1363 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001364 }
1365 }
Mike Stump1eb44332009-09-09 15:08:12 +00001366
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001367 unsigned *Pos
1368 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001369 unsigned LineNo = Pos-SourceLineCacheStart;
Mike Stump1eb44332009-09-09 15:08:12 +00001370
Chris Lattner30fc9332009-02-04 01:06:56 +00001371 LastLineNoFileIDQuery = FID;
Ted Kremenek78d85f52007-10-30 21:08:08 +00001372 LastLineNoContentCache = Content;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001373 LastLineNoFilePos = QueriedFilePos;
1374 LastLineNoResult = LineNo;
1375 return LineNo;
Reid Spencer5f016e22007-07-11 17:01:13 +00001376}
1377
Chandler Carruth5ef04ee2011-02-23 00:47:48 +00001378unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
1379 bool *Invalid) const {
1380 if (isInvalid(Loc, Invalid)) return 0;
1381 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1382 return getLineNumber(LocInfo.first, LocInfo.second);
1383}
Chandler Carruth64211622011-07-25 21:09:52 +00001384unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc,
1385 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001386 if (isInvalid(Loc, Invalid)) return 0;
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +00001387 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Chris Lattner30fc9332009-02-04 01:06:56 +00001388 return getLineNumber(LocInfo.first, LocInfo.second);
1389}
Chandler Carruth5ef04ee2011-02-23 00:47:48 +00001390unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
Douglas Gregor50f6af72010-03-16 05:20:39 +00001391 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001392 if (isInvalid(Loc, Invalid)) return 0;
Chandler Carruth5ef04ee2011-02-23 00:47:48 +00001393 return getPresumedLoc(Loc).getLine();
Chris Lattner30fc9332009-02-04 01:06:56 +00001394}
1395
Chris Lattner6b306672009-02-04 05:33:01 +00001396/// getFileCharacteristic - return the file characteristic of the specified
Mike Stump1eb44332009-09-09 15:08:12 +00001397/// source location, indicating whether this is a normal file, a system
Chris Lattner6b306672009-02-04 05:33:01 +00001398/// header, or an "implicit extern C" system header.
1399///
1400/// This state can be modified with flags on GNU linemarker directives like:
1401/// # 4 "foo.h" 3
1402/// which changes all source locations in the current file after that to be
1403/// considered to be from a system header.
Mike Stump1eb44332009-09-09 15:08:12 +00001404SrcMgr::CharacteristicKind
Chris Lattner6b306672009-02-04 05:33:01 +00001405SourceManager::getFileCharacteristic(SourceLocation Loc) const {
1406 assert(!Loc.isInvalid() && "Can't get file characteristic of invalid loc!");
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +00001407 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Douglas Gregore23ac652011-04-20 00:21:03 +00001408 bool Invalid = false;
1409 const SLocEntry &SEntry = getSLocEntry(LocInfo.first, &Invalid);
1410 if (Invalid || !SEntry.isFile())
1411 return C_User;
1412
1413 const SrcMgr::FileInfo &FI = SEntry.getFile();
Chris Lattner6b306672009-02-04 05:33:01 +00001414
1415 // If there are no #line directives in this file, just return the whole-file
1416 // state.
1417 if (!FI.hasLineDirectives())
1418 return FI.getFileCharacteristic();
Mike Stump1eb44332009-09-09 15:08:12 +00001419
Chris Lattner6b306672009-02-04 05:33:01 +00001420 assert(LineTable && "Can't have linetable entries without a LineTable!");
1421 // See if there is a #line directive before the location.
1422 const LineEntry *Entry =
Douglas Gregor47d9de62012-06-08 16:40:28 +00001423 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001424
Chris Lattner6b306672009-02-04 05:33:01 +00001425 // If this is before the first line marker, use the file characteristic.
1426 if (!Entry)
1427 return FI.getFileCharacteristic();
1428
1429 return Entry->FileKind;
1430}
1431
Chris Lattnerbff5c512009-02-17 08:39:06 +00001432/// Return the filename or buffer identifier of the buffer the location is in.
James Dennettb8950b82012-06-17 03:22:59 +00001433/// Note that this name does not respect \#line directives. Use getPresumedLoc
Chris Lattnerbff5c512009-02-17 08:39:06 +00001434/// for normal clients.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001435const char *SourceManager::getBufferName(SourceLocation Loc,
1436 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001437 if (isInvalid(Loc, Invalid)) return "<invalid loc>";
Mike Stump1eb44332009-09-09 15:08:12 +00001438
Douglas Gregor50f6af72010-03-16 05:20:39 +00001439 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
Chris Lattnerbff5c512009-02-17 08:39:06 +00001440}
1441
Chris Lattner30fc9332009-02-04 01:06:56 +00001442
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001443/// getPresumedLoc - This method returns the "presumed" location of a
James Dennettb8950b82012-06-17 03:22:59 +00001444/// SourceLocation specifies. A "presumed location" can be modified by \#line
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001445/// or GNU line marker directives. This provides a view on the data that a
1446/// user should see in diagnostics, for example.
1447///
Chandler Carruth3201f382011-07-26 05:17:23 +00001448/// Note that a presumed location is always given as the expansion point of an
1449/// expansion location, not at the spelling location.
Richard Smith62221b12012-11-14 23:55:25 +00001450PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc,
1451 bool UseLineDirectives) const {
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001452 if (Loc.isInvalid()) return PresumedLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001453
Chandler Carruth3201f382011-07-26 05:17:23 +00001454 // Presumed locations are always for expansion points.
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +00001455 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +00001456
Douglas Gregore23ac652011-04-20 00:21:03 +00001457 bool Invalid = false;
1458 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1459 if (Invalid || !Entry.isFile())
1460 return PresumedLoc();
1461
1462 const SrcMgr::FileInfo &FI = Entry.getFile();
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001463 const SrcMgr::ContentCache *C = FI.getContentCache();
Mike Stump1eb44332009-09-09 15:08:12 +00001464
Chris Lattner3cd949c2009-02-04 01:55:42 +00001465 // To get the source name, first consult the FileEntry (if one exists)
1466 // before the MemBuffer as this will avoid unnecessarily paging in the
1467 // MemBuffer.
Chris Lattnere127a0d2010-04-20 20:35:58 +00001468 const char *Filename;
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001469 if (C->OrigEntry)
1470 Filename = C->OrigEntry->getName();
Chris Lattnere127a0d2010-04-20 20:35:58 +00001471 else
1472 Filename = C->getBuffer(Diag, *this)->getBufferIdentifier();
Douglas Gregore23ac652011-04-20 00:21:03 +00001473
Douglas Gregorc417fa02010-11-02 00:39:22 +00001474 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1475 if (Invalid)
1476 return PresumedLoc();
1477 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1478 if (Invalid)
1479 return PresumedLoc();
1480
Chris Lattner3cd949c2009-02-04 01:55:42 +00001481 SourceLocation IncludeLoc = FI.getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001482
Chris Lattner3cd949c2009-02-04 01:55:42 +00001483 // If we have #line directives in this file, update and overwrite the physical
1484 // location info if appropriate.
Richard Smith62221b12012-11-14 23:55:25 +00001485 if (UseLineDirectives && FI.hasLineDirectives()) {
Chris Lattner3cd949c2009-02-04 01:55:42 +00001486 assert(LineTable && "Can't have linetable entries without a LineTable!");
1487 // See if there is a #line directive before this. If so, get it.
1488 if (const LineEntry *Entry =
Douglas Gregor47d9de62012-06-08 16:40:28 +00001489 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second)) {
Chris Lattnerfc391332009-02-04 02:00:59 +00001490 // If the LineEntry indicates a filename, use it.
Chris Lattner3cd949c2009-02-04 01:55:42 +00001491 if (Entry->FilenameID != -1)
1492 Filename = LineTable->getFilename(Entry->FilenameID);
Chris Lattnerfc391332009-02-04 02:00:59 +00001493
1494 // Use the line number specified by the LineEntry. This line number may
1495 // be multiple lines down from the line entry. Add the difference in
1496 // physical line numbers from the query point and the line marker to the
1497 // total.
1498 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1499 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001500
Chris Lattner0e0e5da2009-02-04 02:15:40 +00001501 // Note that column numbers are not molested by line markers.
Mike Stump1eb44332009-09-09 15:08:12 +00001502
Chris Lattner137b6a62009-02-04 06:25:26 +00001503 // Handle virtual #include manipulation.
1504 if (Entry->IncludeOffset) {
1505 IncludeLoc = getLocForStartOfFile(LocInfo.first);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001506 IncludeLoc = IncludeLoc.getLocWithOffset(Entry->IncludeOffset);
Chris Lattner137b6a62009-02-04 06:25:26 +00001507 }
Chris Lattner3cd949c2009-02-04 01:55:42 +00001508 }
1509 }
1510
1511 return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc);
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001512}
1513
Benjamin Kramer1b9c5372013-09-27 17:12:50 +00001514/// \brief Returns whether the PresumedLoc for a given SourceLocation is
1515/// in the main file.
1516///
1517/// This computes the "presumed" location for a SourceLocation, then checks
1518/// whether it came from a file other than the main file. This is different
1519/// from isWrittenInMainFile() because it takes line marker directives into
1520/// account.
1521bool SourceManager::isInMainFile(SourceLocation Loc) const {
1522 if (Loc.isInvalid()) return false;
1523
1524 // Presumed locations are always for expansion points.
1525 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1526
1527 bool Invalid = false;
1528 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1529 if (Invalid || !Entry.isFile())
1530 return false;
1531
1532 const SrcMgr::FileInfo &FI = Entry.getFile();
1533
1534 // Check if there is a line directive for this location.
1535 if (FI.hasLineDirectives())
1536 if (const LineEntry *Entry =
1537 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second))
1538 if (Entry->IncludeOffset)
1539 return false;
1540
1541 return FI.getIncludeLoc().isInvalid();
1542}
1543
Stephen Hines651f13c2014-04-23 16:59:28 -07001544/// \brief The size of the SLocEntry that \p FID represents.
Argyrios Kyrtzidis984e42c2011-08-23 21:02:28 +00001545unsigned SourceManager::getFileIDSize(FileID FID) const {
1546 bool Invalid = false;
1547 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1548 if (Invalid)
1549 return 0;
1550
1551 int ID = FID.ID;
1552 unsigned NextOffset;
1553 if ((ID > 0 && unsigned(ID+1) == local_sloc_entry_size()))
1554 NextOffset = getNextLocalOffset();
1555 else if (ID+1 == -1)
1556 NextOffset = MaxLoadedOffset;
1557 else
1558 NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset();
1559
1560 return NextOffset - Entry.getOffset() - 1;
1561}
1562
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001563//===----------------------------------------------------------------------===//
1564// Other miscellaneous methods.
1565//===----------------------------------------------------------------------===//
1566
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001567/// \brief Retrieve the inode for the given file entry, if possible.
1568///
1569/// This routine involves a system call, and therefore should only be used
1570/// in non-performance-critical code.
Rafael Espindola44888352013-07-29 21:26:52 +00001571static Optional<llvm::sys::fs::UniqueID>
1572getActualFileUID(const FileEntry *File) {
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001573 if (!File)
David Blaikie66874fb2013-02-21 01:47:18 +00001574 return None;
Rafael Espindola3dadc852013-07-29 18:43:40 +00001575
Rafael Espindola44888352013-07-29 21:26:52 +00001576 llvm::sys::fs::UniqueID ID;
Rafael Espindola3dadc852013-07-29 18:43:40 +00001577 if (llvm::sys::fs::getUniqueID(File->getName(), ID))
David Blaikie66874fb2013-02-21 01:47:18 +00001578 return None;
Rafael Espindola3dadc852013-07-29 18:43:40 +00001579
1580 return ID;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001581}
1582
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001583/// \brief Get the source location for the given file:line:col triplet.
1584///
1585/// If the source file is included multiple times, the source location will
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001586/// be based upon an arbitrary inclusion.
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001587SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile,
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001588 unsigned Line,
1589 unsigned Col) const {
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001590 assert(SourceFile && "Null source file!");
1591 assert(Line && Col && "Line and column should start from 1!");
1592
Argyrios Kyrtzidisb201e162011-09-27 17:22:25 +00001593 FileID FirstFID = translateFile(SourceFile);
1594 return translateLineCol(FirstFID, Line, Col);
1595}
1596
1597/// \brief Get the FileID for the given file.
1598///
1599/// If the source file is included multiple times, the FileID will be the
1600/// first inclusion.
1601FileID SourceManager::translateFile(const FileEntry *SourceFile) const {
1602 assert(SourceFile && "Null source file!");
1603
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001604 // Find the first file ID that corresponds to the given file.
1605 FileID FirstFID;
Mike Stump1eb44332009-09-09 15:08:12 +00001606
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001607 // First, check the main file ID, since it is common to look for a
1608 // location in the main file.
Rafael Espindola44888352013-07-29 21:26:52 +00001609 Optional<llvm::sys::fs::UniqueID> SourceFileUID;
David Blaikiedc84cd52013-02-20 22:23:23 +00001610 Optional<StringRef> SourceFileName;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001611 if (!MainFileID.isInvalid()) {
Douglas Gregore23ac652011-04-20 00:21:03 +00001612 bool Invalid = false;
1613 const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
1614 if (Invalid)
Argyrios Kyrtzidisb201e162011-09-27 17:22:25 +00001615 return FileID();
Douglas Gregore23ac652011-04-20 00:21:03 +00001616
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001617 if (MainSLoc.isFile()) {
1618 const ContentCache *MainContentCache
1619 = MainSLoc.getFile().getContentCache();
Douglas Gregorb7a18412011-02-11 18:08:15 +00001620 if (!MainContentCache) {
1621 // Can't do anything
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001622 } else if (MainContentCache->OrigEntry == SourceFile) {
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001623 FirstFID = MainFileID;
Douglas Gregorb7a18412011-02-11 18:08:15 +00001624 } else {
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001625 // Fall back: check whether we have the same base name and inode
1626 // as the main file.
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001627 const FileEntry *MainFile = MainContentCache->OrigEntry;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001628 SourceFileName = llvm::sys::path::filename(SourceFile->getName());
1629 if (*SourceFileName == llvm::sys::path::filename(MainFile->getName())) {
Rafael Espindola3dadc852013-07-29 18:43:40 +00001630 SourceFileUID = getActualFileUID(SourceFile);
1631 if (SourceFileUID) {
Rafael Espindola44888352013-07-29 21:26:52 +00001632 if (Optional<llvm::sys::fs::UniqueID> MainFileUID =
1633 getActualFileUID(MainFile)) {
Rafael Espindola3dadc852013-07-29 18:43:40 +00001634 if (*SourceFileUID == *MainFileUID) {
Douglas Gregor37c02bf2011-02-16 19:09:24 +00001635 FirstFID = MainFileID;
1636 SourceFile = MainFile;
1637 }
1638 }
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001639 }
1640 }
1641 }
1642 }
1643 }
1644
1645 if (FirstFID.isInvalid()) {
1646 // The location we're looking for isn't in the main file; look
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001647 // through all of the local source locations.
1648 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
Douglas Gregore23ac652011-04-20 00:21:03 +00001649 bool Invalid = false;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001650 const SLocEntry &SLoc = getLocalSLocEntry(I, &Invalid);
Douglas Gregore23ac652011-04-20 00:21:03 +00001651 if (Invalid)
Argyrios Kyrtzidisb201e162011-09-27 17:22:25 +00001652 return FileID();
Douglas Gregore23ac652011-04-20 00:21:03 +00001653
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001654 if (SLoc.isFile() &&
1655 SLoc.getFile().getContentCache() &&
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001656 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001657 FirstFID = FileID::get(I);
1658 break;
1659 }
1660 }
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001661 // If that still didn't help, try the modules.
1662 if (FirstFID.isInvalid()) {
1663 for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) {
1664 const SLocEntry &SLoc = getLoadedSLocEntry(I);
1665 if (SLoc.isFile() &&
1666 SLoc.getFile().getContentCache() &&
1667 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
1668 FirstFID = FileID::get(-int(I) - 2);
1669 break;
1670 }
1671 }
1672 }
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001673 }
1674
1675 // If we haven't found what we want yet, try again, but this time stat()
1676 // each of the files in case the files have changed since we originally
Rafael Espindola3dadc852013-07-29 18:43:40 +00001677 // parsed the file.
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001678 if (FirstFID.isInvalid() &&
Rafael Espindola3dadc852013-07-29 18:43:40 +00001679 (SourceFileName ||
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001680 (SourceFileName = llvm::sys::path::filename(SourceFile->getName()))) &&
Rafael Espindola3dadc852013-07-29 18:43:40 +00001681 (SourceFileUID || (SourceFileUID = getActualFileUID(SourceFile)))) {
Douglas Gregore23ac652011-04-20 00:21:03 +00001682 bool Invalid = false;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001683 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1684 FileID IFileID;
1685 IFileID.ID = I;
1686 const SLocEntry &SLoc = getSLocEntry(IFileID, &Invalid);
Douglas Gregore23ac652011-04-20 00:21:03 +00001687 if (Invalid)
Argyrios Kyrtzidisb201e162011-09-27 17:22:25 +00001688 return FileID();
Douglas Gregore23ac652011-04-20 00:21:03 +00001689
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001690 if (SLoc.isFile()) {
1691 const ContentCache *FileContentCache
1692 = SLoc.getFile().getContentCache();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001693 const FileEntry *Entry = FileContentCache ? FileContentCache->OrigEntry
1694 : nullptr;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001695 if (Entry &&
Douglas Gregorb7a18412011-02-11 18:08:15 +00001696 *SourceFileName == llvm::sys::path::filename(Entry->getName())) {
Rafael Espindola44888352013-07-29 21:26:52 +00001697 if (Optional<llvm::sys::fs::UniqueID> EntryUID =
1698 getActualFileUID(Entry)) {
Rafael Espindola3dadc852013-07-29 18:43:40 +00001699 if (*SourceFileUID == *EntryUID) {
Douglas Gregorb7a18412011-02-11 18:08:15 +00001700 FirstFID = FileID::get(I);
1701 SourceFile = Entry;
1702 break;
1703 }
1704 }
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001705 }
1706 }
1707 }
1708 }
Argyrios Kyrtzidisb201e162011-09-27 17:22:25 +00001709
Ted Kremenek186ec9c2012-10-12 22:56:33 +00001710 (void) SourceFile;
Argyrios Kyrtzidisb201e162011-09-27 17:22:25 +00001711 return FirstFID;
Argyrios Kyrtzidisefa2ff82011-09-19 20:40:29 +00001712}
1713
1714/// \brief Get the source location in \arg FID for the given line:col.
1715/// Returns null location if \arg FID is not a file SLocEntry.
1716SourceLocation SourceManager::translateLineCol(FileID FID,
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001717 unsigned Line,
1718 unsigned Col) const {
Aaron Ballmanfb21ecf2013-11-18 18:29:00 +00001719 // Lines are used as a one-based index into a zero-based array. This assert
1720 // checks for possible buffer underruns.
1721 assert(Line != 0 && "Passed a zero-based line");
1722
Argyrios Kyrtzidisefa2ff82011-09-19 20:40:29 +00001723 if (FID.isInvalid())
1724 return SourceLocation();
1725
1726 bool Invalid = false;
1727 const SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1728 if (Invalid)
1729 return SourceLocation();
Alexander Kornienkoc8051e62013-07-29 22:26:10 +00001730
Argyrios Kyrtzidisefa2ff82011-09-19 20:40:29 +00001731 if (!Entry.isFile())
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001732 return SourceLocation();
1733
Argyrios Kyrtzidis5e5e95d2011-09-20 22:14:54 +00001734 SourceLocation FileLoc = SourceLocation::getFileLoc(Entry.getOffset());
1735
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001736 if (Line == 1 && Col == 1)
Argyrios Kyrtzidis5e5e95d2011-09-20 22:14:54 +00001737 return FileLoc;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001738
1739 ContentCache *Content
Argyrios Kyrtzidisefa2ff82011-09-19 20:40:29 +00001740 = const_cast<ContentCache *>(Entry.getFile().getContentCache());
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001741 if (!Content)
1742 return SourceLocation();
Alexander Kornienkoc8051e62013-07-29 22:26:10 +00001743
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001744 // If this is the first use of line information for this buffer, compute the
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001745 // SourceLineCache for it on demand.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001746 if (!Content->SourceLineCache) {
Douglas Gregor50f6af72010-03-16 05:20:39 +00001747 bool MyInvalid = false;
Chris Lattnere127a0d2010-04-20 20:35:58 +00001748 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001749 if (MyInvalid)
1750 return SourceLocation();
1751 }
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001752
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001753 if (Line > Content->NumLines) {
Chris Lattnere127a0d2010-04-20 20:35:58 +00001754 unsigned Size = Content->getBuffer(Diag, *this)->getBufferSize();
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001755 if (Size > 0)
1756 --Size;
Argyrios Kyrtzidis5e5e95d2011-09-20 22:14:54 +00001757 return FileLoc.getLocWithOffset(Size);
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001758 }
1759
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001760 llvm::MemoryBuffer *Buffer = Content->getBuffer(Diag, *this);
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001761 unsigned FilePos = Content->SourceLineCache[Line - 1];
Dylan Noblesmith098eaff2011-12-19 08:51:05 +00001762 const char *Buf = Buffer->getBufferStart() + FilePos;
1763 unsigned BufLength = Buffer->getBufferSize() - FilePos;
Argyrios Kyrtzidis5e5e95d2011-09-20 22:14:54 +00001764 if (BufLength == 0)
1765 return FileLoc.getLocWithOffset(FilePos);
1766
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001767 unsigned i = 0;
1768
1769 // Check that the given column is valid.
1770 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1771 ++i;
Alexander Kornienkoc8051e62013-07-29 22:26:10 +00001772 return FileLoc.getLocWithOffset(FilePos + i);
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001773}
1774
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001775/// \brief Compute a map of macro argument chunks to their expanded source
1776/// location. Chunks that are not part of a macro argument will map to an
1777/// invalid source location. e.g. if a file contains one macro argument at
1778/// offset 100 with length 10, this is how the map will be formed:
1779/// 0 -> SourceLocation()
1780/// 100 -> Expanded macro arg location
1781/// 110 -> SourceLocation()
Argyrios Kyrtzidisfb3612e2011-09-26 08:01:50 +00001782void SourceManager::computeMacroArgsCache(MacroArgsMap *&CachePtr,
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001783 FileID FID) const {
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001784 assert(!FID.isInvalid());
Argyrios Kyrtzidisfb3612e2011-09-26 08:01:50 +00001785 assert(!CachePtr);
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001786
Argyrios Kyrtzidisfb3612e2011-09-26 08:01:50 +00001787 CachePtr = new MacroArgsMap();
1788 MacroArgsMap &MacroArgsCache = *CachePtr;
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001789 // Initially no macro argument chunk is present.
1790 MacroArgsCache.insert(std::make_pair(0, SourceLocation()));
1791
1792 int ID = FID.ID;
1793 while (1) {
1794 ++ID;
1795 // Stop if there are no more FileIDs to check.
1796 if (ID > 0) {
1797 if (unsigned(ID) >= local_sloc_entry_size())
1798 return;
1799 } else if (ID == -1) {
1800 return;
1801 }
1802
Argyrios Kyrtzidis4ff32252013-06-07 17:57:59 +00001803 bool Invalid = false;
1804 const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID, &Invalid);
1805 if (Invalid)
1806 return;
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001807 if (Entry.isFile()) {
1808 SourceLocation IncludeLoc = Entry.getFile().getIncludeLoc();
1809 if (IncludeLoc.isInvalid())
1810 continue;
1811 if (!isInFileID(IncludeLoc, FID))
1812 return; // No more files/macros that may be "contained" in this file.
1813
1814 // Skip the files/macros of the #include'd file, we only care about macros
1815 // that lexed macro arguments from our file.
1816 if (Entry.getFile().NumCreatedFIDs)
1817 ID += Entry.getFile().NumCreatedFIDs - 1/*because of next ++ID*/;
1818 continue;
1819 }
1820
Argyrios Kyrtzidiscee5ec92011-12-21 16:56:35 +00001821 const ExpansionInfo &ExpInfo = Entry.getExpansion();
1822
1823 if (ExpInfo.getExpansionLocStart().isFileID()) {
1824 if (!isInFileID(ExpInfo.getExpansionLocStart(), FID))
1825 return; // No more files/macros that may be "contained" in this file.
1826 }
1827
1828 if (!ExpInfo.isMacroArgExpansion())
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001829 continue;
Argyrios Kyrtzidiscee5ec92011-12-21 16:56:35 +00001830
Argyrios Kyrtzidis0872a062012-10-20 00:51:32 +00001831 associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1832 ExpInfo.getSpellingLoc(),
1833 SourceLocation::getMacroLoc(Entry.getOffset()),
1834 getFileIDSize(FileID::get(ID)));
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001835 }
1836}
1837
Argyrios Kyrtzidis0872a062012-10-20 00:51:32 +00001838void SourceManager::associateFileChunkWithMacroArgExp(
1839 MacroArgsMap &MacroArgsCache,
1840 FileID FID,
1841 SourceLocation SpellLoc,
1842 SourceLocation ExpansionLoc,
1843 unsigned ExpansionLength) const {
1844 if (!SpellLoc.isFileID()) {
1845 unsigned SpellBeginOffs = SpellLoc.getOffset();
1846 unsigned SpellEndOffs = SpellBeginOffs + ExpansionLength;
1847
1848 // The spelling range for this macro argument expansion can span multiple
1849 // consecutive FileID entries. Go through each entry contained in the
1850 // spelling range and if one is itself a macro argument expansion, recurse
1851 // and associate the file chunk that it represents.
1852
1853 FileID SpellFID; // Current FileID in the spelling range.
1854 unsigned SpellRelativeOffs;
Stephen Hines651f13c2014-04-23 16:59:28 -07001855 std::tie(SpellFID, SpellRelativeOffs) = getDecomposedLoc(SpellLoc);
Argyrios Kyrtzidis0872a062012-10-20 00:51:32 +00001856 while (1) {
1857 const SLocEntry &Entry = getSLocEntry(SpellFID);
1858 unsigned SpellFIDBeginOffs = Entry.getOffset();
1859 unsigned SpellFIDSize = getFileIDSize(SpellFID);
1860 unsigned SpellFIDEndOffs = SpellFIDBeginOffs + SpellFIDSize;
1861 const ExpansionInfo &Info = Entry.getExpansion();
1862 if (Info.isMacroArgExpansion()) {
1863 unsigned CurrSpellLength;
1864 if (SpellFIDEndOffs < SpellEndOffs)
1865 CurrSpellLength = SpellFIDSize - SpellRelativeOffs;
1866 else
1867 CurrSpellLength = ExpansionLength;
1868 associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1869 Info.getSpellingLoc().getLocWithOffset(SpellRelativeOffs),
1870 ExpansionLoc, CurrSpellLength);
1871 }
1872
1873 if (SpellFIDEndOffs >= SpellEndOffs)
1874 return; // we covered all FileID entries in the spelling range.
1875
1876 // Move to the next FileID entry in the spelling range.
1877 unsigned advance = SpellFIDSize - SpellRelativeOffs + 1;
1878 ExpansionLoc = ExpansionLoc.getLocWithOffset(advance);
1879 ExpansionLength -= advance;
1880 ++SpellFID.ID;
1881 SpellRelativeOffs = 0;
1882 }
1883
1884 }
1885
1886 assert(SpellLoc.isFileID());
1887
1888 unsigned BeginOffs;
1889 if (!isInFileID(SpellLoc, FID, &BeginOffs))
1890 return;
1891
1892 unsigned EndOffs = BeginOffs + ExpansionLength;
1893
1894 // Add a new chunk for this macro argument. A previous macro argument chunk
1895 // may have been lexed again, so e.g. if the map is
1896 // 0 -> SourceLocation()
1897 // 100 -> Expanded loc #1
1898 // 110 -> SourceLocation()
1899 // and we found a new macro FileID that lexed from offet 105 with length 3,
1900 // the new map will be:
1901 // 0 -> SourceLocation()
1902 // 100 -> Expanded loc #1
1903 // 105 -> Expanded loc #2
1904 // 108 -> Expanded loc #1
1905 // 110 -> SourceLocation()
1906 //
1907 // Since re-lexed macro chunks will always be the same size or less of
1908 // previous chunks, we only need to find where the ending of the new macro
1909 // chunk is mapped to and update the map with new begin/end mappings.
1910
1911 MacroArgsMap::iterator I = MacroArgsCache.upper_bound(EndOffs);
1912 --I;
1913 SourceLocation EndOffsMappedLoc = I->second;
1914 MacroArgsCache[BeginOffs] = ExpansionLoc;
1915 MacroArgsCache[EndOffs] = EndOffsMappedLoc;
1916}
1917
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001918/// \brief If \arg Loc points inside a function macro argument, the returned
1919/// location will be the macro location in which the argument was expanded.
1920/// If a macro argument is used multiple times, the expanded location will
1921/// be at the first expansion of the argument.
1922/// e.g.
1923/// MY_MACRO(foo);
1924/// ^
1925/// Passing a file location pointing at 'foo', will yield a macro location
1926/// where 'foo' was expanded into.
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001927SourceLocation
1928SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const {
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001929 if (Loc.isInvalid() || !Loc.isFileID())
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001930 return Loc;
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001931
1932 FileID FID;
1933 unsigned Offset;
Stephen Hines651f13c2014-04-23 16:59:28 -07001934 std::tie(FID, Offset) = getDecomposedLoc(Loc);
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001935 if (FID.isInvalid())
1936 return Loc;
1937
Argyrios Kyrtzidisfb3612e2011-09-26 08:01:50 +00001938 MacroArgsMap *&MacroArgsCache = MacroArgsCacheMap[FID];
1939 if (!MacroArgsCache)
1940 computeMacroArgsCache(MacroArgsCache, FID);
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001941
Argyrios Kyrtzidisfb3612e2011-09-26 08:01:50 +00001942 assert(!MacroArgsCache->empty());
1943 MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset);
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001944 --I;
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001945
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001946 unsigned MacroArgBeginOffs = I->first;
1947 SourceLocation MacroArgExpandedLoc = I->second;
1948 if (MacroArgExpandedLoc.isValid())
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001949 return MacroArgExpandedLoc.getLocWithOffset(Offset - MacroArgBeginOffs);
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001950
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001951 return Loc;
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001952}
1953
Argyrios Kyrtzidisecc65232013-04-13 01:03:57 +00001954std::pair<FileID, unsigned>
1955SourceManager::getDecomposedIncludedLoc(FileID FID) const {
Argyrios Kyrtzidis5b8e1322013-05-24 22:24:04 +00001956 if (FID.isInvalid())
1957 return std::make_pair(FileID(), 0);
1958
Argyrios Kyrtzidisecc65232013-04-13 01:03:57 +00001959 // Uses IncludedLocMap to retrieve/cache the decomposed loc.
1960
1961 typedef std::pair<FileID, unsigned> DecompTy;
1962 typedef llvm::DenseMap<FileID, DecompTy> MapTy;
1963 std::pair<MapTy::iterator, bool>
1964 InsertOp = IncludedLocMap.insert(std::make_pair(FID, DecompTy()));
1965 DecompTy &DecompLoc = InsertOp.first->second;
1966 if (!InsertOp.second)
1967 return DecompLoc; // already in map.
1968
1969 SourceLocation UpperLoc;
Argyrios Kyrtzidis5b8e1322013-05-24 22:24:04 +00001970 bool Invalid = false;
1971 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1972 if (!Invalid) {
1973 if (Entry.isExpansion())
1974 UpperLoc = Entry.getExpansion().getExpansionLocStart();
1975 else
1976 UpperLoc = Entry.getFile().getIncludeLoc();
1977 }
Argyrios Kyrtzidisecc65232013-04-13 01:03:57 +00001978
1979 if (UpperLoc.isValid())
1980 DecompLoc = getDecomposedLoc(UpperLoc);
1981
1982 return DecompLoc;
1983}
1984
Chandler Carruth3201f382011-07-26 05:17:23 +00001985/// Given a decomposed source location, move it up the include/expansion stack
1986/// to the parent source location. If this is possible, return the decomposed
1987/// version of the parent in Loc and return false. If Loc is the top-level
1988/// entry, return true and don't modify it.
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001989static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1990 const SourceManager &SM) {
Argyrios Kyrtzidisecc65232013-04-13 01:03:57 +00001991 std::pair<FileID, unsigned> UpperLoc = SM.getDecomposedIncludedLoc(Loc.first);
1992 if (UpperLoc.first.isInvalid())
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001993 return true; // We reached the top.
Argyrios Kyrtzidisecc65232013-04-13 01:03:57 +00001994
1995 Loc = UpperLoc;
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001996 return false;
1997}
Ted Kremenek2564f812013-02-27 00:00:26 +00001998
1999/// Return the cache entry for comparing the given file IDs
2000/// for isBeforeInTranslationUnit.
2001InBeforeInTUCacheEntry &SourceManager::getInBeforeInTUCache(FileID LFID,
2002 FileID RFID) const {
2003 // This is a magic number for limiting the cache size. It was experimentally
2004 // derived from a small Objective-C project (where the cache filled
2005 // out to ~250 items). We can make it larger if necessary.
2006 enum { MagicCacheSize = 300 };
2007 IsBeforeInTUCacheKey Key(LFID, RFID);
2008
2009 // If the cache size isn't too large, do a lookup and if necessary default
2010 // construct an entry. We can then return it to the caller for direct
2011 // use. When they update the value, the cache will get automatically
2012 // updated as well.
2013 if (IBTUCache.size() < MagicCacheSize)
2014 return IBTUCache[Key];
2015
2016 // Otherwise, do a lookup that will not construct a new value.
2017 InBeforeInTUCache::iterator I = IBTUCache.find(Key);
2018 if (I != IBTUCache.end())
2019 return I->second;
2020
2021 // Fall back to the overflow value.
2022 return IBTUCacheOverflow;
2023}
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00002024
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00002025/// \brief Determines the order of 2 source locations in the translation unit.
2026///
2027/// \returns true if LHS source location comes before RHS, false otherwise.
2028bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
2029 SourceLocation RHS) const {
2030 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
2031 if (LHS == RHS)
2032 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002033
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00002034 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
2035 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002036
Argyrios Kyrtzidisecdbbfa2013-05-24 23:47:43 +00002037 // getDecomposedLoc may have failed to return a valid FileID because, e.g. it
2038 // is a serialized one referring to a file that was removed after we loaded
2039 // the PCH.
Argyrios Kyrtzidis5b8e1322013-05-24 22:24:04 +00002040 if (LOffs.first.isInvalid() || ROffs.first.isInvalid())
Argyrios Kyrtzidis45e1f0e2013-05-25 01:03:03 +00002041 return LOffs.first.isInvalid() && !ROffs.first.isInvalid();
Argyrios Kyrtzidis5b8e1322013-05-24 22:24:04 +00002042
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00002043 // If the source locations are in the same file, just compare offsets.
2044 if (LOffs.first == ROffs.first)
2045 return LOffs.second < ROffs.second;
2046
2047 // If we are comparing a source location with multiple locations in the same
2048 // file, we get a big win by caching the result.
Ted Kremenek2564f812013-02-27 00:00:26 +00002049 InBeforeInTUCacheEntry &IsBeforeInTUCache =
2050 getInBeforeInTUCache(LOffs.first, ROffs.first);
2051
2052 // If we are comparing a source location with multiple locations in the same
2053 // file, we get a big win by caching the result.
Chris Lattner66a915f2010-05-07 05:10:46 +00002054 if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
2055 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
Mike Stump1eb44332009-09-09 15:08:12 +00002056
Chris Lattnerdcb1d682010-05-07 01:17:07 +00002057 // Okay, we missed in the cache, start updating the cache for this query.
Argyrios Kyrtzidis37e59a12011-08-17 00:31:18 +00002058 IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first,
2059 /*isLFIDBeforeRFID=*/LOffs.first.ID < ROffs.first.ID);
Mike Stump1eb44332009-09-09 15:08:12 +00002060
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002061 // We need to find the common ancestor. The only way of doing this is to
2062 // build the complete include chain for one and then walking up the chain
2063 // of the other looking for a match.
2064 // We use a map from FileID to Offset to store the chain. Easier than writing
2065 // a custom set hash info that only depends on the first part of a pair.
Argyrios Kyrtzidisecc65232013-04-13 01:03:57 +00002066 typedef llvm::SmallDenseMap<FileID, unsigned, 16> LocSet;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002067 LocSet LChain;
Chris Lattner48296ba2010-05-07 05:51:13 +00002068 do {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002069 LChain.insert(LOffs);
2070 // We catch the case where LOffs is in a file included by ROffs and
2071 // quit early. The other way round unfortunately remains suboptimal.
2072 } while (LOffs.first != ROffs.first && !MoveUpIncludeHierarchy(LOffs, *this));
2073 LocSet::iterator I;
2074 while((I = LChain.find(ROffs.first)) == LChain.end()) {
2075 if (MoveUpIncludeHierarchy(ROffs, *this))
2076 break; // Met at topmost file.
2077 }
2078 if (I != LChain.end())
2079 LOffs = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00002080
Chris Lattner48296ba2010-05-07 05:51:13 +00002081 // If we exited because we found a nearest common ancestor, compare the
2082 // locations within the common file and cache them.
2083 if (LOffs.first == ROffs.first) {
2084 IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
2085 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00002086 }
Mike Stump1eb44332009-09-09 15:08:12 +00002087
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002088 // This can happen if a location is in a built-ins buffer.
2089 // But see PR5662.
2090 // Clear the lookup cache, it depends on a common location.
Argyrios Kyrtzidis37e59a12011-08-17 00:31:18 +00002091 IsBeforeInTUCache.clear();
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002092 bool LIsBuiltins = strcmp("<built-in>",
2093 getBuffer(LOffs.first)->getBufferIdentifier()) == 0;
2094 bool RIsBuiltins = strcmp("<built-in>",
2095 getBuffer(ROffs.first)->getBufferIdentifier()) == 0;
2096 // built-in is before non-built-in
2097 if (LIsBuiltins != RIsBuiltins)
2098 return LIsBuiltins;
2099 assert(LIsBuiltins && RIsBuiltins &&
2100 "Non-built-in locations must be rooted in the main file");
2101 // Both are in built-in buffers, but from different files. We just claim that
2102 // lower IDs come first.
Chris Lattnerdcb1d682010-05-07 01:17:07 +00002103 return LOffs.first < ROffs.first;
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00002104}
Chris Lattnerde7aeef2009-01-26 00:43:02 +00002105
Reid Spencer5f016e22007-07-11 17:01:13 +00002106void SourceManager::PrintStats() const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00002107 llvm::errs() << "\n*** Source Manager Stats:\n";
2108 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
2109 << " mem buffers mapped.\n";
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002110 llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntry's allocated ("
Ted Kremenek6e36c122011-07-27 18:41:16 +00002111 << llvm::capacity_in_bytes(LocalSLocEntryTable)
Argyrios Kyrtzidisd410e742011-07-07 03:40:24 +00002112 << " bytes of capacity), "
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002113 << NextLocalOffset << "B of Sloc address space used.\n";
2114 llvm::errs() << LoadedSLocEntryTable.size()
2115 << " loaded SLocEntries allocated, "
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00002116 << MaxLoadedOffset - CurrentLoadedOffset
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002117 << "B of Sloc address space used.\n";
2118
Reid Spencer5f016e22007-07-11 17:01:13 +00002119 unsigned NumLineNumsComputed = 0;
2120 unsigned NumFileBytesMapped = 0;
Chris Lattner0d0bf8c2009-02-03 07:30:45 +00002121 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002122 NumLineNumsComputed += I->second->SourceLineCache != nullptr;
Chris Lattner0d0bf8c2009-02-03 07:30:45 +00002123 NumFileBytesMapped += I->second->getSizeBytesMapped();
Reid Spencer5f016e22007-07-11 17:01:13 +00002124 }
Argyrios Kyrtzidisfb3612e2011-09-26 08:01:50 +00002125 unsigned NumMacroArgsComputed = MacroArgsCacheMap.size();
Mike Stump1eb44332009-09-09 15:08:12 +00002126
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00002127 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00002128 << NumLineNumsComputed << " files with line #'s computed, "
2129 << NumMacroArgsComputed << " files with macro args computed.\n";
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00002130 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
2131 << NumBinaryProbes << " binary.\n";
Reid Spencer5f016e22007-07-11 17:01:13 +00002132}
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002133
2134ExternalSLocEntrySource::~ExternalSLocEntrySource() { }
Ted Kremenekf61b8312011-04-28 20:36:42 +00002135
2136/// Return the amount of memory used by memory buffers, breaking down
2137/// by heap-backed versus mmap'ed memory.
2138SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
2139 size_t malloc_bytes = 0;
2140 size_t mmap_bytes = 0;
2141
2142 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)
2143 if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
2144 switch (MemBufferInfos[i]->getMemoryBufferKind()) {
2145 case llvm::MemoryBuffer::MemoryBuffer_MMap:
2146 mmap_bytes += sized_mapped;
2147 break;
2148 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
2149 malloc_bytes += sized_mapped;
2150 break;
2151 }
2152
2153 return MemoryBufferSizes(malloc_bytes, mmap_bytes);
2154}
2155
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00002156size_t SourceManager::getDataStructureSizes() const {
Argyrios Kyrtzidisd54dff02012-05-03 21:50:39 +00002157 size_t size = llvm::capacity_in_bytes(MemBufferInfos)
Ted Kremenek6e36c122011-07-27 18:41:16 +00002158 + llvm::capacity_in_bytes(LocalSLocEntryTable)
2159 + llvm::capacity_in_bytes(LoadedSLocEntryTable)
2160 + llvm::capacity_in_bytes(SLocEntryLoaded)
Argyrios Kyrtzidisd54dff02012-05-03 21:50:39 +00002161 + llvm::capacity_in_bytes(FileInfos);
2162
2163 if (OverriddenFilesInfo)
2164 size += llvm::capacity_in_bytes(OverriddenFilesInfo->OverriddenFiles);
2165
2166 return size;
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00002167}