blob: 85fe474d6643e56d91c73296a6b7c9660eb9f6fa [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SourceManager.cpp - Track and cache source files -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the SourceManager interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Basic/SourceManager.h"
Douglas Gregord4f77aa2009-04-13 15:31:25 +000015#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregoraea67db2010-03-15 22:54:52 +000016#include "clang/Basic/Diagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/Basic/FileManager.h"
Benjamin Kramer5807d9c2010-11-18 12:46:39 +000018#include "llvm/ADT/StringSwitch.h"
Douglas Gregor86a4d0d2011-02-03 17:17:35 +000019#include "llvm/ADT/Optional.h"
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +000020#include "llvm/ADT/STLExtras.h"
Chris Lattner5e36a7a2007-07-24 05:57:19 +000021#include "llvm/Support/Compiler.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "llvm/Support/MemoryBuffer.h"
Chris Lattnerd57a7ef2009-08-23 22:45:33 +000023#include "llvm/Support/raw_ostream.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000024#include "llvm/Support/Path.h"
Ted Kremenek6e36c122011-07-27 18:41:16 +000025#include "llvm/Support/Capacity.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000026#include <algorithm>
Douglas Gregoraea67db2010-03-15 22:54:52 +000027#include <string>
Douglas Gregorf715ca12010-03-16 00:06:06 +000028#include <cstring>
Douglas Gregor86a4d0d2011-02-03 17:17:35 +000029#include <sys/stat.h>
Douglas Gregoraea67db2010-03-15 22:54:52 +000030
Reid Spencer5f016e22007-07-11 17:01:13 +000031using namespace clang;
32using namespace SrcMgr;
33using llvm::MemoryBuffer;
34
Chris Lattner23b5dc62009-02-04 00:40:31 +000035//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +000036// SourceManager Helper Classes
Chris Lattner23b5dc62009-02-04 00:40:31 +000037//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +000038
Ted Kremenek78d85f52007-10-30 21:08:08 +000039ContentCache::~ContentCache() {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000040 if (shouldFreeBuffer())
41 delete Buffer.getPointer();
Reid Spencer5f016e22007-07-11 17:01:13 +000042}
43
Chandler Carruth3201f382011-07-26 05:17:23 +000044/// getSizeBytesMapped - Returns the number of bytes actually mapped for this
45/// ContentCache. This can be 0 if the MemBuffer was not actually expanded.
Ted Kremenekc16c2082009-01-06 01:55:26 +000046unsigned ContentCache::getSizeBytesMapped() const {
Douglas Gregorc8151082010-03-16 22:53:51 +000047 return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 0;
Ted Kremenekc16c2082009-01-06 01:55:26 +000048}
49
Ted Kremenekf61b8312011-04-28 20:36:42 +000050/// Returns the kind of memory used to back the memory buffer for
51/// this content cache. This is used for performance analysis.
52llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const {
53 assert(Buffer.getPointer());
54
55 // Should be unreachable, but keep for sanity.
56 if (!Buffer.getPointer())
57 return llvm::MemoryBuffer::MemoryBuffer_Malloc;
58
59 const llvm::MemoryBuffer *buf = Buffer.getPointer();
60 return buf->getBufferKind();
61}
62
Ted Kremenekc16c2082009-01-06 01:55:26 +000063/// getSize - Returns the size of the content encapsulated by this ContentCache.
64/// This can be the size of the source file or the size of an arbitrary
65/// scratch buffer. If the ContentCache encapsulates a source file, that
Douglas Gregor29684422009-12-02 06:49:09 +000066/// file is not lazily brought in from disk to satisfy this query.
Ted Kremenekc16c2082009-01-06 01:55:26 +000067unsigned ContentCache::getSize() const {
Douglas Gregorc8151082010-03-16 22:53:51 +000068 return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize()
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +000069 : (unsigned) ContentsEntry->getSize();
Ted Kremenekc16c2082009-01-06 01:55:26 +000070}
71
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000072void ContentCache::replaceBuffer(const llvm::MemoryBuffer *B,
73 bool DoNotFree) {
Douglas Gregorc8151082010-03-16 22:53:51 +000074 assert(B != Buffer.getPointer());
Douglas Gregor29684422009-12-02 06:49:09 +000075
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000076 if (shouldFreeBuffer())
77 delete Buffer.getPointer();
Douglas Gregorc8151082010-03-16 22:53:51 +000078 Buffer.setPointer(B);
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000079 Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
Douglas Gregor29684422009-12-02 06:49:09 +000080}
81
David Blaikied6471f72011-09-25 23:23:43 +000082const llvm::MemoryBuffer *ContentCache::getBuffer(DiagnosticsEngine &Diag,
Chris Lattner5c5db4e2010-04-20 20:49:23 +000083 const SourceManager &SM,
Chris Lattnere127a0d2010-04-20 20:35:58 +000084 SourceLocation Loc,
Douglas Gregor36c35ba2010-03-16 00:35:39 +000085 bool *Invalid) const {
Chris Lattnerb088cd32010-11-23 08:50:03 +000086 // Lazily create the Buffer for ContentCaches that wrap files. If we already
Chris Lattnerfc8f0e12011-04-15 05:22:18 +000087 // computed it, just return what we have.
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +000088 if (Buffer.getPointer() || ContentsEntry == 0) {
Chris Lattnerb088cd32010-11-23 08:50:03 +000089 if (Invalid)
90 *Invalid = isBufferInvalid();
Chris Lattner38caec42010-04-20 18:14:03 +000091
Chris Lattnerb088cd32010-11-23 08:50:03 +000092 return Buffer.getPointer();
93 }
Benjamin Kramer5807d9c2010-11-18 12:46:39 +000094
Chris Lattnerb088cd32010-11-23 08:50:03 +000095 std::string ErrorStr;
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +000096 Buffer.setPointer(SM.getFileManager().getBufferForFile(ContentsEntry, &ErrorStr));
Chris Lattnerb088cd32010-11-23 08:50:03 +000097
98 // If we were unable to open the file, then we are in an inconsistent
99 // situation where the content cache referenced a file which no longer
100 // exists. Most likely, we were using a stat cache with an invalid entry but
101 // the file could also have been removed during processing. Since we can't
102 // really deal with this situation, just create an empty buffer.
103 //
104 // FIXME: This is definitely not ideal, but our immediate clients can't
105 // currently handle returning a null entry here. Ideally we should detect
106 // that we are in an inconsistent situation and error out as quickly as
107 // possible.
108 if (!Buffer.getPointer()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000109 const StringRef FillStr("<<<MISSING SOURCE FILE>>>\n");
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000110 Buffer.setPointer(MemoryBuffer::getNewMemBuffer(ContentsEntry->getSize(),
Chris Lattnerb088cd32010-11-23 08:50:03 +0000111 "<invalid>"));
112 char *Ptr = const_cast<char*>(Buffer.getPointer()->getBufferStart());
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000113 for (unsigned i = 0, e = ContentsEntry->getSize(); i != e; ++i)
Chris Lattnerb088cd32010-11-23 08:50:03 +0000114 Ptr[i] = FillStr[i % FillStr.size()];
115
116 if (Diag.isDiagnosticInFlight())
117 Diag.SetDelayedDiagnostic(diag::err_cannot_open_file,
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000118 ContentsEntry->getName(), ErrorStr);
Chris Lattnerb088cd32010-11-23 08:50:03 +0000119 else
120 Diag.Report(Loc, diag::err_cannot_open_file)
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000121 << ContentsEntry->getName() << ErrorStr;
Chris Lattnerb088cd32010-11-23 08:50:03 +0000122
123 Buffer.setInt(Buffer.getInt() | InvalidFlag);
124
125 if (Invalid) *Invalid = true;
126 return Buffer.getPointer();
127 }
128
129 // Check that the file's size is the same as in the file entry (which may
130 // have come from a stat cache).
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000131 if (getRawBuffer()->getBufferSize() != (size_t)ContentsEntry->getSize()) {
Chris Lattnerb088cd32010-11-23 08:50:03 +0000132 if (Diag.isDiagnosticInFlight())
133 Diag.SetDelayedDiagnostic(diag::err_file_modified,
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000134 ContentsEntry->getName());
Chris Lattnerb088cd32010-11-23 08:50:03 +0000135 else
136 Diag.Report(Loc, diag::err_file_modified)
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000137 << ContentsEntry->getName();
Chris Lattnerb088cd32010-11-23 08:50:03 +0000138
139 Buffer.setInt(Buffer.getInt() | InvalidFlag);
140 if (Invalid) *Invalid = true;
141 return Buffer.getPointer();
142 }
Eric Christopher156119d2011-04-09 00:01:04 +0000143
Chris Lattnerb088cd32010-11-23 08:50:03 +0000144 // If the buffer is valid, check to see if it has a UTF Byte Order Mark
Eric Christopher156119d2011-04-09 00:01:04 +0000145 // (BOM). We only support UTF-8 with and without a BOM right now. See
Chris Lattnerb088cd32010-11-23 08:50:03 +0000146 // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000147 StringRef BufStr = Buffer.getPointer()->getBuffer();
Eric Christopher156119d2011-04-09 00:01:04 +0000148 const char *InvalidBOM = llvm::StringSwitch<const char *>(BufStr)
Chris Lattnerb088cd32010-11-23 08:50:03 +0000149 .StartsWith("\xFE\xFF", "UTF-16 (BE)")
150 .StartsWith("\xFF\xFE", "UTF-16 (LE)")
151 .StartsWith("\x00\x00\xFE\xFF", "UTF-32 (BE)")
152 .StartsWith("\xFF\xFE\x00\x00", "UTF-32 (LE)")
153 .StartsWith("\x2B\x2F\x76", "UTF-7")
154 .StartsWith("\xF7\x64\x4C", "UTF-1")
155 .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC")
156 .StartsWith("\x0E\xFE\xFF", "SDSU")
157 .StartsWith("\xFB\xEE\x28", "BOCU-1")
158 .StartsWith("\x84\x31\x95\x33", "GB-18030")
159 .Default(0);
160
Eric Christopher156119d2011-04-09 00:01:04 +0000161 if (InvalidBOM) {
Chris Lattnerb088cd32010-11-23 08:50:03 +0000162 Diag.Report(Loc, diag::err_unsupported_bom)
Eric Christopher156119d2011-04-09 00:01:04 +0000163 << InvalidBOM << ContentsEntry->getName();
Chris Lattnerb088cd32010-11-23 08:50:03 +0000164 Buffer.setInt(Buffer.getInt() | InvalidFlag);
Ted Kremenek5b034ad2009-01-06 22:43:04 +0000165 }
Douglas Gregoraea67db2010-03-15 22:54:52 +0000166
Douglas Gregorc8151082010-03-16 22:53:51 +0000167 if (Invalid)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000168 *Invalid = isBufferInvalid();
Douglas Gregorc8151082010-03-16 22:53:51 +0000169
170 return Buffer.getPointer();
Ted Kremenekc16c2082009-01-06 01:55:26 +0000171}
172
Chris Lattner5f9e2722011-07-23 10:55:15 +0000173unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000174 // Look up the filename in the string table, returning the pre-existing value
175 // if it exists.
Mike Stump1eb44332009-09-09 15:08:12 +0000176 llvm::StringMapEntry<unsigned> &Entry =
Jay Foad65aa6882011-06-21 15:13:30 +0000177 FilenameIDs.GetOrCreateValue(Name, ~0U);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000178 if (Entry.getValue() != ~0U)
179 return Entry.getValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000180
Chris Lattner5b9a5042009-01-26 07:57:50 +0000181 // Otherwise, assign this the next available ID.
182 Entry.setValue(FilenamesByID.size());
183 FilenamesByID.push_back(&Entry);
184 return FilenamesByID.size()-1;
185}
186
Chris Lattnerac50e342009-02-03 22:13:05 +0000187/// AddLineNote - Add a line note to the line table that indicates that there
188/// is a #line at the specified FID/Offset location which changes the presumed
189/// location to LineNo/FilenameID.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000190void LineTableInfo::AddLineNote(int 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
218/// presumed #include stack. If it is 1, this is a file entry, if it is 2 then
219/// this is a file exit. FileKind specifies whether this is a system header or
220/// extern C system header.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000221void LineTableInfo::AddLineNote(int 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 Gregorf62d43d2011-07-19 16:10:42 +0000255const LineEntry *LineTableInfo::FindNearestLineEntry(int 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);
268 if (I == Entries.begin()) return 0;
269 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 Gregorf62d43d2011-07-19 16:10:42 +0000274void LineTableInfo::AddEntry(int 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) {
Chris Lattner5b9a5042009-01-26 07:57:50 +0000282 if (LineTable == 0)
283 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
Chris Lattnerac50e342009-02-03 22:13:05 +0000305 if (LineTable == 0)
306 LineTable = new LineTableInfo();
Chris Lattner23b5dc62009-02-04 00:40:31 +0000307 LineTable->AddLineNote(LocInfo.first.ID, 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
Chris Lattner9d79eba2009-02-04 05:21:58 +0000335 if (LineTable == 0)
336 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
Chris Lattner9d79eba2009-02-04 05:21:58 +0000352 LineTable->AddLineNote(LocInfo.first.ID, LocInfo.second, LineNo, FilenameID,
353 EntryExit, FileKind);
354}
355
Douglas Gregorbd945002009-04-13 16:31:14 +0000356LineTableInfo &SourceManager::getLineTable() {
357 if (LineTable == 0)
358 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
David Blaikied6471f72011-09-25 23:23:43 +0000366SourceManager::SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr)
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +0000367 : Diag(Diag), FileMgr(FileMgr), OverridenFilesKeepOriginalName(true),
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000368 ExternalSLocEntries(0), LineTable(0), NumLinearScans(0),
Douglas Gregore23ac652011-04-20 00:21:03 +0000369 NumBinaryProbes(0), FakeBufferForRecovery(0) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000370 clearIDTables();
371 Diag.setSourceManager(this);
372}
373
Chris Lattner5b9a5042009-01-26 07:57:50 +0000374SourceManager::~SourceManager() {
375 delete LineTable;
Mike Stump1eb44332009-09-09 15:08:12 +0000376
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000377 // Delete FileEntry objects corresponding to content caches. Since the actual
378 // content cache objects are bump pointer allocated, we just have to run the
379 // dtors, but we call the deallocate method for completeness.
380 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) {
381 MemBufferInfos[i]->~ContentCache();
382 ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
383 }
384 for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
385 I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) {
386 I->second->~ContentCache();
387 ContentCacheAlloc.Deallocate(I->second);
388 }
Douglas Gregore23ac652011-04-20 00:21:03 +0000389
390 delete FakeBufferForRecovery;
Argyrios Kyrtzidisfb3612e2011-09-26 08:01:50 +0000391
392 for (llvm::DenseMap<FileID, MacroArgsMap *>::iterator
393 I = MacroArgsCacheMap.begin(),E = MacroArgsCacheMap.end(); I!=E; ++I) {
394 delete I->second;
395 }
Chris Lattner5b9a5042009-01-26 07:57:50 +0000396}
397
398void SourceManager::clearIDTables() {
399 MainFileID = FileID();
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000400 LocalSLocEntryTable.clear();
401 LoadedSLocEntryTable.clear();
402 SLocEntryLoaded.clear();
Chris Lattner5b9a5042009-01-26 07:57:50 +0000403 LastLineNoFileIDQuery = FileID();
404 LastLineNoContentCache = 0;
405 LastFileIDLookup = FileID();
Mike Stump1eb44332009-09-09 15:08:12 +0000406
Chris Lattner5b9a5042009-01-26 07:57:50 +0000407 if (LineTable)
408 LineTable->clear();
Mike Stump1eb44332009-09-09 15:08:12 +0000409
Chandler Carruth3201f382011-07-26 05:17:23 +0000410 // Use up FileID #0 as an invalid expansion.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000411 NextLocalOffset = 0;
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +0000412 CurrentLoadedOffset = MaxLoadedOffset;
Chandler Carruthbf340e42011-07-26 03:03:05 +0000413 createExpansionLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1);
Chris Lattner5b9a5042009-01-26 07:57:50 +0000414}
415
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000416/// getOrCreateContentCache - Create or return a cached ContentCache for the
417/// specified file.
418const ContentCache *
419SourceManager::getOrCreateContentCache(const FileEntry *FileEnt) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000420 assert(FileEnt && "Didn't specify a file entry to use?");
Mike Stump1eb44332009-09-09 15:08:12 +0000421
Reid Spencer5f016e22007-07-11 17:01:13 +0000422 // Do we already have information about this file?
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000423 ContentCache *&Entry = FileInfos[FileEnt];
424 if (Entry) return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +0000425
Chris Lattner00282d62009-02-03 07:41:46 +0000426 // Nope, create a new Cache entry. Make sure it is at least 8-byte aligned
427 // so that FileInfo can use the low 3 bits of the pointer for its own
428 // nefarious purposes.
429 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
430 EntryAlign = std::max(8U, EntryAlign);
431 Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000432
433 // If the file contents are overridden with contents from another file,
434 // pass that file to ContentCache.
435 llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
436 overI = OverriddenFiles.find(FileEnt);
437 if (overI == OverriddenFiles.end())
438 new (Entry) ContentCache(FileEnt);
439 else
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +0000440 new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt
441 : overI->second,
442 overI->second);
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000443
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000444 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000445}
446
447
Ted Kremenekd1c0eee2007-10-31 17:53:38 +0000448/// createMemBufferContentCache - Create a new ContentCache for the specified
449/// memory buffer. This does no caching.
Ted Kremenek78d85f52007-10-30 21:08:08 +0000450const ContentCache*
451SourceManager::createMemBufferContentCache(const MemoryBuffer *Buffer) {
Chris Lattner00282d62009-02-03 07:41:46 +0000452 // Add a new ContentCache to the MemBufferInfos list and return it. Make sure
453 // it is at least 8-byte aligned so that FileInfo can use the low 3 bits of
454 // the pointer for its own nefarious purposes.
455 unsigned EntryAlign = llvm::AlignOf<ContentCache>::Alignment;
456 EntryAlign = std::max(8U, EntryAlign);
457 ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>(1, EntryAlign);
Chris Lattner0d0bf8c2009-02-03 07:30:45 +0000458 new (Entry) ContentCache();
459 MemBufferInfos.push_back(Entry);
460 Entry->setBuffer(Buffer);
461 return Entry;
Reid Spencer5f016e22007-07-11 17:01:13 +0000462}
463
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000464std::pair<int, unsigned>
465SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries,
466 unsigned TotalSize) {
467 assert(ExternalSLocEntries && "Don't have an external sloc source");
468 LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries);
469 SLocEntryLoaded.resize(LoadedSLocEntryTable.size());
470 CurrentLoadedOffset -= TotalSize;
471 assert(CurrentLoadedOffset >= NextLocalOffset && "Out of source locations");
472 int ID = LoadedSLocEntryTable.size();
473 return std::make_pair(-ID - 1, CurrentLoadedOffset);
Douglas Gregor2bf1eb02009-04-27 21:28:04 +0000474}
475
Douglas Gregore23ac652011-04-20 00:21:03 +0000476/// \brief As part of recovering from missing or changed content, produce a
477/// fake, non-empty buffer.
478const llvm::MemoryBuffer *SourceManager::getFakeBufferForRecovery() const {
479 if (!FakeBufferForRecovery)
480 FakeBufferForRecovery
481 = llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>");
482
483 return FakeBufferForRecovery;
484}
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000485
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000486//===----------------------------------------------------------------------===//
Chandler Carruth3201f382011-07-26 05:17:23 +0000487// Methods to create new FileID's and macro expansions.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000488//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000489
Dan Gohman3f86b782010-08-26 21:27:06 +0000490/// createFileID - Create a new FileID for the specified ContentCache and
Ted Kremenek0d892d82007-10-30 22:57:35 +0000491/// include position. This works regardless of whether the ContentCache
492/// corresponds to a file or some other input source.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000493FileID SourceManager::createFileID(const ContentCache *File,
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000494 SourceLocation IncludePos,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000495 SrcMgr::CharacteristicKind FileCharacter,
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000496 int LoadedID, unsigned LoadedOffset) {
497 if (LoadedID < 0) {
498 assert(LoadedID != -1 && "Loading sentinel FileID");
499 unsigned Index = unsigned(-LoadedID) - 2;
500 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
501 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
502 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset,
503 FileInfo::get(IncludePos, File, FileCharacter));
504 SLocEntryLoaded[Index] = true;
505 return FileID::get(LoadedID);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000506 }
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000507 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset,
508 FileInfo::get(IncludePos, File,
509 FileCharacter)));
Ted Kremenekc16c2082009-01-06 01:55:26 +0000510 unsigned FileSize = File->getSize();
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000511 assert(NextLocalOffset + FileSize + 1 > NextLocalOffset &&
512 NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset &&
513 "Ran out of source locations!");
514 // We do a +1 here because we want a SourceLocation that means "the end of the
515 // file", e.g. for the "no newline at the end of the file" diagnostic.
516 NextLocalOffset += FileSize + 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000517
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000518 // Set LastFileIDLookup to the newly created file. The next getFileID call is
519 // almost guaranteed to be from that file.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000520 FileID FID = FileID::get(LocalSLocEntryTable.size()-1);
Argyrios Kyrtzidisea703f12009-06-23 00:42:06 +0000521 return LastFileIDLookup = FID;
Reid Spencer5f016e22007-07-11 17:01:13 +0000522}
523
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000524SourceLocation
Chandler Carruthbf340e42011-07-26 03:03:05 +0000525SourceManager::createMacroArgExpansionLoc(SourceLocation SpellingLoc,
526 SourceLocation ExpansionLoc,
527 unsigned TokLength) {
Chandler Carruth78df8362011-07-26 04:41:47 +0000528 ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc,
529 ExpansionLoc);
530 return createExpansionLocImpl(Info, TokLength);
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000531}
532
533SourceLocation
Chandler Carruthbf340e42011-07-26 03:03:05 +0000534SourceManager::createExpansionLoc(SourceLocation SpellingLoc,
535 SourceLocation ExpansionLocStart,
536 SourceLocation ExpansionLocEnd,
537 unsigned TokLength,
538 int LoadedID,
539 unsigned LoadedOffset) {
Chandler Carruth78df8362011-07-26 04:41:47 +0000540 ExpansionInfo Info = ExpansionInfo::create(SpellingLoc, ExpansionLocStart,
541 ExpansionLocEnd);
542 return createExpansionLocImpl(Info, TokLength, LoadedID, LoadedOffset);
Chandler Carruthbf340e42011-07-26 03:03:05 +0000543}
544
545SourceLocation
Chandler Carruth78df8362011-07-26 04:41:47 +0000546SourceManager::createExpansionLocImpl(const ExpansionInfo &Info,
Chandler Carruthbf340e42011-07-26 03:03:05 +0000547 unsigned TokLength,
548 int LoadedID,
549 unsigned LoadedOffset) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000550 if (LoadedID < 0) {
551 assert(LoadedID != -1 && "Loading sentinel FileID");
552 unsigned Index = unsigned(-LoadedID) - 2;
553 assert(Index < LoadedSLocEntryTable.size() && "FileID out of range");
554 assert(!SLocEntryLoaded[Index] && "FileID already loaded");
Chandler Carruth78df8362011-07-26 04:41:47 +0000555 LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info);
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000556 SLocEntryLoaded[Index] = true;
557 return SourceLocation::getMacroLoc(LoadedOffset);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000558 }
Chandler Carruth78df8362011-07-26 04:41:47 +0000559 LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000560 assert(NextLocalOffset + TokLength + 1 > NextLocalOffset &&
561 NextLocalOffset + TokLength + 1 <= CurrentLoadedOffset &&
562 "Ran out of source locations!");
563 // See createFileID for that +1.
564 NextLocalOffset += TokLength + 1;
565 return SourceLocation::getMacroLoc(NextLocalOffset - (TokLength + 1));
Reid Spencer5f016e22007-07-11 17:01:13 +0000566}
567
Douglas Gregor36c35ba2010-03-16 00:35:39 +0000568const llvm::MemoryBuffer *
Douglas Gregor50f6af72010-03-16 05:20:39 +0000569SourceManager::getMemoryBufferForFile(const FileEntry *File,
570 bool *Invalid) {
Douglas Gregor29684422009-12-02 06:49:09 +0000571 const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
Douglas Gregoraea67db2010-03-15 22:54:52 +0000572 assert(IR && "getOrCreateContentCache() cannot return NULL");
Chris Lattnere127a0d2010-04-20 20:35:58 +0000573 return IR->getBuffer(Diag, *this, SourceLocation(), Invalid);
Douglas Gregor29684422009-12-02 06:49:09 +0000574}
575
Dan Gohman0d06e992010-10-26 20:47:28 +0000576void SourceManager::overrideFileContents(const FileEntry *SourceFile,
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000577 const llvm::MemoryBuffer *Buffer,
578 bool DoNotFree) {
Douglas Gregor29684422009-12-02 06:49:09 +0000579 const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile);
Dan Gohman0d06e992010-10-26 20:47:28 +0000580 assert(IR && "getOrCreateContentCache() cannot return NULL");
Douglas Gregor29684422009-12-02 06:49:09 +0000581
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000582 const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree);
Douglas Gregora081da52011-11-16 20:05:18 +0000583 const_cast<SrcMgr::ContentCache *>(IR)->BufferOverridden = true;
Douglas Gregor29684422009-12-02 06:49:09 +0000584}
585
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000586void SourceManager::overrideFileContents(const FileEntry *SourceFile,
587 const FileEntry *NewFile) {
588 assert(SourceFile->getSize() == NewFile->getSize() &&
589 "Different sizes, use the FileManager to create a virtual file with "
590 "the correct size");
591 assert(FileInfos.count(SourceFile) == 0 &&
592 "This function should be called at the initialization stage, before "
593 "any parsing occurs.");
594 OverriddenFiles[SourceFile] = NewFile;
595}
596
Chris Lattner5f9e2722011-07-23 10:55:15 +0000597StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const {
Douglas Gregoraae58b02010-03-16 20:01:30 +0000598 bool MyInvalid = false;
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000599 const SLocEntry &SLoc = getSLocEntry(FID, &MyInvalid);
Douglas Gregore23ac652011-04-20 00:21:03 +0000600 if (!SLoc.isFile() || MyInvalid) {
Douglas Gregor3de84242011-01-31 22:42:36 +0000601 if (Invalid)
602 *Invalid = true;
603 return "<<<<<INVALID SOURCE LOCATION>>>>>";
604 }
605
606 const llvm::MemoryBuffer *Buf
607 = SLoc.getFile().getContentCache()->getBuffer(Diag, *this, SourceLocation(),
608 &MyInvalid);
Douglas Gregorf715ca12010-03-16 00:06:06 +0000609 if (Invalid)
Douglas Gregoraae58b02010-03-16 20:01:30 +0000610 *Invalid = MyInvalid;
611
612 if (MyInvalid)
Douglas Gregor3de84242011-01-31 22:42:36 +0000613 return "<<<<<INVALID SOURCE LOCATION>>>>>";
Douglas Gregoraae58b02010-03-16 20:01:30 +0000614
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000615 return Buf->getBuffer();
Douglas Gregoraea67db2010-03-15 22:54:52 +0000616}
Chris Lattner2b2453a2009-01-17 06:22:33 +0000617
Chris Lattner23b5dc62009-02-04 00:40:31 +0000618//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000619// SourceLocation manipulation methods.
Chris Lattner23b5dc62009-02-04 00:40:31 +0000620//===----------------------------------------------------------------------===//
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000621
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000622/// \brief Return the FileID for a SourceLocation.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000623///
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000624/// This is the cache-miss path of getFileID. Not as hot as that function, but
625/// still very important. It is responsible for finding the entry in the
626/// SLocEntry tables that contains the specified location.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000627FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const {
Douglas Gregore23ac652011-04-20 00:21:03 +0000628 if (!SLocOffset)
629 return FileID::get(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000630
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000631 // Now it is time to search for the correct file. See where the SLocOffset
632 // sits in the global view and consult local or loaded buffers for it.
633 if (SLocOffset < NextLocalOffset)
634 return getFileIDLocal(SLocOffset);
635 return getFileIDLoaded(SLocOffset);
636}
637
638/// \brief Return the FileID for a SourceLocation with a low offset.
639///
640/// This function knows that the SourceLocation is in a local buffer, not a
641/// loaded one.
642FileID SourceManager::getFileIDLocal(unsigned SLocOffset) const {
643 assert(SLocOffset < NextLocalOffset && "Bad function choice");
644
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000645 // After the first and second level caches, I see two common sorts of
Chandler Carruth3201f382011-07-26 05:17:23 +0000646 // behavior: 1) a lot of searched FileID's are "near" the cached file
647 // location or are "near" the cached expansion location. 2) others are just
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000648 // completely random and may be a very long way away.
649 //
650 // To handle this, we do a linear search for up to 8 steps to catch #1 quickly
651 // then we fall back to a less cache efficient, but more scalable, binary
652 // search to find the location.
Mike Stump1eb44332009-09-09 15:08:12 +0000653
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000654 // See if this is near the file point - worst case we start scanning from the
655 // most newly created FileID.
656 std::vector<SrcMgr::SLocEntry>::const_iterator I;
Mike Stump1eb44332009-09-09 15:08:12 +0000657
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000658 if (LastFileIDLookup.ID < 0 ||
659 LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000660 // Neither loc prunes our search.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000661 I = LocalSLocEntryTable.end();
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000662 } else {
663 // Perhaps it is near the file point.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000664 I = LocalSLocEntryTable.begin()+LastFileIDLookup.ID;
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000665 }
666
667 // Find the FileID that contains this. "I" is an iterator that points to a
668 // FileID whose offset is known to be larger than SLocOffset.
669 unsigned NumProbes = 0;
670 while (1) {
671 --I;
672 if (I->getOffset() <= SLocOffset) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000673 FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin()));
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000674
Chandler Carruth3201f382011-07-26 05:17:23 +0000675 // If this isn't an expansion, remember it. We have good locality across
676 // FileID lookups.
Chandler Carruth17287622011-07-26 04:56:51 +0000677 if (!I->isExpansion())
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000678 LastFileIDLookup = Res;
679 NumLinearScans += NumProbes+1;
680 return Res;
681 }
682 if (++NumProbes == 8)
683 break;
684 }
Mike Stump1eb44332009-09-09 15:08:12 +0000685
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000686 // Convert "I" back into an index. We know that it is an entry whose index is
687 // larger than the offset we are looking for.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000688 unsigned GreaterIndex = I - LocalSLocEntryTable.begin();
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000689 // LessIndex - This is the lower bound of the range that we're searching.
690 // We know that the offset corresponding to the FileID is is less than
691 // SLocOffset.
692 unsigned LessIndex = 0;
693 NumProbes = 0;
694 while (1) {
Douglas Gregore23ac652011-04-20 00:21:03 +0000695 bool Invalid = false;
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000696 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000697 unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset();
Douglas Gregore23ac652011-04-20 00:21:03 +0000698 if (Invalid)
699 return FileID::get(0);
700
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000701 ++NumProbes;
Mike Stump1eb44332009-09-09 15:08:12 +0000702
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000703 // If the offset of the midpoint is too large, chop the high side of the
704 // range to the midpoint.
705 if (MidOffset > SLocOffset) {
706 GreaterIndex = MiddleIndex;
707 continue;
708 }
Mike Stump1eb44332009-09-09 15:08:12 +0000709
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000710 // If the middle index contains the value, succeed and return.
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000711 // FIXME: This could be made faster by using a function that's aware of
712 // being in the local area.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000713 if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000714 FileID Res = FileID::get(MiddleIndex);
715
Chandler Carruth17287622011-07-26 04:56:51 +0000716 // If this isn't a macro expansion, remember it. We have good locality
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000717 // across FileID lookups.
Chandler Carruth17287622011-07-26 04:56:51 +0000718 if (!LocalSLocEntryTable[MiddleIndex].isExpansion())
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000719 LastFileIDLookup = Res;
720 NumBinaryProbes += NumProbes;
721 return Res;
722 }
Mike Stump1eb44332009-09-09 15:08:12 +0000723
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000724 // Otherwise, move the low-side up to the middle index.
725 LessIndex = MiddleIndex;
726 }
727}
728
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000729/// \brief Return the FileID for a SourceLocation with a high offset.
730///
731/// This function knows that the SourceLocation is in a loaded buffer, not a
732/// local one.
733FileID SourceManager::getFileIDLoaded(unsigned SLocOffset) const {
Argyrios Kyrtzidisc3b45752011-10-03 23:43:01 +0000734 // Sanity checking, otherwise a bug may lead to hanging in release build.
Argyrios Kyrtzidis82ccbe72011-10-25 00:29:44 +0000735 if (SLocOffset < CurrentLoadedOffset) {
736 assert(0 && "Invalid SLocOffset or bad function choice");
Argyrios Kyrtzidisc3b45752011-10-03 23:43:01 +0000737 return FileID();
Argyrios Kyrtzidis82ccbe72011-10-25 00:29:44 +0000738 }
Argyrios Kyrtzidisc3b45752011-10-03 23:43:01 +0000739
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000740 // Essentially the same as the local case, but the loaded array is sorted
741 // in the other direction.
742
743 // First do a linear scan from the last lookup position, if possible.
744 unsigned I;
745 int LastID = LastFileIDLookup.ID;
746 if (LastID >= 0 || getLoadedSLocEntryByID(LastID).getOffset() < SLocOffset)
747 I = 0;
748 else
749 I = (-LastID - 2) + 1;
750
751 unsigned NumProbes;
752 for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++I) {
753 // Make sure the entry is loaded!
754 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(I);
755 if (E.getOffset() <= SLocOffset) {
756 FileID Res = FileID::get(-int(I) - 2);
757
Chandler Carruth17287622011-07-26 04:56:51 +0000758 if (!E.isExpansion())
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000759 LastFileIDLookup = Res;
760 NumLinearScans += NumProbes + 1;
761 return Res;
762 }
763 }
764
765 // Linear scan failed. Do the binary search. Note the reverse sorting of the
766 // table: GreaterIndex is the one where the offset is greater, which is
767 // actually a lower index!
768 unsigned GreaterIndex = I;
769 unsigned LessIndex = LoadedSLocEntryTable.size();
770 NumProbes = 0;
771 while (1) {
772 ++NumProbes;
773 unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex;
774 const SrcMgr::SLocEntry &E = getLoadedSLocEntry(MiddleIndex);
775
776 ++NumProbes;
777
778 if (E.getOffset() > SLocOffset) {
779 GreaterIndex = MiddleIndex;
780 continue;
781 }
782
783 if (isOffsetInFileID(FileID::get(-int(MiddleIndex) - 2), SLocOffset)) {
784 FileID Res = FileID::get(-int(MiddleIndex) - 2);
Chandler Carruth17287622011-07-26 04:56:51 +0000785 if (!E.isExpansion())
Douglas Gregorf62d43d2011-07-19 16:10:42 +0000786 LastFileIDLookup = Res;
787 NumBinaryProbes += NumProbes;
788 return Res;
789 }
790
791 LessIndex = MiddleIndex;
792 }
793}
794
Chris Lattneraddb7972009-01-26 20:04:19 +0000795SourceLocation SourceManager::
Chandler Carruthf84ef952011-07-25 20:52:26 +0000796getExpansionLocSlowCase(SourceLocation Loc) const {
Chris Lattneraddb7972009-01-26 20:04:19 +0000797 do {
Chris Lattnera5c6c582010-02-12 19:31:35 +0000798 // Note: If Loc indicates an offset into a token that came from a macro
799 // expansion (e.g. the 5th character of the token) we do not want to add
Chandler Carruth17287622011-07-26 04:56:51 +0000800 // this offset when going to the expansion location. The expansion
Chris Lattnera5c6c582010-02-12 19:31:35 +0000801 // location is the macro invocation, which the offset has nothing to do
802 // with. This is unlike when we get the spelling loc, because the offset
803 // directly correspond to the token whose spelling we're inspecting.
Chandler Carruth17287622011-07-26 04:56:51 +0000804 Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart();
Chris Lattneraddb7972009-01-26 20:04:19 +0000805 } while (!Loc.isFileID());
806
807 return Loc;
808}
809
810SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const {
811 do {
812 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
Chandler Carruth17287622011-07-26 04:56:51 +0000813 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000814 Loc = Loc.getLocWithOffset(LocInfo.second);
Chris Lattneraddb7972009-01-26 20:04:19 +0000815 } while (!Loc.isFileID());
816 return Loc;
817}
818
Argyrios Kyrtzidis796dbfb2011-10-12 07:07:40 +0000819SourceLocation SourceManager::getFileLocSlowCase(SourceLocation Loc) const {
820 do {
821 if (isMacroArgExpansion(Loc))
822 Loc = getImmediateSpellingLoc(Loc);
823 else
824 Loc = getImmediateExpansionRange(Loc).first;
825 } while (!Loc.isFileID());
826 return Loc;
827}
828
Chris Lattneraddb7972009-01-26 20:04:19 +0000829
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000830std::pair<FileID, unsigned>
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000831SourceManager::getDecomposedExpansionLocSlowCase(
Argyrios Kyrtzidis8b86ef02011-07-07 03:40:27 +0000832 const SrcMgr::SLocEntry *E) const {
Chandler Carruth3201f382011-07-26 05:17:23 +0000833 // If this is an expansion record, walk through all the expansion points.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000834 FileID FID;
835 SourceLocation Loc;
Argyrios Kyrtzidis8b86ef02011-07-07 03:40:27 +0000836 unsigned Offset;
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000837 do {
Chandler Carruth17287622011-07-26 04:56:51 +0000838 Loc = E->getExpansion().getExpansionLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000839
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000840 FID = getFileID(Loc);
841 E = &getSLocEntry(FID);
Argyrios Kyrtzidis8b86ef02011-07-07 03:40:27 +0000842 Offset = Loc.getOffset()-E->getOffset();
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000843 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000844
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000845 return std::make_pair(FID, Offset);
846}
847
848std::pair<FileID, unsigned>
849SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E,
850 unsigned Offset) const {
Chandler Carruth3201f382011-07-26 05:17:23 +0000851 // If this is an expansion record, walk through all the expansion points.
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000852 FileID FID;
853 SourceLocation Loc;
854 do {
Chandler Carruth17287622011-07-26 04:56:51 +0000855 Loc = E->getExpansion().getSpellingLoc();
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000856 Loc = Loc.getLocWithOffset(Offset);
Mike Stump1eb44332009-09-09 15:08:12 +0000857
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000858 FID = getFileID(Loc);
859 E = &getSLocEntry(FID);
Argyrios Kyrtzidisb6c465e2011-08-23 21:02:41 +0000860 Offset = Loc.getOffset()-E->getOffset();
Chris Lattnerbcd1a1b2009-01-26 19:41:58 +0000861 } while (!Loc.isFileID());
Mike Stump1eb44332009-09-09 15:08:12 +0000862
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000863 return std::make_pair(FID, Offset);
864}
865
Chris Lattner387616e2009-02-17 08:04:48 +0000866/// getImmediateSpellingLoc - Given a SourceLocation object, return the
867/// spelling location referenced by the ID. This is the first level down
868/// towards the place where the characters that make up the lexed token can be
869/// found. This should not generally be used by clients.
870SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{
871 if (Loc.isFileID()) return Loc;
872 std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc);
Chandler Carruth17287622011-07-26 04:56:51 +0000873 Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc();
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000874 return Loc.getLocWithOffset(LocInfo.second);
Chris Lattner387616e2009-02-17 08:04:48 +0000875}
876
877
Chandler Carruth3201f382011-07-26 05:17:23 +0000878/// getImmediateExpansionRange - Loc is required to be an expansion location.
879/// Return the start/end of the expansion information.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000880std::pair<SourceLocation,SourceLocation>
Chandler Carruth999f7392011-07-25 20:52:21 +0000881SourceManager::getImmediateExpansionRange(SourceLocation Loc) const {
Chandler Carruth3201f382011-07-26 05:17:23 +0000882 assert(Loc.isMacroID() && "Not a macro expansion loc!");
Chandler Carruth17287622011-07-26 04:56:51 +0000883 const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion();
Chandler Carruth78df8362011-07-26 04:41:47 +0000884 return Expansion.getExpansionLocRange();
Chris Lattnere7fb4842009-02-15 20:52:18 +0000885}
886
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000887/// getExpansionRange - Given a SourceLocation object, return the range of
888/// tokens covered by the expansion in the ultimate file.
Chris Lattner66781332009-02-15 21:26:50 +0000889std::pair<SourceLocation,SourceLocation>
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000890SourceManager::getExpansionRange(SourceLocation Loc) const {
Chris Lattner66781332009-02-15 21:26:50 +0000891 if (Loc.isFileID()) return std::make_pair(Loc, Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000892
Chris Lattner66781332009-02-15 21:26:50 +0000893 std::pair<SourceLocation,SourceLocation> Res =
Chandler Carruth999f7392011-07-25 20:52:21 +0000894 getImmediateExpansionRange(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000895
Chandler Carruth3201f382011-07-26 05:17:23 +0000896 // Fully resolve the start and end locations to their ultimate expansion
Chris Lattner66781332009-02-15 21:26:50 +0000897 // points.
898 while (!Res.first.isFileID())
Chandler Carruth999f7392011-07-25 20:52:21 +0000899 Res.first = getImmediateExpansionRange(Res.first).first;
Chris Lattner66781332009-02-15 21:26:50 +0000900 while (!Res.second.isFileID())
Chandler Carruth999f7392011-07-25 20:52:21 +0000901 Res.second = getImmediateExpansionRange(Res.second).second;
Chris Lattner66781332009-02-15 21:26:50 +0000902 return Res;
903}
904
Chandler Carruth96d35892011-07-26 03:03:00 +0000905bool SourceManager::isMacroArgExpansion(SourceLocation Loc) const {
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000906 if (!Loc.isMacroID()) return false;
907
908 FileID FID = getFileID(Loc);
909 const SrcMgr::SLocEntry *E = &getSLocEntry(FID);
Chandler Carruth17287622011-07-26 04:56:51 +0000910 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
Chandler Carruth78df8362011-07-26 04:41:47 +0000911 return Expansion.isMacroArgExpansion();
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000912}
Chris Lattnere7fb4842009-02-15 20:52:18 +0000913
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000914
915//===----------------------------------------------------------------------===//
916// Queries about the code at a SourceLocation.
917//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +0000918
919/// getCharacterData - Return a pointer to the start of the specified location
920/// in the appropriate MemoryBuffer.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000921const char *SourceManager::getCharacterData(SourceLocation SL,
922 bool *Invalid) const {
Reid Spencer5f016e22007-07-11 17:01:13 +0000923 // Note that this is a hot function in the getSpelling() path, which is
924 // heavily used by -E mode.
Chris Lattnerde7aeef2009-01-26 00:43:02 +0000925 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL);
Mike Stump1eb44332009-09-09 15:08:12 +0000926
Ted Kremenekc16c2082009-01-06 01:55:26 +0000927 // Note that calling 'getBuffer()' may lazily page in a source file.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000928 bool CharDataInvalid = false;
Douglas Gregore23ac652011-04-20 00:21:03 +0000929 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid);
930 if (CharDataInvalid || !Entry.isFile()) {
931 if (Invalid)
932 *Invalid = true;
933
934 return "<<<<INVALID BUFFER>>>>";
935 }
Douglas Gregor50f6af72010-03-16 05:20:39 +0000936 const llvm::MemoryBuffer *Buffer
Douglas Gregore23ac652011-04-20 00:21:03 +0000937 = Entry.getFile().getContentCache()
938 ->getBuffer(Diag, *this, SourceLocation(), &CharDataInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000939 if (Invalid)
940 *Invalid = CharDataInvalid;
941 return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second);
Reid Spencer5f016e22007-07-11 17:01:13 +0000942}
943
Reid Spencer5f016e22007-07-11 17:01:13 +0000944
Chris Lattner9dc1f532007-07-20 16:37:10 +0000945/// getColumnNumber - Return the column # for the specified file position.
Chris Lattner7da5aea2009-02-04 00:55:58 +0000946/// this is significantly cheaper to compute than the line number.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000947unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
948 bool *Invalid) const {
949 bool MyInvalid = false;
Argyrios Kyrtzidisd5752542011-12-10 00:30:38 +0000950 const llvm::MemoryBuffer *MemBuf = getBuffer(FID, &MyInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000951 if (Invalid)
952 *Invalid = MyInvalid;
953
954 if (MyInvalid)
955 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +0000956
Argyrios Kyrtzidisd5752542011-12-10 00:30:38 +0000957 const char *Buf = MemBuf->getBufferStart();
958 if (Buf + FilePos >= MemBuf->getBufferEnd()) {
959 if (Invalid)
960 *Invalid = MyInvalid;
961 return 1;
962 }
963
Reid Spencer5f016e22007-07-11 17:01:13 +0000964 unsigned LineStart = FilePos;
965 while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r')
966 --LineStart;
967 return FilePos-LineStart+1;
968}
969
Zhanyong Wan1f24e112010-10-05 17:56:33 +0000970// isInvalid - Return the result of calling loc.isInvalid(), and
971// if Invalid is not null, set its value to same.
972static bool isInvalid(SourceLocation Loc, bool *Invalid) {
973 bool MyInvalid = Loc.isInvalid();
974 if (Invalid)
975 *Invalid = MyInvalid;
976 return MyInvalid;
977}
978
Douglas Gregor50f6af72010-03-16 05:20:39 +0000979unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc,
980 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +0000981 if (isInvalid(Loc, Invalid)) return 0;
Chris Lattner7da5aea2009-02-04 00:55:58 +0000982 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000983 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +0000984}
985
Chandler Carrutha77c0312011-07-25 20:57:57 +0000986unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc,
987 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +0000988 if (isInvalid(Loc, Invalid)) return 0;
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +0000989 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Douglas Gregor50f6af72010-03-16 05:20:39 +0000990 return getColumnNumber(LocInfo.first, LocInfo.second, Invalid);
Chris Lattner7da5aea2009-02-04 00:55:58 +0000991}
992
Chandler Carruth5ef04ee2011-02-23 00:47:48 +0000993unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc,
994 bool *Invalid) const {
995 if (isInvalid(Loc, Invalid)) return 0;
996 return getPresumedLoc(Loc).getColumn();
997}
998
Chandler Carruth14bd9652010-10-23 08:44:57 +0000999static LLVM_ATTRIBUTE_NOINLINE void
David Blaikied6471f72011-09-25 23:23:43 +00001000ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
Chris Lattnere127a0d2010-04-20 20:35:58 +00001001 llvm::BumpPtrAllocator &Alloc,
1002 const SourceManager &SM, bool &Invalid);
David Blaikied6471f72011-09-25 23:23:43 +00001003static void ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
Chris Lattnere127a0d2010-04-20 20:35:58 +00001004 llvm::BumpPtrAllocator &Alloc,
1005 const SourceManager &SM, bool &Invalid) {
Ted Kremenekc16c2082009-01-06 01:55:26 +00001006 // Note that calling 'getBuffer()' may lazily page in the file.
Chris Lattnere127a0d2010-04-20 20:35:58 +00001007 const MemoryBuffer *Buffer = FI->getBuffer(Diag, SM, SourceLocation(),
1008 &Invalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001009 if (Invalid)
1010 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001011
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001012 // Find the file offsets of all of the *physical* source lines. This does
1013 // not look at trigraphs, escaped newlines, or anything else tricky.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001014 SmallVector<unsigned, 256> LineOffsets;
Mike Stump1eb44332009-09-09 15:08:12 +00001015
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001016 // Line #1 starts at char 0.
1017 LineOffsets.push_back(0);
Mike Stump1eb44332009-09-09 15:08:12 +00001018
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001019 const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart();
1020 const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd();
1021 unsigned Offs = 0;
1022 while (1) {
1023 // Skip over the contents of the line.
1024 // TODO: Vectorize this? This is very performance sensitive for programs
1025 // with lots of diagnostics and in -E mode.
1026 const unsigned char *NextBuf = (const unsigned char *)Buf;
1027 while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0')
1028 ++NextBuf;
1029 Offs += NextBuf-Buf;
1030 Buf = NextBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00001031
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001032 if (Buf[0] == '\n' || Buf[0] == '\r') {
1033 // If this is \n\r or \r\n, skip both characters.
1034 if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1])
1035 ++Offs, ++Buf;
1036 ++Offs, ++Buf;
1037 LineOffsets.push_back(Offs);
1038 } else {
1039 // Otherwise, this is a null. If end of file, exit.
1040 if (Buf == End) break;
1041 // Otherwise, skip the null.
1042 ++Offs, ++Buf;
1043 }
1044 }
Mike Stump1eb44332009-09-09 15:08:12 +00001045
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001046 // Copy the offsets into the FileInfo structure.
1047 FI->NumLines = LineOffsets.size();
Chris Lattner0d0bf8c2009-02-03 07:30:45 +00001048 FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size());
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001049 std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache);
1050}
Reid Spencer5f016e22007-07-11 17:01:13 +00001051
Chris Lattnerdf7c17a2009-01-16 07:00:02 +00001052/// getLineNumber - Given a SourceLocation, return the spelling line number
Reid Spencer5f016e22007-07-11 17:01:13 +00001053/// for the position indicated. This requires building and caching a table of
1054/// line offsets for the MemoryBuffer, so this is not cheap: use only when
1055/// about to emit a diagnostic.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001056unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos,
1057 bool *Invalid) const {
Argyrios Kyrtzidis5adc0512011-05-17 22:09:53 +00001058 if (FID.isInvalid()) {
1059 if (Invalid)
1060 *Invalid = true;
1061 return 1;
1062 }
1063
Chris Lattner2b2453a2009-01-17 06:22:33 +00001064 ContentCache *Content;
Chris Lattner30fc9332009-02-04 01:06:56 +00001065 if (LastLineNoFileIDQuery == FID)
Ted Kremenek78d85f52007-10-30 21:08:08 +00001066 Content = LastLineNoContentCache;
Douglas Gregore23ac652011-04-20 00:21:03 +00001067 else {
1068 bool MyInvalid = false;
1069 const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid);
1070 if (MyInvalid || !Entry.isFile()) {
1071 if (Invalid)
1072 *Invalid = true;
1073 return 1;
1074 }
1075
1076 Content = const_cast<ContentCache*>(Entry.getFile().getContentCache());
1077 }
1078
Reid Spencer5f016e22007-07-11 17:01:13 +00001079 // If this is the first use of line information for this buffer, compute the
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001080 /// SourceLineCache for it on demand.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001081 if (Content->SourceLineCache == 0) {
1082 bool MyInvalid = false;
Chris Lattnere127a0d2010-04-20 20:35:58 +00001083 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001084 if (Invalid)
1085 *Invalid = MyInvalid;
1086 if (MyInvalid)
1087 return 1;
1088 } else if (Invalid)
1089 *Invalid = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001090
1091 // Okay, we know we have a line number table. Do a binary search to find the
1092 // line number that this character position lands on.
Ted Kremenek78d85f52007-10-30 21:08:08 +00001093 unsigned *SourceLineCache = Content->SourceLineCache;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001094 unsigned *SourceLineCacheStart = SourceLineCache;
Ted Kremenek78d85f52007-10-30 21:08:08 +00001095 unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines;
Mike Stump1eb44332009-09-09 15:08:12 +00001096
Chris Lattner30fc9332009-02-04 01:06:56 +00001097 unsigned QueriedFilePos = FilePos+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001098
Daniel Dunbar4106d692009-05-18 17:30:52 +00001099 // FIXME: I would like to be convinced that this code is worth being as
Mike Stump1eb44332009-09-09 15:08:12 +00001100 // complicated as it is, binary search isn't that slow.
Daniel Dunbar4106d692009-05-18 17:30:52 +00001101 //
1102 // If it is worth being optimized, then in my opinion it could be more
1103 // performant, simpler, and more obviously correct by just "galloping" outward
1104 // from the queried file position. In fact, this could be incorporated into a
1105 // generic algorithm such as lower_bound_with_hint.
1106 //
1107 // If someone gives me a test case where this matters, and I will do it! - DWD
1108
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001109 // If the previous query was to the same file, we know both the file pos from
1110 // that query and the line number returned. This allows us to narrow the
1111 // search space from the entire file to something near the match.
Chris Lattner30fc9332009-02-04 01:06:56 +00001112 if (LastLineNoFileIDQuery == FID) {
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001113 if (QueriedFilePos >= LastLineNoFilePos) {
Daniel Dunbar4106d692009-05-18 17:30:52 +00001114 // FIXME: Potential overflow?
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001115 SourceLineCache = SourceLineCache+LastLineNoResult-1;
Mike Stump1eb44332009-09-09 15:08:12 +00001116
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001117 // The query is likely to be nearby the previous one. Here we check to
1118 // see if it is within 5, 10 or 20 lines. It can be far away in cases
1119 // where big comment blocks and vertical whitespace eat up lines but
1120 // contribute no tokens.
1121 if (SourceLineCache+5 < SourceLineCacheEnd) {
1122 if (SourceLineCache[5] > QueriedFilePos)
1123 SourceLineCacheEnd = SourceLineCache+5;
1124 else if (SourceLineCache+10 < SourceLineCacheEnd) {
1125 if (SourceLineCache[10] > QueriedFilePos)
1126 SourceLineCacheEnd = SourceLineCache+10;
1127 else if (SourceLineCache+20 < SourceLineCacheEnd) {
1128 if (SourceLineCache[20] > QueriedFilePos)
1129 SourceLineCacheEnd = SourceLineCache+20;
1130 }
1131 }
1132 }
1133 } else {
Daniel Dunbar4106d692009-05-18 17:30:52 +00001134 if (LastLineNoResult < Content->NumLines)
1135 SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001136 }
1137 }
Mike Stump1eb44332009-09-09 15:08:12 +00001138
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001139 // If the spread is large, do a "radix" test as our initial guess, based on
1140 // the assumption that lines average to approximately the same length.
1141 // NOTE: This is currently disabled, as it does not appear to be profitable in
1142 // initial measurements.
1143 if (0 && SourceLineCacheEnd-SourceLineCache > 20) {
Ted Kremenek78d85f52007-10-30 21:08:08 +00001144 unsigned FileLen = Content->SourceLineCache[Content->NumLines-1];
Mike Stump1eb44332009-09-09 15:08:12 +00001145
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001146 // Take a stab at guessing where it is.
Ted Kremenek78d85f52007-10-30 21:08:08 +00001147 unsigned ApproxPos = Content->NumLines*QueriedFilePos / FileLen;
Mike Stump1eb44332009-09-09 15:08:12 +00001148
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001149 // Check for -10 and +10 lines.
1150 unsigned LowerBound = std::max(int(ApproxPos-10), 0);
1151 unsigned UpperBound = std::min(ApproxPos+10, FileLen);
1152
1153 // If the computed lower bound is less than the query location, move it in.
1154 if (SourceLineCache < SourceLineCacheStart+LowerBound &&
1155 SourceLineCacheStart[LowerBound] < QueriedFilePos)
1156 SourceLineCache = SourceLineCacheStart+LowerBound;
Mike Stump1eb44332009-09-09 15:08:12 +00001157
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001158 // If the computed upper bound is greater than the query location, move it.
1159 if (SourceLineCacheEnd > SourceLineCacheStart+UpperBound &&
1160 SourceLineCacheStart[UpperBound] >= QueriedFilePos)
1161 SourceLineCacheEnd = SourceLineCacheStart+UpperBound;
1162 }
Mike Stump1eb44332009-09-09 15:08:12 +00001163
Chris Lattner1cf12bf2007-07-24 06:43:46 +00001164 unsigned *Pos
1165 = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos);
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001166 unsigned LineNo = Pos-SourceLineCacheStart;
Mike Stump1eb44332009-09-09 15:08:12 +00001167
Chris Lattner30fc9332009-02-04 01:06:56 +00001168 LastLineNoFileIDQuery = FID;
Ted Kremenek78d85f52007-10-30 21:08:08 +00001169 LastLineNoContentCache = Content;
Chris Lattner5e36a7a2007-07-24 05:57:19 +00001170 LastLineNoFilePos = QueriedFilePos;
1171 LastLineNoResult = LineNo;
1172 return LineNo;
Reid Spencer5f016e22007-07-11 17:01:13 +00001173}
1174
Chandler Carruth5ef04ee2011-02-23 00:47:48 +00001175unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc,
1176 bool *Invalid) const {
1177 if (isInvalid(Loc, Invalid)) return 0;
1178 std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc);
1179 return getLineNumber(LocInfo.first, LocInfo.second);
1180}
Chandler Carruth64211622011-07-25 21:09:52 +00001181unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc,
1182 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001183 if (isInvalid(Loc, Invalid)) return 0;
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +00001184 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Chris Lattner30fc9332009-02-04 01:06:56 +00001185 return getLineNumber(LocInfo.first, LocInfo.second);
1186}
Chandler Carruth5ef04ee2011-02-23 00:47:48 +00001187unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc,
Douglas Gregor50f6af72010-03-16 05:20:39 +00001188 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001189 if (isInvalid(Loc, Invalid)) return 0;
Chandler Carruth5ef04ee2011-02-23 00:47:48 +00001190 return getPresumedLoc(Loc).getLine();
Chris Lattner30fc9332009-02-04 01:06:56 +00001191}
1192
Chris Lattner6b306672009-02-04 05:33:01 +00001193/// getFileCharacteristic - return the file characteristic of the specified
Mike Stump1eb44332009-09-09 15:08:12 +00001194/// source location, indicating whether this is a normal file, a system
Chris Lattner6b306672009-02-04 05:33:01 +00001195/// header, or an "implicit extern C" system header.
1196///
1197/// This state can be modified with flags on GNU linemarker directives like:
1198/// # 4 "foo.h" 3
1199/// which changes all source locations in the current file after that to be
1200/// considered to be from a system header.
Mike Stump1eb44332009-09-09 15:08:12 +00001201SrcMgr::CharacteristicKind
Chris Lattner6b306672009-02-04 05:33:01 +00001202SourceManager::getFileCharacteristic(SourceLocation Loc) const {
1203 assert(!Loc.isInvalid() && "Can't get file characteristic of invalid loc!");
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +00001204 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Douglas Gregore23ac652011-04-20 00:21:03 +00001205 bool Invalid = false;
1206 const SLocEntry &SEntry = getSLocEntry(LocInfo.first, &Invalid);
1207 if (Invalid || !SEntry.isFile())
1208 return C_User;
1209
1210 const SrcMgr::FileInfo &FI = SEntry.getFile();
Chris Lattner6b306672009-02-04 05:33:01 +00001211
1212 // If there are no #line directives in this file, just return the whole-file
1213 // state.
1214 if (!FI.hasLineDirectives())
1215 return FI.getFileCharacteristic();
Mike Stump1eb44332009-09-09 15:08:12 +00001216
Chris Lattner6b306672009-02-04 05:33:01 +00001217 assert(LineTable && "Can't have linetable entries without a LineTable!");
1218 // See if there is a #line directive before the location.
1219 const LineEntry *Entry =
1220 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001221
Chris Lattner6b306672009-02-04 05:33:01 +00001222 // If this is before the first line marker, use the file characteristic.
1223 if (!Entry)
1224 return FI.getFileCharacteristic();
1225
1226 return Entry->FileKind;
1227}
1228
Chris Lattnerbff5c512009-02-17 08:39:06 +00001229/// Return the filename or buffer identifier of the buffer the location is in.
1230/// Note that this name does not respect #line directives. Use getPresumedLoc
1231/// for normal clients.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001232const char *SourceManager::getBufferName(SourceLocation Loc,
1233 bool *Invalid) const {
Zhanyong Wan1f24e112010-10-05 17:56:33 +00001234 if (isInvalid(Loc, Invalid)) return "<invalid loc>";
Mike Stump1eb44332009-09-09 15:08:12 +00001235
Douglas Gregor50f6af72010-03-16 05:20:39 +00001236 return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
Chris Lattnerbff5c512009-02-17 08:39:06 +00001237}
1238
Chris Lattner30fc9332009-02-04 01:06:56 +00001239
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001240/// getPresumedLoc - This method returns the "presumed" location of a
1241/// SourceLocation specifies. A "presumed location" can be modified by #line
1242/// or GNU line marker directives. This provides a view on the data that a
1243/// user should see in diagnostics, for example.
1244///
Chandler Carruth3201f382011-07-26 05:17:23 +00001245/// Note that a presumed location is always given as the expansion point of an
1246/// expansion location, not at the spelling location.
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001247PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc) const {
1248 if (Loc.isInvalid()) return PresumedLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001249
Chandler Carruth3201f382011-07-26 05:17:23 +00001250 // Presumed locations are always for expansion points.
Chandler Carruthe7b2b6e2011-07-25 20:52:32 +00001251 std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +00001252
Douglas Gregore23ac652011-04-20 00:21:03 +00001253 bool Invalid = false;
1254 const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid);
1255 if (Invalid || !Entry.isFile())
1256 return PresumedLoc();
1257
1258 const SrcMgr::FileInfo &FI = Entry.getFile();
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001259 const SrcMgr::ContentCache *C = FI.getContentCache();
Mike Stump1eb44332009-09-09 15:08:12 +00001260
Chris Lattner3cd949c2009-02-04 01:55:42 +00001261 // To get the source name, first consult the FileEntry (if one exists)
1262 // before the MemBuffer as this will avoid unnecessarily paging in the
1263 // MemBuffer.
Chris Lattnere127a0d2010-04-20 20:35:58 +00001264 const char *Filename;
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001265 if (C->OrigEntry)
1266 Filename = C->OrigEntry->getName();
Chris Lattnere127a0d2010-04-20 20:35:58 +00001267 else
1268 Filename = C->getBuffer(Diag, *this)->getBufferIdentifier();
Douglas Gregore23ac652011-04-20 00:21:03 +00001269
Douglas Gregorc417fa02010-11-02 00:39:22 +00001270 unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid);
1271 if (Invalid)
1272 return PresumedLoc();
1273 unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid);
1274 if (Invalid)
1275 return PresumedLoc();
1276
Chris Lattner3cd949c2009-02-04 01:55:42 +00001277 SourceLocation IncludeLoc = FI.getIncludeLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001278
Chris Lattner3cd949c2009-02-04 01:55:42 +00001279 // If we have #line directives in this file, update and overwrite the physical
1280 // location info if appropriate.
1281 if (FI.hasLineDirectives()) {
1282 assert(LineTable && "Can't have linetable entries without a LineTable!");
1283 // See if there is a #line directive before this. If so, get it.
1284 if (const LineEntry *Entry =
1285 LineTable->FindNearestLineEntry(LocInfo.first.ID, LocInfo.second)) {
Chris Lattnerfc391332009-02-04 02:00:59 +00001286 // If the LineEntry indicates a filename, use it.
Chris Lattner3cd949c2009-02-04 01:55:42 +00001287 if (Entry->FilenameID != -1)
1288 Filename = LineTable->getFilename(Entry->FilenameID);
Chris Lattnerfc391332009-02-04 02:00:59 +00001289
1290 // Use the line number specified by the LineEntry. This line number may
1291 // be multiple lines down from the line entry. Add the difference in
1292 // physical line numbers from the query point and the line marker to the
1293 // total.
1294 unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset);
1295 LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001296
Chris Lattner0e0e5da2009-02-04 02:15:40 +00001297 // Note that column numbers are not molested by line markers.
Mike Stump1eb44332009-09-09 15:08:12 +00001298
Chris Lattner137b6a62009-02-04 06:25:26 +00001299 // Handle virtual #include manipulation.
1300 if (Entry->IncludeOffset) {
1301 IncludeLoc = getLocForStartOfFile(LocInfo.first);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001302 IncludeLoc = IncludeLoc.getLocWithOffset(Entry->IncludeOffset);
Chris Lattner137b6a62009-02-04 06:25:26 +00001303 }
Chris Lattner3cd949c2009-02-04 01:55:42 +00001304 }
1305 }
1306
1307 return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc);
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001308}
1309
Argyrios Kyrtzidis984e42c2011-08-23 21:02:28 +00001310/// \brief The size of the SLocEnty that \arg FID represents.
1311unsigned SourceManager::getFileIDSize(FileID FID) const {
1312 bool Invalid = false;
1313 const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1314 if (Invalid)
1315 return 0;
1316
1317 int ID = FID.ID;
1318 unsigned NextOffset;
1319 if ((ID > 0 && unsigned(ID+1) == local_sloc_entry_size()))
1320 NextOffset = getNextLocalOffset();
1321 else if (ID+1 == -1)
1322 NextOffset = MaxLoadedOffset;
1323 else
1324 NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset();
1325
1326 return NextOffset - Entry.getOffset() - 1;
1327}
1328
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001329//===----------------------------------------------------------------------===//
1330// Other miscellaneous methods.
1331//===----------------------------------------------------------------------===//
1332
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001333/// \brief Retrieve the inode for the given file entry, if possible.
1334///
1335/// This routine involves a system call, and therefore should only be used
1336/// in non-performance-critical code.
1337static llvm::Optional<ino_t> getActualFileInode(const FileEntry *File) {
1338 if (!File)
1339 return llvm::Optional<ino_t>();
1340
1341 struct stat StatBuf;
1342 if (::stat(File->getName(), &StatBuf))
1343 return llvm::Optional<ino_t>();
1344
1345 return StatBuf.st_ino;
1346}
1347
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001348/// \brief Get the source location for the given file:line:col triplet.
1349///
1350/// If the source file is included multiple times, the source location will
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001351/// be based upon an arbitrary inclusion.
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001352SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile,
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001353 unsigned Line,
1354 unsigned Col) const {
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001355 assert(SourceFile && "Null source file!");
1356 assert(Line && Col && "Line and column should start from 1!");
1357
Argyrios Kyrtzidisb201e162011-09-27 17:22:25 +00001358 FileID FirstFID = translateFile(SourceFile);
1359 return translateLineCol(FirstFID, Line, Col);
1360}
1361
1362/// \brief Get the FileID for the given file.
1363///
1364/// If the source file is included multiple times, the FileID will be the
1365/// first inclusion.
1366FileID SourceManager::translateFile(const FileEntry *SourceFile) const {
1367 assert(SourceFile && "Null source file!");
1368
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001369 // Find the first file ID that corresponds to the given file.
1370 FileID FirstFID;
Mike Stump1eb44332009-09-09 15:08:12 +00001371
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001372 // First, check the main file ID, since it is common to look for a
1373 // location in the main file.
1374 llvm::Optional<ino_t> SourceFileInode;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001375 llvm::Optional<StringRef> SourceFileName;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001376 if (!MainFileID.isInvalid()) {
Douglas Gregore23ac652011-04-20 00:21:03 +00001377 bool Invalid = false;
1378 const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid);
1379 if (Invalid)
Argyrios Kyrtzidisb201e162011-09-27 17:22:25 +00001380 return FileID();
Douglas Gregore23ac652011-04-20 00:21:03 +00001381
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001382 if (MainSLoc.isFile()) {
1383 const ContentCache *MainContentCache
1384 = MainSLoc.getFile().getContentCache();
Douglas Gregorb7a18412011-02-11 18:08:15 +00001385 if (!MainContentCache) {
1386 // Can't do anything
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001387 } else if (MainContentCache->OrigEntry == SourceFile) {
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001388 FirstFID = MainFileID;
Douglas Gregorb7a18412011-02-11 18:08:15 +00001389 } else {
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001390 // Fall back: check whether we have the same base name and inode
1391 // as the main file.
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001392 const FileEntry *MainFile = MainContentCache->OrigEntry;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001393 SourceFileName = llvm::sys::path::filename(SourceFile->getName());
1394 if (*SourceFileName == llvm::sys::path::filename(MainFile->getName())) {
1395 SourceFileInode = getActualFileInode(SourceFile);
Douglas Gregor37c02bf2011-02-16 19:09:24 +00001396 if (SourceFileInode) {
1397 if (llvm::Optional<ino_t> MainFileInode
1398 = getActualFileInode(MainFile)) {
1399 if (*SourceFileInode == *MainFileInode) {
1400 FirstFID = MainFileID;
1401 SourceFile = MainFile;
1402 }
1403 }
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001404 }
1405 }
1406 }
1407 }
1408 }
1409
1410 if (FirstFID.isInvalid()) {
1411 // The location we're looking for isn't in the main file; look
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001412 // through all of the local source locations.
1413 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
Douglas Gregore23ac652011-04-20 00:21:03 +00001414 bool Invalid = false;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001415 const SLocEntry &SLoc = getLocalSLocEntry(I, &Invalid);
Douglas Gregore23ac652011-04-20 00:21:03 +00001416 if (Invalid)
Argyrios Kyrtzidisb201e162011-09-27 17:22:25 +00001417 return FileID();
Douglas Gregore23ac652011-04-20 00:21:03 +00001418
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001419 if (SLoc.isFile() &&
1420 SLoc.getFile().getContentCache() &&
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001421 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001422 FirstFID = FileID::get(I);
1423 break;
1424 }
1425 }
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001426 // If that still didn't help, try the modules.
1427 if (FirstFID.isInvalid()) {
1428 for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) {
1429 const SLocEntry &SLoc = getLoadedSLocEntry(I);
1430 if (SLoc.isFile() &&
1431 SLoc.getFile().getContentCache() &&
1432 SLoc.getFile().getContentCache()->OrigEntry == SourceFile) {
1433 FirstFID = FileID::get(-int(I) - 2);
1434 break;
1435 }
1436 }
1437 }
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001438 }
1439
1440 // If we haven't found what we want yet, try again, but this time stat()
1441 // each of the files in case the files have changed since we originally
1442 // parsed the file.
1443 if (FirstFID.isInvalid() &&
1444 (SourceFileName ||
1445 (SourceFileName = llvm::sys::path::filename(SourceFile->getName()))) &&
1446 (SourceFileInode ||
1447 (SourceFileInode = getActualFileInode(SourceFile)))) {
Douglas Gregore23ac652011-04-20 00:21:03 +00001448 bool Invalid = false;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001449 for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) {
1450 FileID IFileID;
1451 IFileID.ID = I;
1452 const SLocEntry &SLoc = getSLocEntry(IFileID, &Invalid);
Douglas Gregore23ac652011-04-20 00:21:03 +00001453 if (Invalid)
Argyrios Kyrtzidisb201e162011-09-27 17:22:25 +00001454 return FileID();
Douglas Gregore23ac652011-04-20 00:21:03 +00001455
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001456 if (SLoc.isFile()) {
1457 const ContentCache *FileContentCache
1458 = SLoc.getFile().getContentCache();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001459 const FileEntry *Entry =FileContentCache? FileContentCache->OrigEntry : 0;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001460 if (Entry &&
Douglas Gregorb7a18412011-02-11 18:08:15 +00001461 *SourceFileName == llvm::sys::path::filename(Entry->getName())) {
1462 if (llvm::Optional<ino_t> EntryInode = getActualFileInode(Entry)) {
1463 if (*SourceFileInode == *EntryInode) {
1464 FirstFID = FileID::get(I);
1465 SourceFile = Entry;
1466 break;
1467 }
1468 }
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001469 }
1470 }
1471 }
1472 }
Argyrios Kyrtzidisb201e162011-09-27 17:22:25 +00001473
1474 return FirstFID;
Argyrios Kyrtzidisefa2ff82011-09-19 20:40:29 +00001475}
1476
1477/// \brief Get the source location in \arg FID for the given line:col.
1478/// Returns null location if \arg FID is not a file SLocEntry.
1479SourceLocation SourceManager::translateLineCol(FileID FID,
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001480 unsigned Line,
1481 unsigned Col) const {
Argyrios Kyrtzidisefa2ff82011-09-19 20:40:29 +00001482 if (FID.isInvalid())
1483 return SourceLocation();
1484
1485 bool Invalid = false;
1486 const SLocEntry &Entry = getSLocEntry(FID, &Invalid);
1487 if (Invalid)
1488 return SourceLocation();
1489
1490 if (!Entry.isFile())
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001491 return SourceLocation();
1492
Argyrios Kyrtzidis5e5e95d2011-09-20 22:14:54 +00001493 SourceLocation FileLoc = SourceLocation::getFileLoc(Entry.getOffset());
1494
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001495 if (Line == 1 && Col == 1)
Argyrios Kyrtzidis5e5e95d2011-09-20 22:14:54 +00001496 return FileLoc;
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001497
1498 ContentCache *Content
Argyrios Kyrtzidisefa2ff82011-09-19 20:40:29 +00001499 = const_cast<ContentCache *>(Entry.getFile().getContentCache());
Douglas Gregor86a4d0d2011-02-03 17:17:35 +00001500 if (!Content)
1501 return SourceLocation();
1502
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001503 // If this is the first use of line information for this buffer, compute the
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001504 // SourceLineCache for it on demand.
Douglas Gregor50f6af72010-03-16 05:20:39 +00001505 if (Content->SourceLineCache == 0) {
1506 bool MyInvalid = false;
Chris Lattnere127a0d2010-04-20 20:35:58 +00001507 ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid);
Douglas Gregor50f6af72010-03-16 05:20:39 +00001508 if (MyInvalid)
1509 return SourceLocation();
1510 }
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001511
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001512 if (Line > Content->NumLines) {
Chris Lattnere127a0d2010-04-20 20:35:58 +00001513 unsigned Size = Content->getBuffer(Diag, *this)->getBufferSize();
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001514 if (Size > 0)
1515 --Size;
Argyrios Kyrtzidis5e5e95d2011-09-20 22:14:54 +00001516 return FileLoc.getLocWithOffset(Size);
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001517 }
1518
1519 unsigned FilePos = Content->SourceLineCache[Line - 1];
Chris Lattnere127a0d2010-04-20 20:35:58 +00001520 const char *Buf = Content->getBuffer(Diag, *this)->getBufferStart() + FilePos;
1521 unsigned BufLength = Content->getBuffer(Diag, *this)->getBufferEnd() - Buf;
Argyrios Kyrtzidis5e5e95d2011-09-20 22:14:54 +00001522 if (BufLength == 0)
1523 return FileLoc.getLocWithOffset(FilePos);
1524
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001525 unsigned i = 0;
1526
1527 // Check that the given column is valid.
1528 while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r')
1529 ++i;
1530 if (i < Col-1)
Argyrios Kyrtzidis5e5e95d2011-09-20 22:14:54 +00001531 return FileLoc.getLocWithOffset(FilePos + i);
Douglas Gregord1eabfb2010-02-27 02:42:25 +00001532
Argyrios Kyrtzidis5e5e95d2011-09-20 22:14:54 +00001533 return FileLoc.getLocWithOffset(FilePos + Col - 1);
Argyrios Kyrtzidis10b46d22009-06-20 08:09:57 +00001534}
1535
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001536/// \brief Compute a map of macro argument chunks to their expanded source
1537/// location. Chunks that are not part of a macro argument will map to an
1538/// invalid source location. e.g. if a file contains one macro argument at
1539/// offset 100 with length 10, this is how the map will be formed:
1540/// 0 -> SourceLocation()
1541/// 100 -> Expanded macro arg location
1542/// 110 -> SourceLocation()
Argyrios Kyrtzidisfb3612e2011-09-26 08:01:50 +00001543void SourceManager::computeMacroArgsCache(MacroArgsMap *&CachePtr,
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001544 FileID FID) const {
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001545 assert(!FID.isInvalid());
Argyrios Kyrtzidisfb3612e2011-09-26 08:01:50 +00001546 assert(!CachePtr);
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001547
Argyrios Kyrtzidisfb3612e2011-09-26 08:01:50 +00001548 CachePtr = new MacroArgsMap();
1549 MacroArgsMap &MacroArgsCache = *CachePtr;
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001550 // Initially no macro argument chunk is present.
1551 MacroArgsCache.insert(std::make_pair(0, SourceLocation()));
1552
1553 int ID = FID.ID;
1554 while (1) {
1555 ++ID;
1556 // Stop if there are no more FileIDs to check.
1557 if (ID > 0) {
1558 if (unsigned(ID) >= local_sloc_entry_size())
1559 return;
1560 } else if (ID == -1) {
1561 return;
1562 }
1563
1564 const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID);
1565 if (Entry.isFile()) {
1566 SourceLocation IncludeLoc = Entry.getFile().getIncludeLoc();
1567 if (IncludeLoc.isInvalid())
1568 continue;
1569 if (!isInFileID(IncludeLoc, FID))
1570 return; // No more files/macros that may be "contained" in this file.
1571
1572 // Skip the files/macros of the #include'd file, we only care about macros
1573 // that lexed macro arguments from our file.
1574 if (Entry.getFile().NumCreatedFIDs)
1575 ID += Entry.getFile().NumCreatedFIDs - 1/*because of next ++ID*/;
1576 continue;
1577 }
1578
1579 if (!Entry.getExpansion().isMacroArgExpansion())
1580 continue;
1581
1582 SourceLocation SpellLoc =
1583 getSpellingLoc(Entry.getExpansion().getSpellingLoc());
1584 unsigned BeginOffs;
1585 if (!isInFileID(SpellLoc, FID, &BeginOffs))
1586 return; // No more files/macros that may be "contained" in this file.
1587 unsigned EndOffs = BeginOffs + getFileIDSize(FileID::get(ID));
1588
1589 // Add a new chunk for this macro argument. A previous macro argument chunk
1590 // may have been lexed again, so e.g. if the map is
1591 // 0 -> SourceLocation()
1592 // 100 -> Expanded loc #1
1593 // 110 -> SourceLocation()
1594 // and we found a new macro FileID that lexed from offet 105 with length 3,
1595 // the new map will be:
1596 // 0 -> SourceLocation()
1597 // 100 -> Expanded loc #1
1598 // 105 -> Expanded loc #2
1599 // 108 -> Expanded loc #1
1600 // 110 -> SourceLocation()
1601 //
1602 // Since re-lexed macro chunks will always be the same size or less of
1603 // previous chunks, we only need to find where the ending of the new macro
1604 // chunk is mapped to and update the map with new begin/end mappings.
1605
Argyrios Kyrtzidisfb3612e2011-09-26 08:01:50 +00001606 MacroArgsMap::iterator I = MacroArgsCache.upper_bound(EndOffs);
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001607 --I;
1608 SourceLocation EndOffsMappedLoc = I->second;
1609 MacroArgsCache[BeginOffs] = SourceLocation::getMacroLoc(Entry.getOffset());
1610 MacroArgsCache[EndOffs] = EndOffsMappedLoc;
1611 }
1612}
1613
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001614/// \brief If \arg Loc points inside a function macro argument, the returned
1615/// location will be the macro location in which the argument was expanded.
1616/// If a macro argument is used multiple times, the expanded location will
1617/// be at the first expansion of the argument.
1618/// e.g.
1619/// MY_MACRO(foo);
1620/// ^
1621/// Passing a file location pointing at 'foo', will yield a macro location
1622/// where 'foo' was expanded into.
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001623SourceLocation
1624SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const {
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001625 if (Loc.isInvalid() || !Loc.isFileID())
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001626 return Loc;
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001627
1628 FileID FID;
1629 unsigned Offset;
1630 llvm::tie(FID, Offset) = getDecomposedLoc(Loc);
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001631 if (FID.isInvalid())
1632 return Loc;
1633
Argyrios Kyrtzidisfb3612e2011-09-26 08:01:50 +00001634 MacroArgsMap *&MacroArgsCache = MacroArgsCacheMap[FID];
1635 if (!MacroArgsCache)
1636 computeMacroArgsCache(MacroArgsCache, FID);
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001637
Argyrios Kyrtzidisfb3612e2011-09-26 08:01:50 +00001638 assert(!MacroArgsCache->empty());
1639 MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset);
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001640 --I;
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001641
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001642 unsigned MacroArgBeginOffs = I->first;
1643 SourceLocation MacroArgExpandedLoc = I->second;
1644 if (MacroArgExpandedLoc.isValid())
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001645 return MacroArgExpandedLoc.getLocWithOffset(Offset - MacroArgBeginOffs);
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001646
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001647 return Loc;
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001648}
1649
Chandler Carruth3201f382011-07-26 05:17:23 +00001650/// Given a decomposed source location, move it up the include/expansion stack
1651/// to the parent source location. If this is possible, return the decomposed
1652/// version of the parent in Loc and return false. If Loc is the top-level
1653/// entry, return true and don't modify it.
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001654static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
1655 const SourceManager &SM) {
1656 SourceLocation UpperLoc;
1657 const SrcMgr::SLocEntry &Entry = SM.getSLocEntry(Loc.first);
Chandler Carruth17287622011-07-26 04:56:51 +00001658 if (Entry.isExpansion())
Argyrios Kyrtzidis50402472011-09-19 20:39:57 +00001659 UpperLoc = Entry.getExpansion().getExpansionLocEnd();
Chris Lattnerd3b8cc22010-05-07 20:35:24 +00001660 else
1661 UpperLoc = Entry.getFile().getIncludeLoc();
1662
1663 if (UpperLoc.isInvalid())
1664 return true; // We reached the top.
1665
1666 Loc = SM.getDecomposedLoc(UpperLoc);
1667 return false;
1668}
1669
1670
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001671/// \brief Determines the order of 2 source locations in the translation unit.
1672///
1673/// \returns true if LHS source location comes before RHS, false otherwise.
1674bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
1675 SourceLocation RHS) const {
1676 assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!");
1677 if (LHS == RHS)
1678 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001679
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001680 std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS);
1681 std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00001682
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001683 // If the source locations are in the same file, just compare offsets.
1684 if (LOffs.first == ROffs.first)
1685 return LOffs.second < ROffs.second;
1686
1687 // If we are comparing a source location with multiple locations in the same
1688 // file, we get a big win by caching the result.
Chris Lattner66a915f2010-05-07 05:10:46 +00001689 if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first))
1690 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001691
Chris Lattnerdcb1d682010-05-07 01:17:07 +00001692 // Okay, we missed in the cache, start updating the cache for this query.
Argyrios Kyrtzidis37e59a12011-08-17 00:31:18 +00001693 IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first,
1694 /*isLFIDBeforeRFID=*/LOffs.first.ID < ROffs.first.ID);
Mike Stump1eb44332009-09-09 15:08:12 +00001695
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001696 // We need to find the common ancestor. The only way of doing this is to
1697 // build the complete include chain for one and then walking up the chain
1698 // of the other looking for a match.
1699 // We use a map from FileID to Offset to store the chain. Easier than writing
1700 // a custom set hash info that only depends on the first part of a pair.
1701 typedef llvm::DenseMap<FileID, unsigned> LocSet;
1702 LocSet LChain;
Chris Lattner48296ba2010-05-07 05:51:13 +00001703 do {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001704 LChain.insert(LOffs);
1705 // We catch the case where LOffs is in a file included by ROffs and
1706 // quit early. The other way round unfortunately remains suboptimal.
1707 } while (LOffs.first != ROffs.first && !MoveUpIncludeHierarchy(LOffs, *this));
1708 LocSet::iterator I;
1709 while((I = LChain.find(ROffs.first)) == LChain.end()) {
1710 if (MoveUpIncludeHierarchy(ROffs, *this))
1711 break; // Met at topmost file.
1712 }
1713 if (I != LChain.end())
1714 LOffs = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001715
Chris Lattner48296ba2010-05-07 05:51:13 +00001716 // If we exited because we found a nearest common ancestor, compare the
1717 // locations within the common file and cache them.
1718 if (LOffs.first == ROffs.first) {
1719 IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second);
1720 return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second);
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001721 }
Mike Stump1eb44332009-09-09 15:08:12 +00001722
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001723 // This can happen if a location is in a built-ins buffer.
1724 // But see PR5662.
1725 // Clear the lookup cache, it depends on a common location.
Argyrios Kyrtzidis37e59a12011-08-17 00:31:18 +00001726 IsBeforeInTUCache.clear();
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001727 bool LIsBuiltins = strcmp("<built-in>",
1728 getBuffer(LOffs.first)->getBufferIdentifier()) == 0;
1729 bool RIsBuiltins = strcmp("<built-in>",
1730 getBuffer(ROffs.first)->getBufferIdentifier()) == 0;
1731 // built-in is before non-built-in
1732 if (LIsBuiltins != RIsBuiltins)
1733 return LIsBuiltins;
1734 assert(LIsBuiltins && RIsBuiltins &&
1735 "Non-built-in locations must be rooted in the main file");
1736 // Both are in built-in buffers, but from different files. We just claim that
1737 // lower IDs come first.
Chris Lattnerdcb1d682010-05-07 01:17:07 +00001738 return LOffs.first < ROffs.first;
Argyrios Kyrtzidis2aa03d52009-06-23 22:01:48 +00001739}
Chris Lattnerde7aeef2009-01-26 00:43:02 +00001740
Reid Spencer5f016e22007-07-11 17:01:13 +00001741/// PrintStats - Print statistics to stderr.
1742///
1743void SourceManager::PrintStats() const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001744 llvm::errs() << "\n*** Source Manager Stats:\n";
1745 llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size()
1746 << " mem buffers mapped.\n";
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001747 llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntry's allocated ("
Ted Kremenek6e36c122011-07-27 18:41:16 +00001748 << llvm::capacity_in_bytes(LocalSLocEntryTable)
Argyrios Kyrtzidisd410e742011-07-07 03:40:24 +00001749 << " bytes of capacity), "
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001750 << NextLocalOffset << "B of Sloc address space used.\n";
1751 llvm::errs() << LoadedSLocEntryTable.size()
1752 << " loaded SLocEntries allocated, "
Argyrios Kyrtzidisac836e42011-08-17 00:31:20 +00001753 << MaxLoadedOffset - CurrentLoadedOffset
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001754 << "B of Sloc address space used.\n";
1755
Reid Spencer5f016e22007-07-11 17:01:13 +00001756 unsigned NumLineNumsComputed = 0;
1757 unsigned NumFileBytesMapped = 0;
Chris Lattner0d0bf8c2009-02-03 07:30:45 +00001758 for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){
1759 NumLineNumsComputed += I->second->SourceLineCache != 0;
1760 NumFileBytesMapped += I->second->getSizeBytesMapped();
Reid Spencer5f016e22007-07-11 17:01:13 +00001761 }
Argyrios Kyrtzidisfb3612e2011-09-26 08:01:50 +00001762 unsigned NumMacroArgsComputed = MacroArgsCacheMap.size();
Mike Stump1eb44332009-09-09 15:08:12 +00001763
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001764 llvm::errs() << NumFileBytesMapped << " bytes of files mapped, "
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001765 << NumLineNumsComputed << " files with line #'s computed, "
1766 << NumMacroArgsComputed << " files with macro args computed.\n";
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +00001767 llvm::errs() << "FileID scans: " << NumLinearScans << " linear, "
1768 << NumBinaryProbes << " binary.\n";
Reid Spencer5f016e22007-07-11 17:01:13 +00001769}
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001770
1771ExternalSLocEntrySource::~ExternalSLocEntrySource() { }
Ted Kremenekf61b8312011-04-28 20:36:42 +00001772
1773/// Return the amount of memory used by memory buffers, breaking down
1774/// by heap-backed versus mmap'ed memory.
1775SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const {
1776 size_t malloc_bytes = 0;
1777 size_t mmap_bytes = 0;
1778
1779 for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i)
1780 if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped())
1781 switch (MemBufferInfos[i]->getMemoryBufferKind()) {
1782 case llvm::MemoryBuffer::MemoryBuffer_MMap:
1783 mmap_bytes += sized_mapped;
1784 break;
1785 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
1786 malloc_bytes += sized_mapped;
1787 break;
1788 }
1789
1790 return MemoryBufferSizes(malloc_bytes, mmap_bytes);
1791}
1792
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00001793size_t SourceManager::getDataStructureSizes() const {
Ted Kremenek6e36c122011-07-27 18:41:16 +00001794 return llvm::capacity_in_bytes(MemBufferInfos)
1795 + llvm::capacity_in_bytes(LocalSLocEntryTable)
1796 + llvm::capacity_in_bytes(LoadedSLocEntryTable)
1797 + llvm::capacity_in_bytes(SLocEntryLoaded)
1798 + llvm::capacity_in_bytes(FileInfos)
1799 + llvm::capacity_in_bytes(OverriddenFiles);
Ted Kremenekca7dc2b2011-07-26 23:46:06 +00001800}