blob: 305dcd43960c7fdce72321d1f5ff47e9ef8048a1 [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
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +000097 bool isVolatile = SM.userFilesAreVolatile() && !IsSystemFile;
Stephen Hines176edba2014-12-01 14:53:08 -080098 auto BufferOrError =
99 SM.getFileManager().getBufferForFile(ContentsEntry, isVolatile);
Chris Lattnerb088cd32010-11-23 08:50:03 +0000100
101 // If we were unable to open the file, then we are in an inconsistent
102 // situation where the content cache referenced a file which no longer
103 // exists. Most likely, we were using a stat cache with an invalid entry but
104 // the file could also have been removed during processing. Since we can't
105 // really deal with this situation, just create an empty buffer.
106 //
107 // FIXME: This is definitely not ideal, but our immediate clients can't
108 // currently handle returning a null entry here. Ideally we should detect
109 // that we are in an inconsistent situation and error out as quickly as
110 // possible.
Stephen Hines176edba2014-12-01 14:53:08 -0800111 if (!BufferOrError) {
112 StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
113 Buffer.setPointer(MemoryBuffer::getNewMemBuffer(ContentsEntry->getSize(),
114 "<invalid>").release());
Chris Lattnerb088cd32010-11-23 08:50:03 +0000115 char *Ptr = const_cast<char*>(Buffer.getPointer()->getBufferStart());
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000116 for (unsigned i = 0, e = ContentsEntry->getSize(); i != e; ++i)
Chris Lattnerb088cd32010-11-23 08:50:03 +0000117 Ptr[i] = FillStr[i % FillStr.size()];
118
119 if (Diag.isDiagnosticInFlight())
Stephen Hines176edba2014-12-01 14:53:08 -0800120 Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
121 ContentsEntry->getName(),
122 BufferOrError.getError().message());
123 else
Chris Lattnerb088cd32010-11-23 08:50:03 +0000124 Diag.Report(Loc, diag::err_cannot_open_file)
Stephen Hines176edba2014-12-01 14:53:08 -0800125 << ContentsEntry->getName() << BufferOrError.getError().message();
Chris Lattnerb088cd32010-11-23 08:50:03 +0000126
127 Buffer.setInt(Buffer.getInt() | InvalidFlag);
128
129 if (Invalid) *Invalid = true;
130 return Buffer.getPointer();
131 }
Stephen Hines176edba2014-12-01 14:53:08 -0800132
133 Buffer.setPointer(BufferOrError->release());
134
Chris Lattnerb088cd32010-11-23 08:50:03 +0000135 // Check that the file's size is the same as in the file entry (which may
136 // have come from a stat cache).
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000137 if (getRawBuffer()->getBufferSize() != (size_t)ContentsEntry->getSize()) {
Chris Lattnerb088cd32010-11-23 08:50:03 +0000138 if (Diag.isDiagnosticInFlight())
139 Diag.SetDelayedDiagnostic(diag::err_file_modified,
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000140 ContentsEntry->getName());
Chris Lattnerb088cd32010-11-23 08:50:03 +0000141 else
142 Diag.Report(Loc, diag::err_file_modified)
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000143 << ContentsEntry->getName();
Chris Lattnerb088cd32010-11-23 08:50:03 +0000144
145 Buffer.setInt(Buffer.getInt() | InvalidFlag);
146 if (Invalid) *Invalid = true;
147 return Buffer.getPointer();
148 }
Eric Christopher156119d2011-04-09 00:01:04 +0000149
Chris Lattnerb088cd32010-11-23 08:50:03 +0000150 // If the buffer is valid, check to see if it has a UTF Byte Order Mark
Eric Christopher156119d2011-04-09 00:01:04 +0000151 // (BOM). We only support UTF-8 with and without a BOM right now. See
Chris Lattnerb088cd32010-11-23 08:50:03 +0000152 // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000153 StringRef BufStr = Buffer.getPointer()->getBuffer();
Eric Christopher156119d2011-04-09 00:01:04 +0000154 const char *InvalidBOM = llvm::StringSwitch<const char *>(BufStr)
Chris Lattnerb088cd32010-11-23 08:50:03 +0000155 .StartsWith("\xFE\xFF", "UTF-16 (BE)")
156 .StartsWith("\xFF\xFE", "UTF-16 (LE)")
157 .StartsWith("\x00\x00\xFE\xFF", "UTF-32 (BE)")
158 .StartsWith("\xFF\xFE\x00\x00", "UTF-32 (LE)")
159 .StartsWith("\x2B\x2F\x76", "UTF-7")
160 .StartsWith("\xF7\x64\x4C", "UTF-1")
161 .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
162 .StartsWith("\x0E\xFE\xFF", "SDSU")
163 .StartsWith("\xFB\xEE\x28", "BOCU-1")
164 .StartsWith("\x84\x31\x95\x33", "GB-18030")
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700165 .Default(nullptr);
Chris Lattnerb088cd32010-11-23 08:50:03 +0000166
Eric Christopher156119d2011-04-09 00:01:04 +0000167 if (InvalidBOM) {
Chris Lattnerb088cd32010-11-23 08:50:03 +0000168 Diag.Report(Loc, diag::err_unsupported_bom)
Eric Christopher156119d2011-04-09 00:01:04 +0000169 << InvalidBOM << ContentsEntry->getName();
Chris Lattnerb088cd32010-11-23 08:50:03 +0000170 Buffer.setInt(Buffer.getInt() | InvalidFlag);
Ted Kremenek5b034ad2009-01-06 22:43:04 +0000171 }
Douglas Gregoraea67db2010-03-15 22:54:52 +0000172
Douglas Gregorc8151082010-03-16 22:53:51 +0000173 if (Invalid)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000174 *Invalid = isBufferInvalid();
Douglas Gregorc8151082010-03-16 22:53:51 +0000175
176 return Buffer.getPointer();
Ted Kremenekc16c2082009-01-06 01:55:26 +0000177}
178
Chris Lattner5f9e2722011-07-23 10:55:15 +0000179unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) {
Stephen Hines176edba2014-12-01 14:53:08 -0800180 auto IterBool =
181 FilenameIDs.insert(std::make_pair(Name, FilenamesByID.size()));
182 if (IterBool.second)
183 FilenamesByID.push_back(&*IterBool.first);
184 return IterBool.first->second;
Chris Lattner5b9a5042009-01-26 07:57:50 +0000185}
186
Chris Lattnerac50e342009-02-03 22:13:05 +0000187/// AddLineNote - Add a line note to the line table that indicates that there
James Dennett7285a062012-06-15 21:28:23 +0000188/// is a \#line at the specified FID/Offset location which changes the presumed
Chris Lattnerac50e342009-02-03 22:13:05 +0000189/// location to LineNo/FilenameID.
Douglas Gregor47d9de62012-06-08 16:40:28 +0000190void LineTableInfo::AddLineNote(FileID FID, unsigned Offset,
Chris Lattnerac50e342009-02-03 22:13:05 +0000191 unsigned LineNo, int FilenameID) {
Chris Lattner23b5dc62009-02-04 00:40:31 +0000192 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump1eb44332009-09-09 15:08:12 +0000193
Chris Lattner23b5dc62009-02-04 00:40:31 +0000194 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
195 "Adding line entries out of order!");
Mike Stump1eb44332009-09-09 15:08:12 +0000196
Chris Lattner9d79eba2009-02-04 05:21:58 +0000197 SrcMgr::CharacteristicKind Kind = SrcMgr::C_User;
Chris Lattner137b6a62009-02-04 06:25:26 +0000198 unsigned IncludeOffset = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000199
Chris Lattner9d79eba2009-02-04 05:21:58 +0000200 if (!Entries.empty()) {
201 // If this is a '#line 4' after '#line 42 "foo.h"', make sure to remember
202 // that we are still in "foo.h".
203 if (FilenameID == -1)
204 FilenameID = Entries.back().FilenameID;
Mike Stump1eb44332009-09-09 15:08:12 +0000205
Chris Lattner137b6a62009-02-04 06:25:26 +0000206 // If we are after a line marker that switched us to system header mode, or
207 // that set #include information, preserve it.
Chris Lattner9d79eba2009-02-04 05:21:58 +0000208 Kind = Entries.back().FileKind;
Chris Lattner137b6a62009-02-04 06:25:26 +0000209 IncludeOffset = Entries.back().IncludeOffset;
Chris Lattner9d79eba2009-02-04 05:21:58 +0000210 }
Mike Stump1eb44332009-09-09 15:08:12 +0000211
Chris Lattner137b6a62009-02-04 06:25:26 +0000212 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, Kind,
213 IncludeOffset));
Chris Lattnerac50e342009-02-03 22:13:05 +0000214}
215
Chris Lattner9d79eba2009-02-04 05:21:58 +0000216/// AddLineNote This is the same as the previous version of AddLineNote, but is
217/// used for GNU line markers. If EntryExit is 0, then this doesn't change the
James Dennettb8950b82012-06-17 03:22:59 +0000218/// presumed \#include stack. If it is 1, this is a file entry, if it is 2 then
Chris Lattner9d79eba2009-02-04 05:21:58 +0000219/// this is a file exit. FileKind specifies whether this is a system header or
220/// extern C system header.
Douglas Gregor47d9de62012-06-08 16:40:28 +0000221void LineTableInfo::AddLineNote(FileID FID, unsigned Offset,
Chris Lattner9d79eba2009-02-04 05:21:58 +0000222 unsigned LineNo, int FilenameID,
223 unsigned EntryExit,
224 SrcMgr::CharacteristicKind FileKind) {
225 assert(FilenameID != -1 && "Unspecified filename should use other accessor");
Mike Stump1eb44332009-09-09 15:08:12 +0000226
Chris Lattner9d79eba2009-02-04 05:21:58 +0000227 std::vector<LineEntry> &Entries = LineEntries[FID];
Mike Stump1eb44332009-09-09 15:08:12 +0000228
Chris Lattner9d79eba2009-02-04 05:21:58 +0000229 assert((Entries.empty() || Entries.back().FileOffset < Offset) &&
230 "Adding line entries out of order!");
231
Chris Lattner137b6a62009-02-04 06:25:26 +0000232 unsigned IncludeOffset = 0;
233 if (EntryExit == 0) { // No #include stack change.
234 IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset;
235 } else if (EntryExit == 1) {
236 IncludeOffset = Offset-1;
237 } else if (EntryExit == 2) {
238 assert(!Entries.empty() && Entries.back().IncludeOffset &&
239 "PPDirectives should have caught case when popping empty include stack");
Mike Stump1eb44332009-09-09 15:08:12 +0000240
Chris Lattner137b6a62009-02-04 06:25:26 +0000241 // Get the include loc of the last entries' include loc as our include loc.
242 IncludeOffset = 0;
243 if (const LineEntry *PrevEntry =
244 FindNearestLineEntry(FID, Entries.back().IncludeOffset))
245 IncludeOffset = PrevEntry->IncludeOffset;
246 }
Mike Stump1eb44332009-09-09 15:08:12 +0000247
Chris Lattner137b6a62009-02-04 06:25:26 +0000248 Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind,
249 IncludeOffset));
Chris Lattner9d79eba2009-02-04 05:21:58 +0000250}
251
252
Chris Lattner3cd949c2009-02-04 01:55:42 +0000253/// FindNearestLineEntry - Find the line entry nearest to FID that is before
254/// it. If there is no line entry before Offset in FID, return null.
Douglas Gregor47d9de62012-06-08 16:40:28 +0000255const LineEntry *LineTableInfo::FindNearestLineEntry(FileID FID,
Chris Lattner3cd949c2009-02-04 01:55:42 +0000256 unsigned Offset) {
257 const std::vector<LineEntry> &Entries = LineEntries[FID];
258 assert(!Entries.empty() && "No #line entries for this FID after all!");
259
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000260 // It is very common for the query to be after the last #line, check this
261 // first.
262 if (Entries.back().FileOffset <= Offset)
263 return &Entries.back();
Chris Lattner3cd949c2009-02-04 01:55:42 +0000264
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000265 // Do a binary search to find the maximal element that is still before Offset.
266 std::vector<LineEntry>::const_iterator I =
267 std::upper_bound(Entries.begin(), Entries.end(), Offset);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700268 if (I == Entries.begin()) return nullptr;
Chris Lattner6c1fbe02009-02-04 04:46:59 +0000269 return &*--I;
Chris Lattner3cd949c2009-02-04 01:55:42 +0000270}
Chris Lattnerac50e342009-02-03 22:13:05 +0000271
Douglas Gregorbd945002009-04-13 16:31:14 +0000272/// \brief Add a new line entry that has already been encoded into
273/// the internal representation of the line table.
Douglas Gregor47d9de62012-06-08 16:40:28 +0000274void LineTableInfo::AddEntry(FileID FID,
Douglas Gregorbd945002009-04-13 16:31:14 +0000275 const std::vector<LineEntry> &Entries) {
276 LineEntries[FID] = Entries;
277}
Chris Lattnerac50e342009-02-03 22:13:05 +0000278
Chris Lattner5b9a5042009-01-26 07:57:50 +0000279/// getLineTableFilenameID - Return the uniqued ID for the specified filename.
Mike Stump1eb44332009-09-09 15:08:12 +0000280///
Chris Lattner5f9e2722011-07-23 10:55:15 +0000281unsigned SourceManager::getLineTableFilenameID(StringRef Name) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700282 if (!LineTable)
Chris Lattner5b9a5042009-01-26 07:57:50 +0000283 LineTable = new LineTableInfo();
Jay Foad65aa6882011-06-21 15:13:30 +0000284 return LineTable->getLineTableFilenameID(Name);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000285}
286
287
Chris Lattner4c4ea172009-02-03 21:52:55 +0000288/// AddLineNote - Add a line note to the line table for the FileID and offset
289/// specified by Loc. If FilenameID is -1, it is considered to be
290/// unspecified.
291void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
292 int FilenameID) {
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000293 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000294
Douglas Gregore23ac652011-04-20 00:21:03 +0000295 bool Invalid = false;
296 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
297 if (!Entry.isFile() || Invalid)
298 return;
299
300 const SrcMgr::FileInfo &FileInfo = Entry.getFile();
Chris Lattnerac50e342009-02-03 22:13:05 +0000301
302 // Remember that this file has #line directives now if it doesn't already.
303 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump1eb44332009-09-09 15:08:12 +0000304
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700305 if (!LineTable)
Chris Lattnerac50e342009-02-03 22:13:05 +0000306 LineTable = new LineTableInfo();
Douglas Gregor47d9de62012-06-08 16:40:28 +0000307 LineTable->AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID);
Chris Lattner4c4ea172009-02-03 21:52:55 +0000308}
309
Chris Lattner9d79eba2009-02-04 05:21:58 +0000310/// AddLineNote - Add a GNU line marker to the line table.
311void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo,
312 int FilenameID, bool IsFileEntry,
313 bool IsFileExit, bool IsSystemHeader,
314 bool IsExternCHeader) {
315 // If there is no filename and no flags, this is treated just like a #line,
316 // which does not change the flags of the previous line marker.
317 if (FilenameID == -1) {
318 assert(!IsFileEntry && !IsFileExit && !IsSystemHeader && !IsExternCHeader &&
319 "Can't set flags without setting the filename!");
320 return AddLineNote(Loc, LineNo, FilenameID);
321 }
Mike Stump1eb44332009-09-09 15:08:12 +0000322
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000323 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Douglas Gregore23ac652011-04-20 00:21:03 +0000324
325 bool Invalid = false;
326 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
327 if (!Entry.isFile() || Invalid)
328 return;
329
330 const SrcMgr::FileInfo &FileInfo = Entry.getFile();
Mike Stump1eb44332009-09-09 15:08:12 +0000331
Chris Lattner9d79eba2009-02-04 05:21:58 +0000332 // Remember that this file has #line directives now if it doesn't already.
333 const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives();
Mike Stump1eb44332009-09-09 15:08:12 +0000334
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700335 if (!LineTable)
Chris Lattner9d79eba2009-02-04 05:21:58 +0000336 LineTable = new LineTableInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000337
Chris Lattner9d79eba2009-02-04 05:21:58 +0000338 SrcMgr::CharacteristicKind FileKind;
339 if (IsExternCHeader)
340 FileKind = SrcMgr::C_ExternCSystem;
341 else if (IsSystemHeader)
342 FileKind = SrcMgr::C_System;
343 else
344 FileKind = SrcMgr::C_User;
Mike Stump1eb44332009-09-09 15:08:12 +0000345
Chris Lattner9d79eba2009-02-04 05:21:58 +0000346 unsigned EntryExit = 0;
347 if (IsFileEntry)
348 EntryExit = 1;
349 else if (IsFileExit)
350 EntryExit = 2;
Mike Stump1eb44332009-09-09 15:08:12 +0000351
Douglas Gregor47d9de62012-06-08 16:40:28 +0000352 LineTable->AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID,
Chris Lattner9d79eba2009-02-04 05:21:58 +0000353 EntryExit, FileKind);
354}
355
Douglas Gregorbd945002009-04-13 16:31:14 +0000356LineTableInfo &SourceManager::getLineTable() {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700357 if (!LineTable)
Douglas Gregorbd945002009-04-13 16:31:14 +0000358 LineTable = new LineTableInfo();
359 return *LineTable;
360}
Chris Lattner4c4ea172009-02-03 21:52:55 +0000361
Chris Lattner23b5dc62009-02-04 00:40:31 +0000362//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000363// Private 'Create' methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000364//===----------------------------------------------------------------------===//
Ted Kremenekc16c2082009-01-06 01:55:26 +0000365
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000366SourceManager::SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr,
367 bool UserFilesAreVolatile)
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +0000368 : Diag(Diag), FileMgr(FileMgr), OverridenFilesKeepOriginalName(true),
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000369 UserFilesAreVolatile(UserFilesAreVolatile),
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700370 ExternalSLocEntries(nullptr), LineTable(nullptr), NumLinearScans(0),
Stephen Hines176edba2014-12-01 14:53:08 -0800371 NumBinaryProbes(0) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000372 clearIDTables();
373 Diag.setSourceManager(this);
374}
375
Chris Lattner5b9a5042009-01-26 07:57:50 +0000376SourceManager::~SourceManager() {
377 delete LineTable;
Mike Stump1eb44332009-09-09 15:08:12 +0000378
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000379 // Delete FileEntry objects corresponding to content caches. Since the actual
380 // content cache objects are bump pointer allocated, we just have to run the
381 // dtors, but we call the deallocate method for completeness.
382 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
Argyrios Kyrtzidis99ee0852011-12-15 23:37:55 +0000383 if (MemBufferInfos[i]) {
384 MemBufferInfos[i]->~ContentCache();
385 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
386 }
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000387 }
388 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
389 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
Argyrios Kyrtzidis99ee0852011-12-15 23:37:55 +0000390 if (I->second) {
391 I->second->~ContentCache();
392 ContentCacheAlloc.Deallocate(I->second);
393 }
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000394 }
Argyrios Kyrtzidisfb3612e2011-09-26 08:01:50 +0000395
Stephen Hines651f13c2014-04-23 16:59:28 -0700396 llvm::DeleteContainerSeconds(MacroArgsCacheMap);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000397}
398
399void SourceManager::clearIDTables() {
400 MainFileID = FileID();
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000401 LocalSLocEntryTable.clear();
402 LoadedSLocEntryTable.clear();
403 SLocEntryLoaded.clear();
Chris Lattner5b9a5042009-01-26 07:57:50 +0000404 LastLineNoFileIDQuery = FileID();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700405 LastLineNoContentCache = nullptr;
Chris Lattner5b9a5042009-01-26 07:57:50 +0000406 LastFileIDLookup = FileID();
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Chris Lattner5b9a5042009-01-26 07:57:50 +0000408 if (LineTable)
409 LineTable->clear();
Mike Stump1eb44332009-09-09 15:08:12 +0000410
Chandler Carruth3201f382011-07-26 05:17:23 +0000411 // Use up FileID #0 as an invalid expansion.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000412 NextLocalOffset = 0;
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +0000413 CurrentLoadedOffset = MaxLoadedOffset;
Chandler Carruthbf340e42011-07-26 03:03:05 +0000414 createExpansionLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000415}
416
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000417/// getOrCreateContentCache - Create or return a cached ContentCache for the
418/// specified file.
419const ContentCache *
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000420SourceManager::getOrCreateContentCache(const FileEntry *FileEnt,
421 bool isSystemFile) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000422 assert(FileEnt && "Didn't specify a file entry to use?");
Mike Stump1eb44332009-09-09 15:08:12 +0000423
Reid Spencer5f016e22007-07-11 17:01:13 +0000424 // Do we already have information about this file?
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000425 ContentCache *&Entry = FileInfos[FileEnt];
426 if (Entry) return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +0000427
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700428 // Nope, create a new Cache entry.
429 Entry = ContentCacheAlloc.Allocate<ContentCache>();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000430
Argyrios Kyrtzidisd54dff02012-05-03 21:50:39 +0000431 if (OverriddenFilesInfo) {
432 // If the file contents are overridden with contents from another file,
433 // pass that file to ContentCache.
434 llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
435 overI = OverriddenFilesInfo->OverriddenFiles.find(FileEnt);
436 if (overI == OverriddenFilesInfo->OverriddenFiles.end())
437 new (Entry) ContentCache(FileEnt);
438 else
439 new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt
440 : overI->second,
441 overI->second);
442 } else {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000443 new (Entry) ContentCache(FileEnt);
Argyrios Kyrtzidisd54dff02012-05-03 21:50:39 +0000444 }
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000445
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000446 Entry->IsSystemFile = isSystemFile;
447
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000448 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000449}
450
451
Ted Kremenekd1c0eee2007-10-31 17:53:38 +0000452/// createMemBufferContentCache - Create a new ContentCache for the specified
453/// memory buffer. This does no caching.
Stephen Hines176edba2014-12-01 14:53:08 -0800454const ContentCache *SourceManager::createMemBufferContentCache(
455 std::unique_ptr<llvm::MemoryBuffer> Buffer) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700456 // Add a new ContentCache to the MemBufferInfos list and return it.
457 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>();
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000458 new (Entry) ContentCache();
459 MemBufferInfos.push_back(Entry);
Stephen Hines176edba2014-12-01 14:53:08 -0800460 Entry->setBuffer(std::move(Buffer));
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000461 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000462}
463
Argyrios Kyrtzidisa4c29b62012-02-20 23:58:07 +0000464const SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index,
465 bool *Invalid) const {
466 assert(!SLocEntryLoaded[Index]);
467 if (ExternalSLocEntries->ReadSLocEntry(-(static_cast<int>(Index) + 2))) {
468 if (Invalid)
469 *Invalid = true;
470 // If the file of the SLocEntry changed we could still have loaded it.
471 if (!SLocEntryLoaded[Index]) {
472 // Try to recover; create a SLocEntry so the rest of clang can handle it.
473 LoadedSLocEntryTable[Index] = SLocEntry::get(0,
474 FileInfo::get(SourceLocation(),
475 getFakeContentCacheForRecovery(),
476 SrcMgr::C_User));
477 }
478 }
479
480 return LoadedSLocEntryTable[Index];
481}
482
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000483std::pair<int, unsigned>
484SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries,
485 unsigned TotalSize) {
486 assert(ExternalSLocEntries && "Don't have an external sloc source");
487 LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries);
488 SLocEntryLoaded.resize(LoadedSLocEntryTable.size());
489 CurrentLoadedOffset -= TotalSize;
490 assert(CurrentLoadedOffset >= NextLocalOffset && "Out of source locations");
491 int ID = LoadedSLocEntryTable.size();
492 return std::make_pair(-ID - 1, CurrentLoadedOffset);
Douglas Gregor2bf1eb02009-04-27 21:28:04 +0000493}
494
Douglas Gregore23ac652011-04-20 00:21:03 +0000495/// \brief As part of recovering from missing or changed content, produce a
496/// fake, non-empty buffer.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700497llvm::MemoryBuffer *SourceManager::getFakeBufferForRecovery() const {
Douglas Gregore23ac652011-04-20 00:21:03 +0000498 if (!FakeBufferForRecovery)
Stephen Hines176edba2014-12-01 14:53:08 -0800499 FakeBufferForRecovery =
500 llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");
501
502 return FakeBufferForRecovery.get();
Douglas Gregore23ac652011-04-20 00:21:03 +0000503}
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000504
Argyrios Kyrtzidisa4c29b62012-02-20 23:58:07 +0000505/// \brief As part of recovering from missing or changed content, produce a
506/// fake content cache.
507const SrcMgr::ContentCache *
508SourceManager::getFakeContentCacheForRecovery() const {
509 if (!FakeContentCacheForRecovery) {
Stephen Hines176edba2014-12-01 14:53:08 -0800510 FakeContentCacheForRecovery = llvm::make_unique<SrcMgr::ContentCache>();
Argyrios Kyrtzidisa4c29b62012-02-20 23:58:07 +0000511 FakeContentCacheForRecovery->replaceBuffer(getFakeBufferForRecovery(),
512 /*DoNotFree=*/true);
513 }
Stephen Hines176edba2014-12-01 14:53:08 -0800514 return FakeContentCacheForRecovery.get();
Argyrios Kyrtzidisa4c29b62012-02-20 23:58:07 +0000515}
516
Argyrios Kyrtzidisc50c6ff2013-05-16 21:37:39 +0000517/// \brief Returns the previous in-order FileID or an invalid FileID if there
518/// is no previous one.
519FileID SourceManager::getPreviousFileID(FileID FID) const {
520 if (FID.isInvalid())
521 return FileID();
522
523 int ID = FID.ID;
524 if (ID == -1)
525 return FileID();
526
527 if (ID > 0) {
528 if (ID-1 == 0)
529 return FileID();
530 } else if (unsigned(-(ID-1) - 2) >= LoadedSLocEntryTable.size()) {
531 return FileID();
532 }
533
534 return FileID::get(ID-1);
535}
536
537/// \brief Returns the next in-order FileID or an invalid FileID if there is
538/// no next one.
539FileID SourceManager::getNextFileID(FileID FID) const {
540 if (FID.isInvalid())
541 return FileID();
542
543 int ID = FID.ID;
544 if (ID > 0) {
545 if (unsigned(ID+1) >= local_sloc_entry_size())
546 return FileID();
547 } else if (ID+1 >= -1) {
548 return FileID();
549 }
550
551 return FileID::get(ID+1);
552}
553
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000554//===----------------------------------------------------------------------===//
Chandler Carruth3201f382011-07-26 05:17:23 +0000555// Methods to create new FileID's and macro expansions.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000556//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000557
Dan Gohman3f86b782010-08-26 21:27:06 +0000558/// createFileID - Create a new FileID for the specified ContentCache and
Ted Kremenek0d892d82007-10-30 22:57:35 +0000559/// include position. This works regardless of whether the ContentCache
560/// corresponds to a file or some other input source.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000561FileID SourceManager::createFileID(const ContentCache *File,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000562 SourceLocation IncludePos,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000563 SrcMgr::CharacteristicKind FileCharacter,
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000564 int LoadedID, unsigned LoadedOffset) {
565 if (LoadedID < 0) {
566 assert(LoadedID != -1 && "Loading sentinel FileID");
567 unsigned Index = unsigned(-LoadedID) - 2;
568 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
569 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
570 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset,
571 FileInfo::get(IncludePos, File, FileCharacter));
572 SLocEntryLoaded[Index] = true;
573 return FileID::get(LoadedID);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000574 }
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000575 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset,
576 FileInfo::get(IncludePos, File,
577 FileCharacter)));
Ted Kremenekc16c2082009-01-06 01:55:26 +0000578 unsigned FileSize = File->getSize();
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000579 assert(NextLocalOffset + FileSize + 1 > NextLocalOffset &&
580 NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset &&
581 "Ran out of source locations!");
582 // We do a +1 here because we want a SourceLocation that means "the end of the
583 // file", e.g. for the "no newline at the end of the file" diagnostic.
584 NextLocalOffset += FileSize + 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000585
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000586 // Set LastFileIDLookup to the newly created file. The next getFileID call is
587 // almost guaranteed to be from that file.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000588 FileID FID = FileID::get(LocalSLocEntryTable.size()-1);
Argyrios Kyrtzidisea703f12009-06-23 00:42:06 +0000589 return LastFileIDLookup = FID;
Reid Spencer5f016e22007-07-11 17:01:13 +0000590}
591
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000592SourceLocation
Chandler Carruthbf340e42011-07-26 03:03:05 +0000593SourceManager::createMacroArgExpansionLoc(SourceLocation SpellingLoc,
594 SourceLocation ExpansionLoc,
595 unsigned TokLength) {
Chandler Carruth78df8362011-07-26 04:41:47 +0000596 ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc,
597 ExpansionLoc);
598 return createExpansionLocImpl(Info, TokLength);
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000599}
600
601SourceLocation
Chandler Carruthbf340e42011-07-26 03:03:05 +0000602SourceManager::createExpansionLoc(SourceLocation SpellingLoc,
603 SourceLocation ExpansionLocStart,
604 SourceLocation ExpansionLocEnd,
605 unsigned TokLength,
606 int LoadedID,
607 unsigned LoadedOffset) {
Chandler Carruth78df8362011-07-26 04:41:47 +0000608 ExpansionInfo Info = ExpansionInfo::create(SpellingLoc, ExpansionLocStart,
609 ExpansionLocEnd);
610 return createExpansionLocImpl(Info, TokLength, LoadedID, LoadedOffset);
Chandler Carruthbf340e42011-07-26 03:03:05 +0000611}
612
613SourceLocation
Chandler Carruth78df8362011-07-26 04:41:47 +0000614SourceManager::createExpansionLocImpl(const ExpansionInfo &Info,
Chandler Carruthbf340e42011-07-26 03:03:05 +0000615 unsigned TokLength,
616 int LoadedID,
617 unsigned LoadedOffset) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000618 if (LoadedID < 0) {
619 assert(LoadedID != -1 && "Loading sentinel FileID");
620 unsigned Index = unsigned(-LoadedID) - 2;
621 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
622 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
Chandler Carruth78df8362011-07-26 04:41:47 +0000623 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info);
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000624 SLocEntryLoaded[Index] = true;
625 return SourceLocation::getMacroLoc(LoadedOffset);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000626 }
Chandler Carruth78df8362011-07-26 04:41:47 +0000627 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000628 assert(NextLocalOffset + TokLength + 1 > NextLocalOffset &&
629 NextLocalOffset + TokLength + 1 <= CurrentLoadedOffset &&
630 "Ran out of source locations!");
631 // See createFileID for that +1.
632 NextLocalOffset += TokLength + 1;
633 return SourceLocation::getMacroLoc(NextLocalOffset - (TokLength + 1));
Reid Spencer5f016e22007-07-11 17:01:13 +0000634}
635
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700636llvm::MemoryBuffer *SourceManager::getMemoryBufferForFile(const FileEntry *File,
637 bool *Invalid) {
Douglas Gregor29684422009-12-02 06:49:09 +0000638 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
Douglas Gregoraea67db2010-03-15 22:54:52 +0000639 assert(IR && "getOrCreateContentCache() cannot return NULL");
Chris Lattnere127a0d2010-04-20 20:35:58 +0000640 return IR->getBuffer(Diag, *this, SourceLocation(), Invalid);
Douglas Gregor29684422009-12-02 06:49:09 +0000641}
642
Dan Gohman0d06e992010-10-26 20:47:28 +0000643void SourceManager::overrideFileContents(const FileEntry *SourceFile,
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700644 llvm::MemoryBuffer *Buffer,
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000645 bool DoNotFree) {
Douglas Gregor29684422009-12-02 06:49:09 +0000646 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
Dan Gohman0d06e992010-10-26 20:47:28 +0000647 assert(IR && "getOrCreateContentCache() cannot return NULL");
Douglas Gregor29684422009-12-02 06:49:09 +0000648
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000649 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree);
Douglas Gregora081da52011-11-16 20:05:18 +0000650 const_cast<SrcMgr::ContentCache *>(IR)->BufferOverridden = true;
Argyrios Kyrtzidisd54dff02012-05-03 21:50:39 +0000651
652 getOverriddenFilesInfo().OverriddenFilesWithBuffer.insert(SourceFile);
Douglas Gregor29684422009-12-02 06:49:09 +0000653}
654
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000655void SourceManager::overrideFileContents(const FileEntry *SourceFile,
656 const FileEntry *NewFile) {
657 assert(SourceFile->getSize() == NewFile->getSize() &&
658 "Different sizes, use the FileManager to create a virtual file with "
659 "the correct size");
660 assert(FileInfos.count(SourceFile) == 0 &&
661 "This function should be called at the initialization stage, before "
662 "any parsing occurs.");
Argyrios Kyrtzidisd54dff02012-05-03 21:50:39 +0000663 getOverriddenFilesInfo().OverriddenFiles[SourceFile] = NewFile;
664}
665
666void SourceManager::disableFileContentsOverride(const FileEntry *File) {
667 if (!isFileOverridden(File))
668 return;
669
670 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700671 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(nullptr);
Argyrios Kyrtzidisd54dff02012-05-03 21:50:39 +0000672 const_cast<SrcMgr::ContentCache *>(IR)->ContentsEntry = IR->OrigEntry;
673
674 assert(OverriddenFilesInfo);
675 OverriddenFilesInfo->OverriddenFiles.erase(File);
676 OverriddenFilesInfo->OverriddenFilesWithBuffer.erase(File);
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000677}
678
Chris Lattner5f9e2722011-07-23 10:55:15 +0000679StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
Douglas Gregoraae58b02010-03-16 20:01:30 +0000680 bool MyInvalid = false;
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000681 const SLocEntry &SLoc = getSLocEntry(FID, &MyInvalid);
Douglas Gregore23ac652011-04-20 00:21:03 +0000682 if (!SLoc.isFile() || MyInvalid) {
Douglas Gregor3de84242011-01-31 22:42:36 +0000683 if (Invalid)
684 *Invalid = true;
685 return "<<<<<INVALID SOURCE LOCATION>>>>>";
686 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700687
688 llvm::MemoryBuffer *Buf = SLoc.getFile().getContentCache()->getBuffer(
689 Diag, *this, SourceLocation(), &MyInvalid);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000690 if (Invalid)
Douglas Gregoraae58b02010-03-16 20:01:30 +0000691 *Invalid = MyInvalid;
692
693 if (MyInvalid)
Douglas Gregor3de84242011-01-31 22:42:36 +0000694 return "<<<<<INVALID SOURCE LOCATION>>>>>";
Douglas Gregoraae58b02010-03-16 20:01:30 +0000695
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000696 return Buf->getBuffer();
Douglas Gregoraea67db2010-03-15 22:54:52 +0000697}
Chris Lattner2b2453a2009-01-17 06:22:33 +0000698
Chris Lattner23b5dc62009-02-04 00:40:31 +0000699//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000700// SourceLocation manipulation methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000701//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000702
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000703/// \brief Return the FileID for a SourceLocation.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000704///
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000705/// This is the cache-miss path of getFileID. Not as hot as that function, but
706/// still very important. It is responsible for finding the entry in the
707/// SLocEntry tables that contains the specified location.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000708FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
Douglas Gregore23ac652011-04-20 00:21:03 +0000709 if (!SLocOffset)
710 return FileID::get(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000711
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000712 // Now it is time to search for the correct file. See where the SLocOffset
713 // sits in the global view and consult local or loaded buffers for it.
714 if (SLocOffset < NextLocalOffset)
715 return getFileIDLocal(SLocOffset);
716 return getFileIDLoaded(SLocOffset);
717}
718
719/// \brief Return the FileID for a SourceLocation with a low offset.
720///
721/// This function knows that the SourceLocation is in a local buffer, not a
722/// loaded one.
723FileID SourceManager::getFileIDLocal(unsigned SLocOffset) const {
724 assert(SLocOffset < NextLocalOffset && "Bad function choice");
725
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000726 // After the first and second level caches, I see two common sorts of
Chandler Carruth3201f382011-07-26 05:17:23 +0000727 // behavior: 1) a lot of searched FileID's are "near" the cached file
728 // location or are "near" the cached expansion location. 2) others are just
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000729 // completely random and may be a very long way away.
730 //
731 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
732 // then we fall back to a less cache efficient, but more scalable, binary
733 // search to find the location.
Mike Stump1eb44332009-09-09 15:08:12 +0000734
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000735 // See if this is near the file point - worst case we start scanning from the
736 // most newly created FileID.
Benjamin Kramerf512ace2013-02-22 18:29:39 +0000737 const SrcMgr::SLocEntry *I;
Mike Stump1eb44332009-09-09 15:08:12 +0000738
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000739 if (LastFileIDLookup.ID < 0 ||
740 LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000741 // Neither loc prunes our search.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000742 I = LocalSLocEntryTable.end();
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000743 } else {
744 // Perhaps it is near the file point.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000745 I = LocalSLocEntryTable.begin()+LastFileIDLookup.ID;
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000746 }
747
748 // Find the FileID that contains this. "I" is an iterator that points to a
749 // FileID whose offset is known to be larger than SLocOffset.
750 unsigned NumProbes = 0;
751 while (1) {
752 --I;
753 if (I->getOffset() <= SLocOffset) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000754 FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin()));
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000755
Chandler Carruth3201f382011-07-26 05:17:23 +0000756 // If this isn't an expansion, remember it. We have good locality across
757 // FileID lookups.
Chandler Carruth17287622011-07-26 04:56:51 +0000758 if (!I->isExpansion())
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000759 LastFileIDLookup = Res;
760 NumLinearScans += NumProbes+1;
761 return Res;
762 }
763 if (++NumProbes == 8)
764 break;
765 }
Mike Stump1eb44332009-09-09 15:08:12 +0000766
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000767 // Convert "I" back into an index. We know that it is an entry whose index is
768 // larger than the offset we are looking for.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000769 unsigned GreaterIndex = I - LocalSLocEntryTable.begin();
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000770 // LessIndex - This is the lower bound of the range that we're searching.
771 // We know that the offset corresponding to the FileID is is less than
772 // SLocOffset.
773 unsigned LessIndex = 0;
774 NumProbes = 0;
775 while (1) {
Douglas Gregore23ac652011-04-20 00:21:03 +0000776 bool Invalid = false;
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000777 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000778 unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset();
Douglas Gregore23ac652011-04-20 00:21:03 +0000779 if (Invalid)
780 return FileID::get(0);
781
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000782 ++NumProbes;
Mike Stump1eb44332009-09-09 15:08:12 +0000783
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000784 // If the offset of the midpoint is too large, chop the high side of the
785 // range to the midpoint.
786 if (MidOffset > SLocOffset) {
787 GreaterIndex = MiddleIndex;
788 continue;
789 }
Mike Stump1eb44332009-09-09 15:08:12 +0000790
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000791 // If the middle index contains the value, succeed and return.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000792 // FIXME: This could be made faster by using a function that's aware of
793 // being in the local area.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000794 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000795 FileID Res = FileID::get(MiddleIndex);
796
Chandler Carruth17287622011-07-26 04:56:51 +0000797 // If this isn't a macro expansion, remember it. We have good locality
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000798 // across FileID lookups.
Chandler Carruth17287622011-07-26 04:56:51 +0000799 if (!LocalSLocEntryTable[MiddleIndex].isExpansion())
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000800 LastFileIDLookup = Res;
801 NumBinaryProbes += NumProbes;
802 return Res;
803 }
Mike Stump1eb44332009-09-09 15:08:12 +0000804
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000805 // Otherwise, move the low-side up to the middle index.
806 LessIndex = MiddleIndex;
807 }
808}
809
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000810/// \brief Return the FileID for a SourceLocation with a high offset.
811///
812/// This function knows that the SourceLocation is in a loaded buffer, not a
813/// local one.
814FileID SourceManager::getFileIDLoaded(unsigned SLocOffset) const {
Argyrios Kyrtzidisc3b45752011-10-03 23:43:01 +0000815 // Sanity checking, otherwise a bug may lead to hanging in release build.
Argyrios Kyrtzidis82ccbe72011-10-25 00:29:44 +0000816 if (SLocOffset < CurrentLoadedOffset) {
817 assert(0 && "Invalid SLocOffset or bad function choice");
Argyrios Kyrtzidisc3b45752011-10-03 23:43:01 +0000818 return FileID();
Argyrios Kyrtzidis82ccbe72011-10-25 00:29:44 +0000819 }
Argyrios Kyrtzidisc3b45752011-10-03 23:43:01 +0000820
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000821 // Essentially the same as the local case, but the loaded array is sorted
822 // in the other direction.
823
824 // First do a linear scan from the last lookup position, if possible.
825 unsigned I;
826 int LastID = LastFileIDLookup.ID;
827 if (LastID >= 0 || getLoadedSLocEntryByID(LastID).getOffset() < SLocOffset)
828 I = 0;
829 else
830 I = (-LastID - 2) + 1;
831
832 unsigned NumProbes;
833 for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++I) {
834 // Make sure the entry is loaded!
835 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(I);
836 if (E.getOffset() <= SLocOffset) {
837 FileID Res = FileID::get(-int(I) - 2);
838
Chandler Carruth17287622011-07-26 04:56:51 +0000839 if (!E.isExpansion())
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000840 LastFileIDLookup = Res;
841 NumLinearScans += NumProbes + 1;
842 return Res;
843 }
844 }
845
846 // Linear scan failed. Do the binary search. Note the reverse sorting of the
847 // table: GreaterIndex is the one where the offset is greater, which is
848 // actually a lower index!
849 unsigned GreaterIndex = I;
850 unsigned LessIndex = LoadedSLocEntryTable.size();
851 NumProbes = 0;
852 while (1) {
853 ++NumProbes;
854 unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex;
855 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(MiddleIndex);
Argyrios Kyrtzidis7db4bb92013-03-01 03:26:00 +0000856 if (E.getOffset() == 0)
857 return FileID(); // invalid entry.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000858
859 ++NumProbes;
860
861 if (E.getOffset() > SLocOffset) {
Argyrios Kyrtzidis7db4bb92013-03-01 03:26:00 +0000862 // Sanity checking, otherwise a bug may lead to hanging in release build.
863 if (GreaterIndex == MiddleIndex) {
864 assert(0 && "binary search missed the entry");
865 return FileID();
866 }
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000867 GreaterIndex = MiddleIndex;
868 continue;
869 }
870
871 if (isOffsetInFileID(FileID::get(-int(MiddleIndex) - 2), SLocOffset)) {
872 FileID Res = FileID::get(-int(MiddleIndex) - 2);
Chandler Carruth17287622011-07-26 04:56:51 +0000873 if (!E.isExpansion())
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000874 LastFileIDLookup = Res;
875 NumBinaryProbes += NumProbes;
876 return Res;
877 }
878
Argyrios Kyrtzidis838a9202013-03-01 03:43:33 +0000879 // Sanity checking, otherwise a bug may lead to hanging in release build.
880 if (LessIndex == MiddleIndex) {
881 assert(0 && "binary search missed the entry");
882 return FileID();
883 }
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000884 LessIndex = MiddleIndex;
885 }
886}
887
Chris Lattneraddb7972009-01-26 20:04:19 +0000888SourceLocation SourceManager::
Chandler Carruthf84ef952011-07-25 20:52:26 +0000889getExpansionLocSlowCase(SourceLocation Loc) const {
Chris Lattneraddb7972009-01-26 20:04:19 +0000890 do {
Chris Lattnera5c6c582010-02-12 19:31:35 +0000891 // Note: If Loc indicates an offset into a token that came from a macro
892 // expansion (e.g. the 5th character of the token) we do not want to add
Chandler Carruth17287622011-07-26 04:56:51 +0000893 // this offset when going to the expansion location. The expansion
Chris Lattnera5c6c582010-02-12 19:31:35 +0000894 // location is the macro invocation, which the offset has nothing to do
895 // with. This is unlike when we get the spelling loc, because the offset
896 // directly correspond to the token whose spelling we're inspecting.
Chandler Carruth17287622011-07-26 04:56:51 +0000897 Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart();
Chris Lattneraddb7972009-01-26 20:04:19 +0000898 } while (!Loc.isFileID());
899
900 return Loc;
901}
902
903SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
904 do {
905 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
Chandler Carruth17287622011-07-26 04:56:51 +0000906 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000907 Loc = Loc.getLocWithOffset(LocInfo.second);
Chris Lattneraddb7972009-01-26 20:04:19 +0000908 } while (!Loc.isFileID());
909 return Loc;
910}
911
Argyrios Kyrtzidis796dbfb2011-10-12 07:07:40 +0000912SourceLocation SourceManager::getFileLocSlowCase(SourceLocation Loc) const {
913 do {
914 if (isMacroArgExpansion(Loc))
915 Loc = getImmediateSpellingLoc(Loc);
916 else
917 Loc = getImmediateExpansionRange(Loc).first;
918 } while (!Loc.isFileID());
919 return Loc;
920}
921
Chris Lattneraddb7972009-01-26 20:04:19 +0000922
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000923std::pair<FileID, unsigned>
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000924SourceManager::getDecomposedExpansionLocSlowCase(
Argyrios Kyrtzidis8b86ef02011-07-07 03:40:27 +0000925 const SrcMgr::SLocEntry *E) const {
Chandler Carruth3201f382011-07-26 05:17:23 +0000926 // If this is an expansion record, walk through all the expansion points.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000927 FileID FID;
928 SourceLocation Loc;
Argyrios Kyrtzidis8b86ef02011-07-07 03:40:27 +0000929 unsigned Offset;
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000930 do {
Chandler Carruth17287622011-07-26 04:56:51 +0000931 Loc = E->getExpansion().getExpansionLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000932
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000933 FID = getFileID(Loc);
934 E = &getSLocEntry(FID);
Argyrios Kyrtzidis8b86ef02011-07-07 03:40:27 +0000935 Offset = Loc.getOffset()-E->getOffset();
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000936 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000937
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000938 return std::make_pair(FID, Offset);
939}
940
941std::pair<FileID, unsigned>
942SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
943 unsigned Offset) const {
Chandler Carruth3201f382011-07-26 05:17:23 +0000944 // If this is an expansion record, walk through all the expansion points.
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000945 FileID FID;
946 SourceLocation Loc;
947 do {
Chandler Carruth17287622011-07-26 04:56:51 +0000948 Loc = E->getExpansion().getSpellingLoc();
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000949 Loc = Loc.getLocWithOffset(Offset);
Mike Stump1eb44332009-09-09 15:08:12 +0000950
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000951 FID = getFileID(Loc);
952 E = &getSLocEntry(FID);
Argyrios Kyrtzidisb6c465e2011-08-23 21:02:41 +0000953 Offset = Loc.getOffset()-E->getOffset();
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000954 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000955
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000956 return std::make_pair(FID, Offset);
957}
958
Chris Lattner387616e2009-02-17 08:04:48 +0000959/// getImmediateSpellingLoc - Given a SourceLocation object, return the
960/// spelling location referenced by the ID. This is the first level down
961/// towards the place where the characters that make up the lexed token can be
962/// found. This should not generally be used by clients.
963SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
964 if (Loc.isFileID()) return Loc;
965 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
Chandler Carruth17287622011-07-26 04:56:51 +0000966 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000967 return Loc.getLocWithOffset(LocInfo.second);
Chris Lattner387616e2009-02-17 08:04:48 +0000968}
969
970
Chandler Carruth3201f382011-07-26 05:17:23 +0000971/// getImmediateExpansionRange - Loc is required to be an expansion location.
972/// Return the start/end of the expansion information.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000973std::pair<SourceLocation,SourceLocation>
Chandler Carruth999f7392011-07-25 20:52:21 +0000974SourceManager::getImmediateExpansionRange(SourceLocation Loc) const {
Chandler Carruth3201f382011-07-26 05:17:23 +0000975 assert(Loc.isMacroID() && "Not a macro expansion loc!");
Chandler Carruth17287622011-07-26 04:56:51 +0000976 const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion();
Chandler Carruth78df8362011-07-26 04:41:47 +0000977 return Expansion.getExpansionLocRange();
Chris Lattnere7fb4842009-02-15 20:52:18 +0000978}
979
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000980/// getExpansionRange - Given a SourceLocation object, return the range of
981/// tokens covered by the expansion in the ultimate file.
Chris Lattner66781332009-02-15 21:26:50 +0000982std::pair<SourceLocation,SourceLocation>
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000983SourceManager::getExpansionRange(SourceLocation Loc) const {
Chris Lattner66781332009-02-15 21:26:50 +0000984 if (Loc.isFileID()) return std::make_pair(Loc, Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000985
Chris Lattner66781332009-02-15 21:26:50 +0000986 std::pair<SourceLocation,SourceLocation> Res =
Chandler Carruth999f7392011-07-25 20:52:21 +0000987 getImmediateExpansionRange(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000988
Chandler Carruth3201f382011-07-26 05:17:23 +0000989 // Fully resolve the start and end locations to their ultimate expansion
Chris Lattner66781332009-02-15 21:26:50 +0000990 // points.
991 while (!Res.first.isFileID())
Chandler Carruth999f7392011-07-25 20:52:21 +0000992 Res.first = getImmediateExpansionRange(Res.first).first;
Chris Lattner66781332009-02-15 21:26:50 +0000993 while (!Res.second.isFileID())
Chandler Carruth999f7392011-07-25 20:52:21 +0000994 Res.second = getImmediateExpansionRange(Res.second).second;
Chris Lattner66781332009-02-15 21:26:50 +0000995 return Res;
996}
997
Chandler Carruth96d35892011-07-26 03:03:00 +0000998bool SourceManager::isMacroArgExpansion(SourceLocation Loc) const {
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000999 if (!Loc.isMacroID()) return false;
1000
1001 FileID FID = getFileID(Loc);
Matt Beaumont-Gayc3cd6f72013-01-12 00:54:16 +00001002 const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
Chandler Carruth78df8362011-07-26 04:41:47 +00001003 return Expansion.isMacroArgExpansion();
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +00001004}
Chris Lattnere7fb4842009-02-15 20:52:18 +00001005
Matt Beaumont-Gayc3cd6f72013-01-12 00:54:16 +00001006bool SourceManager::isMacroBodyExpansion(SourceLocation Loc) const {
1007 if (!Loc.isMacroID()) return false;
1008
1009 FileID FID = getFileID(Loc);
1010 const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion();
1011 return Expansion.isMacroBodyExpansion();
1012}
1013
Argyrios Kyrtzidisc50c6ff2013-05-16 21:37:39 +00001014bool SourceManager::isAtStartOfImmediateMacroExpansion(SourceLocation Loc,
1015 SourceLocation *MacroBegin) const {
1016 assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1017
1018 std::pair<FileID, unsigned> DecompLoc = getDecomposedLoc(Loc);
1019 if (DecompLoc.second > 0)
1020 return false; // Does not point at the start of expansion range.
1021
1022 bool Invalid = false;
1023 const SrcMgr::ExpansionInfo &ExpInfo =
1024 getSLocEntry(DecompLoc.first, &Invalid).getExpansion();
1025 if (Invalid)
1026 return false;
1027 SourceLocation ExpLoc = ExpInfo.getExpansionLocStart();
1028
1029 if (ExpInfo.isMacroArgExpansion()) {
1030 // For macro argument expansions, check if the previous FileID is part of
1031 // the same argument expansion, in which case this Loc is not at the
1032 // beginning of the expansion.
1033 FileID PrevFID = getPreviousFileID(DecompLoc.first);
1034 if (!PrevFID.isInvalid()) {
1035 const SrcMgr::SLocEntry &PrevEntry = getSLocEntry(PrevFID, &Invalid);
1036 if (Invalid)
1037 return false;
1038 if (PrevEntry.isExpansion() &&
1039 PrevEntry.getExpansion().getExpansionLocStart() == ExpLoc)
1040 return false;
1041 }
1042 }
1043
1044 if (MacroBegin)
1045 *MacroBegin = ExpLoc;
1046 return true;
1047}
1048
1049bool SourceManager::isAtEndOfImmediateMacroExpansion(SourceLocation Loc,
1050 SourceLocation *MacroEnd) const {
1051 assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc");
1052
1053 FileID FID = getFileID(Loc);
1054 SourceLocation NextLoc = Loc.getLocWithOffset(1);
1055 if (isInFileID(NextLoc, FID))
1056 return false; // Does not point at the end of expansion range.
1057
1058 bool Invalid = false;
1059 const SrcMgr::ExpansionInfo &ExpInfo =
1060 getSLocEntry(FID, &Invalid).getExpansion();
1061 if (Invalid)
1062 return false;
1063
1064 if (ExpInfo.isMacroArgExpansion()) {
1065 // For macro argument expansions, check if the next FileID is part of the
1066 // same argument expansion, in which case this Loc is not at the end of the
1067 // expansion.
1068 FileID NextFID = getNextFileID(FID);
1069 if (!NextFID.isInvalid()) {
1070 const SrcMgr::SLocEntry &NextEntry = getSLocEntry(NextFID, &Invalid);
1071 if (Invalid)
1072 return false;
1073 if (NextEntry.isExpansion() &&
1074 NextEntry.getExpansion().getExpansionLocStart() ==
1075 ExpInfo.getExpansionLocStart())
1076 return false;
1077 }
1078 }
1079
1080 if (MacroEnd)
1081 *MacroEnd = ExpInfo.getExpansionLocEnd();
1082 return true;
1083}
1084
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001085
1086//===----------------------------------------------------------------------===//
1087// Queries about the code at a SourceLocation.
1088//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00001089
1090/// getCharacterData - Return a pointer to the start of the specified location
1091/// in the appropriate MemoryBuffer.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001092const char *SourceManager::getCharacterData(SourceLocation SL,
1093 bool *Invalid) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001094 // Note that this is a hot function in the getSpelling() path, which is
1095 // heavily used by -E mode.
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001096 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
Mike Stump1eb44332009-09-09 15:08:12 +00001097
Ted Kremenekc16c2082009-01-06 01:55:26 +00001098 // Note that calling 'getBuffer()' may lazily page in a source file.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001099 bool CharDataInvalid = false;
Douglas Gregore23ac652011-04-20 00:21:03 +00001100 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
1101 if (CharDataInvalid || !Entry.isFile()) {
1102 if (Invalid)
1103 *Invalid = true;
1104
1105 return "<<<<INVALID BUFFER>>>>";
1106 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001107 llvm::MemoryBuffer *Buffer = Entry.getFile().getContentCache()->getBuffer(
1108 Diag, *this, SourceLocation(), &CharDataInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001109 if (Invalid)
1110 *Invalid = CharDataInvalid;
1111 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
Reid Spencer5f016e22007-07-11 17:01:13 +00001112}
1113
Reid Spencer5f016e22007-07-11 17:01:13 +00001114
Chris Lattner9dc1f532007-07-20 16:37:10 +00001115/// getColumnNumber - Return the column # for the specified file position.
Chris Lattner7da5aea2009-02-04 00:55:58 +00001116/// this is significantly cheaper to compute than the line number.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001117unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
1118 bool *Invalid) const {
1119 bool MyInvalid = false;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001120 llvm::MemoryBuffer *MemBuf = getBuffer(FID, &MyInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001121 if (Invalid)
1122 *Invalid = MyInvalid;
1123
1124 if (MyInvalid)
1125 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00001126
Jordan Rose2e413f92012-06-19 03:09:38 +00001127 // It is okay to request a position just past the end of the buffer.
1128 if (FilePos > MemBuf->getBufferSize()) {
Argyrios Kyrtzidisd5752542011-12-10 00:30:38 +00001129 if (Invalid)
Jordan Rose2e413f92012-06-19 03:09:38 +00001130 *Invalid = true;
Argyrios Kyrtzidisd5752542011-12-10 00:30:38 +00001131 return 1;
1132 }
1133
Craig Topperd9cad402012-10-19 04:40:38 +00001134 // See if we just calculated the line number for this FilePos and can use
1135 // that to lookup the start of the line instead of searching for it.
1136 if (LastLineNoFileIDQuery == FID &&
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001137 LastLineNoContentCache->SourceLineCache != nullptr &&
Craig Topperd53c2d32012-12-16 05:58:32 +00001138 LastLineNoResult < LastLineNoContentCache->NumLines) {
Craig Topperd9cad402012-10-19 04:40:38 +00001139 unsigned *SourceLineCache = LastLineNoContentCache->SourceLineCache;
1140 unsigned LineStart = SourceLineCache[LastLineNoResult - 1];
1141 unsigned LineEnd = SourceLineCache[LastLineNoResult];
1142 if (FilePos >= LineStart && FilePos < LineEnd)
1143 return FilePos - LineStart + 1;
1144 }
1145
Dylan Noblesmith098eaff2011-12-19 08:51:05 +00001146 const char *Buf = MemBuf->getBufferStart();
Reid Spencer5f016e22007-07-11 17:01:13 +00001147 unsigned LineStart = FilePos;
1148 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
1149 --LineStart;
1150 return FilePos-LineStart+1;
1151}
1152
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001153// isInvalid - Return the result of calling loc.isInvalid(), and
1154// if Invalid is not null, set its value to same.
1155static bool isInvalid(SourceLocation Loc, bool *Invalid) {
1156 bool MyInvalid = Loc.isInvalid();
1157 if (Invalid)
1158 *Invalid = MyInvalid;
1159 return MyInvalid;
1160}
1161
Douglas Gregor50f6af72010-03-16 05:20:39 +00001162unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
1163 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001164 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +00001165 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001166 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +00001167}
1168
Chandler Carrutha77c0312011-07-25 20:57:57 +00001169unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc,
1170 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001171 if (isInvalid(Loc, Invalid)) return 0;
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +00001172 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001173 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +00001174}
1175
Chandler Carruth5ef04ee2011-02-23 00:47:48 +00001176unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
1177 bool *Invalid) const {
1178 if (isInvalid(Loc, Invalid)) return 0;
1179 return getPresumedLoc(Loc).getColumn();
1180}
1181
Benjamin Kramerd2953ce2012-04-06 20:49:55 +00001182#ifdef __SSE2__
1183#include <emmintrin.h>
1184#endif
1185
Chandler Carruth14bd9652010-10-23 08:44:57 +00001186static LLVM_ATTRIBUTE_NOINLINE void
David Blaikied6471f72011-09-25 23:23:43 +00001187ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
Chris Lattnere127a0d2010-04-20 20:35:58 +00001188 llvm::BumpPtrAllocator &Alloc,
1189 const SourceManager &SM, bool &Invalid);
David Blaikied6471f72011-09-25 23:23:43 +00001190static void ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
Chris Lattnere127a0d2010-04-20 20:35:58 +00001191 llvm::BumpPtrAllocator &Alloc,
1192 const SourceManager &SM, bool &Invalid) {
Ted Kremenekc16c2082009-01-06 01:55:26 +00001193 // Note that calling 'getBuffer()' may lazily page in the file.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001194 MemoryBuffer *Buffer = FI->getBuffer(Diag, SM, SourceLocation(), &Invalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001195 if (Invalid)
1196 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001197
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001198 // Find the file offsets of all of the *physical* source lines. This does
1199 // not look at trigraphs, escaped newlines, or anything else tricky.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001200 SmallVector<unsigned, 256> LineOffsets;
Mike Stump1eb44332009-09-09 15:08:12 +00001201
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001202 // Line #1 starts at char 0.
1203 LineOffsets.push_back(0);
Mike Stump1eb44332009-09-09 15:08:12 +00001204
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001205 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
1206 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
1207 unsigned Offs = 0;
1208 while (1) {
1209 // Skip over the contents of the line.
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001210 const unsigned char *NextBuf = (const unsigned char *)Buf;
Benjamin Kramerd2953ce2012-04-06 20:49:55 +00001211
1212#ifdef __SSE2__
1213 // Try to skip to the next newline using SSE instructions. This is very
1214 // performance sensitive for programs with lots of diagnostics and in -E
1215 // mode.
1216 __m128i CRs = _mm_set1_epi8('\r');
1217 __m128i LFs = _mm_set1_epi8('\n');
1218
1219 // First fix up the alignment to 16 bytes.
1220 while (((uintptr_t)NextBuf & 0xF) != 0) {
1221 if (*NextBuf == '\n' || *NextBuf == '\r' || *NextBuf == '\0')
1222 goto FoundSpecialChar;
1223 ++NextBuf;
1224 }
1225
1226 // Scan 16 byte chunks for '\r' and '\n'. Ignore '\0'.
1227 while (NextBuf+16 <= End) {
Roman Divacky31ba6132012-09-06 15:59:27 +00001228 const __m128i Chunk = *(const __m128i*)NextBuf;
Benjamin Kramerd2953ce2012-04-06 20:49:55 +00001229 __m128i Cmp = _mm_or_si128(_mm_cmpeq_epi8(Chunk, CRs),
1230 _mm_cmpeq_epi8(Chunk, LFs));
1231 unsigned Mask = _mm_movemask_epi8(Cmp);
1232
1233 // If we found a newline, adjust the pointer and jump to the handling code.
1234 if (Mask != 0) {
Michael J. Spencer9779fdd2013-05-24 21:42:04 +00001235 NextBuf += llvm::countTrailingZeros(Mask);
Benjamin Kramerd2953ce2012-04-06 20:49:55 +00001236 goto FoundSpecialChar;
1237 }
1238 NextBuf += 16;
1239 }
1240#endif
1241
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001242 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
1243 ++NextBuf;
Benjamin Kramerd2953ce2012-04-06 20:49:55 +00001244
1245#ifdef __SSE2__
1246FoundSpecialChar:
1247#endif
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001248 Offs += NextBuf-Buf;
1249 Buf = NextBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00001250
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001251 if (Buf[0] == '\n' || Buf[0] == '\r') {
1252 // If this is \n\r or \r\n, skip both characters.
1253 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
1254 ++Offs, ++Buf;
1255 ++Offs, ++Buf;
1256 LineOffsets.push_back(Offs);
1257 } else {
1258 // Otherwise, this is a null. If end of file, exit.
1259 if (Buf == End) break;
1260 // Otherwise, skip the null.
1261 ++Offs, ++Buf;
1262 }
1263 }
Mike Stump1eb44332009-09-09 15:08:12 +00001264
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001265 // Copy the offsets into the FileInfo structure.
1266 FI->NumLines = LineOffsets.size();
Chris Lattner0d0bf8c2009-02-03 07:30:45 +00001267 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001268 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
1269}
Reid Spencer5f016e22007-07-11 17:01:13 +00001270
Chris Lattnerdf7c17a2009-01-16 07:00:02 +00001271/// getLineNumber - Given a SourceLocation, return the spelling line number
Reid Spencer5f016e22007-07-11 17:01:13 +00001272/// for the position indicated. This requires building and caching a table of
1273/// line offsets for the MemoryBuffer, so this is not cheap: use only when
1274/// about to emit a diagnostic.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001275unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
1276 bool *Invalid) const {
Argyrios Kyrtzidis5adc0512011-05-17 22:09:53 +00001277 if (FID.isInvalid()) {
1278 if (Invalid)
1279 *Invalid = true;
1280 return 1;
1281 }
1282
Chris Lattner2b2453a2009-01-17 06:22:33 +00001283 ContentCache *Content;
Chris Lattner30fc9332009-02-04 01:06:56 +00001284 if (LastLineNoFileIDQuery == FID)
Ted Kremenek78d85f52007-10-30 21:08:08 +00001285 Content = LastLineNoContentCache;
Douglas Gregore23ac652011-04-20 00:21:03 +00001286 else {
1287 bool MyInvalid = false;
1288 const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
1289 if (MyInvalid || !Entry.isFile()) {
1290 if (Invalid)
1291 *Invalid = true;
1292 return 1;
1293 }
1294
1295 Content = const_cast<ContentCache*>(Entry.getFile().getContentCache());
1296 }
1297
Reid Spencer5f016e22007-07-11 17:01:13 +00001298 // If this is the first use of line information for this buffer, compute the
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001299 /// SourceLineCache for it on demand.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001300 if (!Content->SourceLineCache) {
Douglas Gregor50f6af72010-03-16 05:20:39 +00001301 bool MyInvalid = false;
Chris Lattnere127a0d2010-04-20 20:35:58 +00001302 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001303 if (Invalid)
1304 *Invalid = MyInvalid;
1305 if (MyInvalid)
1306 return 1;
1307 } else if (Invalid)
1308 *Invalid = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001309
1310 // Okay, we know we have a line number table. Do a binary search to find the
1311 // line number that this character position lands on.
Ted Kremenek78d85f52007-10-30 21:08:08 +00001312 unsigned *SourceLineCache = Content->SourceLineCache;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001313 unsigned *SourceLineCacheStart = SourceLineCache;
Ted Kremenek78d85f52007-10-30 21:08:08 +00001314 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
Mike Stump1eb44332009-09-09 15:08:12 +00001315
Chris Lattner30fc9332009-02-04 01:06:56 +00001316 unsigned QueriedFilePos = FilePos+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001317
Daniel Dunbar4106d692009-05-18 17:30:52 +00001318 // FIXME: I would like to be convinced that this code is worth being as
Mike Stump1eb44332009-09-09 15:08:12 +00001319 // complicated as it is, binary search isn't that slow.
Daniel Dunbar4106d692009-05-18 17:30:52 +00001320 //
1321 // If it is worth being optimized, then in my opinion it could be more
1322 // performant, simpler, and more obviously correct by just "galloping" outward
1323 // from the queried file position. In fact, this could be incorporated into a
1324 // generic algorithm such as lower_bound_with_hint.
1325 //
1326 // If someone gives me a test case where this matters, and I will do it! - DWD
1327
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001328 // If the previous query was to the same file, we know both the file pos from
1329 // that query and the line number returned. This allows us to narrow the
1330 // search space from the entire file to something near the match.
Chris Lattner30fc9332009-02-04 01:06:56 +00001331 if (LastLineNoFileIDQuery == FID) {
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001332 if (QueriedFilePos >= LastLineNoFilePos) {
Daniel Dunbar4106d692009-05-18 17:30:52 +00001333 // FIXME: Potential overflow?
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001334 SourceLineCache = SourceLineCache+LastLineNoResult-1;
Mike Stump1eb44332009-09-09 15:08:12 +00001335
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001336 // The query is likely to be nearby the previous one. Here we check to
1337 // see if it is within 5, 10 or 20 lines. It can be far away in cases
1338 // where big comment blocks and vertical whitespace eat up lines but
1339 // contribute no tokens.
1340 if (SourceLineCache+5 < SourceLineCacheEnd) {
1341 if (SourceLineCache[5] > QueriedFilePos)
1342 SourceLineCacheEnd = SourceLineCache+5;
1343 else if (SourceLineCache+10 < SourceLineCacheEnd) {
1344 if (SourceLineCache[10] > QueriedFilePos)
1345 SourceLineCacheEnd = SourceLineCache+10;
1346 else if (SourceLineCache+20 < SourceLineCacheEnd) {
1347 if (SourceLineCache[20] > QueriedFilePos)
1348 SourceLineCacheEnd = SourceLineCache+20;
1349 }
1350 }
1351 }
1352 } else {
Daniel Dunbar4106d692009-05-18 17:30:52 +00001353 if (LastLineNoResult < Content->NumLines)
1354 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001355 }
1356 }
Mike Stump1eb44332009-09-09 15:08:12 +00001357
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001358 unsigned *Pos
1359 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001360 unsigned LineNo = Pos-SourceLineCacheStart;
Mike Stump1eb44332009-09-09 15:08:12 +00001361
Chris Lattner30fc9332009-02-04 01:06:56 +00001362 LastLineNoFileIDQuery = FID;
Ted Kremenek78d85f52007-10-30 21:08:08 +00001363 LastLineNoContentCache = Content;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001364 LastLineNoFilePos = QueriedFilePos;
1365 LastLineNoResult = LineNo;
1366 return LineNo;
Reid Spencer5f016e22007-07-11 17:01:13 +00001367}
1368
Chandler Carruth5ef04ee2011-02-23 00:47:48 +00001369unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
1370 bool *Invalid) const {
1371 if (isInvalid(Loc, Invalid)) return 0;
1372 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1373 return getLineNumber(LocInfo.first, LocInfo.second);
1374}
Chandler Carruth64211622011-07-25 21:09:52 +00001375unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc,
1376 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001377 if (isInvalid(Loc, Invalid)) return 0;
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +00001378 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Chris Lattner30fc9332009-02-04 01:06:56 +00001379 return getLineNumber(LocInfo.first, LocInfo.second);
1380}
Chandler Carruth5ef04ee2011-02-23 00:47:48 +00001381unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
Douglas Gregor50f6af72010-03-16 05:20:39 +00001382 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001383 if (isInvalid(Loc, Invalid)) return 0;
Chandler Carruth5ef04ee2011-02-23 00:47:48 +00001384 return getPresumedLoc(Loc).getLine();
Chris Lattner30fc9332009-02-04 01:06:56 +00001385}
1386
Chris Lattner6b306672009-02-04 05:33:01 +00001387/// getFileCharacteristic - return the file characteristic of the specified
Mike Stump1eb44332009-09-09 15:08:12 +00001388/// source location, indicating whether this is a normal file, a system
Chris Lattner6b306672009-02-04 05:33:01 +00001389/// header, or an "implicit extern C" system header.
1390///
1391/// This state can be modified with flags on GNU linemarker directives like:
1392/// # 4 "foo.h" 3
1393/// which changes all source locations in the current file after that to be
1394/// considered to be from a system header.
Mike Stump1eb44332009-09-09 15:08:12 +00001395SrcMgr::CharacteristicKind
Chris Lattner6b306672009-02-04 05:33:01 +00001396SourceManager::getFileCharacteristic(SourceLocation Loc) const {
1397 assert(!Loc.isInvalid() && "Can't get file characteristic of invalid loc!");
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +00001398 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Douglas Gregore23ac652011-04-20 00:21:03 +00001399 bool Invalid = false;
1400 const SLocEntry &SEntry = getSLocEntry(LocInfo.first, &Invalid);
1401 if (Invalid || !SEntry.isFile())
1402 return C_User;
1403
1404 const SrcMgr::FileInfo &FI = SEntry.getFile();
Chris Lattner6b306672009-02-04 05:33:01 +00001405
1406 // If there are no #line directives in this file, just return the whole-file
1407 // state.
1408 if (!FI.hasLineDirectives())
1409 return FI.getFileCharacteristic();
Mike Stump1eb44332009-09-09 15:08:12 +00001410
Chris Lattner6b306672009-02-04 05:33:01 +00001411 assert(LineTable && "Can't have linetable entries without a LineTable!");
1412 // See if there is a #line directive before the location.
1413 const LineEntry *Entry =
Douglas Gregor47d9de62012-06-08 16:40:28 +00001414 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001415
Chris Lattner6b306672009-02-04 05:33:01 +00001416 // If this is before the first line marker, use the file characteristic.
1417 if (!Entry)
1418 return FI.getFileCharacteristic();
1419
1420 return Entry->FileKind;
1421}
1422
Chris Lattnerbff5c512009-02-17 08:39:06 +00001423/// Return the filename or buffer identifier of the buffer the location is in.
James Dennettb8950b82012-06-17 03:22:59 +00001424/// Note that this name does not respect \#line directives. Use getPresumedLoc
Chris Lattnerbff5c512009-02-17 08:39:06 +00001425/// for normal clients.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001426const char *SourceManager::getBufferName(SourceLocation Loc,
1427 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001428 if (isInvalid(Loc, Invalid)) return "<invalid loc>";
Mike Stump1eb44332009-09-09 15:08:12 +00001429
Douglas Gregor50f6af72010-03-16 05:20:39 +00001430 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
Chris Lattnerbff5c512009-02-17 08:39:06 +00001431}
1432
Chris Lattner30fc9332009-02-04 01:06:56 +00001433
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001434/// getPresumedLoc - This method returns the "presumed" location of a
James Dennettb8950b82012-06-17 03:22:59 +00001435/// SourceLocation specifies. A "presumed location" can be modified by \#line
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001436/// or GNU line marker directives. This provides a view on the data that a
1437/// user should see in diagnostics, for example.
1438///
Chandler Carruth3201f382011-07-26 05:17:23 +00001439/// Note that a presumed location is always given as the expansion point of an
1440/// expansion location, not at the spelling location.
Richard Smith62221b12012-11-14 23:55:25 +00001441PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc,
1442 bool UseLineDirectives) const {
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001443 if (Loc.isInvalid()) return PresumedLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001444
Chandler Carruth3201f382011-07-26 05:17:23 +00001445 // Presumed locations are always for expansion points.
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +00001446 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +00001447
Douglas Gregore23ac652011-04-20 00:21:03 +00001448 bool Invalid = false;
1449 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1450 if (Invalid || !Entry.isFile())
1451 return PresumedLoc();
1452
1453 const SrcMgr::FileInfo &FI = Entry.getFile();
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001454 const SrcMgr::ContentCache *C = FI.getContentCache();
Mike Stump1eb44332009-09-09 15:08:12 +00001455
Chris Lattner3cd949c2009-02-04 01:55:42 +00001456 // To get the source name, first consult the FileEntry (if one exists)
1457 // before the MemBuffer as this will avoid unnecessarily paging in the
1458 // MemBuffer.
Chris Lattnere127a0d2010-04-20 20:35:58 +00001459 const char *Filename;
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001460 if (C->OrigEntry)
1461 Filename = C->OrigEntry->getName();
Chris Lattnere127a0d2010-04-20 20:35:58 +00001462 else
1463 Filename = C->getBuffer(Diag, *this)->getBufferIdentifier();
Douglas Gregore23ac652011-04-20 00:21:03 +00001464
Douglas Gregorc417fa02010-11-02 00:39:22 +00001465 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1466 if (Invalid)
1467 return PresumedLoc();
1468 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1469 if (Invalid)
1470 return PresumedLoc();
1471
Chris Lattner3cd949c2009-02-04 01:55:42 +00001472 SourceLocation IncludeLoc = FI.getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001473
Chris Lattner3cd949c2009-02-04 01:55:42 +00001474 // If we have #line directives in this file, update and overwrite the physical
1475 // location info if appropriate.
Richard Smith62221b12012-11-14 23:55:25 +00001476 if (UseLineDirectives && FI.hasLineDirectives()) {
Chris Lattner3cd949c2009-02-04 01:55:42 +00001477 assert(LineTable && "Can't have linetable entries without a LineTable!");
1478 // See if there is a #line directive before this. If so, get it.
1479 if (const LineEntry *Entry =
Douglas Gregor47d9de62012-06-08 16:40:28 +00001480 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second)) {
Chris Lattnerfc391332009-02-04 02:00:59 +00001481 // If the LineEntry indicates a filename, use it.
Chris Lattner3cd949c2009-02-04 01:55:42 +00001482 if (Entry->FilenameID != -1)
1483 Filename = LineTable->getFilename(Entry->FilenameID);
Chris Lattnerfc391332009-02-04 02:00:59 +00001484
1485 // Use the line number specified by the LineEntry. This line number may
1486 // be multiple lines down from the line entry. Add the difference in
1487 // physical line numbers from the query point and the line marker to the
1488 // total.
1489 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1490 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001491
Chris Lattner0e0e5da2009-02-04 02:15:40 +00001492 // Note that column numbers are not molested by line markers.
Mike Stump1eb44332009-09-09 15:08:12 +00001493
Chris Lattner137b6a62009-02-04 06:25:26 +00001494 // Handle virtual #include manipulation.
1495 if (Entry->IncludeOffset) {
1496 IncludeLoc = getLocForStartOfFile(LocInfo.first);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001497 IncludeLoc = IncludeLoc.getLocWithOffset(Entry->IncludeOffset);
Chris Lattner137b6a62009-02-04 06:25:26 +00001498 }
Chris Lattner3cd949c2009-02-04 01:55:42 +00001499 }
1500 }
1501
1502 return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc);
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001503}
1504
Benjamin Kramer1b9c5372013-09-27 17:12:50 +00001505/// \brief Returns whether the PresumedLoc for a given SourceLocation is
1506/// in the main file.
1507///
1508/// This computes the "presumed" location for a SourceLocation, then checks
1509/// whether it came from a file other than the main file. This is different
1510/// from isWrittenInMainFile() because it takes line marker directives into
1511/// account.
1512bool SourceManager::isInMainFile(SourceLocation Loc) const {
1513 if (Loc.isInvalid()) return false;
1514
1515 // Presumed locations are always for expansion points.
1516 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
1517
1518 bool Invalid = false;
1519 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1520 if (Invalid || !Entry.isFile())
1521 return false;
1522
1523 const SrcMgr::FileInfo &FI = Entry.getFile();
1524
1525 // Check if there is a line directive for this location.
1526 if (FI.hasLineDirectives())
1527 if (const LineEntry *Entry =
1528 LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second))
1529 if (Entry->IncludeOffset)
1530 return false;
1531
1532 return FI.getIncludeLoc().isInvalid();
1533}
1534
Stephen Hines651f13c2014-04-23 16:59:28 -07001535/// \brief The size of the SLocEntry that \p FID represents.
Argyrios Kyrtzidis984e42c2011-08-23 21:02:28 +00001536unsigned SourceManager::getFileIDSize(FileID FID) const {
1537 bool Invalid = false;
1538 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1539 if (Invalid)
1540 return 0;
1541
1542 int ID = FID.ID;
1543 unsigned NextOffset;
1544 if ((ID > 0 && unsigned(ID+1) == local_sloc_entry_size()))
1545 NextOffset = getNextLocalOffset();
1546 else if (ID+1 == -1)
1547 NextOffset = MaxLoadedOffset;
1548 else
1549 NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset();
1550
1551 return NextOffset - Entry.getOffset() - 1;
1552}
1553
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001554//===----------------------------------------------------------------------===//
1555// Other miscellaneous methods.
1556//===----------------------------------------------------------------------===//
1557
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001558/// \brief Retrieve the inode for the given file entry, if possible.
1559///
1560/// This routine involves a system call, and therefore should only be used
1561/// in non-performance-critical code.
Rafael Espindola44888352013-07-29 21:26:52 +00001562static Optional<llvm::sys::fs::UniqueID>
1563getActualFileUID(const FileEntry *File) {
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001564 if (!File)
David Blaikie66874fb2013-02-21 01:47:18 +00001565 return None;
Rafael Espindola3dadc852013-07-29 18:43:40 +00001566
Rafael Espindola44888352013-07-29 21:26:52 +00001567 llvm::sys::fs::UniqueID ID;
Rafael Espindola3dadc852013-07-29 18:43:40 +00001568 if (llvm::sys::fs::getUniqueID(File->getName(), ID))
David Blaikie66874fb2013-02-21 01:47:18 +00001569 return None;
Rafael Espindola3dadc852013-07-29 18:43:40 +00001570
1571 return ID;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001572}
1573
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001574/// \brief Get the source location for the given file:line:col triplet.
1575///
1576/// If the source file is included multiple times, the source location will
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001577/// be based upon an arbitrary inclusion.
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001578SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile,
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001579 unsigned Line,
1580 unsigned Col) const {
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001581 assert(SourceFile && "Null source file!");
1582 assert(Line && Col && "Line and column should start from 1!");
1583
Argyrios Kyrtzidisb201e162011-09-27 17:22:25 +00001584 FileID FirstFID = translateFile(SourceFile);
1585 return translateLineCol(FirstFID, Line, Col);
1586}
1587
1588/// \brief Get the FileID for the given file.
1589///
1590/// If the source file is included multiple times, the FileID will be the
1591/// first inclusion.
1592FileID SourceManager::translateFile(const FileEntry *SourceFile) const {
1593 assert(SourceFile && "Null source file!");
1594
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001595 // Find the first file ID that corresponds to the given file.
1596 FileID FirstFID;
Mike Stump1eb44332009-09-09 15:08:12 +00001597
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001598 // First, check the main file ID, since it is common to look for a
1599 // location in the main file.
Rafael Espindola44888352013-07-29 21:26:52 +00001600 Optional<llvm::sys::fs::UniqueID> SourceFileUID;
David Blaikiedc84cd52013-02-20 22:23:23 +00001601 Optional<StringRef> SourceFileName;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001602 if (!MainFileID.isInvalid()) {
Douglas Gregore23ac652011-04-20 00:21:03 +00001603 bool Invalid = false;
1604 const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
1605 if (Invalid)
Argyrios Kyrtzidisb201e162011-09-27 17:22:25 +00001606 return FileID();
Douglas Gregore23ac652011-04-20 00:21:03 +00001607
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001608 if (MainSLoc.isFile()) {
1609 const ContentCache *MainContentCache
1610 = MainSLoc.getFile().getContentCache();
Douglas Gregorb7a18412011-02-11 18:08:15 +00001611 if (!MainContentCache) {
1612 // Can't do anything
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001613 } else if (MainContentCache->OrigEntry == SourceFile) {
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001614 FirstFID = MainFileID;
Douglas Gregorb7a18412011-02-11 18:08:15 +00001615 } else {
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001616 // Fall back: check whether we have the same base name and inode
1617 // as the main file.
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001618 const FileEntry *MainFile = MainContentCache->OrigEntry;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001619 SourceFileName = llvm::sys::path::filename(SourceFile->getName());
1620 if (*SourceFileName == llvm::sys::path::filename(MainFile->getName())) {
Rafael Espindola3dadc852013-07-29 18:43:40 +00001621 SourceFileUID = getActualFileUID(SourceFile);
1622 if (SourceFileUID) {
Rafael Espindola44888352013-07-29 21:26:52 +00001623 if (Optional<llvm::sys::fs::UniqueID> MainFileUID =
1624 getActualFileUID(MainFile)) {
Rafael Espindola3dadc852013-07-29 18:43:40 +00001625 if (*SourceFileUID == *MainFileUID) {
Douglas Gregor37c02bf2011-02-16 19:09:24 +00001626 FirstFID = MainFileID;
1627 SourceFile = MainFile;
1628 }
1629 }
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001630 }
1631 }
1632 }
1633 }
1634 }
1635
1636 if (FirstFID.isInvalid()) {
1637 // The location we're looking for isn't in the main file; look
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001638 // through all of the local source locations.
1639 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
Douglas Gregore23ac652011-04-20 00:21:03 +00001640 bool Invalid = false;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001641 const SLocEntry &SLoc = getLocalSLocEntry(I, &Invalid);
Douglas Gregore23ac652011-04-20 00:21:03 +00001642 if (Invalid)
Argyrios Kyrtzidisb201e162011-09-27 17:22:25 +00001643 return FileID();
Douglas Gregore23ac652011-04-20 00:21:03 +00001644
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001645 if (SLoc.isFile() &&
1646 SLoc.getFile().getContentCache() &&
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001647 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001648 FirstFID = FileID::get(I);
1649 break;
1650 }
1651 }
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001652 // If that still didn't help, try the modules.
1653 if (FirstFID.isInvalid()) {
1654 for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) {
1655 const SLocEntry &SLoc = getLoadedSLocEntry(I);
1656 if (SLoc.isFile() &&
1657 SLoc.getFile().getContentCache() &&
1658 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
1659 FirstFID = FileID::get(-int(I) - 2);
1660 break;
1661 }
1662 }
1663 }
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001664 }
1665
1666 // If we haven't found what we want yet, try again, but this time stat()
1667 // each of the files in case the files have changed since we originally
Rafael Espindola3dadc852013-07-29 18:43:40 +00001668 // parsed the file.
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001669 if (FirstFID.isInvalid() &&
Rafael Espindola3dadc852013-07-29 18:43:40 +00001670 (SourceFileName ||
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001671 (SourceFileName = llvm::sys::path::filename(SourceFile->getName()))) &&
Rafael Espindola3dadc852013-07-29 18:43:40 +00001672 (SourceFileUID || (SourceFileUID = getActualFileUID(SourceFile)))) {
Douglas Gregore23ac652011-04-20 00:21:03 +00001673 bool Invalid = false;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001674 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1675 FileID IFileID;
1676 IFileID.ID = I;
1677 const SLocEntry &SLoc = getSLocEntry(IFileID, &Invalid);
Douglas Gregore23ac652011-04-20 00:21:03 +00001678 if (Invalid)
Argyrios Kyrtzidisb201e162011-09-27 17:22:25 +00001679 return FileID();
Douglas Gregore23ac652011-04-20 00:21:03 +00001680
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001681 if (SLoc.isFile()) {
1682 const ContentCache *FileContentCache
1683 = SLoc.getFile().getContentCache();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001684 const FileEntry *Entry = FileContentCache ? FileContentCache->OrigEntry
1685 : nullptr;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001686 if (Entry &&
Douglas Gregorb7a18412011-02-11 18:08:15 +00001687 *SourceFileName == llvm::sys::path::filename(Entry->getName())) {
Rafael Espindola44888352013-07-29 21:26:52 +00001688 if (Optional<llvm::sys::fs::UniqueID> EntryUID =
1689 getActualFileUID(Entry)) {
Rafael Espindola3dadc852013-07-29 18:43:40 +00001690 if (*SourceFileUID == *EntryUID) {
Douglas Gregorb7a18412011-02-11 18:08:15 +00001691 FirstFID = FileID::get(I);
1692 SourceFile = Entry;
1693 break;
1694 }
1695 }
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001696 }
1697 }
1698 }
1699 }
Argyrios Kyrtzidisb201e162011-09-27 17:22:25 +00001700
Ted Kremenek186ec9c2012-10-12 22:56:33 +00001701 (void) SourceFile;
Argyrios Kyrtzidisb201e162011-09-27 17:22:25 +00001702 return FirstFID;
Argyrios Kyrtzidisefa2ff82011-09-19 20:40:29 +00001703}
1704
1705/// \brief Get the source location in \arg FID for the given line:col.
1706/// Returns null location if \arg FID is not a file SLocEntry.
1707SourceLocation SourceManager::translateLineCol(FileID FID,
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001708 unsigned Line,
1709 unsigned Col) const {
Aaron Ballmanfb21ecf2013-11-18 18:29:00 +00001710 // Lines are used as a one-based index into a zero-based array. This assert
1711 // checks for possible buffer underruns.
1712 assert(Line != 0 && "Passed a zero-based line");
1713
Argyrios Kyrtzidisefa2ff82011-09-19 20:40:29 +00001714 if (FID.isInvalid())
1715 return SourceLocation();
1716
1717 bool Invalid = false;
1718 const SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1719 if (Invalid)
1720 return SourceLocation();
Alexander Kornienkoc8051e62013-07-29 22:26:10 +00001721
Argyrios Kyrtzidisefa2ff82011-09-19 20:40:29 +00001722 if (!Entry.isFile())
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001723 return SourceLocation();
1724
Argyrios Kyrtzidis5e5e95d2011-09-20 22:14:54 +00001725 SourceLocation FileLoc = SourceLocation::getFileLoc(Entry.getOffset());
1726
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001727 if (Line == 1 && Col == 1)
Argyrios Kyrtzidis5e5e95d2011-09-20 22:14:54 +00001728 return FileLoc;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001729
1730 ContentCache *Content
Argyrios Kyrtzidisefa2ff82011-09-19 20:40:29 +00001731 = const_cast<ContentCache *>(Entry.getFile().getContentCache());
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001732 if (!Content)
1733 return SourceLocation();
Alexander Kornienkoc8051e62013-07-29 22:26:10 +00001734
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001735 // If this is the first use of line information for this buffer, compute the
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001736 // SourceLineCache for it on demand.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001737 if (!Content->SourceLineCache) {
Douglas Gregor50f6af72010-03-16 05:20:39 +00001738 bool MyInvalid = false;
Chris Lattnere127a0d2010-04-20 20:35:58 +00001739 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001740 if (MyInvalid)
1741 return SourceLocation();
1742 }
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001743
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001744 if (Line > Content->NumLines) {
Chris Lattnere127a0d2010-04-20 20:35:58 +00001745 unsigned Size = Content->getBuffer(Diag, *this)->getBufferSize();
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001746 if (Size > 0)
1747 --Size;
Argyrios Kyrtzidis5e5e95d2011-09-20 22:14:54 +00001748 return FileLoc.getLocWithOffset(Size);
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001749 }
1750
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001751 llvm::MemoryBuffer *Buffer = Content->getBuffer(Diag, *this);
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001752 unsigned FilePos = Content->SourceLineCache[Line - 1];
Dylan Noblesmith098eaff2011-12-19 08:51:05 +00001753 const char *Buf = Buffer->getBufferStart() + FilePos;
1754 unsigned BufLength = Buffer->getBufferSize() - FilePos;
Argyrios Kyrtzidis5e5e95d2011-09-20 22:14:54 +00001755 if (BufLength == 0)
1756 return FileLoc.getLocWithOffset(FilePos);
1757
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001758 unsigned i = 0;
1759
1760 // Check that the given column is valid.
1761 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1762 ++i;
Alexander Kornienkoc8051e62013-07-29 22:26:10 +00001763 return FileLoc.getLocWithOffset(FilePos + i);
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001764}
1765
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001766/// \brief Compute a map of macro argument chunks to their expanded source
1767/// location. Chunks that are not part of a macro argument will map to an
1768/// invalid source location. e.g. if a file contains one macro argument at
1769/// offset 100 with length 10, this is how the map will be formed:
1770/// 0 -> SourceLocation()
1771/// 100 -> Expanded macro arg location
1772/// 110 -> SourceLocation()
Argyrios Kyrtzidisfb3612e2011-09-26 08:01:50 +00001773void SourceManager::computeMacroArgsCache(MacroArgsMap *&CachePtr,
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001774 FileID FID) const {
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001775 assert(!FID.isInvalid());
Argyrios Kyrtzidisfb3612e2011-09-26 08:01:50 +00001776 assert(!CachePtr);
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001777
Argyrios Kyrtzidisfb3612e2011-09-26 08:01:50 +00001778 CachePtr = new MacroArgsMap();
1779 MacroArgsMap &MacroArgsCache = *CachePtr;
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001780 // Initially no macro argument chunk is present.
1781 MacroArgsCache.insert(std::make_pair(0, SourceLocation()));
1782
1783 int ID = FID.ID;
1784 while (1) {
1785 ++ID;
1786 // Stop if there are no more FileIDs to check.
1787 if (ID > 0) {
1788 if (unsigned(ID) >= local_sloc_entry_size())
1789 return;
1790 } else if (ID == -1) {
1791 return;
1792 }
1793
Argyrios Kyrtzidis4ff32252013-06-07 17:57:59 +00001794 bool Invalid = false;
1795 const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID, &Invalid);
1796 if (Invalid)
1797 return;
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001798 if (Entry.isFile()) {
1799 SourceLocation IncludeLoc = Entry.getFile().getIncludeLoc();
1800 if (IncludeLoc.isInvalid())
1801 continue;
1802 if (!isInFileID(IncludeLoc, FID))
1803 return; // No more files/macros that may be "contained" in this file.
1804
1805 // Skip the files/macros of the #include'd file, we only care about macros
1806 // that lexed macro arguments from our file.
1807 if (Entry.getFile().NumCreatedFIDs)
1808 ID += Entry.getFile().NumCreatedFIDs - 1/*because of next ++ID*/;
1809 continue;
1810 }
1811
Argyrios Kyrtzidiscee5ec92011-12-21 16:56:35 +00001812 const ExpansionInfo &ExpInfo = Entry.getExpansion();
1813
1814 if (ExpInfo.getExpansionLocStart().isFileID()) {
1815 if (!isInFileID(ExpInfo.getExpansionLocStart(), FID))
1816 return; // No more files/macros that may be "contained" in this file.
1817 }
1818
1819 if (!ExpInfo.isMacroArgExpansion())
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001820 continue;
Argyrios Kyrtzidiscee5ec92011-12-21 16:56:35 +00001821
Argyrios Kyrtzidis0872a062012-10-20 00:51:32 +00001822 associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1823 ExpInfo.getSpellingLoc(),
1824 SourceLocation::getMacroLoc(Entry.getOffset()),
1825 getFileIDSize(FileID::get(ID)));
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001826 }
1827}
1828
Argyrios Kyrtzidis0872a062012-10-20 00:51:32 +00001829void SourceManager::associateFileChunkWithMacroArgExp(
1830 MacroArgsMap &MacroArgsCache,
1831 FileID FID,
1832 SourceLocation SpellLoc,
1833 SourceLocation ExpansionLoc,
1834 unsigned ExpansionLength) const {
1835 if (!SpellLoc.isFileID()) {
1836 unsigned SpellBeginOffs = SpellLoc.getOffset();
1837 unsigned SpellEndOffs = SpellBeginOffs + ExpansionLength;
1838
1839 // The spelling range for this macro argument expansion can span multiple
1840 // consecutive FileID entries. Go through each entry contained in the
1841 // spelling range and if one is itself a macro argument expansion, recurse
1842 // and associate the file chunk that it represents.
1843
1844 FileID SpellFID; // Current FileID in the spelling range.
1845 unsigned SpellRelativeOffs;
Stephen Hines651f13c2014-04-23 16:59:28 -07001846 std::tie(SpellFID, SpellRelativeOffs) = getDecomposedLoc(SpellLoc);
Argyrios Kyrtzidis0872a062012-10-20 00:51:32 +00001847 while (1) {
1848 const SLocEntry &Entry = getSLocEntry(SpellFID);
1849 unsigned SpellFIDBeginOffs = Entry.getOffset();
1850 unsigned SpellFIDSize = getFileIDSize(SpellFID);
1851 unsigned SpellFIDEndOffs = SpellFIDBeginOffs + SpellFIDSize;
1852 const ExpansionInfo &Info = Entry.getExpansion();
1853 if (Info.isMacroArgExpansion()) {
1854 unsigned CurrSpellLength;
1855 if (SpellFIDEndOffs < SpellEndOffs)
1856 CurrSpellLength = SpellFIDSize - SpellRelativeOffs;
1857 else
1858 CurrSpellLength = ExpansionLength;
1859 associateFileChunkWithMacroArgExp(MacroArgsCache, FID,
1860 Info.getSpellingLoc().getLocWithOffset(SpellRelativeOffs),
1861 ExpansionLoc, CurrSpellLength);
1862 }
1863
1864 if (SpellFIDEndOffs >= SpellEndOffs)
1865 return; // we covered all FileID entries in the spelling range.
1866
1867 // Move to the next FileID entry in the spelling range.
1868 unsigned advance = SpellFIDSize - SpellRelativeOffs + 1;
1869 ExpansionLoc = ExpansionLoc.getLocWithOffset(advance);
1870 ExpansionLength -= advance;
1871 ++SpellFID.ID;
1872 SpellRelativeOffs = 0;
1873 }
1874
1875 }
1876
1877 assert(SpellLoc.isFileID());
1878
1879 unsigned BeginOffs;
1880 if (!isInFileID(SpellLoc, FID, &BeginOffs))
1881 return;
1882
1883 unsigned EndOffs = BeginOffs + ExpansionLength;
1884
1885 // Add a new chunk for this macro argument. A previous macro argument chunk
1886 // may have been lexed again, so e.g. if the map is
1887 // 0 -> SourceLocation()
1888 // 100 -> Expanded loc #1
1889 // 110 -> SourceLocation()
1890 // and we found a new macro FileID that lexed from offet 105 with length 3,
1891 // the new map will be:
1892 // 0 -> SourceLocation()
1893 // 100 -> Expanded loc #1
1894 // 105 -> Expanded loc #2
1895 // 108 -> Expanded loc #1
1896 // 110 -> SourceLocation()
1897 //
1898 // Since re-lexed macro chunks will always be the same size or less of
1899 // previous chunks, we only need to find where the ending of the new macro
1900 // chunk is mapped to and update the map with new begin/end mappings.
1901
1902 MacroArgsMap::iterator I = MacroArgsCache.upper_bound(EndOffs);
1903 --I;
1904 SourceLocation EndOffsMappedLoc = I->second;
1905 MacroArgsCache[BeginOffs] = ExpansionLoc;
1906 MacroArgsCache[EndOffs] = EndOffsMappedLoc;
1907}
1908
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001909/// \brief If \arg Loc points inside a function macro argument, the returned
1910/// location will be the macro location in which the argument was expanded.
1911/// If a macro argument is used multiple times, the expanded location will
1912/// be at the first expansion of the argument.
1913/// e.g.
1914/// MY_MACRO(foo);
1915/// ^
1916/// Passing a file location pointing at 'foo', will yield a macro location
1917/// where 'foo' was expanded into.
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001918SourceLocation
1919SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const {
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001920 if (Loc.isInvalid() || !Loc.isFileID())
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001921 return Loc;
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001922
1923 FileID FID;
1924 unsigned Offset;
Stephen Hines651f13c2014-04-23 16:59:28 -07001925 std::tie(FID, Offset) = getDecomposedLoc(Loc);
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001926 if (FID.isInvalid())
1927 return Loc;
1928
Argyrios Kyrtzidisfb3612e2011-09-26 08:01:50 +00001929 MacroArgsMap *&MacroArgsCache = MacroArgsCacheMap[FID];
1930 if (!MacroArgsCache)
1931 computeMacroArgsCache(MacroArgsCache, FID);
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001932
Argyrios Kyrtzidisfb3612e2011-09-26 08:01:50 +00001933 assert(!MacroArgsCache->empty());
1934 MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset);
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001935 --I;
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001936
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001937 unsigned MacroArgBeginOffs = I->first;
1938 SourceLocation MacroArgExpandedLoc = I->second;
1939 if (MacroArgExpandedLoc.isValid())
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001940 return MacroArgExpandedLoc.getLocWithOffset(Offset - MacroArgBeginOffs);
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001941
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001942 return Loc;
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001943}
1944
Argyrios Kyrtzidisecc65232013-04-13 01:03:57 +00001945std::pair<FileID, unsigned>
1946SourceManager::getDecomposedIncludedLoc(FileID FID) const {
Argyrios Kyrtzidis5b8e1322013-05-24 22:24:04 +00001947 if (FID.isInvalid())
1948 return std::make_pair(FileID(), 0);
1949
Argyrios Kyrtzidisecc65232013-04-13 01:03:57 +00001950 // Uses IncludedLocMap to retrieve/cache the decomposed loc.
1951
1952 typedef std::pair<FileID, unsigned> DecompTy;
1953 typedef llvm::DenseMap<FileID, DecompTy> MapTy;
1954 std::pair<MapTy::iterator, bool>
1955 InsertOp = IncludedLocMap.insert(std::make_pair(FID, DecompTy()));
1956 DecompTy &DecompLoc = InsertOp.first->second;
1957 if (!InsertOp.second)
1958 return DecompLoc; // already in map.
1959
1960 SourceLocation UpperLoc;
Argyrios Kyrtzidis5b8e1322013-05-24 22:24:04 +00001961 bool Invalid = false;
1962 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1963 if (!Invalid) {
1964 if (Entry.isExpansion())
1965 UpperLoc = Entry.getExpansion().getExpansionLocStart();
1966 else
1967 UpperLoc = Entry.getFile().getIncludeLoc();
1968 }
Argyrios Kyrtzidisecc65232013-04-13 01:03:57 +00001969
1970 if (UpperLoc.isValid())
1971 DecompLoc = getDecomposedLoc(UpperLoc);
1972
1973 return DecompLoc;
1974}
1975
Chandler Carruth3201f382011-07-26 05:17:23 +00001976/// Given a decomposed source location, move it up the include/expansion stack
1977/// to the parent source location. If this is possible, return the decomposed
1978/// version of the parent in Loc and return false. If Loc is the top-level
1979/// entry, return true and don't modify it.
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001980static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1981 const SourceManager &SM) {
Argyrios Kyrtzidisecc65232013-04-13 01:03:57 +00001982 std::pair<FileID, unsigned> UpperLoc = SM.getDecomposedIncludedLoc(Loc.first);
1983 if (UpperLoc.first.isInvalid())
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001984 return true; // We reached the top.
Argyrios Kyrtzidisecc65232013-04-13 01:03:57 +00001985
1986 Loc = UpperLoc;
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001987 return false;
1988}
Ted Kremenek2564f812013-02-27 00:00:26 +00001989
1990/// Return the cache entry for comparing the given file IDs
1991/// for isBeforeInTranslationUnit.
1992InBeforeInTUCacheEntry &SourceManager::getInBeforeInTUCache(FileID LFID,
1993 FileID RFID) const {
1994 // This is a magic number for limiting the cache size. It was experimentally
1995 // derived from a small Objective-C project (where the cache filled
1996 // out to ~250 items). We can make it larger if necessary.
1997 enum { MagicCacheSize = 300 };
1998 IsBeforeInTUCacheKey Key(LFID, RFID);
1999
2000 // If the cache size isn't too large, do a lookup and if necessary default
2001 // construct an entry. We can then return it to the caller for direct
2002 // use. When they update the value, the cache will get automatically
2003 // updated as well.
2004 if (IBTUCache.size() < MagicCacheSize)
2005 return IBTUCache[Key];
2006
2007 // Otherwise, do a lookup that will not construct a new value.
2008 InBeforeInTUCache::iterator I = IBTUCache.find(Key);
2009 if (I != IBTUCache.end())
2010 return I->second;
2011
2012 // Fall back to the overflow value.
2013 return IBTUCacheOverflow;
2014}
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00002015
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00002016/// \brief Determines the order of 2 source locations in the translation unit.
2017///
2018/// \returns true if LHS source location comes before RHS, false otherwise.
2019bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
2020 SourceLocation RHS) const {
2021 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
2022 if (LHS == RHS)
2023 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002024
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00002025 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
2026 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002027
Argyrios Kyrtzidisecdbbfa2013-05-24 23:47:43 +00002028 // getDecomposedLoc may have failed to return a valid FileID because, e.g. it
2029 // is a serialized one referring to a file that was removed after we loaded
2030 // the PCH.
Argyrios Kyrtzidis5b8e1322013-05-24 22:24:04 +00002031 if (LOffs.first.isInvalid() || ROffs.first.isInvalid())
Argyrios Kyrtzidis45e1f0e2013-05-25 01:03:03 +00002032 return LOffs.first.isInvalid() && !ROffs.first.isInvalid();
Argyrios Kyrtzidis5b8e1322013-05-24 22:24:04 +00002033
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00002034 // If the source locations are in the same file, just compare offsets.
2035 if (LOffs.first == ROffs.first)
2036 return LOffs.second < ROffs.second;
2037
2038 // If we are comparing a source location with multiple locations in the same
2039 // file, we get a big win by caching the result.
Ted Kremenek2564f812013-02-27 00:00:26 +00002040 InBeforeInTUCacheEntry &IsBeforeInTUCache =
2041 getInBeforeInTUCache(LOffs.first, ROffs.first);
2042
2043 // If we are comparing a source location with multiple locations in the same
2044 // file, we get a big win by caching the result.
Chris Lattner66a915f2010-05-07 05:10:46 +00002045 if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
2046 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
Mike Stump1eb44332009-09-09 15:08:12 +00002047
Chris Lattnerdcb1d682010-05-07 01:17:07 +00002048 // Okay, we missed in the cache, start updating the cache for this query.
Argyrios Kyrtzidis37e59a12011-08-17 00:31:18 +00002049 IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first,
2050 /*isLFIDBeforeRFID=*/LOffs.first.ID < ROffs.first.ID);
Mike Stump1eb44332009-09-09 15:08:12 +00002051
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002052 // We need to find the common ancestor. The only way of doing this is to
2053 // build the complete include chain for one and then walking up the chain
2054 // of the other looking for a match.
2055 // We use a map from FileID to Offset to store the chain. Easier than writing
2056 // a custom set hash info that only depends on the first part of a pair.
Argyrios Kyrtzidisecc65232013-04-13 01:03:57 +00002057 typedef llvm::SmallDenseMap<FileID, unsigned, 16> LocSet;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002058 LocSet LChain;
Chris Lattner48296ba2010-05-07 05:51:13 +00002059 do {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002060 LChain.insert(LOffs);
2061 // We catch the case where LOffs is in a file included by ROffs and
2062 // quit early. The other way round unfortunately remains suboptimal.
2063 } while (LOffs.first != ROffs.first && !MoveUpIncludeHierarchy(LOffs, *this));
2064 LocSet::iterator I;
2065 while((I = LChain.find(ROffs.first)) == LChain.end()) {
2066 if (MoveUpIncludeHierarchy(ROffs, *this))
2067 break; // Met at topmost file.
2068 }
2069 if (I != LChain.end())
2070 LOffs = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00002071
Chris Lattner48296ba2010-05-07 05:51:13 +00002072 // If we exited because we found a nearest common ancestor, compare the
2073 // locations within the common file and cache them.
2074 if (LOffs.first == ROffs.first) {
2075 IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
2076 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00002077 }
Mike Stump1eb44332009-09-09 15:08:12 +00002078
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002079 // This can happen if a location is in a built-ins buffer.
2080 // But see PR5662.
2081 // Clear the lookup cache, it depends on a common location.
Argyrios Kyrtzidis37e59a12011-08-17 00:31:18 +00002082 IsBeforeInTUCache.clear();
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002083 bool LIsBuiltins = strcmp("<built-in>",
2084 getBuffer(LOffs.first)->getBufferIdentifier()) == 0;
2085 bool RIsBuiltins = strcmp("<built-in>",
2086 getBuffer(ROffs.first)->getBufferIdentifier()) == 0;
2087 // built-in is before non-built-in
2088 if (LIsBuiltins != RIsBuiltins)
2089 return LIsBuiltins;
2090 assert(LIsBuiltins && RIsBuiltins &&
2091 "Non-built-in locations must be rooted in the main file");
2092 // Both are in built-in buffers, but from different files. We just claim that
2093 // lower IDs come first.
Chris Lattnerdcb1d682010-05-07 01:17:07 +00002094 return LOffs.first < ROffs.first;
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00002095}
Chris Lattnerde7aeef2009-01-26 00:43:02 +00002096
Reid Spencer5f016e22007-07-11 17:01:13 +00002097void SourceManager::PrintStats() const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00002098 llvm::errs() << "\n*** Source Manager Stats:\n";
2099 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
2100 << " mem buffers mapped.\n";
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002101 llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntry's allocated ("
Ted Kremenek6e36c122011-07-27 18:41:16 +00002102 << llvm::capacity_in_bytes(LocalSLocEntryTable)
Argyrios Kyrtzidisd410e742011-07-07 03:40:24 +00002103 << " bytes of capacity), "
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002104 << NextLocalOffset << "B of Sloc address space used.\n";
2105 llvm::errs() << LoadedSLocEntryTable.size()
2106 << " loaded SLocEntries allocated, "
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00002107 << MaxLoadedOffset - CurrentLoadedOffset
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002108 << "B of Sloc address space used.\n";
2109
Reid Spencer5f016e22007-07-11 17:01:13 +00002110 unsigned NumLineNumsComputed = 0;
2111 unsigned NumFileBytesMapped = 0;
Chris Lattner0d0bf8c2009-02-03 07:30:45 +00002112 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002113 NumLineNumsComputed += I->second->SourceLineCache != nullptr;
Chris Lattner0d0bf8c2009-02-03 07:30:45 +00002114 NumFileBytesMapped += I->second->getSizeBytesMapped();
Reid Spencer5f016e22007-07-11 17:01:13 +00002115 }
Argyrios Kyrtzidisfb3612e2011-09-26 08:01:50 +00002116 unsigned NumMacroArgsComputed = MacroArgsCacheMap.size();
Mike Stump1eb44332009-09-09 15:08:12 +00002117
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00002118 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00002119 << NumLineNumsComputed << " files with line #'s computed, "
2120 << NumMacroArgsComputed << " files with macro args computed.\n";
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00002121 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
2122 << NumBinaryProbes << " binary.\n";
Reid Spencer5f016e22007-07-11 17:01:13 +00002123}
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002124
2125ExternalSLocEntrySource::~ExternalSLocEntrySource() { }
Ted Kremenekf61b8312011-04-28 20:36:42 +00002126
2127/// Return the amount of memory used by memory buffers, breaking down
2128/// by heap-backed versus mmap'ed memory.
2129SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
2130 size_t malloc_bytes = 0;
2131 size_t mmap_bytes = 0;
2132
2133 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)
2134 if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
2135 switch (MemBufferInfos[i]->getMemoryBufferKind()) {
2136 case llvm::MemoryBuffer::MemoryBuffer_MMap:
2137 mmap_bytes += sized_mapped;
2138 break;
2139 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
2140 malloc_bytes += sized_mapped;
2141 break;
2142 }
2143
2144 return MemoryBufferSizes(malloc_bytes, mmap_bytes);
2145}
2146
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00002147size_t SourceManager::getDataStructureSizes() const {
Argyrios Kyrtzidisd54dff02012-05-03 21:50:39 +00002148 size_t size = llvm::capacity_in_bytes(MemBufferInfos)
Ted Kremenek6e36c122011-07-27 18:41:16 +00002149 + llvm::capacity_in_bytes(LocalSLocEntryTable)
2150 + llvm::capacity_in_bytes(LoadedSLocEntryTable)
2151 + llvm::capacity_in_bytes(SLocEntryLoaded)
Argyrios Kyrtzidisd54dff02012-05-03 21:50:39 +00002152 + llvm::capacity_in_bytes(FileInfos);
2153
2154 if (OverriddenFilesInfo)
2155 size += llvm::capacity_in_bytes(OverriddenFilesInfo->OverriddenFiles);
2156
2157 return size;
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00002158}